Home | History | Annotate | Download | only in simpleperf
      1 /*
      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 
     19 #include <inttypes.h>
     20 #include <stdio.h>
     21 #include <stdlib.h>
     22 
     23 #include <limits>
     24 #include <set>
     25 #include <unordered_map>
     26 #include <vector>
     27 
     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>
     33 
     34 #if defined(__ANDROID__)
     35 #include <sys/system_properties.h>
     36 #endif
     37 
     38 #include "read_elf.h"
     39 #include "utils.h"
     40 
     41 class LineReader {
     42  public:
     43   LineReader(FILE* fp) : fp_(fp), buf_(nullptr), bufsize_(0) {
     44   }
     45 
     46   ~LineReader() {
     47     free(buf_);
     48     fclose(fp_);
     49   }
     50 
     51   char* ReadLine() {
     52     if (getline(&buf_, &bufsize_, fp_) != -1) {
     53       return buf_;
     54     }
     55     return nullptr;
     56   }
     57 
     58   size_t MaxLineSize() {
     59     return bufsize_;
     60   }
     61 
     62  private:
     63   FILE* fp_;
     64   char* buf_;
     65   size_t bufsize_;
     66 };
     67 
     68 std::vector<int> GetOnlineCpus() {
     69   std::vector<int> result;
     70   FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
     71   if (fp == nullptr) {
     72     PLOG(ERROR) << "can't open online cpu information";
     73     return result;
     74   }
     75 
     76   LineReader reader(fp);
     77   char* line;
     78   if ((line = reader.ReadLine()) != nullptr) {
     79     result = GetCpusFromString(line);
     80   }
     81   CHECK(!result.empty()) << "can't get online cpu information";
     82   return result;
     83 }
     84 
     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();
     89   char* endp;
     90   int last_cpu;
     91   long cpu;
     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) {
     96         cpu_set.insert(t);
     97       }
     98     }
     99     have_dash = false;
    100     cpu_set.insert(cpu);
    101     last_cpu = cpu;
    102     p = endp;
    103     while (!isdigit(*p) && *p != '\0') {
    104       if (*p == '-') {
    105         have_dash = true;
    106       }
    107       ++p;
    108     }
    109   }
    110   return std::vector<int>(cpu_set.begin(), cpu_set.end());
    111 }
    112 
    113 bool ProcessKernelSymbols(const std::string& symbol_file,
    114                           std::function<bool(const KernelSymbol&)> callback) {
    115   FILE* fp = fopen(symbol_file.c_str(), "re");
    116   if (fp == nullptr) {
    117     PLOG(ERROR) << "failed to open file " << symbol_file;
    118     return false;
    119   }
    120   LineReader reader(fp);
    121   char* line;
    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()];
    126     strcpy(module, "");
    127 
    128     KernelSymbol symbol;
    129     if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
    130       continue;
    131     }
    132     symbol.name = name;
    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];
    137     } else {
    138       symbol.module = nullptr;
    139     }
    140 
    141     if (callback(symbol)) {
    142       return true;
    143     }
    144   }
    145   return false;
    146 }
    147 
    148 static std::vector<KernelMmap> GetLoadedModules() {
    149   std::vector<KernelMmap> result;
    150   FILE* fp = fopen("/proc/modules", "re");
    151   if (fp == nullptr) {
    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";
    154     return result;
    155   }
    156   LineReader reader(fp);
    157   char* line;
    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()];
    161     uint64_t addr;
    162     if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
    163       KernelMmap map;
    164       map.name = name;
    165       map.start_addr = addr;
    166       result.push_back(map);
    167     }
    168   }
    169   return result;
    170 }
    171 
    172 static std::string GetLinuxVersion() {
    173   std::string content;
    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) {
    177       return s;
    178     }
    179   }
    180   PLOG(FATAL) << "can't read linux version";
    181   return "";
    182 }
    183 
    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));
    194     }
    195   }
    196   for (auto& name : subdirs) {
    197     GetAllModuleFiles(path + "/" + name, module_file_map);
    198   }
    199 }
    200 
    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;
    212     }
    213   }
    214   return module_mmaps;
    215 }
    216 
    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 + "]";
    225     }
    226   }
    227 
    228   if (module_mmaps->size() == 0) {
    229     kernel_mmap->len = std::numeric_limits<unsigned long long>::max() - kernel_mmap->start_addr;
    230   } else {
    231     std::sort(
    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;
    237     } else {
    238       kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
    239     }
    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;
    243       } else {
    244         (*module_mmaps)[i].len =
    245             (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
    246       }
    247     }
    248     module_mmaps->back().len =
    249         std::numeric_limits<unsigned long long>::max() - module_mmaps->back().start_addr;
    250   }
    251 }
    252 
    253 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
    254   FILE* fp = fopen(status_file.c_str(), "re");
    255   if (fp == nullptr) {
    256     return false;
    257   }
    258   bool read_comm = false;
    259   bool read_tgid = false;
    260   LineReader reader(fp);
    261   char* line;
    262   while ((line = reader.ReadLine()) != nullptr) {
    263     char s[reader.MaxLineSize()];
    264     if (sscanf(line, "Name:%s", s) == 1) {
    265       *comm = s;
    266       read_comm = true;
    267     } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
    268       read_tgid = true;
    269     }
    270     if (read_comm && read_tgid) {
    271       return true;
    272     }
    273   }
    274   return false;
    275 }
    276 
    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) {
    283     int tid;
    284     if (!android::base::ParseInt(name.c_str(), &tid, 0)) {
    285       continue;
    286     }
    287     result.push_back(tid);
    288   }
    289   return result;
    290 }
    291 
    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);
    296     std::string comm;
    297     pid_t tgid;
    298     // It is possible that the process or thread exited before we can read its status.
    299     if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
    300       continue;
    301     }
    302     CHECK_EQ(pid, tgid);
    303     ThreadComm thread;
    304     thread.tid = tid;
    305     thread.pid = pid;
    306     thread.comm = comm;
    307     thread_comms->push_back(thread);
    308   }
    309   return true;
    310 }
    311 
    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) {
    317     int pid;
    318     if (!android::base::ParseInt(name.c_str(), &pid, 0)) {
    319       continue;
    320     }
    321     if (!GetThreadComm(pid, thread_comms)) {
    322       return false;
    323     }
    324   }
    325   return true;
    326 }
    327 
    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");
    331   if (fp == nullptr) {
    332     PLOG(DEBUG) << "can't open file " << map_file;
    333     return false;
    334   }
    335   thread_mmaps->clear();
    336   LineReader reader(fp);
    337   char* line;
    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) {
    346       continue;
    347     }
    348     if (strcmp(execname, "") == 0) {
    349       strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
    350     }
    351     ThreadMmap thread;
    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);
    358   }
    359   return true;
    360 }
    361 
    362 bool GetKernelBuildId(BuildId* build_id) {
    363   return GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
    364 }
    365 
    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);
    369 }
    370 
    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) {
    374     int pid;
    375     if (!android::base::ParseInt(s.c_str(), &pid, 0)) {
    376       LOG(ERROR) << "Invalid pid '" << s << "'";
    377       return false;
    378     }
    379     std::vector<pid_t> tids = GetThreadsInProcess(pid);
    380     if (tids.empty()) {
    381       LOG(ERROR) << "Non existing process '" << pid << "'";
    382       return false;
    383     }
    384     tid_set->insert(tids.begin(), tids.end());
    385   }
    386   return true;
    387 }
    388 
    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) {
    392     int tid;
    393     if (!android::base::ParseInt(s.c_str(), &tid, 0)) {
    394       LOG(ERROR) << "Invalid tid '" << s << "'";
    395       return false;
    396     }
    397     if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
    398       LOG(ERROR) << "Non existing thread '" << tid << "'";
    399       return false;
    400     }
    401     tid_set->insert(tid);
    402   }
    403   return true;
    404 }
    405 
    406 bool GetExecPath(std::string* exec_path) {
    407   char path[PATH_MAX];
    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";
    411     return false;
    412   }
    413   path[path_len] = '\0';
    414   *exec_path = path;
    415   return true;
    416 }
    417 
    418 /*
    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
    425  */
    426 static bool ReadPerfEventParanoid(int* value) {
    427   std::string s;
    428   if (!android::base::ReadFileToString("/proc/sys/kernel/perf_event_paranoid", &s)) {
    429     PLOG(ERROR) << "failed to read /proc/sys/kernel/perf_event_paranoid";
    430     return false;
    431   }
    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;
    435     return false;
    436   }
    437   return true;
    438 }
    439 
    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";
    448   }
    449 }
    450 
    451 bool CheckPerfEventLimit() {
    452   // root is not limited by /proc/sys/kernel/perf_event_paranoid.
    453   if (IsRoot()) {
    454     return true;
    455   }
    456   int limit_level;
    457   if (!ReadPerfEventParanoid(&limit_level)) {
    458     return false;
    459   }
    460   if (limit_level <= 1) {
    461     return true;
    462   }
    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) {
    466     sleep(1);
    467     if (ReadPerfEventParanoid(&limit_level) && limit_level <= 1) {
    468       return true;
    469     }
    470   }
    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.";
    474 #else
    475   LOG(WARNING) << "/proc/sys/kernel/perf_event_paranoid is " << limit_level
    476       << ", " << GetLimitLevelDescription(limit_level) << ".";
    477 #endif
    478   return true;
    479 }
    480