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