xref: /aosp_15_r20/system/extras/simpleperf/environment.cpp (revision 288bf5226967eb3dac5cce6c939ccc2a7f2b4fe5)
1*288bf522SAndroid Build Coastguard Worker /*
2*288bf522SAndroid Build Coastguard Worker  * Copyright (C) 2015 The Android Open Source Project
3*288bf522SAndroid Build Coastguard Worker  *
4*288bf522SAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*288bf522SAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*288bf522SAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*288bf522SAndroid Build Coastguard Worker  *
8*288bf522SAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*288bf522SAndroid Build Coastguard Worker  *
10*288bf522SAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*288bf522SAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*288bf522SAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*288bf522SAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*288bf522SAndroid Build Coastguard Worker  * limitations under the License.
15*288bf522SAndroid Build Coastguard Worker  */
16*288bf522SAndroid Build Coastguard Worker 
17*288bf522SAndroid Build Coastguard Worker #include "environment.h"
18*288bf522SAndroid Build Coastguard Worker 
19*288bf522SAndroid Build Coastguard Worker #include <inttypes.h>
20*288bf522SAndroid Build Coastguard Worker #include <signal.h>
21*288bf522SAndroid Build Coastguard Worker #include <stdio.h>
22*288bf522SAndroid Build Coastguard Worker #include <stdlib.h>
23*288bf522SAndroid Build Coastguard Worker #include <string.h>
24*288bf522SAndroid Build Coastguard Worker #include <sys/resource.h>
25*288bf522SAndroid Build Coastguard Worker #include <sys/sysinfo.h>
26*288bf522SAndroid Build Coastguard Worker #include <sys/utsname.h>
27*288bf522SAndroid Build Coastguard Worker #include <unistd.h>
28*288bf522SAndroid Build Coastguard Worker 
29*288bf522SAndroid Build Coastguard Worker #include <limits>
30*288bf522SAndroid Build Coastguard Worker #include <optional>
31*288bf522SAndroid Build Coastguard Worker #include <set>
32*288bf522SAndroid Build Coastguard Worker #include <unordered_map>
33*288bf522SAndroid Build Coastguard Worker #include <vector>
34*288bf522SAndroid Build Coastguard Worker 
35*288bf522SAndroid Build Coastguard Worker #include <android-base/file.h>
36*288bf522SAndroid Build Coastguard Worker #include <android-base/logging.h>
37*288bf522SAndroid Build Coastguard Worker #include <android-base/parseint.h>
38*288bf522SAndroid Build Coastguard Worker #include <android-base/stringprintf.h>
39*288bf522SAndroid Build Coastguard Worker #include <android-base/strings.h>
40*288bf522SAndroid Build Coastguard Worker #include <procinfo/process.h>
41*288bf522SAndroid Build Coastguard Worker #include <procinfo/process_map.h>
42*288bf522SAndroid Build Coastguard Worker 
43*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
44*288bf522SAndroid Build Coastguard Worker #include <android-base/properties.h>
45*288bf522SAndroid Build Coastguard Worker #include <cutils/android_filesystem_config.h>
46*288bf522SAndroid Build Coastguard Worker #endif
47*288bf522SAndroid Build Coastguard Worker 
48*288bf522SAndroid Build Coastguard Worker #include "IOEventLoop.h"
49*288bf522SAndroid Build Coastguard Worker #include "command.h"
50*288bf522SAndroid Build Coastguard Worker #include "event_type.h"
51*288bf522SAndroid Build Coastguard Worker #include "kallsyms.h"
52*288bf522SAndroid Build Coastguard Worker #include "read_elf.h"
53*288bf522SAndroid Build Coastguard Worker #include "thread_tree.h"
54*288bf522SAndroid Build Coastguard Worker #include "utils.h"
55*288bf522SAndroid Build Coastguard Worker #include "workload.h"
56*288bf522SAndroid Build Coastguard Worker 
57*288bf522SAndroid Build Coastguard Worker namespace simpleperf {
58*288bf522SAndroid Build Coastguard Worker 
GetOnlineCpus()59*288bf522SAndroid Build Coastguard Worker std::vector<int> GetOnlineCpus() {
60*288bf522SAndroid Build Coastguard Worker   std::vector<int> result;
61*288bf522SAndroid Build Coastguard Worker   LineReader reader("/sys/devices/system/cpu/online");
62*288bf522SAndroid Build Coastguard Worker   if (!reader.Ok()) {
63*288bf522SAndroid Build Coastguard Worker     PLOG(ERROR) << "can't open online cpu information";
64*288bf522SAndroid Build Coastguard Worker     return result;
65*288bf522SAndroid Build Coastguard Worker   }
66*288bf522SAndroid Build Coastguard Worker 
67*288bf522SAndroid Build Coastguard Worker   std::string* line;
68*288bf522SAndroid Build Coastguard Worker   if ((line = reader.ReadLine()) != nullptr) {
69*288bf522SAndroid Build Coastguard Worker     if (auto cpus = GetCpusFromString(*line); cpus) {
70*288bf522SAndroid Build Coastguard Worker       result.assign(cpus->begin(), cpus->end());
71*288bf522SAndroid Build Coastguard Worker     }
72*288bf522SAndroid Build Coastguard Worker   }
73*288bf522SAndroid Build Coastguard Worker   CHECK(!result.empty()) << "can't get online cpu information";
74*288bf522SAndroid Build Coastguard Worker   return result;
75*288bf522SAndroid Build Coastguard Worker }
76*288bf522SAndroid Build Coastguard Worker 
GetAllModuleFiles(const std::string & path,std::unordered_map<std::string,std::string> * module_file_map)77*288bf522SAndroid Build Coastguard Worker static void GetAllModuleFiles(const std::string& path,
78*288bf522SAndroid Build Coastguard Worker                               std::unordered_map<std::string, std::string>* module_file_map) {
79*288bf522SAndroid Build Coastguard Worker   if (!IsDir(path)) {
80*288bf522SAndroid Build Coastguard Worker     return;
81*288bf522SAndroid Build Coastguard Worker   }
82*288bf522SAndroid Build Coastguard Worker   for (const auto& name : GetEntriesInDir(path)) {
83*288bf522SAndroid Build Coastguard Worker     std::string entry_path = path + "/" + name;
84*288bf522SAndroid Build Coastguard Worker     if (IsRegularFile(entry_path) && android::base::EndsWith(name, ".ko")) {
85*288bf522SAndroid Build Coastguard Worker       std::string module_name = name.substr(0, name.size() - 3);
86*288bf522SAndroid Build Coastguard Worker       std::replace(module_name.begin(), module_name.end(), '-', '_');
87*288bf522SAndroid Build Coastguard Worker       module_file_map->insert(std::make_pair(module_name, entry_path));
88*288bf522SAndroid Build Coastguard Worker     } else if (IsDir(entry_path)) {
89*288bf522SAndroid Build Coastguard Worker       GetAllModuleFiles(entry_path, module_file_map);
90*288bf522SAndroid Build Coastguard Worker     }
91*288bf522SAndroid Build Coastguard Worker   }
92*288bf522SAndroid Build Coastguard Worker }
93*288bf522SAndroid Build Coastguard Worker 
GetModulesInUse()94*288bf522SAndroid Build Coastguard Worker static std::vector<KernelMmap> GetModulesInUse() {
95*288bf522SAndroid Build Coastguard Worker   std::vector<KernelMmap> module_mmaps = GetLoadedModules();
96*288bf522SAndroid Build Coastguard Worker   if (module_mmaps.empty()) {
97*288bf522SAndroid Build Coastguard Worker     return std::vector<KernelMmap>();
98*288bf522SAndroid Build Coastguard Worker   }
99*288bf522SAndroid Build Coastguard Worker   std::unordered_map<std::string, std::string> module_file_map;
100*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
101*288bf522SAndroid Build Coastguard Worker   // On Android, kernel modules are stored in /system/lib/modules, /vendor/lib/modules,
102*288bf522SAndroid Build Coastguard Worker   // /odm/lib/modules.
103*288bf522SAndroid Build Coastguard Worker   // See https://source.android.com/docs/core/architecture/partitions/gki-partitions and
104*288bf522SAndroid Build Coastguard Worker   // https://source.android.com/docs/core/architecture/partitions/vendor-odm-dlkm-partition.
105*288bf522SAndroid Build Coastguard Worker   // They can also be stored in vendor_kernel_ramdisk.img, which isn't accessible from userspace.
106*288bf522SAndroid Build Coastguard Worker   // See https://source.android.com/docs/core/architecture/kernel/kernel-module-support.
107*288bf522SAndroid Build Coastguard Worker   for (const auto& path : {"/system/lib/modules", "/vendor/lib/modules", "/odm/lib/modules"}) {
108*288bf522SAndroid Build Coastguard Worker     GetAllModuleFiles(path, &module_file_map);
109*288bf522SAndroid Build Coastguard Worker   }
110*288bf522SAndroid Build Coastguard Worker #else
111*288bf522SAndroid Build Coastguard Worker   utsname uname_buf;
112*288bf522SAndroid Build Coastguard Worker   if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
113*288bf522SAndroid Build Coastguard Worker     PLOG(ERROR) << "uname() failed";
114*288bf522SAndroid Build Coastguard Worker     return std::vector<KernelMmap>();
115*288bf522SAndroid Build Coastguard Worker   }
116*288bf522SAndroid Build Coastguard Worker   std::string linux_version = uname_buf.release;
117*288bf522SAndroid Build Coastguard Worker   std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
118*288bf522SAndroid Build Coastguard Worker   GetAllModuleFiles(module_dirpath, &module_file_map);
119*288bf522SAndroid Build Coastguard Worker #endif
120*288bf522SAndroid Build Coastguard Worker   for (auto& module : module_mmaps) {
121*288bf522SAndroid Build Coastguard Worker     auto it = module_file_map.find(module.name);
122*288bf522SAndroid Build Coastguard Worker     if (it != module_file_map.end()) {
123*288bf522SAndroid Build Coastguard Worker       module.filepath = it->second;
124*288bf522SAndroid Build Coastguard Worker     }
125*288bf522SAndroid Build Coastguard Worker   }
126*288bf522SAndroid Build Coastguard Worker   return module_mmaps;
127*288bf522SAndroid Build Coastguard Worker }
128*288bf522SAndroid Build Coastguard Worker 
GetKernelAndModuleMmaps(KernelMmap * kernel_mmap,std::vector<KernelMmap> * module_mmaps)129*288bf522SAndroid Build Coastguard Worker void GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<KernelMmap>* module_mmaps) {
130*288bf522SAndroid Build Coastguard Worker   kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
131*288bf522SAndroid Build Coastguard Worker   kernel_mmap->start_addr = 0;
132*288bf522SAndroid Build Coastguard Worker   kernel_mmap->len = std::numeric_limits<uint64_t>::max();
133*288bf522SAndroid Build Coastguard Worker   if (uint64_t kstart_addr = GetKernelStartAddress(); kstart_addr != 0) {
134*288bf522SAndroid Build Coastguard Worker     kernel_mmap->name = std::string(DEFAULT_KERNEL_MMAP_NAME) + "_stext";
135*288bf522SAndroid Build Coastguard Worker     kernel_mmap->start_addr = kstart_addr;
136*288bf522SAndroid Build Coastguard Worker     kernel_mmap->len = std::numeric_limits<uint64_t>::max() - kstart_addr;
137*288bf522SAndroid Build Coastguard Worker   }
138*288bf522SAndroid Build Coastguard Worker   kernel_mmap->filepath = kernel_mmap->name;
139*288bf522SAndroid Build Coastguard Worker   *module_mmaps = GetModulesInUse();
140*288bf522SAndroid Build Coastguard Worker   for (auto& map : *module_mmaps) {
141*288bf522SAndroid Build Coastguard Worker     if (map.filepath.empty()) {
142*288bf522SAndroid Build Coastguard Worker       map.filepath = "[" + map.name + "]";
143*288bf522SAndroid Build Coastguard Worker     }
144*288bf522SAndroid Build Coastguard Worker   }
145*288bf522SAndroid Build Coastguard Worker }
146*288bf522SAndroid Build Coastguard Worker 
ReadThreadNameAndPid(pid_t tid,std::string * comm,pid_t * pid)147*288bf522SAndroid Build Coastguard Worker bool ReadThreadNameAndPid(pid_t tid, std::string* comm, pid_t* pid) {
148*288bf522SAndroid Build Coastguard Worker   android::procinfo::ProcessInfo procinfo;
149*288bf522SAndroid Build Coastguard Worker   if (!android::procinfo::GetProcessInfo(tid, &procinfo)) {
150*288bf522SAndroid Build Coastguard Worker     return false;
151*288bf522SAndroid Build Coastguard Worker   }
152*288bf522SAndroid Build Coastguard Worker   if (comm != nullptr) {
153*288bf522SAndroid Build Coastguard Worker     *comm = procinfo.name;
154*288bf522SAndroid Build Coastguard Worker   }
155*288bf522SAndroid Build Coastguard Worker   if (pid != nullptr) {
156*288bf522SAndroid Build Coastguard Worker     *pid = procinfo.pid;
157*288bf522SAndroid Build Coastguard Worker   }
158*288bf522SAndroid Build Coastguard Worker   return true;
159*288bf522SAndroid Build Coastguard Worker }
160*288bf522SAndroid Build Coastguard Worker 
GetThreadsInProcess(pid_t pid)161*288bf522SAndroid Build Coastguard Worker std::vector<pid_t> GetThreadsInProcess(pid_t pid) {
162*288bf522SAndroid Build Coastguard Worker   std::vector<pid_t> result;
163*288bf522SAndroid Build Coastguard Worker   android::procinfo::GetProcessTids(pid, &result);
164*288bf522SAndroid Build Coastguard Worker   return result;
165*288bf522SAndroid Build Coastguard Worker }
166*288bf522SAndroid Build Coastguard Worker 
IsThreadAlive(pid_t tid)167*288bf522SAndroid Build Coastguard Worker bool IsThreadAlive(pid_t tid) {
168*288bf522SAndroid Build Coastguard Worker   return IsDir(android::base::StringPrintf("/proc/%d", tid));
169*288bf522SAndroid Build Coastguard Worker }
170*288bf522SAndroid Build Coastguard Worker 
GetProcessForThread(pid_t tid,pid_t * pid)171*288bf522SAndroid Build Coastguard Worker bool GetProcessForThread(pid_t tid, pid_t* pid) {
172*288bf522SAndroid Build Coastguard Worker   return ReadThreadNameAndPid(tid, nullptr, pid);
173*288bf522SAndroid Build Coastguard Worker }
174*288bf522SAndroid Build Coastguard Worker 
GetThreadName(pid_t tid,std::string * name)175*288bf522SAndroid Build Coastguard Worker bool GetThreadName(pid_t tid, std::string* name) {
176*288bf522SAndroid Build Coastguard Worker   return ReadThreadNameAndPid(tid, name, nullptr);
177*288bf522SAndroid Build Coastguard Worker }
178*288bf522SAndroid Build Coastguard Worker 
GetAllProcesses()179*288bf522SAndroid Build Coastguard Worker std::vector<pid_t> GetAllProcesses() {
180*288bf522SAndroid Build Coastguard Worker   std::vector<pid_t> result;
181*288bf522SAndroid Build Coastguard Worker   std::vector<std::string> entries = GetEntriesInDir("/proc");
182*288bf522SAndroid Build Coastguard Worker   for (const auto& entry : entries) {
183*288bf522SAndroid Build Coastguard Worker     pid_t pid;
184*288bf522SAndroid Build Coastguard Worker     if (!android::base::ParseInt(entry.c_str(), &pid, 0)) {
185*288bf522SAndroid Build Coastguard Worker       continue;
186*288bf522SAndroid Build Coastguard Worker     }
187*288bf522SAndroid Build Coastguard Worker     result.push_back(pid);
188*288bf522SAndroid Build Coastguard Worker   }
189*288bf522SAndroid Build Coastguard Worker   return result;
190*288bf522SAndroid Build Coastguard Worker }
191*288bf522SAndroid Build Coastguard Worker 
GetThreadMmapsInProcess(pid_t pid,std::vector<ThreadMmap> * thread_mmaps)192*288bf522SAndroid Build Coastguard Worker bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
193*288bf522SAndroid Build Coastguard Worker   thread_mmaps->clear();
194*288bf522SAndroid Build Coastguard Worker   return android::procinfo::ReadProcessMaps(pid, [&](const android::procinfo::MapInfo& mapinfo) {
195*288bf522SAndroid Build Coastguard Worker     thread_mmaps->emplace_back(mapinfo.start, mapinfo.end - mapinfo.start, mapinfo.pgoff,
196*288bf522SAndroid Build Coastguard Worker                                mapinfo.name.c_str(), mapinfo.flags);
197*288bf522SAndroid Build Coastguard Worker   });
198*288bf522SAndroid Build Coastguard Worker }
199*288bf522SAndroid Build Coastguard Worker 
GetKernelBuildId(BuildId * build_id)200*288bf522SAndroid Build Coastguard Worker bool GetKernelBuildId(BuildId* build_id) {
201*288bf522SAndroid Build Coastguard Worker   ElfStatus result = GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
202*288bf522SAndroid Build Coastguard Worker   if (result != ElfStatus::NO_ERROR) {
203*288bf522SAndroid Build Coastguard Worker     LOG(DEBUG) << "failed to read /sys/kernel/notes: " << result;
204*288bf522SAndroid Build Coastguard Worker   }
205*288bf522SAndroid Build Coastguard Worker   return result == ElfStatus::NO_ERROR;
206*288bf522SAndroid Build Coastguard Worker }
207*288bf522SAndroid Build Coastguard Worker 
GetModuleBuildId(const std::string & module_name,BuildId * build_id,const std::string & sysfs_dir)208*288bf522SAndroid Build Coastguard Worker bool GetModuleBuildId(const std::string& module_name, BuildId* build_id,
209*288bf522SAndroid Build Coastguard Worker                       const std::string& sysfs_dir) {
210*288bf522SAndroid Build Coastguard Worker   std::string notefile = sysfs_dir + "/module/" + module_name + "/notes/.note.gnu.build-id";
211*288bf522SAndroid Build Coastguard Worker   return GetBuildIdFromNoteFile(notefile, build_id) == ElfStatus::NO_ERROR;
212*288bf522SAndroid Build Coastguard Worker }
213*288bf522SAndroid Build Coastguard Worker 
214*288bf522SAndroid Build Coastguard Worker /*
215*288bf522SAndroid Build Coastguard Worker  * perf event allow level:
216*288bf522SAndroid Build Coastguard Worker  *  -1 - everything allowed
217*288bf522SAndroid Build Coastguard Worker  *   0 - disallow raw tracepoint access for unpriv
218*288bf522SAndroid Build Coastguard Worker  *   1 - disallow cpu events for unpriv
219*288bf522SAndroid Build Coastguard Worker  *   2 - disallow kernel profiling for unpriv
220*288bf522SAndroid Build Coastguard Worker  *   3 - disallow user profiling for unpriv
221*288bf522SAndroid Build Coastguard Worker  */
222*288bf522SAndroid Build Coastguard Worker static const char* perf_event_allow_path = "/proc/sys/kernel/perf_event_paranoid";
223*288bf522SAndroid Build Coastguard Worker 
ReadPerfEventAllowStatus()224*288bf522SAndroid Build Coastguard Worker static std::optional<int> ReadPerfEventAllowStatus() {
225*288bf522SAndroid Build Coastguard Worker   std::string s;
226*288bf522SAndroid Build Coastguard Worker   if (!android::base::ReadFileToString(perf_event_allow_path, &s)) {
227*288bf522SAndroid Build Coastguard Worker     PLOG(DEBUG) << "failed to read " << perf_event_allow_path;
228*288bf522SAndroid Build Coastguard Worker     return std::nullopt;
229*288bf522SAndroid Build Coastguard Worker   }
230*288bf522SAndroid Build Coastguard Worker   s = android::base::Trim(s);
231*288bf522SAndroid Build Coastguard Worker   int value;
232*288bf522SAndroid Build Coastguard Worker   if (!android::base::ParseInt(s.c_str(), &value)) {
233*288bf522SAndroid Build Coastguard Worker     PLOG(ERROR) << "failed to parse " << perf_event_allow_path << ": " << s;
234*288bf522SAndroid Build Coastguard Worker     return std::nullopt;
235*288bf522SAndroid Build Coastguard Worker   }
236*288bf522SAndroid Build Coastguard Worker   return value;
237*288bf522SAndroid Build Coastguard Worker }
238*288bf522SAndroid Build Coastguard Worker 
CanRecordRawData()239*288bf522SAndroid Build Coastguard Worker bool CanRecordRawData() {
240*288bf522SAndroid Build Coastguard Worker   if (IsRoot()) {
241*288bf522SAndroid Build Coastguard Worker     return true;
242*288bf522SAndroid Build Coastguard Worker   }
243*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
244*288bf522SAndroid Build Coastguard Worker   // Android R uses selinux to control perf_event_open. Whether raw data can be recorded is hard
245*288bf522SAndroid Build Coastguard Worker   // to check unless we really try it. And probably there is no need to record raw data in non-root
246*288bf522SAndroid Build Coastguard Worker   // users.
247*288bf522SAndroid Build Coastguard Worker   return false;
248*288bf522SAndroid Build Coastguard Worker #else
249*288bf522SAndroid Build Coastguard Worker   return ReadPerfEventAllowStatus() == -1;
250*288bf522SAndroid Build Coastguard Worker #endif
251*288bf522SAndroid Build Coastguard Worker }
252*288bf522SAndroid Build Coastguard Worker 
GetMemorySize()253*288bf522SAndroid Build Coastguard Worker uint64_t GetMemorySize() {
254*288bf522SAndroid Build Coastguard Worker   struct sysinfo info;
255*288bf522SAndroid Build Coastguard Worker   sysinfo(&info);
256*288bf522SAndroid Build Coastguard Worker   return info.totalram;
257*288bf522SAndroid Build Coastguard Worker }
258*288bf522SAndroid Build Coastguard Worker 
GetLimitLevelDescription(int limit_level)259*288bf522SAndroid Build Coastguard Worker static const char* GetLimitLevelDescription(int limit_level) {
260*288bf522SAndroid Build Coastguard Worker   switch (limit_level) {
261*288bf522SAndroid Build Coastguard Worker     case -1:
262*288bf522SAndroid Build Coastguard Worker       return "unlimited";
263*288bf522SAndroid Build Coastguard Worker     case 0:
264*288bf522SAndroid Build Coastguard Worker       return "disallowing raw tracepoint access for unpriv";
265*288bf522SAndroid Build Coastguard Worker     case 1:
266*288bf522SAndroid Build Coastguard Worker       return "disallowing cpu events for unpriv";
267*288bf522SAndroid Build Coastguard Worker     case 2:
268*288bf522SAndroid Build Coastguard Worker       return "disallowing kernel profiling for unpriv";
269*288bf522SAndroid Build Coastguard Worker     case 3:
270*288bf522SAndroid Build Coastguard Worker       return "disallowing user profiling for unpriv";
271*288bf522SAndroid Build Coastguard Worker     default:
272*288bf522SAndroid Build Coastguard Worker       return "unknown level";
273*288bf522SAndroid Build Coastguard Worker   }
274*288bf522SAndroid Build Coastguard Worker }
275*288bf522SAndroid Build Coastguard Worker 
CheckPerfEventLimit()276*288bf522SAndroid Build Coastguard Worker bool CheckPerfEventLimit() {
277*288bf522SAndroid Build Coastguard Worker   std::optional<int> old_level = ReadPerfEventAllowStatus();
278*288bf522SAndroid Build Coastguard Worker 
279*288bf522SAndroid Build Coastguard Worker   // Root is not limited by perf_event_allow_path. However, the monitored threads
280*288bf522SAndroid Build Coastguard Worker   // may create child processes not running as root. To make sure the child processes have
281*288bf522SAndroid Build Coastguard Worker   // enough permission to create inherited tracepoint events, write -1 to perf_event_allow_path.
282*288bf522SAndroid Build Coastguard Worker   // See http://b/62230699.
283*288bf522SAndroid Build Coastguard Worker   if (IsRoot()) {
284*288bf522SAndroid Build Coastguard Worker     if (old_level == -1) {
285*288bf522SAndroid Build Coastguard Worker       return true;
286*288bf522SAndroid Build Coastguard Worker     }
287*288bf522SAndroid Build Coastguard Worker     if (android::base::WriteStringToFile("-1", perf_event_allow_path)) {
288*288bf522SAndroid Build Coastguard Worker       return true;
289*288bf522SAndroid Build Coastguard Worker     }
290*288bf522SAndroid Build Coastguard Worker     // On host, we may not be able to write to perf_event_allow_path (like when running in docker).
291*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
292*288bf522SAndroid Build Coastguard Worker     PLOG(ERROR) << "failed to write -1 to " << perf_event_allow_path;
293*288bf522SAndroid Build Coastguard Worker     return false;
294*288bf522SAndroid Build Coastguard Worker #endif
295*288bf522SAndroid Build Coastguard Worker   }
296*288bf522SAndroid Build Coastguard Worker   if (old_level.has_value() && old_level <= 1) {
297*288bf522SAndroid Build Coastguard Worker     return true;
298*288bf522SAndroid Build Coastguard Worker   }
299*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
300*288bf522SAndroid Build Coastguard Worker   const std::string prop_name = "security.perf_harden";
301*288bf522SAndroid Build Coastguard Worker   std::string prop_value = android::base::GetProperty(prop_name, "");
302*288bf522SAndroid Build Coastguard Worker   if (prop_value.empty()) {
303*288bf522SAndroid Build Coastguard Worker     // can't do anything if there is no such property.
304*288bf522SAndroid Build Coastguard Worker     return true;
305*288bf522SAndroid Build Coastguard Worker   }
306*288bf522SAndroid Build Coastguard Worker   if (prop_value == "0") {
307*288bf522SAndroid Build Coastguard Worker     return true;
308*288bf522SAndroid Build Coastguard Worker   }
309*288bf522SAndroid Build Coastguard Worker   // Try to enable perf events by setprop security.perf_harden=0.
310*288bf522SAndroid Build Coastguard Worker   if (android::base::SetProperty(prop_name, "0")) {
311*288bf522SAndroid Build Coastguard Worker     sleep(1);
312*288bf522SAndroid Build Coastguard Worker     // Check the result of setprop, by reading allow status or the property value.
313*288bf522SAndroid Build Coastguard Worker     if (auto level = ReadPerfEventAllowStatus(); level.has_value() && level <= 1) {
314*288bf522SAndroid Build Coastguard Worker       return true;
315*288bf522SAndroid Build Coastguard Worker     }
316*288bf522SAndroid Build Coastguard Worker     if (android::base::GetProperty(prop_name, "") == "0") {
317*288bf522SAndroid Build Coastguard Worker       return true;
318*288bf522SAndroid Build Coastguard Worker     }
319*288bf522SAndroid Build Coastguard Worker   }
320*288bf522SAndroid Build Coastguard Worker   if (old_level.has_value()) {
321*288bf522SAndroid Build Coastguard Worker     LOG(ERROR) << perf_event_allow_path << " is " << old_level.value() << ", "
322*288bf522SAndroid Build Coastguard Worker                << GetLimitLevelDescription(old_level.value()) << ".";
323*288bf522SAndroid Build Coastguard Worker   }
324*288bf522SAndroid Build Coastguard Worker   LOG(ERROR) << "Try using `adb shell setprop security.perf_harden 0` to allow profiling.";
325*288bf522SAndroid Build Coastguard Worker   return false;
326*288bf522SAndroid Build Coastguard Worker #else
327*288bf522SAndroid Build Coastguard Worker   if (old_level.has_value()) {
328*288bf522SAndroid Build Coastguard Worker     LOG(ERROR) << perf_event_allow_path << " is " << old_level.value() << ", "
329*288bf522SAndroid Build Coastguard Worker                << GetLimitLevelDescription(old_level.value()) << ". Try using `echo -1 >"
330*288bf522SAndroid Build Coastguard Worker                << perf_event_allow_path << "` to enable profiling.";
331*288bf522SAndroid Build Coastguard Worker     return false;
332*288bf522SAndroid Build Coastguard Worker   }
333*288bf522SAndroid Build Coastguard Worker #endif
334*288bf522SAndroid Build Coastguard Worker   return true;
335*288bf522SAndroid Build Coastguard Worker }
336*288bf522SAndroid Build Coastguard Worker 
337*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
SetProperty(const char * prop_name,uint64_t value)338*288bf522SAndroid Build Coastguard Worker static bool SetProperty(const char* prop_name, uint64_t value) {
339*288bf522SAndroid Build Coastguard Worker   if (!android::base::SetProperty(prop_name, std::to_string(value))) {
340*288bf522SAndroid Build Coastguard Worker     LOG(ERROR) << "Failed to SetProperty " << prop_name << " to " << value;
341*288bf522SAndroid Build Coastguard Worker     return false;
342*288bf522SAndroid Build Coastguard Worker   }
343*288bf522SAndroid Build Coastguard Worker   return true;
344*288bf522SAndroid Build Coastguard Worker }
345*288bf522SAndroid Build Coastguard Worker 
SetPerfEventLimits(uint64_t sample_freq,size_t cpu_percent,uint64_t mlock_kb)346*288bf522SAndroid Build Coastguard Worker bool SetPerfEventLimits(uint64_t sample_freq, size_t cpu_percent, uint64_t mlock_kb) {
347*288bf522SAndroid Build Coastguard Worker   if (!SetProperty("debug.perf_event_max_sample_rate", sample_freq) ||
348*288bf522SAndroid Build Coastguard Worker       !SetProperty("debug.perf_cpu_time_max_percent", cpu_percent) ||
349*288bf522SAndroid Build Coastguard Worker       !SetProperty("debug.perf_event_mlock_kb", mlock_kb) ||
350*288bf522SAndroid Build Coastguard Worker       !SetProperty("security.perf_harden", 0)) {
351*288bf522SAndroid Build Coastguard Worker     return false;
352*288bf522SAndroid Build Coastguard Worker   }
353*288bf522SAndroid Build Coastguard Worker   // Wait for init process to change perf event limits based on properties.
354*288bf522SAndroid Build Coastguard Worker   const size_t max_wait_us = 3 * 1000000;
355*288bf522SAndroid Build Coastguard Worker   const size_t interval_us = 10000;
356*288bf522SAndroid Build Coastguard Worker   int finish_mask = 0;
357*288bf522SAndroid Build Coastguard Worker   for (size_t i = 0; i < max_wait_us && finish_mask != 7; i += interval_us) {
358*288bf522SAndroid Build Coastguard Worker     usleep(interval_us);  // Wait 10ms to avoid busy loop.
359*288bf522SAndroid Build Coastguard Worker     if ((finish_mask & 1) == 0) {
360*288bf522SAndroid Build Coastguard Worker       uint64_t freq;
361*288bf522SAndroid Build Coastguard Worker       if (!GetMaxSampleFrequency(&freq) || freq == sample_freq) {
362*288bf522SAndroid Build Coastguard Worker         finish_mask |= 1;
363*288bf522SAndroid Build Coastguard Worker       }
364*288bf522SAndroid Build Coastguard Worker     }
365*288bf522SAndroid Build Coastguard Worker     if ((finish_mask & 2) == 0) {
366*288bf522SAndroid Build Coastguard Worker       size_t percent;
367*288bf522SAndroid Build Coastguard Worker       if (!GetCpuTimeMaxPercent(&percent) || percent == cpu_percent) {
368*288bf522SAndroid Build Coastguard Worker         finish_mask |= 2;
369*288bf522SAndroid Build Coastguard Worker       }
370*288bf522SAndroid Build Coastguard Worker     }
371*288bf522SAndroid Build Coastguard Worker     if ((finish_mask & 4) == 0) {
372*288bf522SAndroid Build Coastguard Worker       uint64_t kb;
373*288bf522SAndroid Build Coastguard Worker       if (!GetPerfEventMlockKb(&kb) || kb == mlock_kb) {
374*288bf522SAndroid Build Coastguard Worker         finish_mask |= 4;
375*288bf522SAndroid Build Coastguard Worker       }
376*288bf522SAndroid Build Coastguard Worker     }
377*288bf522SAndroid Build Coastguard Worker   }
378*288bf522SAndroid Build Coastguard Worker   if (finish_mask != 7) {
379*288bf522SAndroid Build Coastguard Worker     LOG(WARNING) << "Wait setting perf event limits timeout";
380*288bf522SAndroid Build Coastguard Worker   }
381*288bf522SAndroid Build Coastguard Worker   return true;
382*288bf522SAndroid Build Coastguard Worker }
383*288bf522SAndroid Build Coastguard Worker #else  // !defined(__ANDROID__)
SetPerfEventLimits(uint64_t,size_t,uint64_t)384*288bf522SAndroid Build Coastguard Worker bool SetPerfEventLimits(uint64_t, size_t, uint64_t) {
385*288bf522SAndroid Build Coastguard Worker   return true;
386*288bf522SAndroid Build Coastguard Worker }
387*288bf522SAndroid Build Coastguard Worker #endif
388*288bf522SAndroid Build Coastguard Worker 
389*288bf522SAndroid Build Coastguard Worker template <typename T>
ReadUintFromProcFile(const std::string & path,T * value)390*288bf522SAndroid Build Coastguard Worker static bool ReadUintFromProcFile(const std::string& path, T* value) {
391*288bf522SAndroid Build Coastguard Worker   std::string s;
392*288bf522SAndroid Build Coastguard Worker   if (!android::base::ReadFileToString(path, &s)) {
393*288bf522SAndroid Build Coastguard Worker     PLOG(DEBUG) << "failed to read " << path;
394*288bf522SAndroid Build Coastguard Worker     return false;
395*288bf522SAndroid Build Coastguard Worker   }
396*288bf522SAndroid Build Coastguard Worker   s = android::base::Trim(s);
397*288bf522SAndroid Build Coastguard Worker   if (!android::base::ParseUint(s.c_str(), value)) {
398*288bf522SAndroid Build Coastguard Worker     LOG(ERROR) << "failed to parse " << path << ": " << s;
399*288bf522SAndroid Build Coastguard Worker     return false;
400*288bf522SAndroid Build Coastguard Worker   }
401*288bf522SAndroid Build Coastguard Worker   return true;
402*288bf522SAndroid Build Coastguard Worker }
403*288bf522SAndroid Build Coastguard Worker 
404*288bf522SAndroid Build Coastguard Worker template <typename T>
WriteUintToProcFile(const std::string & path,T value)405*288bf522SAndroid Build Coastguard Worker static bool WriteUintToProcFile(const std::string& path, T value) {
406*288bf522SAndroid Build Coastguard Worker   if (IsRoot()) {
407*288bf522SAndroid Build Coastguard Worker     return android::base::WriteStringToFile(std::to_string(value), path);
408*288bf522SAndroid Build Coastguard Worker   }
409*288bf522SAndroid Build Coastguard Worker   return false;
410*288bf522SAndroid Build Coastguard Worker }
411*288bf522SAndroid Build Coastguard Worker 
GetMaxSampleFrequency(uint64_t * max_sample_freq)412*288bf522SAndroid Build Coastguard Worker bool GetMaxSampleFrequency(uint64_t* max_sample_freq) {
413*288bf522SAndroid Build Coastguard Worker   return ReadUintFromProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
414*288bf522SAndroid Build Coastguard Worker }
415*288bf522SAndroid Build Coastguard Worker 
SetMaxSampleFrequency(uint64_t max_sample_freq)416*288bf522SAndroid Build Coastguard Worker bool SetMaxSampleFrequency(uint64_t max_sample_freq) {
417*288bf522SAndroid Build Coastguard Worker   return WriteUintToProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
418*288bf522SAndroid Build Coastguard Worker }
419*288bf522SAndroid Build Coastguard Worker 
GetCpuTimeMaxPercent(size_t * percent)420*288bf522SAndroid Build Coastguard Worker bool GetCpuTimeMaxPercent(size_t* percent) {
421*288bf522SAndroid Build Coastguard Worker   return ReadUintFromProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
422*288bf522SAndroid Build Coastguard Worker }
423*288bf522SAndroid Build Coastguard Worker 
SetCpuTimeMaxPercent(size_t percent)424*288bf522SAndroid Build Coastguard Worker bool SetCpuTimeMaxPercent(size_t percent) {
425*288bf522SAndroid Build Coastguard Worker   return WriteUintToProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
426*288bf522SAndroid Build Coastguard Worker }
427*288bf522SAndroid Build Coastguard Worker 
GetPerfEventMlockKb(uint64_t * mlock_kb)428*288bf522SAndroid Build Coastguard Worker bool GetPerfEventMlockKb(uint64_t* mlock_kb) {
429*288bf522SAndroid Build Coastguard Worker   return ReadUintFromProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
430*288bf522SAndroid Build Coastguard Worker }
431*288bf522SAndroid Build Coastguard Worker 
SetPerfEventMlockKb(uint64_t mlock_kb)432*288bf522SAndroid Build Coastguard Worker bool SetPerfEventMlockKb(uint64_t mlock_kb) {
433*288bf522SAndroid Build Coastguard Worker   return WriteUintToProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
434*288bf522SAndroid Build Coastguard Worker }
435*288bf522SAndroid Build Coastguard Worker 
GetMachineArch()436*288bf522SAndroid Build Coastguard Worker ArchType GetMachineArch() {
437*288bf522SAndroid Build Coastguard Worker #if defined(__i386__)
438*288bf522SAndroid Build Coastguard Worker   // For 32 bit x86 build, we can't get machine arch by uname().
439*288bf522SAndroid Build Coastguard Worker   ArchType arch = ARCH_UNSUPPORTED;
440*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<FILE, decltype(&pclose)> fp(popen("uname -m", "re"), pclose);
441*288bf522SAndroid Build Coastguard Worker   if (fp) {
442*288bf522SAndroid Build Coastguard Worker     char machine[40];
443*288bf522SAndroid Build Coastguard Worker     if (fgets(machine, sizeof(machine), fp.get()) == machine) {
444*288bf522SAndroid Build Coastguard Worker       arch = GetArchType(android::base::Trim(machine));
445*288bf522SAndroid Build Coastguard Worker     }
446*288bf522SAndroid Build Coastguard Worker   }
447*288bf522SAndroid Build Coastguard Worker #else
448*288bf522SAndroid Build Coastguard Worker   utsname uname_buf;
449*288bf522SAndroid Build Coastguard Worker   if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
450*288bf522SAndroid Build Coastguard Worker     PLOG(WARNING) << "uname() failed";
451*288bf522SAndroid Build Coastguard Worker     return GetTargetArch();
452*288bf522SAndroid Build Coastguard Worker   }
453*288bf522SAndroid Build Coastguard Worker   ArchType arch = GetArchType(uname_buf.machine);
454*288bf522SAndroid Build Coastguard Worker #endif
455*288bf522SAndroid Build Coastguard Worker   if (arch != ARCH_UNSUPPORTED) {
456*288bf522SAndroid Build Coastguard Worker     return arch;
457*288bf522SAndroid Build Coastguard Worker   }
458*288bf522SAndroid Build Coastguard Worker   return GetTargetArch();
459*288bf522SAndroid Build Coastguard Worker }
460*288bf522SAndroid Build Coastguard Worker 
PrepareVdsoFile()461*288bf522SAndroid Build Coastguard Worker void PrepareVdsoFile() {
462*288bf522SAndroid Build Coastguard Worker   // vdso is an elf file in memory loaded in each process's user space by the kernel. To read
463*288bf522SAndroid Build Coastguard Worker   // symbols from it and unwind through it, we need to dump it into a file in storage.
464*288bf522SAndroid Build Coastguard Worker   // It doesn't affect much when failed to prepare vdso file, so there is no need to return values.
465*288bf522SAndroid Build Coastguard Worker   std::vector<ThreadMmap> thread_mmaps;
466*288bf522SAndroid Build Coastguard Worker   if (!GetThreadMmapsInProcess(getpid(), &thread_mmaps)) {
467*288bf522SAndroid Build Coastguard Worker     return;
468*288bf522SAndroid Build Coastguard Worker   }
469*288bf522SAndroid Build Coastguard Worker   const ThreadMmap* vdso_map = nullptr;
470*288bf522SAndroid Build Coastguard Worker   for (const auto& map : thread_mmaps) {
471*288bf522SAndroid Build Coastguard Worker     if (map.name == "[vdso]") {
472*288bf522SAndroid Build Coastguard Worker       vdso_map = &map;
473*288bf522SAndroid Build Coastguard Worker       break;
474*288bf522SAndroid Build Coastguard Worker     }
475*288bf522SAndroid Build Coastguard Worker   }
476*288bf522SAndroid Build Coastguard Worker   if (vdso_map == nullptr) {
477*288bf522SAndroid Build Coastguard Worker     return;
478*288bf522SAndroid Build Coastguard Worker   }
479*288bf522SAndroid Build Coastguard Worker   std::string s(vdso_map->len, '\0');
480*288bf522SAndroid Build Coastguard Worker   memcpy(&s[0], reinterpret_cast<void*>(static_cast<uintptr_t>(vdso_map->start_addr)),
481*288bf522SAndroid Build Coastguard Worker          vdso_map->len);
482*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<TemporaryFile> tmpfile = ScopedTempFiles::CreateTempFile();
483*288bf522SAndroid Build Coastguard Worker   if (!android::base::WriteStringToFd(s, tmpfile->fd)) {
484*288bf522SAndroid Build Coastguard Worker     return;
485*288bf522SAndroid Build Coastguard Worker   }
486*288bf522SAndroid Build Coastguard Worker   Dso::SetVdsoFile(tmpfile->path, sizeof(size_t) == sizeof(uint64_t));
487*288bf522SAndroid Build Coastguard Worker }
488*288bf522SAndroid Build Coastguard Worker 
HasOpenedAppApkFile(int pid)489*288bf522SAndroid Build Coastguard Worker static bool HasOpenedAppApkFile(int pid) {
490*288bf522SAndroid Build Coastguard Worker   std::string fd_path = "/proc/" + std::to_string(pid) + "/fd/";
491*288bf522SAndroid Build Coastguard Worker   std::vector<std::string> files = GetEntriesInDir(fd_path);
492*288bf522SAndroid Build Coastguard Worker   for (const auto& file : files) {
493*288bf522SAndroid Build Coastguard Worker     std::string real_path;
494*288bf522SAndroid Build Coastguard Worker     if (!android::base::Readlink(fd_path + file, &real_path)) {
495*288bf522SAndroid Build Coastguard Worker       continue;
496*288bf522SAndroid Build Coastguard Worker     }
497*288bf522SAndroid Build Coastguard Worker     if (real_path.find("app") != std::string::npos && real_path.find(".apk") != std::string::npos) {
498*288bf522SAndroid Build Coastguard Worker       return true;
499*288bf522SAndroid Build Coastguard Worker     }
500*288bf522SAndroid Build Coastguard Worker   }
501*288bf522SAndroid Build Coastguard Worker   return false;
502*288bf522SAndroid Build Coastguard Worker }
503*288bf522SAndroid Build Coastguard Worker 
WaitForAppProcesses(const std::string & package_name)504*288bf522SAndroid Build Coastguard Worker std::set<pid_t> WaitForAppProcesses(const std::string& package_name) {
505*288bf522SAndroid Build Coastguard Worker   std::set<pid_t> result;
506*288bf522SAndroid Build Coastguard Worker   size_t loop_count = 0;
507*288bf522SAndroid Build Coastguard Worker   while (true) {
508*288bf522SAndroid Build Coastguard Worker     std::vector<pid_t> pids = GetAllProcesses();
509*288bf522SAndroid Build Coastguard Worker     for (pid_t pid : pids) {
510*288bf522SAndroid Build Coastguard Worker       std::string process_name = GetCompleteProcessName(pid);
511*288bf522SAndroid Build Coastguard Worker       if (process_name.empty()) {
512*288bf522SAndroid Build Coastguard Worker         continue;
513*288bf522SAndroid Build Coastguard Worker       }
514*288bf522SAndroid Build Coastguard Worker       // The app may have multiple processes, with process name like
515*288bf522SAndroid Build Coastguard Worker       // com.google.android.googlequicksearchbox:search.
516*288bf522SAndroid Build Coastguard Worker       size_t split_pos = process_name.find(':');
517*288bf522SAndroid Build Coastguard Worker       if (split_pos != std::string::npos) {
518*288bf522SAndroid Build Coastguard Worker         process_name = process_name.substr(0, split_pos);
519*288bf522SAndroid Build Coastguard Worker       }
520*288bf522SAndroid Build Coastguard Worker       if (process_name != package_name) {
521*288bf522SAndroid Build Coastguard Worker         continue;
522*288bf522SAndroid Build Coastguard Worker       }
523*288bf522SAndroid Build Coastguard Worker       // If a debuggable app with wrap.sh runs on Android O, the app will be started with
524*288bf522SAndroid Build Coastguard Worker       // logwrapper as below:
525*288bf522SAndroid Build Coastguard Worker       // 1. Zygote forks a child process, rename it to package_name.
526*288bf522SAndroid Build Coastguard Worker       // 2. The child process execute sh, which starts a child process running
527*288bf522SAndroid Build Coastguard Worker       //    /system/bin/logwrapper.
528*288bf522SAndroid Build Coastguard Worker       // 3. logwrapper starts a child process running sh, which interprets wrap.sh.
529*288bf522SAndroid Build Coastguard Worker       // 4. wrap.sh starts a child process running the app.
530*288bf522SAndroid Build Coastguard Worker       // The problem here is we want to profile the process started in step 4, but sometimes we
531*288bf522SAndroid Build Coastguard Worker       // run into the process started in step 1. To solve it, we can check if the process has
532*288bf522SAndroid Build Coastguard Worker       // opened an apk file in some app dirs.
533*288bf522SAndroid Build Coastguard Worker       if (!HasOpenedAppApkFile(pid)) {
534*288bf522SAndroid Build Coastguard Worker         continue;
535*288bf522SAndroid Build Coastguard Worker       }
536*288bf522SAndroid Build Coastguard Worker       if (loop_count > 0u) {
537*288bf522SAndroid Build Coastguard Worker         LOG(INFO) << "Got process " << pid << " for package " << package_name;
538*288bf522SAndroid Build Coastguard Worker       }
539*288bf522SAndroid Build Coastguard Worker       result.insert(pid);
540*288bf522SAndroid Build Coastguard Worker     }
541*288bf522SAndroid Build Coastguard Worker     if (!result.empty()) {
542*288bf522SAndroid Build Coastguard Worker       return result;
543*288bf522SAndroid Build Coastguard Worker     }
544*288bf522SAndroid Build Coastguard Worker     if (++loop_count == 1u) {
545*288bf522SAndroid Build Coastguard Worker       LOG(INFO) << "Waiting for process of app " << package_name;
546*288bf522SAndroid Build Coastguard Worker     }
547*288bf522SAndroid Build Coastguard Worker     usleep(1000);
548*288bf522SAndroid Build Coastguard Worker   }
549*288bf522SAndroid Build Coastguard Worker }
550*288bf522SAndroid Build Coastguard Worker 
551*288bf522SAndroid Build Coastguard Worker namespace {
552*288bf522SAndroid Build Coastguard Worker 
IsAppDebuggable(int user_id,const std::string & package_name)553*288bf522SAndroid Build Coastguard Worker bool IsAppDebuggable(int user_id, const std::string& package_name) {
554*288bf522SAndroid Build Coastguard Worker   return Workload::RunCmd({"run-as", package_name, "--user", std::to_string(user_id), "echo",
555*288bf522SAndroid Build Coastguard Worker                            ">/dev/null", "2>/dev/null"},
556*288bf522SAndroid Build Coastguard Worker                           false);
557*288bf522SAndroid Build Coastguard Worker }
558*288bf522SAndroid Build Coastguard Worker 
559*288bf522SAndroid Build Coastguard Worker class InAppRunner {
560*288bf522SAndroid Build Coastguard Worker  public:
InAppRunner(int user_id,const std::string & package_name)561*288bf522SAndroid Build Coastguard Worker   InAppRunner(int user_id, const std::string& package_name)
562*288bf522SAndroid Build Coastguard Worker       : user_id_(std::to_string(user_id)), package_name_(package_name) {}
~InAppRunner()563*288bf522SAndroid Build Coastguard Worker   virtual ~InAppRunner() {
564*288bf522SAndroid Build Coastguard Worker     if (!tracepoint_file_.empty()) {
565*288bf522SAndroid Build Coastguard Worker       unlink(tracepoint_file_.c_str());
566*288bf522SAndroid Build Coastguard Worker     }
567*288bf522SAndroid Build Coastguard Worker   }
568*288bf522SAndroid Build Coastguard Worker   virtual bool Prepare() = 0;
569*288bf522SAndroid Build Coastguard Worker   bool RunCmdInApp(const std::string& cmd, const std::vector<std::string>& args,
570*288bf522SAndroid Build Coastguard Worker                    size_t workload_args_size, const std::string& output_filepath,
571*288bf522SAndroid Build Coastguard Worker                    bool need_tracepoint_events);
572*288bf522SAndroid Build Coastguard Worker 
573*288bf522SAndroid Build Coastguard Worker  protected:
574*288bf522SAndroid Build Coastguard Worker   virtual std::vector<std::string> GetPrefixArgs(const std::string& cmd) = 0;
575*288bf522SAndroid Build Coastguard Worker 
576*288bf522SAndroid Build Coastguard Worker   const std::string user_id_;
577*288bf522SAndroid Build Coastguard Worker   const std::string package_name_;
578*288bf522SAndroid Build Coastguard Worker   std::string tracepoint_file_;
579*288bf522SAndroid Build Coastguard Worker };
580*288bf522SAndroid Build Coastguard Worker 
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)581*288bf522SAndroid Build Coastguard Worker bool InAppRunner::RunCmdInApp(const std::string& cmd, const std::vector<std::string>& cmd_args,
582*288bf522SAndroid Build Coastguard Worker                               size_t workload_args_size, const std::string& output_filepath,
583*288bf522SAndroid Build Coastguard Worker                               bool need_tracepoint_events) {
584*288bf522SAndroid Build Coastguard Worker   // 1. Build cmd args running in app's context.
585*288bf522SAndroid Build Coastguard Worker   std::vector<std::string> args = GetPrefixArgs(cmd);
586*288bf522SAndroid Build Coastguard Worker   args.insert(args.end(), {"--in-app", "--log", GetLogSeverityName()});
587*288bf522SAndroid Build Coastguard Worker   if (log_to_android_buffer) {
588*288bf522SAndroid Build Coastguard Worker     args.emplace_back("--log-to-android-buffer");
589*288bf522SAndroid Build Coastguard Worker   }
590*288bf522SAndroid Build Coastguard Worker   if (need_tracepoint_events) {
591*288bf522SAndroid Build Coastguard Worker     // Since we can't read tracepoint events from tracefs in app's context, we need to prepare
592*288bf522SAndroid Build Coastguard Worker     // them in tracepoint_file in shell's context, and pass the path of tracepoint_file to the
593*288bf522SAndroid Build Coastguard Worker     // child process using --tracepoint-events option.
594*288bf522SAndroid Build Coastguard Worker     const std::string tracepoint_file = "/data/local/tmp/tracepoint_events";
595*288bf522SAndroid Build Coastguard Worker     if (!EventTypeManager::Instance().WriteTracepointsToFile(tracepoint_file)) {
596*288bf522SAndroid Build Coastguard Worker       PLOG(ERROR) << "Failed to store tracepoint events";
597*288bf522SAndroid Build Coastguard Worker       return false;
598*288bf522SAndroid Build Coastguard Worker     }
599*288bf522SAndroid Build Coastguard Worker     tracepoint_file_ = tracepoint_file;
600*288bf522SAndroid Build Coastguard Worker     args.insert(args.end(), {"--tracepoint-events", tracepoint_file_});
601*288bf522SAndroid Build Coastguard Worker   }
602*288bf522SAndroid Build Coastguard Worker 
603*288bf522SAndroid Build Coastguard Worker   android::base::unique_fd out_fd;
604*288bf522SAndroid Build Coastguard Worker   if (!output_filepath.empty()) {
605*288bf522SAndroid Build Coastguard Worker     // A process running in app's context can't open a file outside it's data directory to write.
606*288bf522SAndroid Build Coastguard Worker     // So pass it a file descriptor to write.
607*288bf522SAndroid Build Coastguard Worker     out_fd = FileHelper::OpenWriteOnly(output_filepath);
608*288bf522SAndroid Build Coastguard Worker     if (out_fd == -1) {
609*288bf522SAndroid Build Coastguard Worker       PLOG(ERROR) << "Failed to open " << output_filepath;
610*288bf522SAndroid Build Coastguard Worker       return false;
611*288bf522SAndroid Build Coastguard Worker     }
612*288bf522SAndroid Build Coastguard Worker     args.insert(args.end(), {"--out-fd", std::to_string(int(out_fd))});
613*288bf522SAndroid Build Coastguard Worker   }
614*288bf522SAndroid Build Coastguard Worker 
615*288bf522SAndroid Build Coastguard Worker   // We can't send signal to a process running in app's context. So use a pipe file to send stop
616*288bf522SAndroid Build Coastguard Worker   // signal.
617*288bf522SAndroid Build Coastguard Worker   android::base::unique_fd stop_signal_rfd;
618*288bf522SAndroid Build Coastguard Worker   android::base::unique_fd stop_signal_wfd;
619*288bf522SAndroid Build Coastguard Worker   if (!android::base::Pipe(&stop_signal_rfd, &stop_signal_wfd, 0)) {
620*288bf522SAndroid Build Coastguard Worker     PLOG(ERROR) << "pipe";
621*288bf522SAndroid Build Coastguard Worker     return false;
622*288bf522SAndroid Build Coastguard Worker   }
623*288bf522SAndroid Build Coastguard Worker   args.insert(args.end(), {"--stop-signal-fd", std::to_string(int(stop_signal_rfd))});
624*288bf522SAndroid Build Coastguard Worker 
625*288bf522SAndroid Build Coastguard Worker   for (size_t i = 0; i < cmd_args.size(); ++i) {
626*288bf522SAndroid Build Coastguard Worker     if (i < cmd_args.size() - workload_args_size) {
627*288bf522SAndroid Build Coastguard Worker       // Omit "-o output_file". It is replaced by "--out-fd fd".
628*288bf522SAndroid Build Coastguard Worker       if (cmd_args[i] == "-o" || cmd_args[i] == "--app") {
629*288bf522SAndroid Build Coastguard Worker         i++;
630*288bf522SAndroid Build Coastguard Worker         continue;
631*288bf522SAndroid Build Coastguard Worker       }
632*288bf522SAndroid Build Coastguard Worker     }
633*288bf522SAndroid Build Coastguard Worker     args.push_back(cmd_args[i]);
634*288bf522SAndroid Build Coastguard Worker   }
635*288bf522SAndroid Build Coastguard Worker   char* argv[args.size() + 1];
636*288bf522SAndroid Build Coastguard Worker   for (size_t i = 0; i < args.size(); ++i) {
637*288bf522SAndroid Build Coastguard Worker     argv[i] = &args[i][0];
638*288bf522SAndroid Build Coastguard Worker   }
639*288bf522SAndroid Build Coastguard Worker   argv[args.size()] = nullptr;
640*288bf522SAndroid Build Coastguard Worker 
641*288bf522SAndroid Build Coastguard Worker   // 2. Run child process in app's context.
642*288bf522SAndroid Build Coastguard Worker   auto ChildProcFn = [&]() {
643*288bf522SAndroid Build Coastguard Worker     stop_signal_wfd.reset();
644*288bf522SAndroid Build Coastguard Worker     execvp(argv[0], argv);
645*288bf522SAndroid Build Coastguard Worker     exit(1);
646*288bf522SAndroid Build Coastguard Worker   };
647*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<Workload> workload = Workload::CreateWorkload(ChildProcFn);
648*288bf522SAndroid Build Coastguard Worker   if (!workload) {
649*288bf522SAndroid Build Coastguard Worker     return false;
650*288bf522SAndroid Build Coastguard Worker   }
651*288bf522SAndroid Build Coastguard Worker   stop_signal_rfd.reset();
652*288bf522SAndroid Build Coastguard Worker 
653*288bf522SAndroid Build Coastguard Worker   // Wait on signals.
654*288bf522SAndroid Build Coastguard Worker   IOEventLoop loop;
655*288bf522SAndroid Build Coastguard Worker   bool need_to_stop_child = false;
656*288bf522SAndroid Build Coastguard Worker   std::vector<int> stop_signals = {SIGINT, SIGTERM};
657*288bf522SAndroid Build Coastguard Worker   if (!SignalIsIgnored(SIGHUP)) {
658*288bf522SAndroid Build Coastguard Worker     stop_signals.push_back(SIGHUP);
659*288bf522SAndroid Build Coastguard Worker   }
660*288bf522SAndroid Build Coastguard Worker   if (!loop.AddSignalEvents(stop_signals, [&]() {
661*288bf522SAndroid Build Coastguard Worker         need_to_stop_child = true;
662*288bf522SAndroid Build Coastguard Worker         return loop.ExitLoop();
663*288bf522SAndroid Build Coastguard Worker       })) {
664*288bf522SAndroid Build Coastguard Worker     return false;
665*288bf522SAndroid Build Coastguard Worker   }
666*288bf522SAndroid Build Coastguard Worker   if (!loop.AddSignalEvent(SIGCHLD, [&]() { return loop.ExitLoop(); })) {
667*288bf522SAndroid Build Coastguard Worker     return false;
668*288bf522SAndroid Build Coastguard Worker   }
669*288bf522SAndroid Build Coastguard Worker 
670*288bf522SAndroid Build Coastguard Worker   if (!workload->Start()) {
671*288bf522SAndroid Build Coastguard Worker     return false;
672*288bf522SAndroid Build Coastguard Worker   }
673*288bf522SAndroid Build Coastguard Worker   if (!loop.RunLoop()) {
674*288bf522SAndroid Build Coastguard Worker     return false;
675*288bf522SAndroid Build Coastguard Worker   }
676*288bf522SAndroid Build Coastguard Worker   if (need_to_stop_child) {
677*288bf522SAndroid Build Coastguard Worker     stop_signal_wfd.reset();
678*288bf522SAndroid Build Coastguard Worker   }
679*288bf522SAndroid Build Coastguard Worker   int exit_code;
680*288bf522SAndroid Build Coastguard Worker   if (!workload->WaitChildProcess(true, &exit_code) || exit_code != 0) {
681*288bf522SAndroid Build Coastguard Worker     return false;
682*288bf522SAndroid Build Coastguard Worker   }
683*288bf522SAndroid Build Coastguard Worker   return true;
684*288bf522SAndroid Build Coastguard Worker }
685*288bf522SAndroid Build Coastguard Worker 
686*288bf522SAndroid Build Coastguard Worker class RunAs : public InAppRunner {
687*288bf522SAndroid Build Coastguard Worker  public:
RunAs(int user_id,const std::string & package_name)688*288bf522SAndroid Build Coastguard Worker   RunAs(int user_id, const std::string& package_name) : InAppRunner(user_id, package_name) {}
~RunAs()689*288bf522SAndroid Build Coastguard Worker   virtual ~RunAs() {
690*288bf522SAndroid Build Coastguard Worker     if (simpleperf_copied_in_app_) {
691*288bf522SAndroid Build Coastguard Worker       Workload::RunCmd({"run-as", package_name_, "--user", user_id_, "rm", "-rf", "simpleperf"});
692*288bf522SAndroid Build Coastguard Worker     }
693*288bf522SAndroid Build Coastguard Worker   }
694*288bf522SAndroid Build Coastguard Worker   bool Prepare() override;
695*288bf522SAndroid Build Coastguard Worker 
696*288bf522SAndroid Build Coastguard Worker  protected:
GetPrefixArgs(const std::string & cmd)697*288bf522SAndroid Build Coastguard Worker   std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
698*288bf522SAndroid Build Coastguard Worker     std::vector<std::string> args = {"run-as",
699*288bf522SAndroid Build Coastguard Worker                                      package_name_,
700*288bf522SAndroid Build Coastguard Worker                                      "--user",
701*288bf522SAndroid Build Coastguard Worker                                      user_id_,
702*288bf522SAndroid Build Coastguard Worker                                      simpleperf_copied_in_app_ ? "./simpleperf" : simpleperf_path_,
703*288bf522SAndroid Build Coastguard Worker                                      cmd,
704*288bf522SAndroid Build Coastguard Worker                                      "--app",
705*288bf522SAndroid Build Coastguard Worker                                      package_name_};
706*288bf522SAndroid Build Coastguard Worker     if (cmd == "record") {
707*288bf522SAndroid Build Coastguard Worker       if (simpleperf_copied_in_app_ || GetAndroidVersion() >= kAndroidVersionS) {
708*288bf522SAndroid Build Coastguard Worker         args.emplace_back("--add-meta-info");
709*288bf522SAndroid Build Coastguard Worker         args.emplace_back("app_type=debuggable");
710*288bf522SAndroid Build Coastguard Worker       }
711*288bf522SAndroid Build Coastguard Worker     }
712*288bf522SAndroid Build Coastguard Worker     return args;
713*288bf522SAndroid Build Coastguard Worker   }
714*288bf522SAndroid Build Coastguard Worker 
715*288bf522SAndroid Build Coastguard Worker   bool simpleperf_copied_in_app_ = false;
716*288bf522SAndroid Build Coastguard Worker   std::string simpleperf_path_;
717*288bf522SAndroid Build Coastguard Worker };
718*288bf522SAndroid Build Coastguard Worker 
Prepare()719*288bf522SAndroid Build Coastguard Worker bool RunAs::Prepare() {
720*288bf522SAndroid Build Coastguard Worker   // run-as can't run /data/local/tmp/simpleperf directly. So copy simpleperf binary if needed.
721*288bf522SAndroid Build Coastguard Worker   if (!android::base::Readlink("/proc/self/exe", &simpleperf_path_)) {
722*288bf522SAndroid Build Coastguard Worker     PLOG(ERROR) << "ReadLink failed";
723*288bf522SAndroid Build Coastguard Worker     return false;
724*288bf522SAndroid Build Coastguard Worker   }
725*288bf522SAndroid Build Coastguard Worker   if (simpleperf_path_.find("CtsSimpleperfTest") != std::string::npos) {
726*288bf522SAndroid Build Coastguard Worker     simpleperf_path_ = "/system/bin/simpleperf";
727*288bf522SAndroid Build Coastguard Worker     return true;
728*288bf522SAndroid Build Coastguard Worker   }
729*288bf522SAndroid Build Coastguard Worker   if (android::base::StartsWith(simpleperf_path_, "/system")) {
730*288bf522SAndroid Build Coastguard Worker     return true;
731*288bf522SAndroid Build Coastguard Worker   }
732*288bf522SAndroid Build Coastguard Worker   if (!Workload::RunCmd(
733*288bf522SAndroid Build Coastguard Worker           {"run-as", package_name_, "--user", user_id_, "cp", simpleperf_path_, "simpleperf"})) {
734*288bf522SAndroid Build Coastguard Worker     return false;
735*288bf522SAndroid Build Coastguard Worker   }
736*288bf522SAndroid Build Coastguard Worker   simpleperf_copied_in_app_ = true;
737*288bf522SAndroid Build Coastguard Worker   return true;
738*288bf522SAndroid Build Coastguard Worker }
739*288bf522SAndroid Build Coastguard Worker 
740*288bf522SAndroid Build Coastguard Worker class SimpleperfAppRunner : public InAppRunner {
741*288bf522SAndroid Build Coastguard Worker  public:
SimpleperfAppRunner(int user_id,const std::string & package_name,const std::string & app_type)742*288bf522SAndroid Build Coastguard Worker   SimpleperfAppRunner(int user_id, const std::string& package_name, const std::string& app_type)
743*288bf522SAndroid Build Coastguard Worker       : InAppRunner(user_id, package_name) {
744*288bf522SAndroid Build Coastguard Worker     // On Android < S, the app type is unknown before running simpleperf_app_runner. Assume it's
745*288bf522SAndroid Build Coastguard Worker     // profileable.
746*288bf522SAndroid Build Coastguard Worker     app_type_ = app_type == "unknown" ? "profileable" : app_type;
747*288bf522SAndroid Build Coastguard Worker   }
Prepare()748*288bf522SAndroid Build Coastguard Worker   bool Prepare() override { return GetAndroidVersion() >= kAndroidVersionQ; }
749*288bf522SAndroid Build Coastguard Worker 
750*288bf522SAndroid Build Coastguard Worker  protected:
GetPrefixArgs(const std::string & cmd)751*288bf522SAndroid Build Coastguard Worker   std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
752*288bf522SAndroid Build Coastguard Worker     std::vector<std::string> args = {"simpleperf_app_runner", package_name_};
753*288bf522SAndroid Build Coastguard Worker     if (user_id_ != "0") {
754*288bf522SAndroid Build Coastguard Worker       args.emplace_back("--user");
755*288bf522SAndroid Build Coastguard Worker       args.emplace_back(user_id_);
756*288bf522SAndroid Build Coastguard Worker     }
757*288bf522SAndroid Build Coastguard Worker     args.emplace_back(cmd);
758*288bf522SAndroid Build Coastguard Worker     if (cmd == "record" && GetAndroidVersion() >= kAndroidVersionS) {
759*288bf522SAndroid Build Coastguard Worker       args.emplace_back("--add-meta-info");
760*288bf522SAndroid Build Coastguard Worker       args.emplace_back("app_type=" + app_type_);
761*288bf522SAndroid Build Coastguard Worker     }
762*288bf522SAndroid Build Coastguard Worker     return args;
763*288bf522SAndroid Build Coastguard Worker   }
764*288bf522SAndroid Build Coastguard Worker 
765*288bf522SAndroid Build Coastguard Worker   std::string app_type_;
766*288bf522SAndroid Build Coastguard Worker };
767*288bf522SAndroid Build Coastguard Worker 
768*288bf522SAndroid Build Coastguard Worker }  // namespace
769*288bf522SAndroid Build Coastguard Worker 
770*288bf522SAndroid Build Coastguard Worker static bool allow_run_as = true;
771*288bf522SAndroid Build Coastguard Worker static bool allow_simpleperf_app_runner = true;
772*288bf522SAndroid Build Coastguard Worker 
SetRunInAppToolForTesting(bool run_as,bool simpleperf_app_runner)773*288bf522SAndroid Build Coastguard Worker void SetRunInAppToolForTesting(bool run_as, bool simpleperf_app_runner) {
774*288bf522SAndroid Build Coastguard Worker   allow_run_as = run_as;
775*288bf522SAndroid Build Coastguard Worker   allow_simpleperf_app_runner = simpleperf_app_runner;
776*288bf522SAndroid Build Coastguard Worker }
777*288bf522SAndroid Build Coastguard Worker 
GetCurrentUserId()778*288bf522SAndroid Build Coastguard Worker static int GetCurrentUserId() {
779*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<FILE, decltype(&pclose)> fd(popen("am get-current-user", "r"), pclose);
780*288bf522SAndroid Build Coastguard Worker   if (fd) {
781*288bf522SAndroid Build Coastguard Worker     char buf[128];
782*288bf522SAndroid Build Coastguard Worker     if (fgets(buf, sizeof(buf), fd.get()) != nullptr) {
783*288bf522SAndroid Build Coastguard Worker       int user_id;
784*288bf522SAndroid Build Coastguard Worker       if (android::base::ParseInt(android::base::Trim(buf), &user_id, 0)) {
785*288bf522SAndroid Build Coastguard Worker         return user_id;
786*288bf522SAndroid Build Coastguard Worker       }
787*288bf522SAndroid Build Coastguard Worker     }
788*288bf522SAndroid Build Coastguard Worker   }
789*288bf522SAndroid Build Coastguard Worker   return 0;
790*288bf522SAndroid Build Coastguard Worker }
791*288bf522SAndroid Build Coastguard Worker 
GetAppType(const std::string & app_package_name)792*288bf522SAndroid Build Coastguard Worker std::string GetAppType(const std::string& app_package_name) {
793*288bf522SAndroid Build Coastguard Worker   if (GetAndroidVersion() < kAndroidVersionS) {
794*288bf522SAndroid Build Coastguard Worker     return "unknown";
795*288bf522SAndroid Build Coastguard Worker   }
796*288bf522SAndroid Build Coastguard Worker   std::string cmd = "simpleperf_app_runner " + app_package_name + " --show-app-type";
797*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<FILE, decltype(&pclose)> fp(popen(cmd.c_str(), "re"), pclose);
798*288bf522SAndroid Build Coastguard Worker   if (fp) {
799*288bf522SAndroid Build Coastguard Worker     char buf[128];
800*288bf522SAndroid Build Coastguard Worker     if (fgets(buf, sizeof(buf), fp.get()) != nullptr) {
801*288bf522SAndroid Build Coastguard Worker       return android::base::Trim(buf);
802*288bf522SAndroid Build Coastguard Worker     }
803*288bf522SAndroid Build Coastguard Worker   }
804*288bf522SAndroid Build Coastguard Worker   // Can't get app_type. It means the app doesn't exist.
805*288bf522SAndroid Build Coastguard Worker   return "not_exist";
806*288bf522SAndroid Build Coastguard Worker }
807*288bf522SAndroid Build Coastguard Worker 
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)808*288bf522SAndroid Build Coastguard Worker bool RunInAppContext(const std::string& app_package_name, const std::string& cmd,
809*288bf522SAndroid Build Coastguard Worker                      const std::vector<std::string>& args, size_t workload_args_size,
810*288bf522SAndroid Build Coastguard Worker                      const std::string& output_filepath, bool need_tracepoint_events) {
811*288bf522SAndroid Build Coastguard Worker   int user_id = GetCurrentUserId();
812*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<InAppRunner> in_app_runner;
813*288bf522SAndroid Build Coastguard Worker 
814*288bf522SAndroid Build Coastguard Worker   std::string app_type = GetAppType(app_package_name);
815*288bf522SAndroid Build Coastguard Worker   if (app_type == "unknown" && IsAppDebuggable(user_id, app_package_name)) {
816*288bf522SAndroid Build Coastguard Worker     app_type = "debuggable";
817*288bf522SAndroid Build Coastguard Worker   }
818*288bf522SAndroid Build Coastguard Worker 
819*288bf522SAndroid Build Coastguard Worker   if (allow_run_as && app_type == "debuggable") {
820*288bf522SAndroid Build Coastguard Worker     in_app_runner.reset(new RunAs(user_id, app_package_name));
821*288bf522SAndroid Build Coastguard Worker     if (!in_app_runner->Prepare()) {
822*288bf522SAndroid Build Coastguard Worker       in_app_runner = nullptr;
823*288bf522SAndroid Build Coastguard Worker     }
824*288bf522SAndroid Build Coastguard Worker   }
825*288bf522SAndroid Build Coastguard Worker   if (!in_app_runner && allow_simpleperf_app_runner) {
826*288bf522SAndroid Build Coastguard Worker     if (app_type == "debuggable" || app_type == "profileable" || app_type == "unknown") {
827*288bf522SAndroid Build Coastguard Worker       in_app_runner.reset(new SimpleperfAppRunner(user_id, app_package_name, app_type));
828*288bf522SAndroid Build Coastguard Worker       if (!in_app_runner->Prepare()) {
829*288bf522SAndroid Build Coastguard Worker         in_app_runner = nullptr;
830*288bf522SAndroid Build Coastguard Worker       }
831*288bf522SAndroid Build Coastguard Worker     }
832*288bf522SAndroid Build Coastguard Worker   }
833*288bf522SAndroid Build Coastguard Worker   if (!in_app_runner) {
834*288bf522SAndroid Build Coastguard Worker     LOG(ERROR) << "Package " << app_package_name
835*288bf522SAndroid Build Coastguard Worker                << " doesn't exist or isn't debuggable/profileable.";
836*288bf522SAndroid Build Coastguard Worker     return false;
837*288bf522SAndroid Build Coastguard Worker   }
838*288bf522SAndroid Build Coastguard Worker   return in_app_runner->RunCmdInApp(cmd, args, workload_args_size, output_filepath,
839*288bf522SAndroid Build Coastguard Worker                                     need_tracepoint_events);
840*288bf522SAndroid Build Coastguard Worker }
841*288bf522SAndroid Build Coastguard Worker 
AllowMoreOpenedFiles()842*288bf522SAndroid Build Coastguard Worker void AllowMoreOpenedFiles() {
843*288bf522SAndroid Build Coastguard Worker   // On Android <= O, the hard limit is 4096, and the soft limit is 1024.
844*288bf522SAndroid Build Coastguard Worker   // On Android >= P, both the hard and soft limit are 32768.
845*288bf522SAndroid Build Coastguard Worker   rlimit limit;
846*288bf522SAndroid Build Coastguard Worker   if (getrlimit(RLIMIT_NOFILE, &limit) != 0) {
847*288bf522SAndroid Build Coastguard Worker     return;
848*288bf522SAndroid Build Coastguard Worker   }
849*288bf522SAndroid Build Coastguard Worker   rlim_t new_limit = limit.rlim_max;
850*288bf522SAndroid Build Coastguard Worker   if (IsRoot()) {
851*288bf522SAndroid Build Coastguard Worker     rlim_t sysctl_nr_open = 0;
852*288bf522SAndroid Build Coastguard Worker     if (ReadUintFromProcFile("/proc/sys/fs/nr_open", &sysctl_nr_open) &&
853*288bf522SAndroid Build Coastguard Worker         sysctl_nr_open > new_limit) {
854*288bf522SAndroid Build Coastguard Worker       new_limit = sysctl_nr_open;
855*288bf522SAndroid Build Coastguard Worker     }
856*288bf522SAndroid Build Coastguard Worker   }
857*288bf522SAndroid Build Coastguard Worker   if (limit.rlim_cur < new_limit) {
858*288bf522SAndroid Build Coastguard Worker     limit.rlim_cur = limit.rlim_max = new_limit;
859*288bf522SAndroid Build Coastguard Worker     if (setrlimit(RLIMIT_NOFILE, &limit) == 0) {
860*288bf522SAndroid Build Coastguard Worker       LOG(DEBUG) << "increased open file limit to " << new_limit;
861*288bf522SAndroid Build Coastguard Worker     }
862*288bf522SAndroid Build Coastguard Worker   }
863*288bf522SAndroid Build Coastguard Worker }
864*288bf522SAndroid Build Coastguard Worker 
865*288bf522SAndroid Build Coastguard Worker std::string ScopedTempFiles::tmp_dir_;
866*288bf522SAndroid Build Coastguard Worker std::vector<std::string> ScopedTempFiles::files_to_delete_;
867*288bf522SAndroid Build Coastguard Worker 
Create(const std::string & tmp_dir)868*288bf522SAndroid Build Coastguard Worker std::unique_ptr<ScopedTempFiles> ScopedTempFiles::Create(const std::string& tmp_dir) {
869*288bf522SAndroid Build Coastguard Worker   if (access(tmp_dir.c_str(), W_OK | X_OK) != 0) {
870*288bf522SAndroid Build Coastguard Worker     return nullptr;
871*288bf522SAndroid Build Coastguard Worker   }
872*288bf522SAndroid Build Coastguard Worker   return std::unique_ptr<ScopedTempFiles>(new ScopedTempFiles(tmp_dir));
873*288bf522SAndroid Build Coastguard Worker }
874*288bf522SAndroid Build Coastguard Worker 
ScopedTempFiles(const std::string & tmp_dir)875*288bf522SAndroid Build Coastguard Worker ScopedTempFiles::ScopedTempFiles(const std::string& tmp_dir) {
876*288bf522SAndroid Build Coastguard Worker   CHECK(tmp_dir_.empty());  // No other ScopedTempFiles.
877*288bf522SAndroid Build Coastguard Worker   tmp_dir_ = tmp_dir;
878*288bf522SAndroid Build Coastguard Worker }
879*288bf522SAndroid Build Coastguard Worker 
~ScopedTempFiles()880*288bf522SAndroid Build Coastguard Worker ScopedTempFiles::~ScopedTempFiles() {
881*288bf522SAndroid Build Coastguard Worker   tmp_dir_.clear();
882*288bf522SAndroid Build Coastguard Worker   for (auto& file : files_to_delete_) {
883*288bf522SAndroid Build Coastguard Worker     unlink(file.c_str());
884*288bf522SAndroid Build Coastguard Worker   }
885*288bf522SAndroid Build Coastguard Worker   files_to_delete_.clear();
886*288bf522SAndroid Build Coastguard Worker }
887*288bf522SAndroid Build Coastguard Worker 
CreateTempFile(bool delete_in_destructor)888*288bf522SAndroid Build Coastguard Worker std::unique_ptr<TemporaryFile> ScopedTempFiles::CreateTempFile(bool delete_in_destructor) {
889*288bf522SAndroid Build Coastguard Worker   CHECK(!tmp_dir_.empty());
890*288bf522SAndroid Build Coastguard Worker   std::unique_ptr<TemporaryFile> tmp_file(new TemporaryFile(tmp_dir_));
891*288bf522SAndroid Build Coastguard Worker   CHECK_NE(tmp_file->fd, -1) << "failed to create tmpfile under " << tmp_dir_;
892*288bf522SAndroid Build Coastguard Worker   if (delete_in_destructor) {
893*288bf522SAndroid Build Coastguard Worker     tmp_file->DoNotRemove();
894*288bf522SAndroid Build Coastguard Worker     files_to_delete_.push_back(tmp_file->path);
895*288bf522SAndroid Build Coastguard Worker   }
896*288bf522SAndroid Build Coastguard Worker   return tmp_file;
897*288bf522SAndroid Build Coastguard Worker }
898*288bf522SAndroid Build Coastguard Worker 
RegisterTempFile(const std::string & path)899*288bf522SAndroid Build Coastguard Worker void ScopedTempFiles::RegisterTempFile(const std::string& path) {
900*288bf522SAndroid Build Coastguard Worker   files_to_delete_.emplace_back(path);
901*288bf522SAndroid Build Coastguard Worker }
902*288bf522SAndroid Build Coastguard Worker 
SignalIsIgnored(int signo)903*288bf522SAndroid Build Coastguard Worker bool SignalIsIgnored(int signo) {
904*288bf522SAndroid Build Coastguard Worker   struct sigaction act;
905*288bf522SAndroid Build Coastguard Worker   if (sigaction(signo, nullptr, &act) != 0) {
906*288bf522SAndroid Build Coastguard Worker     PLOG(FATAL) << "failed to query signal handler for signal " << signo;
907*288bf522SAndroid Build Coastguard Worker   }
908*288bf522SAndroid Build Coastguard Worker 
909*288bf522SAndroid Build Coastguard Worker   if ((act.sa_flags & SA_SIGINFO)) {
910*288bf522SAndroid Build Coastguard Worker     return false;
911*288bf522SAndroid Build Coastguard Worker   }
912*288bf522SAndroid Build Coastguard Worker 
913*288bf522SAndroid Build Coastguard Worker   return act.sa_handler == SIG_IGN;
914*288bf522SAndroid Build Coastguard Worker }
915*288bf522SAndroid Build Coastguard Worker 
GetAndroidVersion()916*288bf522SAndroid Build Coastguard Worker int GetAndroidVersion() {
917*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
918*288bf522SAndroid Build Coastguard Worker   static int android_version = -1;
919*288bf522SAndroid Build Coastguard Worker   if (android_version == -1) {
920*288bf522SAndroid Build Coastguard Worker     android_version = 0;
921*288bf522SAndroid Build Coastguard Worker 
922*288bf522SAndroid Build Coastguard Worker     auto parse_version = [&](const std::string& s) {
923*288bf522SAndroid Build Coastguard Worker       // The release string can be a list of numbers (like 8.1.0), a character (like Q)
924*288bf522SAndroid Build Coastguard Worker       // or many characters (like OMR1).
925*288bf522SAndroid Build Coastguard Worker       if (!s.empty()) {
926*288bf522SAndroid Build Coastguard Worker         // Each Android version has a version number: L is 5, M is 6, N is 7, O is 8, etc.
927*288bf522SAndroid Build Coastguard Worker         if (s[0] >= 'L' && s[0] <= 'V') {
928*288bf522SAndroid Build Coastguard Worker           android_version = s[0] - 'P' + kAndroidVersionP;
929*288bf522SAndroid Build Coastguard Worker         } else if (isdigit(s[0])) {
930*288bf522SAndroid Build Coastguard Worker           sscanf(s.c_str(), "%d", &android_version);
931*288bf522SAndroid Build Coastguard Worker         }
932*288bf522SAndroid Build Coastguard Worker       }
933*288bf522SAndroid Build Coastguard Worker     };
934*288bf522SAndroid Build Coastguard Worker     std::string s = android::base::GetProperty("ro.build.version.codename", "REL");
935*288bf522SAndroid Build Coastguard Worker     if (s != "REL") {
936*288bf522SAndroid Build Coastguard Worker       parse_version(s);
937*288bf522SAndroid Build Coastguard Worker     }
938*288bf522SAndroid Build Coastguard Worker     if (android_version == 0) {
939*288bf522SAndroid Build Coastguard Worker       s = android::base::GetProperty("ro.build.version.release", "");
940*288bf522SAndroid Build Coastguard Worker       parse_version(s);
941*288bf522SAndroid Build Coastguard Worker     }
942*288bf522SAndroid Build Coastguard Worker     if (android_version == 0) {
943*288bf522SAndroid Build Coastguard Worker       s = android::base::GetProperty("ro.build.version.sdk", "");
944*288bf522SAndroid Build Coastguard Worker       int sdk_version = 0;
945*288bf522SAndroid Build Coastguard Worker       const int SDK_VERSION_V = 35;
946*288bf522SAndroid Build Coastguard Worker       if (sscanf(s.c_str(), "%d", &sdk_version) == 1 && sdk_version >= SDK_VERSION_V) {
947*288bf522SAndroid Build Coastguard Worker         android_version = kAndroidVersionV;
948*288bf522SAndroid Build Coastguard Worker       }
949*288bf522SAndroid Build Coastguard Worker     }
950*288bf522SAndroid Build Coastguard Worker   }
951*288bf522SAndroid Build Coastguard Worker   return android_version;
952*288bf522SAndroid Build Coastguard Worker #else  // defined(__ANDROID__)
953*288bf522SAndroid Build Coastguard Worker   return 0;
954*288bf522SAndroid Build Coastguard Worker #endif
955*288bf522SAndroid Build Coastguard Worker }
956*288bf522SAndroid Build Coastguard Worker 
GetHardwareFromCpuInfo(const std::string & cpu_info)957*288bf522SAndroid Build Coastguard Worker std::string GetHardwareFromCpuInfo(const std::string& cpu_info) {
958*288bf522SAndroid Build Coastguard Worker   for (auto& line : android::base::Split(cpu_info, "\n")) {
959*288bf522SAndroid Build Coastguard Worker     size_t pos = line.find(':');
960*288bf522SAndroid Build Coastguard Worker     if (pos != std::string::npos) {
961*288bf522SAndroid Build Coastguard Worker       std::string key = android::base::Trim(line.substr(0, pos));
962*288bf522SAndroid Build Coastguard Worker       if (key == "Hardware") {
963*288bf522SAndroid Build Coastguard Worker         return android::base::Trim(line.substr(pos + 1));
964*288bf522SAndroid Build Coastguard Worker       }
965*288bf522SAndroid Build Coastguard Worker     }
966*288bf522SAndroid Build Coastguard Worker   }
967*288bf522SAndroid Build Coastguard Worker   return "";
968*288bf522SAndroid Build Coastguard Worker }
969*288bf522SAndroid Build Coastguard Worker 
MappedFileOnlyExistInMemory(const char * filename)970*288bf522SAndroid Build Coastguard Worker bool MappedFileOnlyExistInMemory(const char* filename) {
971*288bf522SAndroid Build Coastguard Worker   // Mapped files only existing in memory:
972*288bf522SAndroid Build Coastguard Worker   //   empty name
973*288bf522SAndroid Build Coastguard Worker   //   [anon:???]
974*288bf522SAndroid Build Coastguard Worker   //   [stack]
975*288bf522SAndroid Build Coastguard Worker   //   /dev/*
976*288bf522SAndroid Build Coastguard Worker   //   //anon: generated by kernel/events/core.c.
977*288bf522SAndroid Build Coastguard Worker   //   /memfd: created by memfd_create.
978*288bf522SAndroid Build Coastguard Worker   return filename[0] == '\0' || (filename[0] == '[' && strcmp(filename, "[vdso]") != 0) ||
979*288bf522SAndroid Build Coastguard Worker          strncmp(filename, "//", 2) == 0 || strncmp(filename, "/dev/", 5) == 0 ||
980*288bf522SAndroid Build Coastguard Worker          strncmp(filename, "/memfd:", 7) == 0;
981*288bf522SAndroid Build Coastguard Worker }
982*288bf522SAndroid Build Coastguard Worker 
GetCompleteProcessName(pid_t pid)983*288bf522SAndroid Build Coastguard Worker std::string GetCompleteProcessName(pid_t pid) {
984*288bf522SAndroid Build Coastguard Worker   std::string argv0;
985*288bf522SAndroid Build Coastguard Worker   if (!android::base::ReadFileToString("/proc/" + std::to_string(pid) + "/cmdline", &argv0)) {
986*288bf522SAndroid Build Coastguard Worker     // Maybe we don't have permission to read it.
987*288bf522SAndroid Build Coastguard Worker     return std::string();
988*288bf522SAndroid Build Coastguard Worker   }
989*288bf522SAndroid Build Coastguard Worker   size_t pos = argv0.find('\0');
990*288bf522SAndroid Build Coastguard Worker   if (pos != std::string::npos) {
991*288bf522SAndroid Build Coastguard Worker     argv0.resize(pos);
992*288bf522SAndroid Build Coastguard Worker   }
993*288bf522SAndroid Build Coastguard Worker   // argv0 can be empty if the process is in zombie state. In that case, we don't want to pass argv0
994*288bf522SAndroid Build Coastguard Worker   // to Basename(), which returns ".".
995*288bf522SAndroid Build Coastguard Worker   return argv0.empty() ? std::string() : android::base::Basename(argv0);
996*288bf522SAndroid Build Coastguard Worker }
997*288bf522SAndroid Build Coastguard Worker 
GetTraceFsDir()998*288bf522SAndroid Build Coastguard Worker const char* GetTraceFsDir() {
999*288bf522SAndroid Build Coastguard Worker   static const char* tracefs_dir = nullptr;
1000*288bf522SAndroid Build Coastguard Worker   if (tracefs_dir == nullptr) {
1001*288bf522SAndroid Build Coastguard Worker     for (const char* path : {"/sys/kernel/debug/tracing", "/sys/kernel/tracing"}) {
1002*288bf522SAndroid Build Coastguard Worker       if (IsDir(path)) {
1003*288bf522SAndroid Build Coastguard Worker         tracefs_dir = path;
1004*288bf522SAndroid Build Coastguard Worker         break;
1005*288bf522SAndroid Build Coastguard Worker       }
1006*288bf522SAndroid Build Coastguard Worker     }
1007*288bf522SAndroid Build Coastguard Worker   }
1008*288bf522SAndroid Build Coastguard Worker   return tracefs_dir;
1009*288bf522SAndroid Build Coastguard Worker }
1010*288bf522SAndroid Build Coastguard Worker 
GetKernelVersion()1011*288bf522SAndroid Build Coastguard Worker std::optional<std::pair<int, int>> GetKernelVersion() {
1012*288bf522SAndroid Build Coastguard Worker   static std::optional<std::pair<int, int>> kernel_version;
1013*288bf522SAndroid Build Coastguard Worker   if (!kernel_version.has_value()) {
1014*288bf522SAndroid Build Coastguard Worker     utsname uname_buf;
1015*288bf522SAndroid Build Coastguard Worker     int major;
1016*288bf522SAndroid Build Coastguard Worker     int minor;
1017*288bf522SAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0 ||
1018*288bf522SAndroid Build Coastguard Worker         sscanf(uname_buf.release, "%d.%d", &major, &minor) != 2) {
1019*288bf522SAndroid Build Coastguard Worker       return std::nullopt;
1020*288bf522SAndroid Build Coastguard Worker     }
1021*288bf522SAndroid Build Coastguard Worker     kernel_version = std::make_pair(major, minor);
1022*288bf522SAndroid Build Coastguard Worker   }
1023*288bf522SAndroid Build Coastguard Worker   return kernel_version;
1024*288bf522SAndroid Build Coastguard Worker }
1025*288bf522SAndroid Build Coastguard Worker 
1026*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
IsInAppUid()1027*288bf522SAndroid Build Coastguard Worker bool IsInAppUid() {
1028*288bf522SAndroid Build Coastguard Worker   return getuid() % AID_USER_OFFSET >= AID_APP_START;
1029*288bf522SAndroid Build Coastguard Worker }
1030*288bf522SAndroid Build Coastguard Worker #endif
1031*288bf522SAndroid Build Coastguard Worker 
GetProcessUid(pid_t pid)1032*288bf522SAndroid Build Coastguard Worker std::optional<uid_t> GetProcessUid(pid_t pid) {
1033*288bf522SAndroid Build Coastguard Worker   std::string status_file = "/proc/" + std::to_string(pid) + "/status";
1034*288bf522SAndroid Build Coastguard Worker   LineReader reader(status_file);
1035*288bf522SAndroid Build Coastguard Worker   if (!reader.Ok()) {
1036*288bf522SAndroid Build Coastguard Worker     return std::nullopt;
1037*288bf522SAndroid Build Coastguard Worker   }
1038*288bf522SAndroid Build Coastguard Worker 
1039*288bf522SAndroid Build Coastguard Worker   std::string* line;
1040*288bf522SAndroid Build Coastguard Worker   while ((line = reader.ReadLine()) != nullptr) {
1041*288bf522SAndroid Build Coastguard Worker     if (android::base::StartsWith(*line, "Uid:")) {
1042*288bf522SAndroid Build Coastguard Worker       uid_t uid;
1043*288bf522SAndroid Build Coastguard Worker       if (sscanf(line->data() + strlen("Uid:"), "%u", &uid) == 1) {
1044*288bf522SAndroid Build Coastguard Worker         return uid;
1045*288bf522SAndroid Build Coastguard Worker       }
1046*288bf522SAndroid Build Coastguard Worker     }
1047*288bf522SAndroid Build Coastguard Worker   }
1048*288bf522SAndroid Build Coastguard Worker   return std::nullopt;
1049*288bf522SAndroid Build Coastguard Worker }
1050*288bf522SAndroid Build Coastguard Worker 
1051*288bf522SAndroid Build Coastguard Worker namespace {
1052*288bf522SAndroid Build Coastguard Worker 
1053*288bf522SAndroid Build Coastguard Worker class CPUModelParser {
1054*288bf522SAndroid Build Coastguard Worker  public:
ParseARMCpuModel(const std::vector<std::string> & lines)1055*288bf522SAndroid Build Coastguard Worker   std::vector<CpuModel> ParseARMCpuModel(const std::vector<std::string>& lines) {
1056*288bf522SAndroid Build Coastguard Worker     std::vector<CpuModel> cpu_models;
1057*288bf522SAndroid Build Coastguard Worker     uint32_t processor = 0;
1058*288bf522SAndroid Build Coastguard Worker     CpuModel model;
1059*288bf522SAndroid Build Coastguard Worker     model.arch = "arm";
1060*288bf522SAndroid Build Coastguard Worker     int parsed = 0;
1061*288bf522SAndroid Build Coastguard Worker 
1062*288bf522SAndroid Build Coastguard Worker     auto line_callback = [&](const std::string& name, const std::string& value) {
1063*288bf522SAndroid Build Coastguard Worker       if (name == "processor" && android::base::ParseUint(value, &processor)) {
1064*288bf522SAndroid Build Coastguard Worker         parsed |= 1;
1065*288bf522SAndroid Build Coastguard Worker       } else if (name == "CPU implementer" &&
1066*288bf522SAndroid Build Coastguard Worker                  android::base::ParseUint(value, &model.arm_data.implementer)) {
1067*288bf522SAndroid Build Coastguard Worker         parsed |= 2;
1068*288bf522SAndroid Build Coastguard Worker       } else if (name == "CPU part" && android::base::ParseUint(value, &model.arm_data.partnum) &&
1069*288bf522SAndroid Build Coastguard Worker                  parsed == 0x3) {
1070*288bf522SAndroid Build Coastguard Worker         AddCpuModel(processor, model, cpu_models);
1071*288bf522SAndroid Build Coastguard Worker         parsed = 0;
1072*288bf522SAndroid Build Coastguard Worker       }
1073*288bf522SAndroid Build Coastguard Worker     };
1074*288bf522SAndroid Build Coastguard Worker     ProcessLines(lines, line_callback);
1075*288bf522SAndroid Build Coastguard Worker     return cpu_models;
1076*288bf522SAndroid Build Coastguard Worker   }
1077*288bf522SAndroid Build Coastguard Worker 
ParseRISCVCpuModel(const std::vector<std::string> & lines)1078*288bf522SAndroid Build Coastguard Worker   std::vector<CpuModel> ParseRISCVCpuModel(const std::vector<std::string>& lines) {
1079*288bf522SAndroid Build Coastguard Worker     std::vector<CpuModel> cpu_models;
1080*288bf522SAndroid Build Coastguard Worker     uint32_t processor = 0;
1081*288bf522SAndroid Build Coastguard Worker     CpuModel model;
1082*288bf522SAndroid Build Coastguard Worker     model.arch = "riscv";
1083*288bf522SAndroid Build Coastguard Worker     int parsed = 0;
1084*288bf522SAndroid Build Coastguard Worker 
1085*288bf522SAndroid Build Coastguard Worker     auto line_callback = [&](const std::string& name, const std::string& value) {
1086*288bf522SAndroid Build Coastguard Worker       if (name == "processor" && android::base::ParseUint(value, &processor)) {
1087*288bf522SAndroid Build Coastguard Worker         parsed |= 1;
1088*288bf522SAndroid Build Coastguard Worker       } else if (name == "mvendorid" &&
1089*288bf522SAndroid Build Coastguard Worker                  android::base::ParseUint(value, &model.riscv_data.mvendorid)) {
1090*288bf522SAndroid Build Coastguard Worker         parsed |= 2;
1091*288bf522SAndroid Build Coastguard Worker       } else if (name == "marchid" && android::base::ParseUint(value, &model.riscv_data.marchid)) {
1092*288bf522SAndroid Build Coastguard Worker         parsed |= 4;
1093*288bf522SAndroid Build Coastguard Worker       } else if (name == "mimpid" && android::base::ParseUint(value, &model.riscv_data.mimpid) &&
1094*288bf522SAndroid Build Coastguard Worker                  parsed == 0x7) {
1095*288bf522SAndroid Build Coastguard Worker         AddCpuModel(processor, model, cpu_models);
1096*288bf522SAndroid Build Coastguard Worker         parsed = 0;
1097*288bf522SAndroid Build Coastguard Worker       }
1098*288bf522SAndroid Build Coastguard Worker     };
1099*288bf522SAndroid Build Coastguard Worker     ProcessLines(lines, line_callback);
1100*288bf522SAndroid Build Coastguard Worker     return cpu_models;
1101*288bf522SAndroid Build Coastguard Worker   }
1102*288bf522SAndroid Build Coastguard Worker 
ParseX86CpuModel(const std::vector<std::string> & lines)1103*288bf522SAndroid Build Coastguard Worker   std::vector<CpuModel> ParseX86CpuModel(const std::vector<std::string>& lines) {
1104*288bf522SAndroid Build Coastguard Worker     std::vector<CpuModel> cpu_models;
1105*288bf522SAndroid Build Coastguard Worker     uint32_t processor = 0;
1106*288bf522SAndroid Build Coastguard Worker     CpuModel model;
1107*288bf522SAndroid Build Coastguard Worker     model.arch = "x86";
1108*288bf522SAndroid Build Coastguard Worker     int parsed = 0;
1109*288bf522SAndroid Build Coastguard Worker 
1110*288bf522SAndroid Build Coastguard Worker     auto line_callback = [&](const std::string& name, const std::string& value) {
1111*288bf522SAndroid Build Coastguard Worker       if (name == "processor" && android::base::ParseUint(value, &processor)) {
1112*288bf522SAndroid Build Coastguard Worker         parsed |= 1;
1113*288bf522SAndroid Build Coastguard Worker       } else if (name == "vendor_id") {
1114*288bf522SAndroid Build Coastguard Worker         model.x86_data.vendor_id = value;
1115*288bf522SAndroid Build Coastguard Worker         AddCpuModel(processor, model, cpu_models);
1116*288bf522SAndroid Build Coastguard Worker         parsed = 0;
1117*288bf522SAndroid Build Coastguard Worker       }
1118*288bf522SAndroid Build Coastguard Worker     };
1119*288bf522SAndroid Build Coastguard Worker     ProcessLines(lines, line_callback);
1120*288bf522SAndroid Build Coastguard Worker     return cpu_models;
1121*288bf522SAndroid Build Coastguard Worker   }
1122*288bf522SAndroid Build Coastguard Worker 
1123*288bf522SAndroid Build Coastguard Worker  private:
ProcessLines(const std::vector<std::string> & lines,const std::function<void (const std::string &,const std::string &)> & callback)1124*288bf522SAndroid Build Coastguard Worker   void ProcessLines(const std::vector<std::string>& lines,
1125*288bf522SAndroid Build Coastguard Worker                     const std::function<void(const std::string&, const std::string&)>& callback) {
1126*288bf522SAndroid Build Coastguard Worker     for (const auto& line : lines) {
1127*288bf522SAndroid Build Coastguard Worker       std::vector<std::string> strs = android::base::Split(line, ":");
1128*288bf522SAndroid Build Coastguard Worker       if (strs.size() != 2) {
1129*288bf522SAndroid Build Coastguard Worker         continue;
1130*288bf522SAndroid Build Coastguard Worker       }
1131*288bf522SAndroid Build Coastguard Worker       std::string name = android::base::Trim(strs[0]);
1132*288bf522SAndroid Build Coastguard Worker       std::string value = android::base::Trim(strs[1]);
1133*288bf522SAndroid Build Coastguard Worker       callback(name, value);
1134*288bf522SAndroid Build Coastguard Worker     }
1135*288bf522SAndroid Build Coastguard Worker   }
1136*288bf522SAndroid Build Coastguard Worker 
AddCpuModel(uint32_t processor,const CpuModel & model,std::vector<CpuModel> & cpu_models)1137*288bf522SAndroid Build Coastguard Worker   void AddCpuModel(uint32_t processor, const CpuModel& model, std::vector<CpuModel>& cpu_models) {
1138*288bf522SAndroid Build Coastguard Worker     for (auto& m : cpu_models) {
1139*288bf522SAndroid Build Coastguard Worker       if (model.arch == "arm") {
1140*288bf522SAndroid Build Coastguard Worker         if (model.arm_data.implementer == m.arm_data.implementer &&
1141*288bf522SAndroid Build Coastguard Worker             model.arm_data.partnum == m.arm_data.partnum) {
1142*288bf522SAndroid Build Coastguard Worker           m.cpus.push_back(processor);
1143*288bf522SAndroid Build Coastguard Worker           return;
1144*288bf522SAndroid Build Coastguard Worker         }
1145*288bf522SAndroid Build Coastguard Worker       } else if (model.arch == "riscv") {
1146*288bf522SAndroid Build Coastguard Worker         if (model.riscv_data.mvendorid == m.riscv_data.mvendorid &&
1147*288bf522SAndroid Build Coastguard Worker             model.riscv_data.marchid == m.riscv_data.marchid &&
1148*288bf522SAndroid Build Coastguard Worker             model.riscv_data.mimpid == m.riscv_data.mimpid) {
1149*288bf522SAndroid Build Coastguard Worker           m.cpus.push_back(processor);
1150*288bf522SAndroid Build Coastguard Worker           return;
1151*288bf522SAndroid Build Coastguard Worker         }
1152*288bf522SAndroid Build Coastguard Worker       } else if (model.arch == "x86") {
1153*288bf522SAndroid Build Coastguard Worker         if (model.x86_data.vendor_id == m.x86_data.vendor_id) {
1154*288bf522SAndroid Build Coastguard Worker           m.cpus.push_back(processor);
1155*288bf522SAndroid Build Coastguard Worker           return;
1156*288bf522SAndroid Build Coastguard Worker         }
1157*288bf522SAndroid Build Coastguard Worker       }
1158*288bf522SAndroid Build Coastguard Worker     }
1159*288bf522SAndroid Build Coastguard Worker     cpu_models.push_back(model);
1160*288bf522SAndroid Build Coastguard Worker     cpu_models.back().cpus.push_back(processor);
1161*288bf522SAndroid Build Coastguard Worker   }
1162*288bf522SAndroid Build Coastguard Worker };
1163*288bf522SAndroid Build Coastguard Worker 
1164*288bf522SAndroid Build Coastguard Worker }  // namespace
1165*288bf522SAndroid Build Coastguard Worker 
GetCpuModels()1166*288bf522SAndroid Build Coastguard Worker std::vector<CpuModel> GetCpuModels() {
1167*288bf522SAndroid Build Coastguard Worker   std::string data;
1168*288bf522SAndroid Build Coastguard Worker   if (!android::base::ReadFileToString("/proc/cpuinfo", &data)) {
1169*288bf522SAndroid Build Coastguard Worker     return {};
1170*288bf522SAndroid Build Coastguard Worker   }
1171*288bf522SAndroid Build Coastguard Worker   std::vector<std::string> lines = android::base::Split(data, "\n");
1172*288bf522SAndroid Build Coastguard Worker   CPUModelParser parser;
1173*288bf522SAndroid Build Coastguard Worker #if defined(__aarch64__) || defined(__arm__)
1174*288bf522SAndroid Build Coastguard Worker   return parser.ParseARMCpuModel(lines);
1175*288bf522SAndroid Build Coastguard Worker #elif defined(__riscv)
1176*288bf522SAndroid Build Coastguard Worker   return parser.ParseRISCVCpuModel(lines);
1177*288bf522SAndroid Build Coastguard Worker #elif defined(__x86_64__) || defined(__i386__)
1178*288bf522SAndroid Build Coastguard Worker   return parser.ParseX86CpuModel(lines);
1179*288bf522SAndroid Build Coastguard Worker #else
1180*288bf522SAndroid Build Coastguard Worker   return {};
1181*288bf522SAndroid Build Coastguard Worker #endif
1182*288bf522SAndroid Build Coastguard Worker }
1183*288bf522SAndroid Build Coastguard Worker 
1184*288bf522SAndroid Build Coastguard Worker }  // namespace simpleperf
1185