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>
34 #if defined(__ANDROID__)
35 #include <sys/system_properties.h>
43 LineReader(FILE* fp) : fp_(fp), buf_(nullptr), bufsize_(0) {
52 if (getline(&buf_, &bufsize_, fp_) != -1) {
58 size_t MaxLineSize() {
68 std::vector<int> GetOnlineCpus() {
69 std::vector<int> result;
70 FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
72 PLOG(ERROR) << "can't open online cpu information";
76 LineReader reader(fp);
78 if ((line = reader.ReadLine()) != nullptr) {
79 result = GetCpusFromString(line);
81 CHECK(!result.empty()) << "can't get online cpu information";
85 std::vector<int> GetCpusFromString(const std::string& s) {
86 std::set<int> cpu_set;
87 bool have_dash = false;
88 const char* p = s.c_str();
92 // Parse line like: 0,1-3, 5, 7-8
93 while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) {
94 if (have_dash && !cpu_set.empty()) {
95 for (int t = last_cpu + 1; t < cpu; ++t) {
103 while (!isdigit(*p) && *p != '\0') {
110 return std::vector<int>(cpu_set.begin(), cpu_set.end());
113 bool ProcessKernelSymbols(const std::string& symbol_file,
114 std::function<bool(const KernelSymbol&)> callback) {
115 FILE* fp = fopen(symbol_file.c_str(), "re");
117 PLOG(ERROR) << "failed to open file " << symbol_file;
120 LineReader reader(fp);
122 while ((line = reader.ReadLine()) != nullptr) {
123 // Parse line like: ffffffffa005c4e4 d __warned.41698 [libsas]
124 char name[reader.MaxLineSize()];
125 char module[reader.MaxLineSize()];
129 if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
133 size_t module_len = strlen(module);
134 if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
135 module[module_len - 1] = '\0';
136 symbol.module = &module[1];
138 symbol.module = nullptr;
141 if (callback(symbol)) {
148 static std::vector<KernelMmap> GetLoadedModules() {
149 std::vector<KernelMmap> result;
150 FILE* fp = fopen("/proc/modules", "re");
152 // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
153 PLOG(DEBUG) << "failed to open file /proc/modules";
156 LineReader reader(fp);
158 while ((line = reader.ReadLine()) != nullptr) {
159 // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
160 char name[reader.MaxLineSize()];
162 if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
165 map.start_addr = addr;
166 result.push_back(map);
172 static std::string GetLinuxVersion() {
174 if (android::base::ReadFileToString("/proc/version", &content)) {
175 char s[content.size() + 1];
176 if (sscanf(content.c_str(), "Linux version %s", s) == 1) {
180 PLOG(FATAL) << "can't read linux version";
184 static void GetAllModuleFiles(const std::string& path,
185 std::unordered_map<std::string, std::string>* module_file_map) {
186 std::vector<std::string> files;
187 std::vector<std::string> subdirs;
188 GetEntriesInDir(path, &files, &subdirs);
189 for (auto& name : files) {
190 if (android::base::EndsWith(name, ".ko")) {
191 std::string module_name = name.substr(0, name.size() - 3);
192 std::replace(module_name.begin(), module_name.end(), '-', '_');
193 module_file_map->insert(std::make_pair(module_name, path + "/" + name));
196 for (auto& name : subdirs) {
197 GetAllModuleFiles(path + "/" + name, module_file_map);
201 static std::vector<KernelMmap> GetModulesInUse() {
202 // TODO: There is no /proc/modules or /lib/modules on Android, find methods work on it.
203 std::vector<KernelMmap> module_mmaps = GetLoadedModules();
204 std::string linux_version = GetLinuxVersion();
205 std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
206 std::unordered_map<std::string, std::string> module_file_map;
207 GetAllModuleFiles(module_dirpath, &module_file_map);
208 for (auto& module : module_mmaps) {
209 auto it = module_file_map.find(module.name);
210 if (it != module_file_map.end()) {
211 module.filepath = it->second;
217 void GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<KernelMmap>* module_mmaps) {
218 kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
219 kernel_mmap->start_addr = 0;
220 kernel_mmap->filepath = kernel_mmap->name;
221 *module_mmaps = GetModulesInUse();
222 for (auto& map : *module_mmaps) {
223 if (map.filepath.empty()) {
224 map.filepath = "[" + map.name + "]";
228 if (module_mmaps->size() == 0) {
229 kernel_mmap->len = std::numeric_limits<unsigned long long>::max() - kernel_mmap->start_addr;
232 module_mmaps->begin(), module_mmaps->end(),
233 [](const KernelMmap& m1, const KernelMmap& m2) { return m1.start_addr < m2.start_addr; });
234 // When not having enough privilege, all addresses are read as 0.
235 if (kernel_mmap->start_addr == (*module_mmaps)[0].start_addr) {
236 kernel_mmap->len = 0;
238 kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
240 for (size_t i = 0; i + 1 < module_mmaps->size(); ++i) {
241 if ((*module_mmaps)[i].start_addr == (*module_mmaps)[i + 1].start_addr) {
242 (*module_mmaps)[i].len = 0;
244 (*module_mmaps)[i].len =
245 (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
248 module_mmaps->back().len =
249 std::numeric_limits<unsigned long long>::max() - module_mmaps->back().start_addr;
253 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
254 FILE* fp = fopen(status_file.c_str(), "re");
258 bool read_comm = false;
259 bool read_tgid = false;
260 LineReader reader(fp);
262 while ((line = reader.ReadLine()) != nullptr) {
263 char s[reader.MaxLineSize()];
264 if (sscanf(line, "Name:%s", s) == 1) {
267 } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
270 if (read_comm && read_tgid) {
277 static std::vector<pid_t> GetThreadsInProcess(pid_t pid) {
278 std::vector<pid_t> result;
279 std::string task_dirname = android::base::StringPrintf("/proc/%d/task", pid);
280 std::vector<std::string> subdirs;
281 GetEntriesInDir(task_dirname, nullptr, &subdirs);
282 for (const auto& name : subdirs) {
284 if (!android::base::ParseInt(name.c_str(), &tid, 0)) {
287 result.push_back(tid);
292 static bool GetThreadComm(pid_t pid, std::vector<ThreadComm>* thread_comms) {
293 std::vector<pid_t> tids = GetThreadsInProcess(pid);
294 for (auto& tid : tids) {
295 std::string status_file = android::base::StringPrintf("/proc/%d/task/%d/status", pid, tid);
298 // It is possible that the process or thread exited before we can read its status.
299 if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
307 thread_comms->push_back(thread);
312 bool GetThreadComms(std::vector<ThreadComm>* thread_comms) {
313 thread_comms->clear();
314 std::vector<std::string> subdirs;
315 GetEntriesInDir("/proc", nullptr, &subdirs);
316 for (auto& name : subdirs) {
318 if (!android::base::ParseInt(name.c_str(), &pid, 0)) {
321 if (!GetThreadComm(pid, thread_comms)) {
328 bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
329 std::string map_file = android::base::StringPrintf("/proc/%d/maps", pid);
330 FILE* fp = fopen(map_file.c_str(), "re");
332 PLOG(DEBUG) << "can't open file " << map_file;
335 thread_mmaps->clear();
336 LineReader reader(fp);
338 while ((line = reader.ReadLine()) != nullptr) {
339 // Parse line like: 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
340 uint64_t start_addr, end_addr, pgoff;
341 char type[reader.MaxLineSize()];
342 char execname[reader.MaxLineSize()];
343 strcpy(execname, "");
344 if (sscanf(line, "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " %*x:%*x %*u %s\n", &start_addr,
345 &end_addr, type, &pgoff, execname) < 4) {
348 if (strcmp(execname, "") == 0) {
349 strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
352 thread.start_addr = start_addr;
353 thread.len = end_addr - start_addr;
354 thread.pgoff = pgoff;
355 thread.name = execname;
356 thread.executable = (type[2] == 'x');
357 thread_mmaps->push_back(thread);
362 bool GetKernelBuildId(BuildId* build_id) {
363 return GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
366 bool GetModuleBuildId(const std::string& module_name, BuildId* build_id) {
367 std::string notefile = "/sys/module/" + module_name + "/notes/.note.gnu.build-id";
368 return GetBuildIdFromNoteFile(notefile, build_id);
371 bool GetValidThreadsFromProcessString(const std::string& pid_str, std::set<pid_t>* tid_set) {
372 std::vector<std::string> strs = android::base::Split(pid_str, ",");
373 for (const auto& s : strs) {
375 if (!android::base::ParseInt(s.c_str(), &pid, 0)) {
376 LOG(ERROR) << "Invalid pid '" << s << "'";
379 std::vector<pid_t> tids = GetThreadsInProcess(pid);
381 LOG(ERROR) << "Non existing process '" << pid << "'";
384 tid_set->insert(tids.begin(), tids.end());
389 bool GetValidThreadsFromThreadString(const std::string& tid_str, std::set<pid_t>* tid_set) {
390 std::vector<std::string> strs = android::base::Split(tid_str, ",");
391 for (const auto& s : strs) {
393 if (!android::base::ParseInt(s.c_str(), &tid, 0)) {
394 LOG(ERROR) << "Invalid tid '" << s << "'";
397 if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
398 LOG(ERROR) << "Non existing thread '" << tid << "'";
401 tid_set->insert(tid);
406 bool GetExecPath(std::string* exec_path) {
408 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
409 if (path_len <= 0 || path_len >= static_cast<ssize_t>(sizeof(path))) {
410 PLOG(ERROR) << "readlink failed";
413 path[path_len] = '\0';
419 * perf event paranoia level:
420 * -1 - not paranoid at all
421 * 0 - disallow raw tracepoint access for unpriv
422 * 1 - disallow cpu events for unpriv
423 * 2 - disallow kernel profiling for unpriv
424 * 3 - disallow user profiling for unpriv
426 static bool ReadPerfEventParanoid(int* value) {
428 if (!android::base::ReadFileToString("/proc/sys/kernel/perf_event_paranoid", &s)) {
429 PLOG(ERROR) << "failed to read /proc/sys/kernel/perf_event_paranoid";
432 s = android::base::Trim(s);
433 if (!android::base::ParseInt(s.c_str(), value)) {
434 PLOG(ERROR) << "failed to parse /proc/sys/kernel/perf_event_paranoid: " << s;
440 static const char* GetLimitLevelDescription(int limit_level) {
441 switch (limit_level) {
442 case -1: return "unlimited";
443 case 0: return "disallowing raw tracepoint access for unpriv";
444 case 1: return "disallowing cpu events for unpriv";
445 case 2: return "disallowing kernel profiling for unpriv";
446 case 3: return "disallowing user profiling for unpriv";
447 default: return "unknown level";
451 bool CheckPerfEventLimit() {
452 // root is not limited by /proc/sys/kernel/perf_event_paranoid.
457 if (!ReadPerfEventParanoid(&limit_level)) {
460 if (limit_level <= 1) {
463 #if defined(__ANDROID__)
464 // Try to enable perf_event_paranoid by setprop security.perf_harden=0.
465 if (__system_property_set("security.perf_harden", "0") == 0) {
467 if (ReadPerfEventParanoid(&limit_level) && limit_level <= 1) {
471 LOG(WARNING) << "/proc/sys/kernel/perf_event_paranoid is " << limit_level
472 << ", " << GetLimitLevelDescription(limit_level) << ".";
473 LOG(WARNING) << "Try using `adb shell setprop security.perf_harden 0` to allow profiling.";
475 LOG(WARNING) << "/proc/sys/kernel/perf_event_paranoid is " << limit_level
476 << ", " << GetLimitLevelDescription(limit_level) << ".";