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 <signal.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/resource.h>
25 #include <sys/utsname.h>
26 
27 #include <limits>
28 #include <set>
29 #include <unordered_map>
30 #include <vector>
31 
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 #include <android-base/parseint.h>
35 #include <android-base/strings.h>
36 #include <android-base/stringprintf.h>
37 #include <procinfo/process.h>
38 #include <procinfo/process_map.h>
39 
40 #if defined(__ANDROID__)
41 #include <android-base/properties.h>
42 #endif
43 
44 #include "command.h"
45 #include "event_type.h"
46 #include "IOEventLoop.h"
47 #include "read_elf.h"
48 #include "thread_tree.h"
49 #include "utils.h"
50 #include "workload.h"
51 
52 using namespace simpleperf;
53 
54 class LineReader {
55  public:
LineReader(FILE * fp)56   explicit LineReader(FILE* fp) : fp_(fp), buf_(nullptr), bufsize_(0) {
57   }
58 
~LineReader()59   ~LineReader() {
60     free(buf_);
61     fclose(fp_);
62   }
63 
ReadLine()64   char* ReadLine() {
65     if (getline(&buf_, &bufsize_, fp_) != -1) {
66       return buf_;
67     }
68     return nullptr;
69   }
70 
MaxLineSize()71   size_t MaxLineSize() {
72     return bufsize_;
73   }
74 
75  private:
76   FILE* fp_;
77   char* buf_;
78   size_t bufsize_;
79 };
80 
GetOnlineCpus()81 std::vector<int> GetOnlineCpus() {
82   std::vector<int> result;
83   FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
84   if (fp == nullptr) {
85     PLOG(ERROR) << "can't open online cpu information";
86     return result;
87   }
88 
89   LineReader reader(fp);
90   char* line;
91   if ((line = reader.ReadLine()) != nullptr) {
92     result = GetCpusFromString(line);
93   }
94   CHECK(!result.empty()) << "can't get online cpu information";
95   return result;
96 }
97 
GetLoadedModules()98 static std::vector<KernelMmap> GetLoadedModules() {
99   std::vector<KernelMmap> result;
100   FILE* fp = fopen("/proc/modules", "re");
101   if (fp == nullptr) {
102     // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
103     PLOG(DEBUG) << "failed to open file /proc/modules";
104     return result;
105   }
106   LineReader reader(fp);
107   char* line;
108   while ((line = reader.ReadLine()) != nullptr) {
109     // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
110     char name[reader.MaxLineSize()];
111     uint64_t addr;
112     uint64_t len;
113     if (sscanf(line, "%s%" PRIu64 "%*u%*s%*s 0x%" PRIx64, name, &len, &addr) == 3) {
114       KernelMmap map;
115       map.name = name;
116       map.start_addr = addr;
117       map.len = len;
118       result.push_back(map);
119     }
120   }
121   bool all_zero = true;
122   for (const auto& map : result) {
123     if (map.start_addr != 0) {
124       all_zero = false;
125     }
126   }
127   if (all_zero) {
128     LOG(DEBUG) << "addresses in /proc/modules are all zero, so ignore kernel modules";
129     return std::vector<KernelMmap>();
130   }
131   return result;
132 }
133 
GetAllModuleFiles(const std::string & path,std::unordered_map<std::string,std::string> * module_file_map)134 static void GetAllModuleFiles(const std::string& path,
135                               std::unordered_map<std::string, std::string>* module_file_map) {
136   for (const auto& name : GetEntriesInDir(path)) {
137     std::string entry_path = path + "/" + name;
138     if (IsRegularFile(entry_path) && android::base::EndsWith(name, ".ko")) {
139       std::string module_name = name.substr(0, name.size() - 3);
140       std::replace(module_name.begin(), module_name.end(), '-', '_');
141       module_file_map->insert(std::make_pair(module_name, entry_path));
142     } else if (IsDir(entry_path)) {
143       GetAllModuleFiles(entry_path, module_file_map);
144     }
145   }
146 }
147 
GetModulesInUse()148 static std::vector<KernelMmap> GetModulesInUse() {
149   std::vector<KernelMmap> module_mmaps = GetLoadedModules();
150   if (module_mmaps.empty()) {
151     return std::vector<KernelMmap>();
152   }
153   std::unordered_map<std::string, std::string> module_file_map;
154 #if defined(__ANDROID__)
155   // Search directories listed in "File locations" section in
156   // https://source.android.com/devices/architecture/kernel/modular-kernels.
157   for (const auto& path : {"/vendor/lib/modules", "/odm/lib/modules", "/lib/modules"}) {
158     GetAllModuleFiles(path, &module_file_map);
159   }
160 #else
161   utsname uname_buf;
162   if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
163     PLOG(ERROR) << "uname() failed";
164     return std::vector<KernelMmap>();
165   }
166   std::string linux_version = uname_buf.release;
167   std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
168   GetAllModuleFiles(module_dirpath, &module_file_map);
169 #endif
170   for (auto& module : module_mmaps) {
171     auto it = module_file_map.find(module.name);
172     if (it != module_file_map.end()) {
173       module.filepath = it->second;
174     }
175   }
176   return module_mmaps;
177 }
178 
GetKernelAndModuleMmaps(KernelMmap * kernel_mmap,std::vector<KernelMmap> * module_mmaps)179 void GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<KernelMmap>* module_mmaps) {
180   kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
181   kernel_mmap->start_addr = 0;
182   kernel_mmap->len = std::numeric_limits<uint64_t>::max();
183   kernel_mmap->filepath = kernel_mmap->name;
184   *module_mmaps = GetModulesInUse();
185   for (auto& map : *module_mmaps) {
186     if (map.filepath.empty()) {
187       map.filepath = "[" + map.name + "]";
188     }
189   }
190 }
191 
ReadThreadNameAndPid(pid_t tid,std::string * comm,pid_t * pid)192 bool ReadThreadNameAndPid(pid_t tid, std::string* comm, pid_t* pid) {
193   android::procinfo::ProcessInfo procinfo;
194   if (!android::procinfo::GetProcessInfo(tid, &procinfo)) {
195     return false;
196   }
197   if (comm != nullptr) {
198     *comm = procinfo.name;
199   }
200   if (pid != nullptr) {
201     *pid = procinfo.pid;
202   }
203   return true;
204 }
205 
GetThreadsInProcess(pid_t pid)206 std::vector<pid_t> GetThreadsInProcess(pid_t pid) {
207   std::vector<pid_t> result;
208   android::procinfo::GetProcessTids(pid, &result);
209   return result;
210 }
211 
IsThreadAlive(pid_t tid)212 bool IsThreadAlive(pid_t tid) {
213   return IsDir(android::base::StringPrintf("/proc/%d", tid));
214 }
215 
GetProcessForThread(pid_t tid,pid_t * pid)216 bool GetProcessForThread(pid_t tid, pid_t* pid) {
217   return ReadThreadNameAndPid(tid, nullptr, pid);
218 }
219 
GetThreadName(pid_t tid,std::string * name)220 bool GetThreadName(pid_t tid, std::string* name) {
221   return ReadThreadNameAndPid(tid, name, nullptr);
222 }
223 
GetAllProcesses()224 std::vector<pid_t> GetAllProcesses() {
225   std::vector<pid_t> result;
226   std::vector<std::string> entries = GetEntriesInDir("/proc");
227   for (const auto& entry : entries) {
228     pid_t pid;
229     if (!android::base::ParseInt(entry.c_str(), &pid, 0)) {
230       continue;
231     }
232     result.push_back(pid);
233   }
234   return result;
235 }
236 
GetThreadMmapsInProcess(pid_t pid,std::vector<ThreadMmap> * thread_mmaps)237 bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
238   thread_mmaps->clear();
239   return android::procinfo::ReadProcessMaps(
240       pid, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
241                ino_t, const char* name) {
242         thread_mmaps->emplace_back(start, end - start, pgoff, name, flags);
243       });
244 }
245 
GetKernelBuildId(BuildId * build_id)246 bool GetKernelBuildId(BuildId* build_id) {
247   ElfStatus result = GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
248   if (result != ElfStatus::NO_ERROR) {
249     LOG(DEBUG) << "failed to read /sys/kernel/notes: " << result;
250   }
251   return result == ElfStatus::NO_ERROR;
252 }
253 
GetModuleBuildId(const std::string & module_name,BuildId * build_id,const std::string & sysfs_dir)254 bool GetModuleBuildId(const std::string& module_name, BuildId* build_id,
255                       const std::string& sysfs_dir) {
256   std::string notefile = sysfs_dir + "/module/" + module_name + "/notes/.note.gnu.build-id";
257   return GetBuildIdFromNoteFile(notefile, build_id) == ElfStatus::NO_ERROR;
258 }
259 
GetValidThreadsFromThreadString(const std::string & tid_str,std::set<pid_t> * tid_set)260 bool GetValidThreadsFromThreadString(const std::string& tid_str, std::set<pid_t>* tid_set) {
261   std::vector<std::string> strs = android::base::Split(tid_str, ",");
262   for (const auto& s : strs) {
263     int tid;
264     if (!android::base::ParseInt(s.c_str(), &tid, 0)) {
265       LOG(ERROR) << "Invalid tid '" << s << "'";
266       return false;
267     }
268     if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
269       LOG(ERROR) << "Non existing thread '" << tid << "'";
270       return false;
271     }
272     tid_set->insert(tid);
273   }
274   return true;
275 }
276 
277 /*
278  * perf event allow level:
279  *  -1 - everything allowed
280  *   0 - disallow raw tracepoint access for unpriv
281  *   1 - disallow cpu events for unpriv
282  *   2 - disallow kernel profiling for unpriv
283  *   3 - disallow user profiling for unpriv
284  */
285 static const char* perf_event_allow_path = "/proc/sys/kernel/perf_event_paranoid";
286 
ReadPerfEventAllowStatus(int * value)287 static bool ReadPerfEventAllowStatus(int* value) {
288   std::string s;
289   if (!android::base::ReadFileToString(perf_event_allow_path, &s)) {
290     PLOG(DEBUG) << "failed to read " << perf_event_allow_path;
291     return false;
292   }
293   s = android::base::Trim(s);
294   if (!android::base::ParseInt(s.c_str(), value)) {
295     PLOG(ERROR) << "failed to parse " << perf_event_allow_path << ": " << s;
296     return false;
297   }
298   return true;
299 }
300 
CanRecordRawData()301 bool CanRecordRawData() {
302   if (IsRoot()) {
303     return true;
304   }
305 #if defined(__ANDROID__)
306   // Android R uses selinux to control perf_event_open. Whether raw data can be recorded is hard
307   // to check unless we really try it. And probably there is no need to record raw data in non-root
308   // users.
309   return false;
310 #else
311   int value;
312   return ReadPerfEventAllowStatus(&value) && value == -1;
313 #endif
314 }
315 
GetLimitLevelDescription(int limit_level)316 static const char* GetLimitLevelDescription(int limit_level) {
317   switch (limit_level) {
318     case -1: return "unlimited";
319     case 0: return "disallowing raw tracepoint access for unpriv";
320     case 1: return "disallowing cpu events for unpriv";
321     case 2: return "disallowing kernel profiling for unpriv";
322     case 3: return "disallowing user profiling for unpriv";
323     default: return "unknown level";
324   }
325 }
326 
CheckPerfEventLimit()327 bool CheckPerfEventLimit() {
328   // Root is not limited by perf_event_allow_path. However, the monitored threads
329   // may create child processes not running as root. To make sure the child processes have
330   // enough permission to create inherited tracepoint events, write -1 to perf_event_allow_path.
331   // See http://b/62230699.
332   if (IsRoot()) {
333     return android::base::WriteStringToFile("-1", perf_event_allow_path);
334   }
335   int limit_level;
336   bool can_read_allow_file = ReadPerfEventAllowStatus(&limit_level);
337   if (can_read_allow_file && limit_level <= 1) {
338     return true;
339   }
340 #if defined(__ANDROID__)
341   const std::string prop_name = "security.perf_harden";
342   std::string prop_value = android::base::GetProperty(prop_name, "");
343   if (prop_value.empty()) {
344     // can't do anything if there is no such property.
345     return true;
346   }
347   if (prop_value == "0") {
348     return true;
349   }
350   // Try to enable perf events by setprop security.perf_harden=0.
351   if (android::base::SetProperty(prop_name, "0")) {
352     sleep(1);
353     if (can_read_allow_file && ReadPerfEventAllowStatus(&limit_level) && limit_level <= 1) {
354       return true;
355     }
356     if (android::base::GetProperty(prop_name, "") == "0") {
357       return true;
358     }
359   }
360   if (can_read_allow_file) {
361     LOG(WARNING) << perf_event_allow_path << " is " << limit_level << ", "
362                  << GetLimitLevelDescription(limit_level) << ".";
363   }
364   LOG(WARNING) << "Try using `adb shell setprop security.perf_harden 0` to allow profiling.";
365   return false;
366 #else
367   if (can_read_allow_file) {
368     LOG(WARNING) << perf_event_allow_path << " is " << limit_level
369         << ", " << GetLimitLevelDescription(limit_level) << ".";
370     return false;
371   }
372 #endif
373   return true;
374 }
375 
376 #if defined(__ANDROID__)
SetProperty(const char * prop_name,uint64_t value)377 static bool SetProperty(const char* prop_name, uint64_t value) {
378   if (!android::base::SetProperty(prop_name, std::to_string(value))) {
379     LOG(ERROR) << "Failed to SetProperty " << prop_name << " to " << value;
380     return false;
381   }
382   return true;
383 }
384 
SetPerfEventLimits(uint64_t sample_freq,size_t cpu_percent,uint64_t mlock_kb)385 bool SetPerfEventLimits(uint64_t sample_freq, size_t cpu_percent, uint64_t mlock_kb) {
386   if (!SetProperty("debug.perf_event_max_sample_rate", sample_freq) ||
387       !SetProperty("debug.perf_cpu_time_max_percent", cpu_percent) ||
388       !SetProperty("debug.perf_event_mlock_kb", mlock_kb) ||
389       !SetProperty("security.perf_harden", 0)) {
390     return false;
391   }
392   // Wait for init process to change perf event limits based on properties.
393   const size_t max_wait_us = 3 * 1000000;
394   int finish_mask = 0;
395   for (size_t i = 0; i < max_wait_us && finish_mask != 7; ++i) {
396     usleep(1);  // Wait 1us to avoid busy loop.
397     if ((finish_mask & 1) == 0) {
398       uint64_t freq;
399       if (!GetMaxSampleFrequency(&freq) || freq == sample_freq) {
400         finish_mask |= 1;
401       }
402     }
403     if ((finish_mask & 2) == 0) {
404       size_t percent;
405       if (!GetCpuTimeMaxPercent(&percent) || percent == cpu_percent) {
406         finish_mask |= 2;
407       }
408     }
409     if ((finish_mask & 4) == 0) {
410       uint64_t kb;
411       if (!GetPerfEventMlockKb(&kb) || kb == mlock_kb) {
412         finish_mask |= 4;
413       }
414     }
415   }
416   if (finish_mask != 7) {
417     LOG(WARNING) << "Wait setting perf event limits timeout";
418   }
419   return true;
420 }
421 #else  // !defined(__ANDROID__)
SetPerfEventLimits(uint64_t,size_t,uint64_t)422 bool SetPerfEventLimits(uint64_t, size_t, uint64_t) {
423   return true;
424 }
425 #endif
426 
427 template <typename T>
ReadUintFromProcFile(const std::string & path,T * value)428 static bool ReadUintFromProcFile(const std::string& path, T* value) {
429   std::string s;
430   if (!android::base::ReadFileToString(path, &s)) {
431     PLOG(DEBUG) << "failed to read " << path;
432     return false;
433   }
434   s = android::base::Trim(s);
435   if (!android::base::ParseUint(s.c_str(), value)) {
436     LOG(ERROR) << "failed to parse " << path << ": " << s;
437     return false;
438   }
439   return true;
440 }
441 
442 template <typename T>
WriteUintToProcFile(const std::string & path,T value)443 static bool WriteUintToProcFile(const std::string& path, T value) {
444   if (IsRoot()) {
445     return android::base::WriteStringToFile(std::to_string(value), path);
446   }
447   return false;
448 }
449 
GetMaxSampleFrequency(uint64_t * max_sample_freq)450 bool GetMaxSampleFrequency(uint64_t* max_sample_freq) {
451   return ReadUintFromProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
452 }
453 
SetMaxSampleFrequency(uint64_t max_sample_freq)454 bool SetMaxSampleFrequency(uint64_t max_sample_freq) {
455   return WriteUintToProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
456 }
457 
GetCpuTimeMaxPercent(size_t * percent)458 bool GetCpuTimeMaxPercent(size_t* percent) {
459   return ReadUintFromProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
460 }
461 
SetCpuTimeMaxPercent(size_t percent)462 bool SetCpuTimeMaxPercent(size_t percent) {
463   return WriteUintToProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
464 }
465 
GetPerfEventMlockKb(uint64_t * mlock_kb)466 bool GetPerfEventMlockKb(uint64_t* mlock_kb) {
467   return ReadUintFromProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
468 }
469 
SetPerfEventMlockKb(uint64_t mlock_kb)470 bool SetPerfEventMlockKb(uint64_t mlock_kb) {
471   return WriteUintToProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
472 }
473 
CheckKernelSymbolAddresses()474 bool CheckKernelSymbolAddresses() {
475   const std::string kptr_restrict_file = "/proc/sys/kernel/kptr_restrict";
476   std::string s;
477   if (!android::base::ReadFileToString(kptr_restrict_file, &s)) {
478     PLOG(DEBUG) << "failed to read " << kptr_restrict_file;
479     return false;
480   }
481   s = android::base::Trim(s);
482   int value;
483   if (!android::base::ParseInt(s.c_str(), &value)) {
484     LOG(ERROR) << "failed to parse " << kptr_restrict_file << ": " << s;
485     return false;
486   }
487   // Accessible to everyone?
488   if (value == 0) {
489     return true;
490   }
491   // Accessible to root?
492   if (value == 1 && IsRoot()) {
493     return true;
494   }
495   // Can we make it accessible to us?
496   if (IsRoot() && android::base::WriteStringToFile("1", kptr_restrict_file)) {
497     return true;
498   }
499   LOG(WARNING) << "Access to kernel symbol addresses is restricted. If "
500       << "possible, please do `echo 0 >/proc/sys/kernel/kptr_restrict` "
501       << "to fix this.";
502   return false;
503 }
504 
GetMachineArch()505 ArchType GetMachineArch() {
506   utsname uname_buf;
507   if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
508     PLOG(WARNING) << "uname() failed";
509     return GetBuildArch();
510   }
511   ArchType arch = GetArchType(uname_buf.machine);
512   if (arch != ARCH_UNSUPPORTED) {
513     return arch;
514   }
515   return GetBuildArch();
516 }
517 
PrepareVdsoFile()518 void PrepareVdsoFile() {
519   // vdso is an elf file in memory loaded in each process's user space by the kernel. To read
520   // symbols from it and unwind through it, we need to dump it into a file in storage.
521   // It doesn't affect much when failed to prepare vdso file, so there is no need to return values.
522   std::vector<ThreadMmap> thread_mmaps;
523   if (!GetThreadMmapsInProcess(getpid(), &thread_mmaps)) {
524     return;
525   }
526   const ThreadMmap* vdso_map = nullptr;
527   for (const auto& map : thread_mmaps) {
528     if (map.name == "[vdso]") {
529       vdso_map = &map;
530       break;
531     }
532   }
533   if (vdso_map == nullptr) {
534     return;
535   }
536   std::string s(vdso_map->len, '\0');
537   memcpy(&s[0], reinterpret_cast<void*>(static_cast<uintptr_t>(vdso_map->start_addr)),
538          vdso_map->len);
539   std::unique_ptr<TemporaryFile> tmpfile = ScopedTempFiles::CreateTempFile();
540   if (!android::base::WriteStringToFd(s, tmpfile->fd)) {
541     return;
542   }
543   Dso::SetVdsoFile(tmpfile->path, sizeof(size_t) == sizeof(uint64_t));
544 }
545 
HasOpenedAppApkFile(int pid)546 static bool HasOpenedAppApkFile(int pid) {
547   std::string fd_path = "/proc/" + std::to_string(pid) + "/fd/";
548   std::vector<std::string> files = GetEntriesInDir(fd_path);
549   for (const auto& file : files) {
550     std::string real_path;
551     if (!android::base::Readlink(fd_path + file, &real_path)) {
552       continue;
553     }
554     if (real_path.find("app") != std::string::npos && real_path.find(".apk") != std::string::npos) {
555       return true;
556     }
557   }
558   return false;
559 }
560 
WaitForAppProcesses(const std::string & package_name)561 std::set<pid_t> WaitForAppProcesses(const std::string& package_name) {
562   std::set<pid_t> result;
563   size_t loop_count = 0;
564   while (true) {
565     std::vector<pid_t> pids = GetAllProcesses();
566     for (pid_t pid : pids) {
567       std::string cmdline;
568       if (!android::base::ReadFileToString("/proc/" + std::to_string(pid) + "/cmdline", &cmdline)) {
569         // Maybe we don't have permission to read it.
570         continue;
571       }
572       std::string process_name = android::base::Basename(cmdline);
573       // The app may have multiple processes, with process name like
574       // com.google.android.googlequicksearchbox:search.
575       size_t split_pos = process_name.find(':');
576       if (split_pos != std::string::npos) {
577         process_name = process_name.substr(0, split_pos);
578       }
579       if (process_name != package_name) {
580         continue;
581       }
582       // If a debuggable app with wrap.sh runs on Android O, the app will be started with
583       // logwrapper as below:
584       // 1. Zygote forks a child process, rename it to package_name.
585       // 2. The child process execute sh, which starts a child process running
586       //    /system/bin/logwrapper.
587       // 3. logwrapper starts a child process running sh, which interprets wrap.sh.
588       // 4. wrap.sh starts a child process running the app.
589       // The problem here is we want to profile the process started in step 4, but sometimes we
590       // run into the process started in step 1. To solve it, we can check if the process has
591       // opened an apk file in some app dirs.
592       if (!HasOpenedAppApkFile(pid)) {
593         continue;
594       }
595       if (loop_count > 0u) {
596         LOG(INFO) << "Got process " << pid << " for package " << package_name;
597       }
598       result.insert(pid);
599     }
600     if (!result.empty()) {
601       return result;
602     }
603     if (++loop_count == 1u) {
604       LOG(INFO) << "Waiting for process of app " << package_name;
605     }
606     usleep(1000);
607   }
608 }
609 
IsAppDebuggable(const std::string & package_name)610 bool IsAppDebuggable(const std::string& package_name) {
611   return Workload::RunCmd({"run-as", package_name, "echo", ">/dev/null", "2>/dev/null"}, false);
612 }
613 
614 namespace {
615 
616 class InAppRunner {
617  public:
InAppRunner(const std::string & package_name)618   InAppRunner(const std::string& package_name) : package_name_(package_name) {}
~InAppRunner()619   virtual ~InAppRunner() {
620     if (!tracepoint_file_.empty()) {
621       unlink(tracepoint_file_.c_str());
622     }
623   }
624   virtual bool Prepare() = 0;
625   bool RunCmdInApp(const std::string& cmd, const std::vector<std::string>& args,
626                    size_t workload_args_size, const std::string& output_filepath,
627                    bool need_tracepoint_events);
628  protected:
629   virtual std::vector<std::string> GetPrefixArgs(const std::string& cmd) = 0;
630 
631   const std::string package_name_;
632   std::string tracepoint_file_;
633 };
634 
RunCmdInApp(const std::string & cmd,const std::vector<std::string> & cmd_args,size_t workload_args_size,const std::string & output_filepath,bool need_tracepoint_events)635 bool InAppRunner::RunCmdInApp(const std::string& cmd, const std::vector<std::string>& cmd_args,
636                               size_t workload_args_size, const std::string& output_filepath,
637                               bool need_tracepoint_events) {
638   // 1. Build cmd args running in app's context.
639   std::vector<std::string> args = GetPrefixArgs(cmd);
640   args.insert(args.end(), {"--in-app", "--log", GetLogSeverityName()});
641   if (log_to_android_buffer) {
642     args.emplace_back("--log-to-android-buffer");
643   }
644   if (need_tracepoint_events) {
645     // Since we can't read tracepoint events from tracefs in app's context, we need to prepare
646     // them in tracepoint_file in shell's context, and pass the path of tracepoint_file to the
647     // child process using --tracepoint-events option.
648     const std::string tracepoint_file = "/data/local/tmp/tracepoint_events";
649     if (!android::base::WriteStringToFile(GetTracepointEvents(), tracepoint_file)) {
650       PLOG(ERROR) << "Failed to store tracepoint events";
651       return false;
652     }
653     tracepoint_file_ = tracepoint_file;
654     args.insert(args.end(), {"--tracepoint-events", tracepoint_file_});
655   }
656 
657   android::base::unique_fd out_fd;
658   if (!output_filepath.empty()) {
659     // A process running in app's context can't open a file outside it's data directory to write.
660     // So pass it a file descriptor to write.
661     out_fd = FileHelper::OpenWriteOnly(output_filepath);
662     if (out_fd == -1) {
663       PLOG(ERROR) << "Failed to open " << output_filepath;
664       return false;
665     }
666     args.insert(args.end(), {"--out-fd", std::to_string(int(out_fd))});
667   }
668 
669   // We can't send signal to a process running in app's context. So use a pipe file to send stop
670   // signal.
671   android::base::unique_fd stop_signal_rfd;
672   android::base::unique_fd stop_signal_wfd;
673   if (!android::base::Pipe(&stop_signal_rfd, &stop_signal_wfd, 0)) {
674     PLOG(ERROR) << "pipe";
675     return false;
676   }
677   args.insert(args.end(), {"--stop-signal-fd", std::to_string(int(stop_signal_rfd))});
678 
679   for (size_t i = 0; i < cmd_args.size(); ++i) {
680     if (i < cmd_args.size() - workload_args_size) {
681       // Omit "-o output_file". It is replaced by "--out-fd fd".
682       if (cmd_args[i] == "-o" || cmd_args[i] == "--app") {
683         i++;
684         continue;
685       }
686     }
687     args.push_back(cmd_args[i]);
688   }
689   char* argv[args.size() + 1];
690   for (size_t i = 0; i < args.size(); ++i) {
691     argv[i] = &args[i][0];
692   }
693   argv[args.size()] = nullptr;
694 
695   // 2. Run child process in app's context.
696   auto ChildProcFn = [&]() {
697     stop_signal_wfd.reset();
698     execvp(argv[0], argv);
699     exit(1);
700   };
701   std::unique_ptr<Workload> workload = Workload::CreateWorkload(ChildProcFn);
702   if (!workload) {
703     return false;
704   }
705   stop_signal_rfd.reset();
706 
707   // Wait on signals.
708   IOEventLoop loop;
709   bool need_to_stop_child = false;
710   std::vector<int> stop_signals = {SIGINT, SIGTERM};
711   if (!SignalIsIgnored(SIGHUP)) {
712     stop_signals.push_back(SIGHUP);
713   }
714   if (!loop.AddSignalEvents(stop_signals,
715                             [&]() { need_to_stop_child = true; return loop.ExitLoop(); })) {
716     return false;
717   }
718   if (!loop.AddSignalEvent(SIGCHLD, [&]() { return loop.ExitLoop(); })) {
719     return false;
720   }
721 
722   if (!workload->Start()) {
723     return false;
724   }
725   if (!loop.RunLoop()) {
726     return false;
727   }
728   if (need_to_stop_child) {
729     stop_signal_wfd.reset();
730   }
731   int exit_code;
732   if (!workload->WaitChildProcess(&exit_code) || exit_code != 0) {
733     return false;
734   }
735   return true;
736 }
737 
738 class RunAs : public InAppRunner {
739  public:
RunAs(const std::string & package_name)740   RunAs(const std::string& package_name) : InAppRunner(package_name) {}
~RunAs()741   virtual ~RunAs() {
742     if (simpleperf_copied_in_app_) {
743       Workload::RunCmd({"run-as", package_name_, "rm", "-rf", "simpleperf"});
744     }
745   }
746   bool Prepare() override;
747 
748  protected:
GetPrefixArgs(const std::string & cmd)749   std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
750     return {"run-as", package_name_,
751             simpleperf_copied_in_app_ ? "./simpleperf" : simpleperf_path_, cmd,
752             "--app", package_name_};
753   }
754 
755   bool simpleperf_copied_in_app_ = false;
756   std::string simpleperf_path_;
757 };
758 
Prepare()759 bool RunAs::Prepare() {
760   // Test if run-as can access the package.
761   if (!IsAppDebuggable(package_name_)) {
762     return false;
763   }
764   // run-as can't run /data/local/tmp/simpleperf directly. So copy simpleperf binary if needed.
765   if (!android::base::Readlink("/proc/self/exe", &simpleperf_path_)) {
766     PLOG(ERROR) << "ReadLink failed";
767     return false;
768   }
769   if (simpleperf_path_.find("CtsSimpleperfTest") != std::string::npos) {
770     simpleperf_path_ = "/system/bin/simpleperf";
771     return true;
772   }
773   if (android::base::StartsWith(simpleperf_path_, "/system")) {
774     return true;
775   }
776   if (!Workload::RunCmd({"run-as", package_name_, "cp", simpleperf_path_, "simpleperf"})) {
777     return false;
778   }
779   simpleperf_copied_in_app_ = true;
780   return true;
781 }
782 
783 class SimpleperfAppRunner : public InAppRunner {
784  public:
SimpleperfAppRunner(const std::string & package_name)785   SimpleperfAppRunner(const std::string& package_name) : InAppRunner(package_name) {}
Prepare()786   bool Prepare() override {
787     return GetAndroidVersion() >= kAndroidVersionP + 1;
788   }
789 
790  protected:
GetPrefixArgs(const std::string & cmd)791   std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
792     return {"simpleperf_app_runner", package_name_, cmd};
793   }
794 };
795 
796 }  // namespace
797 
798 static bool allow_run_as = true;
799 static bool allow_simpleperf_app_runner = true;
800 
SetRunInAppToolForTesting(bool run_as,bool simpleperf_app_runner)801 void SetRunInAppToolForTesting(bool run_as, bool simpleperf_app_runner) {
802   allow_run_as = run_as;
803   allow_simpleperf_app_runner = simpleperf_app_runner;
804 }
805 
RunInAppContext(const std::string & app_package_name,const std::string & cmd,const std::vector<std::string> & args,size_t workload_args_size,const std::string & output_filepath,bool need_tracepoint_events)806 bool RunInAppContext(const std::string& app_package_name, const std::string& cmd,
807                      const std::vector<std::string>& args, size_t workload_args_size,
808                      const std::string& output_filepath, bool need_tracepoint_events) {
809   std::unique_ptr<InAppRunner> in_app_runner;
810   if (allow_run_as) {
811     in_app_runner.reset(new RunAs(app_package_name));
812     if (!in_app_runner->Prepare()) {
813       in_app_runner = nullptr;
814     }
815   }
816   if (!in_app_runner && allow_simpleperf_app_runner) {
817     in_app_runner.reset(new SimpleperfAppRunner(app_package_name));
818     if (!in_app_runner->Prepare()) {
819       in_app_runner = nullptr;
820     }
821   }
822   if (!in_app_runner) {
823     LOG(ERROR) << "Package " << app_package_name
824                << " doesn't exist or isn't debuggable/profileable.";
825     return false;
826   }
827   return in_app_runner->RunCmdInApp(cmd, args, workload_args_size, output_filepath,
828                                     need_tracepoint_events);
829 }
830 
AllowMoreOpenedFiles()831 void AllowMoreOpenedFiles() {
832   // On Android <= O, the hard limit is 4096, and the soft limit is 1024.
833   // On Android >= P, both the hard and soft limit are 32768.
834   rlimit limit;
835   if (getrlimit(RLIMIT_NOFILE, &limit) == 0) {
836     limit.rlim_cur = limit.rlim_max;
837     setrlimit(RLIMIT_NOFILE, &limit);
838   }
839 }
840 
841 std::string ScopedTempFiles::tmp_dir_;
842 std::vector<std::string> ScopedTempFiles::files_to_delete_;
843 
ScopedTempFiles(const std::string & tmp_dir)844 ScopedTempFiles::ScopedTempFiles(const std::string& tmp_dir) {
845   CHECK(tmp_dir_.empty());  // No other ScopedTempFiles.
846   tmp_dir_ = tmp_dir;
847 }
848 
~ScopedTempFiles()849 ScopedTempFiles::~ScopedTempFiles() {
850   tmp_dir_.clear();
851   for (auto& file : files_to_delete_) {
852     unlink(file.c_str());
853   }
854   files_to_delete_.clear();
855 }
856 
CreateTempFile(bool delete_in_destructor)857 std::unique_ptr<TemporaryFile> ScopedTempFiles::CreateTempFile(bool delete_in_destructor) {
858   CHECK(!tmp_dir_.empty());
859   std::unique_ptr<TemporaryFile> tmp_file(new TemporaryFile(tmp_dir_));
860   CHECK_NE(tmp_file->fd, -1) << "failed to create tmpfile under " << tmp_dir_;
861   if (delete_in_destructor) {
862     tmp_file->DoNotRemove();
863     files_to_delete_.push_back(tmp_file->path);
864   }
865   return tmp_file;
866 }
867 
RegisterTempFile(const std::string & path)868 void ScopedTempFiles::RegisterTempFile(const std::string& path) {
869   files_to_delete_.emplace_back(path);
870 }
871 
SignalIsIgnored(int signo)872 bool SignalIsIgnored(int signo) {
873   struct sigaction act;
874   if (sigaction(signo, nullptr, &act) != 0) {
875     PLOG(FATAL) << "failed to query signal handler for signal " << signo;
876   }
877 
878   if ((act.sa_flags & SA_SIGINFO)) {
879     return false;
880   }
881 
882   return act.sa_handler == SIG_IGN;
883 }
884 
GetAndroidVersion()885 int GetAndroidVersion() {
886 #if defined(__ANDROID__)
887   static int android_version = -1;
888   if (android_version == -1) {
889     android_version = 0;
890     std::string s = android::base::GetProperty("ro.build.version.release", "");
891     // The release string can be a list of numbers (like 8.1.0), a character (like Q)
892     // or many characters (like OMR1).
893     if (!s.empty()) {
894       // Each Android version has a version number: L is 5, M is 6, N is 7, O is 8, etc.
895       if (s[0] >= 'A' && s[0] <= 'Z') {
896         android_version = s[0] - 'P' + kAndroidVersionP;
897       } else if (isdigit(s[0])) {
898         sscanf(s.c_str(), "%d", &android_version);
899       }
900     }
901   }
902   return android_version;
903 #else  // defined(__ANDROID__)
904   return 0;
905 #endif
906 }
907 
GetHardwareFromCpuInfo(const std::string & cpu_info)908 std::string GetHardwareFromCpuInfo(const std::string& cpu_info) {
909   for (auto& line : android::base::Split(cpu_info, "\n")) {
910     size_t pos = line.find(':');
911     if (pos != std::string::npos) {
912       std::string key = android::base::Trim(line.substr(0, pos));
913       if (key == "Hardware") {
914         return android::base::Trim(line.substr(pos + 1));
915       }
916     }
917   }
918   return "";
919 }
920 
MappedFileOnlyExistInMemory(const char * filename)921 bool MappedFileOnlyExistInMemory(const char* filename) {
922   // Mapped files only existing in memory:
923   //   empty name
924   //   [anon:???]
925   //   [stack]
926   //   /dev/*
927   //   //anon: generated by kernel/events/core.c.
928   //   /memfd: created by memfd_create.
929   return filename[0] == '\0' ||
930            (filename[0] == '[' && strcmp(filename, "[vdso]") != 0) ||
931             strncmp(filename, "//", 2) == 0 ||
932             strncmp(filename, "/dev/", 5) == 0 ||
933             strncmp(filename, "/memfd:", 7) == 0;
934 }
935 
GetCompleteProcessName(pid_t pid)936 std::string GetCompleteProcessName(pid_t pid) {
937   std::string s;
938   if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid), &s)) {
939     s.clear();
940   }
941   for (size_t i = 0; i < s.size(); ++i) {
942     // /proc/pid/cmdline uses 0 to separate arguments.
943     if (isspace(s[i]) || s[i] == 0) {
944       s.resize(i);
945       break;
946     }
947   }
948   return s;
949 }
950 
GetTraceFsDir()951 const char* GetTraceFsDir() {
952   static const char* tracefs_dirs[] = {
953     "/sys/kernel/debug/tracing", "/sys/kernel/tracing"
954   };
955   for (const char* path : tracefs_dirs) {
956     if (IsDir(path)) {
957       return path;
958     }
959   }
960   return nullptr;
961 }
962 
GetKernelVersion(int * major,int * minor)963 bool GetKernelVersion(int* major, int* minor) {
964   utsname uname_buf;
965   if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
966     return false;
967   }
968   return sscanf(uname_buf.release, "%d.%d", major, minor) == 2;
969 }
970