blob: 8e95d449869ffd90d83ee3ee27441a097d220c35 [file] [log] [blame]
Yabin Cui323e9452015-04-20 18:07:17 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "environment.h"
18
Yabin Cui7d59bb42015-05-04 20:27:57 -070019#include <inttypes.h>
Yabin Cuia80f8f72017-07-12 15:50:20 -070020#include <signal.h>
Yabin Cui7d59bb42015-05-04 20:27:57 -070021#include <stdio.h>
Yabin Cui323e9452015-04-20 18:07:17 -070022#include <stdlib.h>
Yabin Cui2db05b42018-07-16 14:04:49 -070023#include <string.h>
Yabin Cui7c5fe4e2017-12-05 17:44:05 -080024#include <sys/resource.h>
Yabin Cui0a7a06d2016-10-28 13:27:41 -070025#include <sys/utsname.h>
Yabin Cui554f3bb2021-05-05 13:34:59 -070026#include <unistd.h>
Yabin Cuic8485602015-08-20 15:04:39 -070027
28#include <limits>
Yabin Cuicb4c17e2015-10-26 16:15:29 -070029#include <set>
Yabin Cui7d59bb42015-05-04 20:27:57 -070030#include <unordered_map>
Yabin Cui323e9452015-04-20 18:07:17 -070031#include <vector>
32
Elliott Hughes66dd09e2015-12-04 14:00:57 -080033#include <android-base/file.h>
34#include <android-base/logging.h>
Yabin Cui569f64a2016-02-05 17:32:08 -080035#include <android-base/parseint.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080036#include <android-base/stringprintf.h>
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +020037#include <android-base/strings.h>
Yabin Cui7e5aa132016-11-16 22:47:53 +000038#include <procinfo/process.h>
Yabin Cui4f79dc82018-05-09 18:25:25 -070039#include <procinfo/process_map.h>
Yabin Cui323e9452015-04-20 18:07:17 -070040
Yabin Cuiebf79f32016-06-01 15:39:39 -070041#if defined(__ANDROID__)
Yabin Cui80a1e122017-08-11 14:52:51 -070042#include <android-base/properties.h>
Yabin Cui3485af92021-10-27 10:50:53 -070043#include <cutils/android_filesystem_config.h>
Yabin Cuiebf79f32016-06-01 15:39:39 -070044#endif
45
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +020046#include "IOEventLoop.h"
Yabin Cuia556c562020-02-14 16:50:10 -080047#include "command.h"
Yabin Cuif8974522017-07-17 14:36:37 -070048#include "event_type.h"
Thiébaud Weksteene7e750e2020-11-19 15:07:46 +010049#include "kallsyms.h"
Yabin Cui8f622512015-05-05 19:58:07 -070050#include "read_elf.h"
Yabin Cui003b2452016-09-29 15:32:45 -070051#include "thread_tree.h"
Yabin Cui323e9452015-04-20 18:07:17 -070052#include "utils.h"
Yabin Cuia80f8f72017-07-12 15:50:20 -070053#include "workload.h"
Yabin Cui323e9452015-04-20 18:07:17 -070054
Yabin Cuifaa7b922021-01-11 17:35:57 -080055namespace simpleperf {
Yabin Cuia556c562020-02-14 16:50:10 -080056
Yabin Cui323e9452015-04-20 18:07:17 -070057std::vector<int> GetOnlineCpus() {
58 std::vector<int> result;
Yabin Cui40eef9e2021-04-13 13:08:31 -070059 LineReader reader("/sys/devices/system/cpu/online");
60 if (!reader.Ok()) {
Yabin Cui323e9452015-04-20 18:07:17 -070061 PLOG(ERROR) << "can't open online cpu information";
62 return result;
63 }
64
Yabin Cui40eef9e2021-04-13 13:08:31 -070065 std::string* line;
Yabin Cui323e9452015-04-20 18:07:17 -070066 if ((line = reader.ReadLine()) != nullptr) {
Yabin Cui40eef9e2021-04-13 13:08:31 -070067 if (auto cpus = GetCpusFromString(*line); cpus) {
Yabin Cuie3ca9982020-10-16 13:16:26 -070068 result.assign(cpus->begin(), cpus->end());
69 }
Yabin Cui323e9452015-04-20 18:07:17 -070070 }
71 CHECK(!result.empty()) << "can't get online cpu information";
72 return result;
73}
74
Yabin Cui7d59bb42015-05-04 20:27:57 -070075static void GetAllModuleFiles(const std::string& path,
76 std::unordered_map<std::string, std::string>* module_file_map) {
Yabin Cui07865862016-08-22 13:39:19 -070077 for (const auto& name : GetEntriesInDir(path)) {
78 std::string entry_path = path + "/" + name;
79 if (IsRegularFile(entry_path) && android::base::EndsWith(name, ".ko")) {
Yabin Cui7d59bb42015-05-04 20:27:57 -070080 std::string module_name = name.substr(0, name.size() - 3);
81 std::replace(module_name.begin(), module_name.end(), '-', '_');
Yabin Cui07865862016-08-22 13:39:19 -070082 module_file_map->insert(std::make_pair(module_name, entry_path));
83 } else if (IsDir(entry_path)) {
84 GetAllModuleFiles(entry_path, module_file_map);
Yabin Cui7d59bb42015-05-04 20:27:57 -070085 }
86 }
Yabin Cui7d59bb42015-05-04 20:27:57 -070087}
88
Yabin Cui7134f382016-03-25 17:43:43 -070089static std::vector<KernelMmap> GetModulesInUse() {
Yabin Cuib068c102017-11-01 17:53:10 -070090 std::vector<KernelMmap> module_mmaps = GetLoadedModules();
91 if (module_mmaps.empty()) {
92 return std::vector<KernelMmap>();
93 }
94 std::unordered_map<std::string, std::string> module_file_map;
95#if defined(__ANDROID__)
96 // Search directories listed in "File locations" section in
97 // https://source.android.com/devices/architecture/kernel/modular-kernels.
98 for (const auto& path : {"/vendor/lib/modules", "/odm/lib/modules", "/lib/modules"}) {
99 GetAllModuleFiles(path, &module_file_map);
100 }
101#else
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700102 utsname uname_buf;
103 if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
104 PLOG(ERROR) << "uname() failed";
105 return std::vector<KernelMmap>();
106 }
107 std::string linux_version = uname_buf.release;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700108 std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
Yabin Cui7d59bb42015-05-04 20:27:57 -0700109 GetAllModuleFiles(module_dirpath, &module_file_map);
Yabin Cuib068c102017-11-01 17:53:10 -0700110#endif
Yabin Cui7d59bb42015-05-04 20:27:57 -0700111 for (auto& module : module_mmaps) {
112 auto it = module_file_map.find(module.name);
113 if (it != module_file_map.end()) {
114 module.filepath = it->second;
115 }
116 }
117 return module_mmaps;
118}
119
Yabin Cui7134f382016-03-25 17:43:43 -0700120void GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<KernelMmap>* module_mmaps) {
Yabin Cui7d59bb42015-05-04 20:27:57 -0700121 kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
Yabin Cui7134f382016-03-25 17:43:43 -0700122 kernel_mmap->start_addr = 0;
Yabin Cuib068c102017-11-01 17:53:10 -0700123 kernel_mmap->len = std::numeric_limits<uint64_t>::max();
Yabin Cuic13ff892020-11-10 13:11:01 -0800124 if (uint64_t kstart_addr = GetKernelStartAddress(); kstart_addr != 0) {
125 kernel_mmap->name = std::string(DEFAULT_KERNEL_MMAP_NAME) + "_stext";
126 kernel_mmap->start_addr = kstart_addr;
127 kernel_mmap->len = std::numeric_limits<uint64_t>::max() - kstart_addr;
128 }
Yabin Cui7134f382016-03-25 17:43:43 -0700129 kernel_mmap->filepath = kernel_mmap->name;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700130 *module_mmaps = GetModulesInUse();
Yabin Cui7134f382016-03-25 17:43:43 -0700131 for (auto& map : *module_mmaps) {
132 if (map.filepath.empty()) {
133 map.filepath = "[" + map.name + "]";
134 }
135 }
Yabin Cui7d59bb42015-05-04 20:27:57 -0700136}
137
Yabin Cuidc2708c2020-01-10 15:33:11 -0800138bool ReadThreadNameAndPid(pid_t tid, std::string* comm, pid_t* pid) {
Yabin Cui7e5aa132016-11-16 22:47:53 +0000139 android::procinfo::ProcessInfo procinfo;
140 if (!android::procinfo::GetProcessInfo(tid, &procinfo)) {
Yabin Cui7d59bb42015-05-04 20:27:57 -0700141 return false;
142 }
Yabin Cui7e5aa132016-11-16 22:47:53 +0000143 if (comm != nullptr) {
144 *comm = procinfo.name;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700145 }
Yabin Cui7e5aa132016-11-16 22:47:53 +0000146 if (pid != nullptr) {
147 *pid = procinfo.pid;
148 }
149 return true;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700150}
151
Yabin Cuibc2a1022016-08-29 12:33:17 -0700152std::vector<pid_t> GetThreadsInProcess(pid_t pid) {
Yabin Cuib032de72015-06-17 21:15:09 -0700153 std::vector<pid_t> result;
Yabin Cui7e5aa132016-11-16 22:47:53 +0000154 android::procinfo::GetProcessTids(pid, &result);
Yabin Cuib032de72015-06-17 21:15:09 -0700155 return result;
156}
157
Yabin Cui5f43fc42016-12-13 13:47:49 -0800158bool IsThreadAlive(pid_t tid) {
159 return IsDir(android::base::StringPrintf("/proc/%d", tid));
160}
161
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700162bool GetProcessForThread(pid_t tid, pid_t* pid) {
163 return ReadThreadNameAndPid(tid, nullptr, pid);
Yabin Cui7d59bb42015-05-04 20:27:57 -0700164}
165
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700166bool GetThreadName(pid_t tid, std::string* name) {
167 return ReadThreadNameAndPid(tid, name, nullptr);
168}
169
170std::vector<pid_t> GetAllProcesses() {
171 std::vector<pid_t> result;
172 std::vector<std::string> entries = GetEntriesInDir("/proc");
173 for (const auto& entry : entries) {
174 pid_t pid;
175 if (!android::base::ParseInt(entry.c_str(), &pid, 0)) {
Yabin Cui7d59bb42015-05-04 20:27:57 -0700176 continue;
177 }
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700178 result.push_back(pid);
Yabin Cui7d59bb42015-05-04 20:27:57 -0700179 }
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700180 return result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700181}
182
183bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
Yabin Cui7d59bb42015-05-04 20:27:57 -0700184 thread_mmaps->clear();
Yabin Cui58740ff2021-03-23 13:34:51 -0700185 return android::procinfo::ReadProcessMaps(pid, [&](const android::procinfo::MapInfo& mapinfo) {
186 thread_mmaps->emplace_back(mapinfo.start, mapinfo.end - mapinfo.start, mapinfo.pgoff,
187 mapinfo.name.c_str(), mapinfo.flags);
188 });
Yabin Cui7d59bb42015-05-04 20:27:57 -0700189}
Yabin Cui8f622512015-05-05 19:58:07 -0700190
191bool GetKernelBuildId(BuildId* build_id) {
Yabin Cuidec43c12016-07-29 16:40:40 -0700192 ElfStatus result = GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
193 if (result != ElfStatus::NO_ERROR) {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700194 LOG(DEBUG) << "failed to read /sys/kernel/notes: " << result;
Yabin Cuidec43c12016-07-29 16:40:40 -0700195 }
196 return result == ElfStatus::NO_ERROR;
Yabin Cui8f622512015-05-05 19:58:07 -0700197}
198
Yabin Cuiea105c82020-07-22 13:01:31 -0700199bool GetModuleBuildId(const std::string& module_name, BuildId* build_id,
200 const std::string& sysfs_dir) {
201 std::string notefile = sysfs_dir + "/module/" + module_name + "/notes/.note.gnu.build-id";
202 return GetBuildIdFromNoteFile(notefile, build_id) == ElfStatus::NO_ERROR;
Yabin Cui8f622512015-05-05 19:58:07 -0700203}
Yabin Cuib032de72015-06-17 21:15:09 -0700204
Yabin Cuiebf79f32016-06-01 15:39:39 -0700205/*
Yabin Cui17cffbb2020-07-28 17:11:39 -0700206 * perf event allow level:
207 * -1 - everything allowed
Yabin Cuiebf79f32016-06-01 15:39:39 -0700208 * 0 - disallow raw tracepoint access for unpriv
209 * 1 - disallow cpu events for unpriv
210 * 2 - disallow kernel profiling for unpriv
211 * 3 - disallow user profiling for unpriv
212 */
Yabin Cui17cffbb2020-07-28 17:11:39 -0700213static const char* perf_event_allow_path = "/proc/sys/kernel/perf_event_paranoid";
214
215static bool ReadPerfEventAllowStatus(int* value) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700216 std::string s;
Yabin Cui17cffbb2020-07-28 17:11:39 -0700217 if (!android::base::ReadFileToString(perf_event_allow_path, &s)) {
218 PLOG(DEBUG) << "failed to read " << perf_event_allow_path;
Yabin Cuiebf79f32016-06-01 15:39:39 -0700219 return false;
220 }
221 s = android::base::Trim(s);
222 if (!android::base::ParseInt(s.c_str(), value)) {
Yabin Cui17cffbb2020-07-28 17:11:39 -0700223 PLOG(ERROR) << "failed to parse " << perf_event_allow_path << ": " << s;
Yabin Cuiebf79f32016-06-01 15:39:39 -0700224 return false;
225 }
226 return true;
227}
228
Yabin Cuif8974522017-07-17 14:36:37 -0700229bool CanRecordRawData() {
Yabin Cuic3a9bf12020-02-27 16:55:38 -0800230 if (IsRoot()) {
231 return true;
Yabin Cuia5697762020-01-13 14:48:01 -0800232 }
Yabin Cuic3a9bf12020-02-27 16:55:38 -0800233#if defined(__ANDROID__)
Yabin Cuic98cb112020-04-06 16:26:41 -0700234 // Android R uses selinux to control perf_event_open. Whether raw data can be recorded is hard
235 // to check unless we really try it. And probably there is no need to record raw data in non-root
236 // users.
237 return false;
238#else
239 int value;
Yabin Cui17cffbb2020-07-28 17:11:39 -0700240 return ReadPerfEventAllowStatus(&value) && value == -1;
Yabin Cuic3a9bf12020-02-27 16:55:38 -0800241#endif
Yabin Cuif8974522017-07-17 14:36:37 -0700242}
243
Yabin Cuiebf79f32016-06-01 15:39:39 -0700244static const char* GetLimitLevelDescription(int limit_level) {
245 switch (limit_level) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200246 case -1:
247 return "unlimited";
248 case 0:
249 return "disallowing raw tracepoint access for unpriv";
250 case 1:
251 return "disallowing cpu events for unpriv";
252 case 2:
253 return "disallowing kernel profiling for unpriv";
254 case 3:
255 return "disallowing user profiling for unpriv";
256 default:
257 return "unknown level";
Yabin Cuiebf79f32016-06-01 15:39:39 -0700258 }
259}
260
261bool CheckPerfEventLimit() {
Yabin Cui17cffbb2020-07-28 17:11:39 -0700262 // Root is not limited by perf_event_allow_path. However, the monitored threads
Yabin Cui1137a8c2017-06-01 13:23:29 -0700263 // may create child processes not running as root. To make sure the child processes have
Yabin Cui17cffbb2020-07-28 17:11:39 -0700264 // enough permission to create inherited tracepoint events, write -1 to perf_event_allow_path.
Yabin Cui1137a8c2017-06-01 13:23:29 -0700265 // See http://b/62230699.
Yabin Cui5edb7fc2018-08-29 14:54:19 -0700266 if (IsRoot()) {
Yabin Cuic765ccb2021-02-23 15:53:09 -0800267 if (android::base::WriteStringToFile("-1", perf_event_allow_path)) {
268 return true;
269 }
270 // On host, we may not be able to write to perf_event_allow_path (like when running in docker).
271#if defined(__ANDROID__)
272 PLOG(ERROR) << "failed to write -1 to " << perf_event_allow_path;
273 return false;
274#endif
Yabin Cui4f41df62016-06-01 17:29:06 -0700275 }
Yabin Cuiebf79f32016-06-01 15:39:39 -0700276 int limit_level;
Yabin Cui17cffbb2020-07-28 17:11:39 -0700277 bool can_read_allow_file = ReadPerfEventAllowStatus(&limit_level);
278 if (can_read_allow_file && limit_level <= 1) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700279 return true;
280 }
281#if defined(__ANDROID__)
Yabin Cui80a1e122017-08-11 14:52:51 -0700282 const std::string prop_name = "security.perf_harden";
283 std::string prop_value = android::base::GetProperty(prop_name, "");
284 if (prop_value.empty()) {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700285 // can't do anything if there is no such property.
286 return true;
287 }
Yabin Cui80a1e122017-08-11 14:52:51 -0700288 if (prop_value == "0") {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700289 return true;
290 }
Yabin Cui17cffbb2020-07-28 17:11:39 -0700291 // Try to enable perf events by setprop security.perf_harden=0.
Yabin Cui80a1e122017-08-11 14:52:51 -0700292 if (android::base::SetProperty(prop_name, "0")) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700293 sleep(1);
Yabin Cui17cffbb2020-07-28 17:11:39 -0700294 if (can_read_allow_file && ReadPerfEventAllowStatus(&limit_level) && limit_level <= 1) {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700295 return true;
296 }
Yabin Cui80a1e122017-08-11 14:52:51 -0700297 if (android::base::GetProperty(prop_name, "") == "0") {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700298 return true;
299 }
300 }
Yabin Cui17cffbb2020-07-28 17:11:39 -0700301 if (can_read_allow_file) {
302 LOG(WARNING) << perf_event_allow_path << " is " << limit_level << ", "
303 << GetLimitLevelDescription(limit_level) << ".";
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700304 }
Yabin Cuiebf79f32016-06-01 15:39:39 -0700305 LOG(WARNING) << "Try using `adb shell setprop security.perf_harden 0` to allow profiling.";
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700306 return false;
Yabin Cuiebf79f32016-06-01 15:39:39 -0700307#else
Yabin Cui17cffbb2020-07-28 17:11:39 -0700308 if (can_read_allow_file) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200309 LOG(WARNING) << perf_event_allow_path << " is " << limit_level << ", "
310 << GetLimitLevelDescription(limit_level) << ".";
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700311 return false;
312 }
Yabin Cuiebf79f32016-06-01 15:39:39 -0700313#endif
314 return true;
315}
Yabin Cuib8915492016-06-22 12:43:09 -0700316
Yabin Cui6e173a42018-08-13 15:58:25 -0700317#if defined(__ANDROID__)
318static bool SetProperty(const char* prop_name, uint64_t value) {
319 if (!android::base::SetProperty(prop_name, std::to_string(value))) {
320 LOG(ERROR) << "Failed to SetProperty " << prop_name << " to " << value;
Yabin Cui0720d482017-03-06 17:05:50 -0800321 return false;
322 }
323 return true;
324}
325
Yabin Cui6e173a42018-08-13 15:58:25 -0700326bool SetPerfEventLimits(uint64_t sample_freq, size_t cpu_percent, uint64_t mlock_kb) {
327 if (!SetProperty("debug.perf_event_max_sample_rate", sample_freq) ||
328 !SetProperty("debug.perf_cpu_time_max_percent", cpu_percent) ||
329 !SetProperty("debug.perf_event_mlock_kb", mlock_kb) ||
330 !SetProperty("security.perf_harden", 0)) {
331 return false;
332 }
333 // Wait for init process to change perf event limits based on properties.
334 const size_t max_wait_us = 3 * 1000000;
335 int finish_mask = 0;
336 for (size_t i = 0; i < max_wait_us && finish_mask != 7; ++i) {
337 usleep(1); // Wait 1us to avoid busy loop.
338 if ((finish_mask & 1) == 0) {
339 uint64_t freq;
340 if (!GetMaxSampleFrequency(&freq) || freq == sample_freq) {
341 finish_mask |= 1;
342 }
343 }
344 if ((finish_mask & 2) == 0) {
345 size_t percent;
346 if (!GetCpuTimeMaxPercent(&percent) || percent == cpu_percent) {
347 finish_mask |= 2;
348 }
349 }
350 if ((finish_mask & 4) == 0) {
351 uint64_t kb;
352 if (!GetPerfEventMlockKb(&kb) || kb == mlock_kb) {
353 finish_mask |= 4;
354 }
355 }
356 }
357 if (finish_mask != 7) {
358 LOG(WARNING) << "Wait setting perf event limits timeout";
359 }
360 return true;
361}
362#else // !defined(__ANDROID__)
363bool SetPerfEventLimits(uint64_t, size_t, uint64_t) {
364 return true;
365}
366#endif
367
368template <typename T>
369static bool ReadUintFromProcFile(const std::string& path, T* value) {
370 std::string s;
371 if (!android::base::ReadFileToString(path, &s)) {
372 PLOG(DEBUG) << "failed to read " << path;
373 return false;
374 }
375 s = android::base::Trim(s);
376 if (!android::base::ParseUint(s.c_str(), value)) {
377 LOG(ERROR) << "failed to parse " << path << ": " << s;
378 return false;
379 }
380 return true;
381}
382
383template <typename T>
384static bool WriteUintToProcFile(const std::string& path, T value) {
385 if (IsRoot()) {
386 return android::base::WriteStringToFile(std::to_string(value), path);
387 }
388 return false;
389}
390
391bool GetMaxSampleFrequency(uint64_t* max_sample_freq) {
392 return ReadUintFromProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
393}
394
395bool SetMaxSampleFrequency(uint64_t max_sample_freq) {
396 return WriteUintToProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
397}
398
399bool GetCpuTimeMaxPercent(size_t* percent) {
400 return ReadUintFromProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
401}
402
403bool SetCpuTimeMaxPercent(size_t percent) {
404 return WriteUintToProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
405}
406
407bool GetPerfEventMlockKb(uint64_t* mlock_kb) {
408 return ReadUintFromProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
409}
410
411bool SetPerfEventMlockKb(uint64_t mlock_kb) {
412 return WriteUintToProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
413}
414
Yabin Cui417df292016-11-16 12:26:13 -0800415ArchType GetMachineArch() {
Yabin Cuif227b6d2021-01-06 14:01:53 -0800416#if defined(__i386__)
417 // For 32 bit x86 build, we can't get machine arch by uname().
418 ArchType arch = ARCH_UNSUPPORTED;
419 std::unique_ptr<FILE, decltype(&pclose)> fp(popen("uname -m", "re"), pclose);
420 if (fp) {
421 char machine[40];
422 if (fgets(machine, sizeof(machine), fp.get()) == machine) {
423 arch = GetArchType(android::base::Trim(machine));
424 }
425 }
426#else
Yabin Cui417df292016-11-16 12:26:13 -0800427 utsname uname_buf;
428 if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
429 PLOG(WARNING) << "uname() failed";
Yabin Cui38076912021-08-16 16:59:09 -0700430 return GetTargetArch();
Yabin Cui417df292016-11-16 12:26:13 -0800431 }
432 ArchType arch = GetArchType(uname_buf.machine);
Yabin Cuif227b6d2021-01-06 14:01:53 -0800433#endif
Yabin Cui417df292016-11-16 12:26:13 -0800434 if (arch != ARCH_UNSUPPORTED) {
435 return arch;
436 }
Yabin Cui38076912021-08-16 16:59:09 -0700437 return GetTargetArch();
Yabin Cui417df292016-11-16 12:26:13 -0800438}
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700439
440void PrepareVdsoFile() {
441 // vdso is an elf file in memory loaded in each process's user space by the kernel. To read
442 // symbols from it and unwind through it, we need to dump it into a file in storage.
443 // It doesn't affect much when failed to prepare vdso file, so there is no need to return values.
444 std::vector<ThreadMmap> thread_mmaps;
445 if (!GetThreadMmapsInProcess(getpid(), &thread_mmaps)) {
446 return;
447 }
448 const ThreadMmap* vdso_map = nullptr;
449 for (const auto& map : thread_mmaps) {
450 if (map.name == "[vdso]") {
451 vdso_map = &map;
452 break;
453 }
454 }
455 if (vdso_map == nullptr) {
456 return;
457 }
458 std::string s(vdso_map->len, '\0');
459 memcpy(&s[0], reinterpret_cast<void*>(static_cast<uintptr_t>(vdso_map->start_addr)),
460 vdso_map->len);
Yabin Cuic68e66d2018-03-07 15:47:15 -0800461 std::unique_ptr<TemporaryFile> tmpfile = ScopedTempFiles::CreateTempFile();
462 if (!android::base::WriteStringToFd(s, tmpfile->fd)) {
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700463 return;
464 }
Yabin Cuic68e66d2018-03-07 15:47:15 -0800465 Dso::SetVdsoFile(tmpfile->path, sizeof(size_t) == sizeof(uint64_t));
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700466}
Yabin Cuia80f8f72017-07-12 15:50:20 -0700467
Yabin Cui88387692017-08-28 15:49:33 -0700468static bool HasOpenedAppApkFile(int pid) {
469 std::string fd_path = "/proc/" + std::to_string(pid) + "/fd/";
470 std::vector<std::string> files = GetEntriesInDir(fd_path);
471 for (const auto& file : files) {
472 std::string real_path;
473 if (!android::base::Readlink(fd_path + file, &real_path)) {
474 continue;
475 }
476 if (real_path.find("app") != std::string::npos && real_path.find(".apk") != std::string::npos) {
477 return true;
478 }
479 }
480 return false;
481}
482
Yabin Cui7cb6f292017-08-28 14:49:04 -0700483std::set<pid_t> WaitForAppProcesses(const std::string& package_name) {
484 std::set<pid_t> result;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700485 size_t loop_count = 0;
486 while (true) {
487 std::vector<pid_t> pids = GetAllProcesses();
488 for (pid_t pid : pids) {
489 std::string cmdline;
490 if (!android::base::ReadFileToString("/proc/" + std::to_string(pid) + "/cmdline", &cmdline)) {
491 // Maybe we don't have permission to read it.
492 continue;
493 }
Yabin Cui7cb6f292017-08-28 14:49:04 -0700494 std::string process_name = android::base::Basename(cmdline);
495 // The app may have multiple processes, with process name like
496 // com.google.android.googlequicksearchbox:search.
497 size_t split_pos = process_name.find(':');
498 if (split_pos != std::string::npos) {
499 process_name = process_name.substr(0, split_pos);
500 }
501 if (process_name != package_name) {
Yabin Cui88387692017-08-28 15:49:33 -0700502 continue;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700503 }
Yabin Cui88387692017-08-28 15:49:33 -0700504 // If a debuggable app with wrap.sh runs on Android O, the app will be started with
505 // logwrapper as below:
506 // 1. Zygote forks a child process, rename it to package_name.
507 // 2. The child process execute sh, which starts a child process running
508 // /system/bin/logwrapper.
509 // 3. logwrapper starts a child process running sh, which interprets wrap.sh.
510 // 4. wrap.sh starts a child process running the app.
511 // The problem here is we want to profile the process started in step 4, but sometimes we
512 // run into the process started in step 1. To solve it, we can check if the process has
513 // opened an apk file in some app dirs.
514 if (!HasOpenedAppApkFile(pid)) {
515 continue;
516 }
517 if (loop_count > 0u) {
518 LOG(INFO) << "Got process " << pid << " for package " << package_name;
519 }
Yabin Cui7cb6f292017-08-28 14:49:04 -0700520 result.insert(pid);
521 }
522 if (!result.empty()) {
523 return result;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700524 }
525 if (++loop_count == 1u) {
526 LOG(INFO) << "Waiting for process of app " << package_name;
527 }
528 usleep(1000);
529 }
530}
531
Yabin Cui1a30a582019-01-10 15:35:39 -0800532namespace {
Yabin Cuif8974522017-07-17 14:36:37 -0700533
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700534bool IsAppDebuggable(int user_id, const std::string& package_name) {
535 return Workload::RunCmd({"run-as", package_name, "--user", std::to_string(user_id), "echo",
536 ">/dev/null", "2>/dev/null"},
537 false);
Yabin Cui902f9082020-10-15 17:32:48 -0700538}
539
Yabin Cui1a30a582019-01-10 15:35:39 -0800540class InAppRunner {
541 public:
Yabin Cui902f9082020-10-15 17:32:48 -0700542 InAppRunner(int user_id, const std::string& package_name)
543 : user_id_(std::to_string(user_id)), package_name_(package_name) {}
Yabin Cui1a30a582019-01-10 15:35:39 -0800544 virtual ~InAppRunner() {
545 if (!tracepoint_file_.empty()) {
546 unlink(tracepoint_file_.c_str());
Yabin Cuif8974522017-07-17 14:36:37 -0700547 }
548 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800549 virtual bool Prepare() = 0;
550 bool RunCmdInApp(const std::string& cmd, const std::vector<std::string>& args,
551 size_t workload_args_size, const std::string& output_filepath,
552 bool need_tracepoint_events);
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200553
Yabin Cui1a30a582019-01-10 15:35:39 -0800554 protected:
555 virtual std::vector<std::string> GetPrefixArgs(const std::string& cmd) = 0;
Yabin Cuif8974522017-07-17 14:36:37 -0700556
Yabin Cui902f9082020-10-15 17:32:48 -0700557 const std::string user_id_;
Yabin Cui1a30a582019-01-10 15:35:39 -0800558 const std::string package_name_;
559 std::string tracepoint_file_;
Yabin Cuif8974522017-07-17 14:36:37 -0700560};
561
Yabin Cui1a30a582019-01-10 15:35:39 -0800562bool InAppRunner::RunCmdInApp(const std::string& cmd, const std::vector<std::string>& cmd_args,
563 size_t workload_args_size, const std::string& output_filepath,
564 bool need_tracepoint_events) {
565 // 1. Build cmd args running in app's context.
566 std::vector<std::string> args = GetPrefixArgs(cmd);
567 args.insert(args.end(), {"--in-app", "--log", GetLogSeverityName()});
Yabin Cuia556c562020-02-14 16:50:10 -0800568 if (log_to_android_buffer) {
569 args.emplace_back("--log-to-android-buffer");
570 }
Yabin Cuif8974522017-07-17 14:36:37 -0700571 if (need_tracepoint_events) {
572 // Since we can't read tracepoint events from tracefs in app's context, we need to prepare
573 // them in tracepoint_file in shell's context, and pass the path of tracepoint_file to the
574 // child process using --tracepoint-events option.
Yabin Cui1a30a582019-01-10 15:35:39 -0800575 const std::string tracepoint_file = "/data/local/tmp/tracepoint_events";
Yabin Cui16a6ace2020-10-01 14:56:32 -0700576 if (!EventTypeManager::Instance().WriteTracepointsToFile(tracepoint_file)) {
Yabin Cuif8974522017-07-17 14:36:37 -0700577 PLOG(ERROR) << "Failed to store tracepoint events";
578 return false;
579 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800580 tracepoint_file_ = tracepoint_file;
581 args.insert(args.end(), {"--tracepoint-events", tracepoint_file_});
Yabin Cuif8974522017-07-17 14:36:37 -0700582 }
Yabin Cuia80f8f72017-07-12 15:50:20 -0700583
Yabin Cui1a30a582019-01-10 15:35:39 -0800584 android::base::unique_fd out_fd;
585 if (!output_filepath.empty()) {
586 // A process running in app's context can't open a file outside it's data directory to write.
587 // So pass it a file descriptor to write.
588 out_fd = FileHelper::OpenWriteOnly(output_filepath);
589 if (out_fd == -1) {
590 PLOG(ERROR) << "Failed to open " << output_filepath;
591 return false;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700592 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800593 args.insert(args.end(), {"--out-fd", std::to_string(int(out_fd))});
Yabin Cuia80f8f72017-07-12 15:50:20 -0700594 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800595
596 // We can't send signal to a process running in app's context. So use a pipe file to send stop
597 // signal.
598 android::base::unique_fd stop_signal_rfd;
599 android::base::unique_fd stop_signal_wfd;
600 if (!android::base::Pipe(&stop_signal_rfd, &stop_signal_wfd, 0)) {
601 PLOG(ERROR) << "pipe";
602 return false;
603 }
604 args.insert(args.end(), {"--stop-signal-fd", std::to_string(int(stop_signal_rfd))});
605
606 for (size_t i = 0; i < cmd_args.size(); ++i) {
607 if (i < cmd_args.size() - workload_args_size) {
608 // Omit "-o output_file". It is replaced by "--out-fd fd".
609 if (cmd_args[i] == "-o" || cmd_args[i] == "--app") {
610 i++;
611 continue;
612 }
613 }
614 args.push_back(cmd_args[i]);
615 }
616 char* argv[args.size() + 1];
617 for (size_t i = 0; i < args.size(); ++i) {
618 argv[i] = &args[i][0];
619 }
620 argv[args.size()] = nullptr;
621
622 // 2. Run child process in app's context.
623 auto ChildProcFn = [&]() {
624 stop_signal_wfd.reset();
625 execvp(argv[0], argv);
626 exit(1);
627 };
628 std::unique_ptr<Workload> workload = Workload::CreateWorkload(ChildProcFn);
Yabin Cuia80f8f72017-07-12 15:50:20 -0700629 if (!workload) {
630 return false;
631 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800632 stop_signal_rfd.reset();
Yabin Cuia80f8f72017-07-12 15:50:20 -0700633
Yabin Cui1a30a582019-01-10 15:35:39 -0800634 // Wait on signals.
Yabin Cuia80f8f72017-07-12 15:50:20 -0700635 IOEventLoop loop;
Yabin Cui1a30a582019-01-10 15:35:39 -0800636 bool need_to_stop_child = false;
Yabin Cuid5d9c422018-04-11 17:50:56 -0700637 std::vector<int> stop_signals = {SIGINT, SIGTERM};
638 if (!SignalIsIgnored(SIGHUP)) {
639 stop_signals.push_back(SIGHUP);
640 }
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200641 if (!loop.AddSignalEvents(stop_signals, [&]() {
642 need_to_stop_child = true;
643 return loop.ExitLoop();
644 })) {
Yabin Cuia80f8f72017-07-12 15:50:20 -0700645 return false;
646 }
647 if (!loop.AddSignalEvent(SIGCHLD, [&]() { return loop.ExitLoop(); })) {
648 return false;
649 }
650
Yabin Cuia80f8f72017-07-12 15:50:20 -0700651 if (!workload->Start()) {
652 return false;
653 }
654 if (!loop.RunLoop()) {
655 return false;
656 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800657 if (need_to_stop_child) {
658 stop_signal_wfd.reset();
Yabin Cuia80f8f72017-07-12 15:50:20 -0700659 }
660 int exit_code;
Yabin Cui248ef5e2021-12-16 14:09:39 -0800661 if (!workload->WaitChildProcess(true, &exit_code) || exit_code != 0) {
Yabin Cuia80f8f72017-07-12 15:50:20 -0700662 return false;
663 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800664 return true;
665}
Yabin Cuia80f8f72017-07-12 15:50:20 -0700666
Yabin Cui1a30a582019-01-10 15:35:39 -0800667class RunAs : public InAppRunner {
668 public:
Yabin Cui902f9082020-10-15 17:32:48 -0700669 RunAs(int user_id, const std::string& package_name) : InAppRunner(user_id, package_name) {}
Yabin Cui1a30a582019-01-10 15:35:39 -0800670 virtual ~RunAs() {
671 if (simpleperf_copied_in_app_) {
Yabin Cui902f9082020-10-15 17:32:48 -0700672 Workload::RunCmd({"run-as", package_name_, "--user", user_id_, "rm", "-rf", "simpleperf"});
Yabin Cuia80f8f72017-07-12 15:50:20 -0700673 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800674 }
675 bool Prepare() override;
676
677 protected:
678 std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
Yabin Cui8729bc62021-05-11 11:29:38 -0700679 std::vector<std::string> args = {"run-as",
680 package_name_,
681 "--user",
682 user_id_,
683 simpleperf_copied_in_app_ ? "./simpleperf" : simpleperf_path_,
684 cmd,
685 "--app",
686 package_name_};
687 if (cmd == "record") {
688 if (simpleperf_copied_in_app_ || GetAndroidVersion() >= kAndroidVersionS) {
689 args.emplace_back("--add-meta-info");
690 args.emplace_back("app_type=debuggable");
691 }
692 }
693 return args;
Yabin Cui1a30a582019-01-10 15:35:39 -0800694 }
695
696 bool simpleperf_copied_in_app_ = false;
697 std::string simpleperf_path_;
698};
699
700bool RunAs::Prepare() {
Yabin Cui1a30a582019-01-10 15:35:39 -0800701 // run-as can't run /data/local/tmp/simpleperf directly. So copy simpleperf binary if needed.
702 if (!android::base::Readlink("/proc/self/exe", &simpleperf_path_)) {
703 PLOG(ERROR) << "ReadLink failed";
704 return false;
705 }
Yabin Cuia24cf962019-01-29 17:06:42 -0800706 if (simpleperf_path_.find("CtsSimpleperfTest") != std::string::npos) {
707 simpleperf_path_ = "/system/bin/simpleperf";
708 return true;
709 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800710 if (android::base::StartsWith(simpleperf_path_, "/system")) {
711 return true;
712 }
Yabin Cui902f9082020-10-15 17:32:48 -0700713 if (!Workload::RunCmd(
714 {"run-as", package_name_, "--user", user_id_, "cp", simpleperf_path_, "simpleperf"})) {
Yabin Cui1a30a582019-01-10 15:35:39 -0800715 return false;
716 }
717 simpleperf_copied_in_app_ = true;
718 return true;
719}
720
721class SimpleperfAppRunner : public InAppRunner {
722 public:
Greg Kaiserde124ee2021-05-17 12:54:14 -0700723 SimpleperfAppRunner(int user_id, const std::string& package_name, const std::string& app_type)
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700724 : InAppRunner(user_id, package_name) {
725 // On Android < S, the app type is unknown before running simpleperf_app_runner. Assume it's
726 // profileable.
727 app_type_ = app_type == "unknown" ? "profileable" : app_type;
728 }
Yabin Cui8729bc62021-05-11 11:29:38 -0700729 bool Prepare() override { return GetAndroidVersion() >= kAndroidVersionQ; }
Yabin Cui1a30a582019-01-10 15:35:39 -0800730
731 protected:
732 std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
Yabin Cui92825be2020-12-02 17:06:54 -0800733 std::vector<std::string> args = {"simpleperf_app_runner", package_name_};
734 if (user_id_ != "0") {
735 args.emplace_back("--user");
736 args.emplace_back(user_id_);
737 }
738 args.emplace_back(cmd);
Yabin Cui8729bc62021-05-11 11:29:38 -0700739 if (cmd == "record" && GetAndroidVersion() >= kAndroidVersionS) {
740 args.emplace_back("--add-meta-info");
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700741 args.emplace_back("app_type=" + app_type_);
Yabin Cui8729bc62021-05-11 11:29:38 -0700742 }
Yabin Cui92825be2020-12-02 17:06:54 -0800743 return args;
Yabin Cui1a30a582019-01-10 15:35:39 -0800744 }
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700745
746 std::string app_type_;
Yabin Cui1a30a582019-01-10 15:35:39 -0800747};
748
749} // namespace
750
Yabin Cui94c148d2020-02-18 14:32:33 -0800751static bool allow_run_as = true;
752static bool allow_simpleperf_app_runner = true;
753
754void SetRunInAppToolForTesting(bool run_as, bool simpleperf_app_runner) {
755 allow_run_as = run_as;
756 allow_simpleperf_app_runner = simpleperf_app_runner;
757}
758
Yabin Cui902f9082020-10-15 17:32:48 -0700759static int GetCurrentUserId() {
760 std::unique_ptr<FILE, decltype(&pclose)> fd(popen("am get-current-user", "r"), pclose);
761 if (fd) {
762 char buf[128];
763 if (fgets(buf, sizeof(buf), fd.get()) != nullptr) {
764 int user_id;
765 if (android::base::ParseInt(android::base::Trim(buf), &user_id, 0)) {
766 return user_id;
767 }
768 }
769 }
770 return 0;
771}
772
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700773std::string GetAppType(const std::string& app_package_name) {
774 if (GetAndroidVersion() < kAndroidVersionS) {
775 return "unknown";
776 }
777 std::string cmd = "simpleperf_app_runner " + app_package_name + " --show-app-type";
778 std::unique_ptr<FILE, decltype(&pclose)> fp(popen(cmd.c_str(), "re"), pclose);
779 if (fp) {
780 char buf[128];
781 if (fgets(buf, sizeof(buf), fp.get()) != nullptr) {
782 return android::base::Trim(buf);
783 }
784 }
785 // Can't get app_type. It means the app doesn't exist.
786 return "not_exist";
787}
788
Yabin Cui1a30a582019-01-10 15:35:39 -0800789bool RunInAppContext(const std::string& app_package_name, const std::string& cmd,
790 const std::vector<std::string>& args, size_t workload_args_size,
791 const std::string& output_filepath, bool need_tracepoint_events) {
Yabin Cui902f9082020-10-15 17:32:48 -0700792 int user_id = GetCurrentUserId();
Yabin Cui94c148d2020-02-18 14:32:33 -0800793 std::unique_ptr<InAppRunner> in_app_runner;
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700794
795 std::string app_type = GetAppType(app_package_name);
796 if (app_type == "unknown" && IsAppDebuggable(user_id, app_package_name)) {
797 app_type = "debuggable";
798 }
799
800 if (allow_run_as && app_type == "debuggable") {
Yabin Cui902f9082020-10-15 17:32:48 -0700801 in_app_runner.reset(new RunAs(user_id, app_package_name));
Yabin Cui94c148d2020-02-18 14:32:33 -0800802 if (!in_app_runner->Prepare()) {
803 in_app_runner = nullptr;
804 }
805 }
806 if (!in_app_runner && allow_simpleperf_app_runner) {
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700807 if (app_type == "debuggable" || app_type == "profileable" || app_type == "unknown") {
808 in_app_runner.reset(new SimpleperfAppRunner(user_id, app_package_name, app_type));
809 if (!in_app_runner->Prepare()) {
810 in_app_runner = nullptr;
811 }
Yabin Cuia80f8f72017-07-12 15:50:20 -0700812 }
813 }
Yabin Cui94c148d2020-02-18 14:32:33 -0800814 if (!in_app_runner) {
815 LOG(ERROR) << "Package " << app_package_name
816 << " doesn't exist or isn't debuggable/profileable.";
817 return false;
818 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800819 return in_app_runner->RunCmdInApp(cmd, args, workload_args_size, output_filepath,
820 need_tracepoint_events);
Yabin Cuia80f8f72017-07-12 15:50:20 -0700821}
Yabin Cui616b3a02017-07-14 15:59:56 -0700822
Yabin Cui7c5fe4e2017-12-05 17:44:05 -0800823void AllowMoreOpenedFiles() {
824 // On Android <= O, the hard limit is 4096, and the soft limit is 1024.
825 // On Android >= P, both the hard and soft limit are 32768.
826 rlimit limit;
827 if (getrlimit(RLIMIT_NOFILE, &limit) == 0) {
828 limit.rlim_cur = limit.rlim_max;
829 setrlimit(RLIMIT_NOFILE, &limit);
830 }
831}
Yabin Cui38b6a902017-12-06 14:15:48 -0800832
Yabin Cuic68e66d2018-03-07 15:47:15 -0800833std::string ScopedTempFiles::tmp_dir_;
834std::vector<std::string> ScopedTempFiles::files_to_delete_;
835
Yabin Cui554f3bb2021-05-05 13:34:59 -0700836std::unique_ptr<ScopedTempFiles> ScopedTempFiles::Create(const std::string& tmp_dir) {
837 if (access(tmp_dir.c_str(), W_OK | X_OK) != 0) {
838 return nullptr;
839 }
840 return std::unique_ptr<ScopedTempFiles>(new ScopedTempFiles(tmp_dir));
841}
842
Yabin Cuic68e66d2018-03-07 15:47:15 -0800843ScopedTempFiles::ScopedTempFiles(const std::string& tmp_dir) {
844 CHECK(tmp_dir_.empty()); // No other ScopedTempFiles.
845 tmp_dir_ = tmp_dir;
Yabin Cui38b6a902017-12-06 14:15:48 -0800846}
847
Yabin Cuic68e66d2018-03-07 15:47:15 -0800848ScopedTempFiles::~ScopedTempFiles() {
849 tmp_dir_.clear();
850 for (auto& file : files_to_delete_) {
851 unlink(file.c_str());
852 }
853 files_to_delete_.clear();
854}
855
856std::unique_ptr<TemporaryFile> ScopedTempFiles::CreateTempFile(bool delete_in_destructor) {
857 CHECK(!tmp_dir_.empty());
858 std::unique_ptr<TemporaryFile> tmp_file(new TemporaryFile(tmp_dir_));
Yabin Cuia9cfcde2020-06-29 14:04:44 -0700859 CHECK_NE(tmp_file->fd, -1) << "failed to create tmpfile under " << tmp_dir_;
Yabin Cuic68e66d2018-03-07 15:47:15 -0800860 if (delete_in_destructor) {
861 tmp_file->DoNotRemove();
862 files_to_delete_.push_back(tmp_file->path);
863 }
864 return tmp_file;
Yabin Cui38b6a902017-12-06 14:15:48 -0800865}
Josh Gao30535f22017-12-14 16:10:28 -0800866
Yabin Cuie32ed2b2020-07-23 15:30:14 -0700867void ScopedTempFiles::RegisterTempFile(const std::string& path) {
868 files_to_delete_.emplace_back(path);
869}
870
Josh Gao30535f22017-12-14 16:10:28 -0800871bool SignalIsIgnored(int signo) {
872 struct sigaction act;
873 if (sigaction(signo, nullptr, &act) != 0) {
874 PLOG(FATAL) << "failed to query signal handler for signal " << signo;
875 }
876
877 if ((act.sa_flags & SA_SIGINFO)) {
878 return false;
879 }
880
881 return act.sa_handler == SIG_IGN;
882}
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800883
884int GetAndroidVersion() {
885#if defined(__ANDROID__)
Yabin Cui6e173a42018-08-13 15:58:25 -0700886 static int android_version = -1;
887 if (android_version == -1) {
888 android_version = 0;
Yabin Cui58740ff2021-03-23 13:34:51 -0700889 std::string s = android::base::GetProperty("ro.build.version.codename", "REL");
890 if (s == "REL") {
891 s = android::base::GetProperty("ro.build.version.release", "");
892 }
Yabin Cui6e173a42018-08-13 15:58:25 -0700893 // The release string can be a list of numbers (like 8.1.0), a character (like Q)
894 // or many characters (like OMR1).
895 if (!s.empty()) {
896 // Each Android version has a version number: L is 5, M is 6, N is 7, O is 8, etc.
897 if (s[0] >= 'A' && s[0] <= 'Z') {
898 android_version = s[0] - 'P' + kAndroidVersionP;
899 } else if (isdigit(s[0])) {
900 sscanf(s.c_str(), "%d", &android_version);
901 }
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800902 }
903 }
Yabin Cui6e173a42018-08-13 15:58:25 -0700904 return android_version;
905#else // defined(__ANDROID__)
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800906 return 0;
Yabin Cui6e173a42018-08-13 15:58:25 -0700907#endif
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800908}
Yabin Cui8faa6152018-06-07 15:52:57 -0700909
910std::string GetHardwareFromCpuInfo(const std::string& cpu_info) {
911 for (auto& line : android::base::Split(cpu_info, "\n")) {
912 size_t pos = line.find(':');
913 if (pos != std::string::npos) {
914 std::string key = android::base::Trim(line.substr(0, pos));
915 if (key == "Hardware") {
916 return android::base::Trim(line.substr(pos + 1));
917 }
918 }
919 }
920 return "";
921}
Yabin Cui2db05b42018-07-16 14:04:49 -0700922
923bool MappedFileOnlyExistInMemory(const char* filename) {
924 // Mapped files only existing in memory:
925 // empty name
926 // [anon:???]
927 // [stack]
928 // /dev/*
929 // //anon: generated by kernel/events/core.c.
Yabin Cui739b1542018-10-17 17:19:56 -0700930 // /memfd: created by memfd_create.
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200931 return filename[0] == '\0' || (filename[0] == '[' && strcmp(filename, "[vdso]") != 0) ||
932 strncmp(filename, "//", 2) == 0 || strncmp(filename, "/dev/", 5) == 0 ||
933 strncmp(filename, "/memfd:", 7) == 0;
Yabin Cui2db05b42018-07-16 14:04:49 -0700934}
Yabin Cui38335f42018-07-17 16:06:21 -0700935
936std::string GetCompleteProcessName(pid_t pid) {
937 std::string s;
938 if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid), &s)) {
939 s.clear();
940 }
941 for (size_t i = 0; i < s.size(); ++i) {
Yabin Cui3939b9d2018-07-20 17:12:13 -0700942 // /proc/pid/cmdline uses 0 to separate arguments.
943 if (isspace(s[i]) || s[i] == 0) {
Yabin Cui38335f42018-07-17 16:06:21 -0700944 s.resize(i);
945 break;
946 }
947 }
948 return s;
949}
Yabin Cuia22efeb2020-01-29 13:27:33 -0800950
951const char* GetTraceFsDir() {
Yabin Cui142acc82020-10-14 10:24:38 -0700952 static const char* tracefs_dir = nullptr;
953 if (tracefs_dir == nullptr) {
954 for (const char* path : {"/sys/kernel/debug/tracing", "/sys/kernel/tracing"}) {
955 if (IsDir(path)) {
956 tracefs_dir = path;
957 break;
958 }
Yabin Cuia22efeb2020-01-29 13:27:33 -0800959 }
960 }
Yabin Cui142acc82020-10-14 10:24:38 -0700961 return tracefs_dir;
Yabin Cuia22efeb2020-01-29 13:27:33 -0800962}
Yabin Cui84c55ff2020-07-09 14:14:22 -0700963
Yabin Cuid703bb32021-01-05 16:45:52 -0800964std::optional<std::pair<int, int>> GetKernelVersion() {
Yabin Cui71aec162021-11-03 15:23:22 -0700965 static std::optional<std::pair<int, int>> kernel_version;
966 if (!kernel_version.has_value()) {
967 utsname uname_buf;
968 int major;
969 int minor;
970 if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0 ||
971 sscanf(uname_buf.release, "%d.%d", &major, &minor) != 2) {
972 return std::nullopt;
973 }
974 kernel_version = std::make_pair(major, minor);
Yabin Cui84c55ff2020-07-09 14:14:22 -0700975 }
Yabin Cui71aec162021-11-03 15:23:22 -0700976 return kernel_version;
Yabin Cui84c55ff2020-07-09 14:14:22 -0700977}
Yabin Cuifaa7b922021-01-11 17:35:57 -0800978
Yabin Cui3485af92021-10-27 10:50:53 -0700979#if defined(__ANDROID__)
980bool IsInAppUid() {
981 return getuid() % AID_USER_OFFSET >= AID_APP_START;
982}
983#endif
984
Yabin Cuia89a3742021-02-11 13:14:54 -0800985std::optional<uid_t> GetProcessUid(pid_t pid) {
986 std::string status_file = "/proc/" + std::to_string(pid) + "/status";
Yabin Cui40eef9e2021-04-13 13:08:31 -0700987 LineReader reader(status_file);
988 if (!reader.Ok()) {
Yabin Cuia89a3742021-02-11 13:14:54 -0800989 return std::nullopt;
990 }
991
Yabin Cui40eef9e2021-04-13 13:08:31 -0700992 std::string* line;
Yabin Cuia89a3742021-02-11 13:14:54 -0800993 while ((line = reader.ReadLine()) != nullptr) {
Yabin Cui40eef9e2021-04-13 13:08:31 -0700994 if (android::base::StartsWith(*line, "Uid:")) {
Yabin Cuia89a3742021-02-11 13:14:54 -0800995 uid_t uid;
Yabin Cui40eef9e2021-04-13 13:08:31 -0700996 if (sscanf(line->data() + strlen("Uid:"), "%u", &uid) == 1) {
Yabin Cuia89a3742021-02-11 13:14:54 -0800997 return uid;
998 }
999 }
1000 }
1001 return std::nullopt;
1002}
1003
Yabin Cuifaa7b922021-01-11 17:35:57 -08001004} // namespace simpleperf