blob: 5ff09160d69ccb5ec805d201d2d5a6bb78692e15 [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 Cuicfdc7832023-03-02 15:35:01 -0800244std::optional<uint64_t> GetMemorySize() {
245 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("/proc/meminfo", "r"), fclose);
246 uint64_t size;
247 if (fp && fscanf(fp.get(), "MemTotal:%" PRIu64 " k", &size) == 1) {
248 return size * kKilobyte;
249 }
250 PLOG(ERROR) << "failed to get memory size";
251 return std::nullopt;
252}
253
Yabin Cuiebf79f32016-06-01 15:39:39 -0700254static const char* GetLimitLevelDescription(int limit_level) {
255 switch (limit_level) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200256 case -1:
257 return "unlimited";
258 case 0:
259 return "disallowing raw tracepoint access for unpriv";
260 case 1:
261 return "disallowing cpu events for unpriv";
262 case 2:
263 return "disallowing kernel profiling for unpriv";
264 case 3:
265 return "disallowing user profiling for unpriv";
266 default:
267 return "unknown level";
Yabin Cuiebf79f32016-06-01 15:39:39 -0700268 }
269}
270
271bool CheckPerfEventLimit() {
Yabin Cui17cffbb2020-07-28 17:11:39 -0700272 // Root is not limited by perf_event_allow_path. However, the monitored threads
Yabin Cui1137a8c2017-06-01 13:23:29 -0700273 // may create child processes not running as root. To make sure the child processes have
Yabin Cui17cffbb2020-07-28 17:11:39 -0700274 // enough permission to create inherited tracepoint events, write -1 to perf_event_allow_path.
Yabin Cui1137a8c2017-06-01 13:23:29 -0700275 // See http://b/62230699.
Yabin Cui5edb7fc2018-08-29 14:54:19 -0700276 if (IsRoot()) {
Yabin Cuic765ccb2021-02-23 15:53:09 -0800277 if (android::base::WriteStringToFile("-1", perf_event_allow_path)) {
278 return true;
279 }
280 // On host, we may not be able to write to perf_event_allow_path (like when running in docker).
281#if defined(__ANDROID__)
282 PLOG(ERROR) << "failed to write -1 to " << perf_event_allow_path;
283 return false;
284#endif
Yabin Cui4f41df62016-06-01 17:29:06 -0700285 }
Yabin Cuiebf79f32016-06-01 15:39:39 -0700286 int limit_level;
Yabin Cui17cffbb2020-07-28 17:11:39 -0700287 bool can_read_allow_file = ReadPerfEventAllowStatus(&limit_level);
288 if (can_read_allow_file && limit_level <= 1) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700289 return true;
290 }
291#if defined(__ANDROID__)
Yabin Cui80a1e122017-08-11 14:52:51 -0700292 const std::string prop_name = "security.perf_harden";
293 std::string prop_value = android::base::GetProperty(prop_name, "");
294 if (prop_value.empty()) {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700295 // can't do anything if there is no such property.
296 return true;
297 }
Yabin Cui80a1e122017-08-11 14:52:51 -0700298 if (prop_value == "0") {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700299 return true;
300 }
Yabin Cui17cffbb2020-07-28 17:11:39 -0700301 // Try to enable perf events by setprop security.perf_harden=0.
Yabin Cui80a1e122017-08-11 14:52:51 -0700302 if (android::base::SetProperty(prop_name, "0")) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700303 sleep(1);
Yabin Cui17cffbb2020-07-28 17:11:39 -0700304 if (can_read_allow_file && ReadPerfEventAllowStatus(&limit_level) && limit_level <= 1) {
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700305 return true;
306 }
Yabin Cui80a1e122017-08-11 14:52:51 -0700307 if (android::base::GetProperty(prop_name, "") == "0") {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700308 return true;
309 }
310 }
Yabin Cui17cffbb2020-07-28 17:11:39 -0700311 if (can_read_allow_file) {
Yabin Cuic95e3472022-09-22 09:55:31 -0700312 LOG(ERROR) << perf_event_allow_path << " is " << limit_level << ", "
313 << GetLimitLevelDescription(limit_level) << ".";
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700314 }
Yabin Cuic95e3472022-09-22 09:55:31 -0700315 LOG(ERROR) << "Try using `adb shell setprop security.perf_harden 0` to allow profiling.";
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700316 return false;
Yabin Cuiebf79f32016-06-01 15:39:39 -0700317#else
Yabin Cui17cffbb2020-07-28 17:11:39 -0700318 if (can_read_allow_file) {
Yabin Cuic95e3472022-09-22 09:55:31 -0700319 LOG(ERROR) << perf_event_allow_path << " is " << limit_level << ", "
320 << GetLimitLevelDescription(limit_level) << ". Try using `echo -1 >"
321 << perf_event_allow_path << "` to enable profiling.";
Yabin Cui0a7a06d2016-10-28 13:27:41 -0700322 return false;
323 }
Yabin Cuiebf79f32016-06-01 15:39:39 -0700324#endif
325 return true;
326}
Yabin Cuib8915492016-06-22 12:43:09 -0700327
Yabin Cui6e173a42018-08-13 15:58:25 -0700328#if defined(__ANDROID__)
329static bool SetProperty(const char* prop_name, uint64_t value) {
330 if (!android::base::SetProperty(prop_name, std::to_string(value))) {
331 LOG(ERROR) << "Failed to SetProperty " << prop_name << " to " << value;
Yabin Cui0720d482017-03-06 17:05:50 -0800332 return false;
333 }
334 return true;
335}
336
Yabin Cui6e173a42018-08-13 15:58:25 -0700337bool SetPerfEventLimits(uint64_t sample_freq, size_t cpu_percent, uint64_t mlock_kb) {
338 if (!SetProperty("debug.perf_event_max_sample_rate", sample_freq) ||
339 !SetProperty("debug.perf_cpu_time_max_percent", cpu_percent) ||
340 !SetProperty("debug.perf_event_mlock_kb", mlock_kb) ||
341 !SetProperty("security.perf_harden", 0)) {
342 return false;
343 }
344 // Wait for init process to change perf event limits based on properties.
345 const size_t max_wait_us = 3 * 1000000;
Yury Khmel9e269cf2023-05-18 14:31:05 -0700346 const size_t interval_us = 10000;
Yabin Cui6e173a42018-08-13 15:58:25 -0700347 int finish_mask = 0;
Yury Khmel9e269cf2023-05-18 14:31:05 -0700348 for (size_t i = 0; i < max_wait_us && finish_mask != 7; i += interval_us) {
349 usleep(interval_us); // Wait 10ms to avoid busy loop.
Yabin Cui6e173a42018-08-13 15:58:25 -0700350 if ((finish_mask & 1) == 0) {
351 uint64_t freq;
352 if (!GetMaxSampleFrequency(&freq) || freq == sample_freq) {
353 finish_mask |= 1;
354 }
355 }
356 if ((finish_mask & 2) == 0) {
357 size_t percent;
358 if (!GetCpuTimeMaxPercent(&percent) || percent == cpu_percent) {
359 finish_mask |= 2;
360 }
361 }
362 if ((finish_mask & 4) == 0) {
363 uint64_t kb;
364 if (!GetPerfEventMlockKb(&kb) || kb == mlock_kb) {
365 finish_mask |= 4;
366 }
367 }
368 }
369 if (finish_mask != 7) {
370 LOG(WARNING) << "Wait setting perf event limits timeout";
371 }
372 return true;
373}
374#else // !defined(__ANDROID__)
375bool SetPerfEventLimits(uint64_t, size_t, uint64_t) {
376 return true;
377}
378#endif
379
380template <typename T>
381static bool ReadUintFromProcFile(const std::string& path, T* value) {
382 std::string s;
383 if (!android::base::ReadFileToString(path, &s)) {
384 PLOG(DEBUG) << "failed to read " << path;
385 return false;
386 }
387 s = android::base::Trim(s);
388 if (!android::base::ParseUint(s.c_str(), value)) {
389 LOG(ERROR) << "failed to parse " << path << ": " << s;
390 return false;
391 }
392 return true;
393}
394
395template <typename T>
396static bool WriteUintToProcFile(const std::string& path, T value) {
397 if (IsRoot()) {
398 return android::base::WriteStringToFile(std::to_string(value), path);
399 }
400 return false;
401}
402
403bool GetMaxSampleFrequency(uint64_t* max_sample_freq) {
404 return ReadUintFromProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
405}
406
407bool SetMaxSampleFrequency(uint64_t max_sample_freq) {
408 return WriteUintToProcFile("/proc/sys/kernel/perf_event_max_sample_rate", max_sample_freq);
409}
410
411bool GetCpuTimeMaxPercent(size_t* percent) {
412 return ReadUintFromProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
413}
414
415bool SetCpuTimeMaxPercent(size_t percent) {
416 return WriteUintToProcFile("/proc/sys/kernel/perf_cpu_time_max_percent", percent);
417}
418
419bool GetPerfEventMlockKb(uint64_t* mlock_kb) {
420 return ReadUintFromProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
421}
422
423bool SetPerfEventMlockKb(uint64_t mlock_kb) {
424 return WriteUintToProcFile("/proc/sys/kernel/perf_event_mlock_kb", mlock_kb);
425}
426
Yabin Cui417df292016-11-16 12:26:13 -0800427ArchType GetMachineArch() {
Yabin Cuif227b6d2021-01-06 14:01:53 -0800428#if defined(__i386__)
429 // For 32 bit x86 build, we can't get machine arch by uname().
430 ArchType arch = ARCH_UNSUPPORTED;
431 std::unique_ptr<FILE, decltype(&pclose)> fp(popen("uname -m", "re"), pclose);
432 if (fp) {
433 char machine[40];
434 if (fgets(machine, sizeof(machine), fp.get()) == machine) {
435 arch = GetArchType(android::base::Trim(machine));
436 }
437 }
438#else
Yabin Cui417df292016-11-16 12:26:13 -0800439 utsname uname_buf;
440 if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0) {
441 PLOG(WARNING) << "uname() failed";
Yabin Cui38076912021-08-16 16:59:09 -0700442 return GetTargetArch();
Yabin Cui417df292016-11-16 12:26:13 -0800443 }
444 ArchType arch = GetArchType(uname_buf.machine);
Yabin Cuif227b6d2021-01-06 14:01:53 -0800445#endif
Yabin Cui417df292016-11-16 12:26:13 -0800446 if (arch != ARCH_UNSUPPORTED) {
447 return arch;
448 }
Yabin Cui38076912021-08-16 16:59:09 -0700449 return GetTargetArch();
Yabin Cui417df292016-11-16 12:26:13 -0800450}
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700451
452void PrepareVdsoFile() {
453 // vdso is an elf file in memory loaded in each process's user space by the kernel. To read
454 // symbols from it and unwind through it, we need to dump it into a file in storage.
455 // It doesn't affect much when failed to prepare vdso file, so there is no need to return values.
456 std::vector<ThreadMmap> thread_mmaps;
457 if (!GetThreadMmapsInProcess(getpid(), &thread_mmaps)) {
458 return;
459 }
460 const ThreadMmap* vdso_map = nullptr;
461 for (const auto& map : thread_mmaps) {
462 if (map.name == "[vdso]") {
463 vdso_map = &map;
464 break;
465 }
466 }
467 if (vdso_map == nullptr) {
468 return;
469 }
470 std::string s(vdso_map->len, '\0');
471 memcpy(&s[0], reinterpret_cast<void*>(static_cast<uintptr_t>(vdso_map->start_addr)),
472 vdso_map->len);
Yabin Cuic68e66d2018-03-07 15:47:15 -0800473 std::unique_ptr<TemporaryFile> tmpfile = ScopedTempFiles::CreateTempFile();
474 if (!android::base::WriteStringToFd(s, tmpfile->fd)) {
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700475 return;
476 }
Yabin Cuic68e66d2018-03-07 15:47:15 -0800477 Dso::SetVdsoFile(tmpfile->path, sizeof(size_t) == sizeof(uint64_t));
Yabin Cui63a1c3d2017-05-19 12:57:44 -0700478}
Yabin Cuia80f8f72017-07-12 15:50:20 -0700479
Yabin Cui88387692017-08-28 15:49:33 -0700480static bool HasOpenedAppApkFile(int pid) {
481 std::string fd_path = "/proc/" + std::to_string(pid) + "/fd/";
482 std::vector<std::string> files = GetEntriesInDir(fd_path);
483 for (const auto& file : files) {
484 std::string real_path;
485 if (!android::base::Readlink(fd_path + file, &real_path)) {
486 continue;
487 }
488 if (real_path.find("app") != std::string::npos && real_path.find(".apk") != std::string::npos) {
489 return true;
490 }
491 }
492 return false;
493}
494
Yabin Cui7cb6f292017-08-28 14:49:04 -0700495std::set<pid_t> WaitForAppProcesses(const std::string& package_name) {
496 std::set<pid_t> result;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700497 size_t loop_count = 0;
498 while (true) {
499 std::vector<pid_t> pids = GetAllProcesses();
500 for (pid_t pid : pids) {
Yabin Cui1c6be752023-02-28 11:46:37 -0800501 std::string process_name = GetCompleteProcessName(pid);
502 if (process_name.empty()) {
Yabin Cuia80f8f72017-07-12 15:50:20 -0700503 continue;
504 }
Yabin Cui7cb6f292017-08-28 14:49:04 -0700505 // The app may have multiple processes, with process name like
506 // com.google.android.googlequicksearchbox:search.
507 size_t split_pos = process_name.find(':');
508 if (split_pos != std::string::npos) {
509 process_name = process_name.substr(0, split_pos);
510 }
511 if (process_name != package_name) {
Yabin Cui88387692017-08-28 15:49:33 -0700512 continue;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700513 }
Yabin Cui88387692017-08-28 15:49:33 -0700514 // If a debuggable app with wrap.sh runs on Android O, the app will be started with
515 // logwrapper as below:
516 // 1. Zygote forks a child process, rename it to package_name.
517 // 2. The child process execute sh, which starts a child process running
518 // /system/bin/logwrapper.
519 // 3. logwrapper starts a child process running sh, which interprets wrap.sh.
520 // 4. wrap.sh starts a child process running the app.
521 // The problem here is we want to profile the process started in step 4, but sometimes we
522 // run into the process started in step 1. To solve it, we can check if the process has
523 // opened an apk file in some app dirs.
524 if (!HasOpenedAppApkFile(pid)) {
525 continue;
526 }
527 if (loop_count > 0u) {
528 LOG(INFO) << "Got process " << pid << " for package " << package_name;
529 }
Yabin Cui7cb6f292017-08-28 14:49:04 -0700530 result.insert(pid);
531 }
532 if (!result.empty()) {
533 return result;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700534 }
535 if (++loop_count == 1u) {
536 LOG(INFO) << "Waiting for process of app " << package_name;
537 }
538 usleep(1000);
539 }
540}
541
Yabin Cui1a30a582019-01-10 15:35:39 -0800542namespace {
Yabin Cuif8974522017-07-17 14:36:37 -0700543
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700544bool IsAppDebuggable(int user_id, const std::string& package_name) {
545 return Workload::RunCmd({"run-as", package_name, "--user", std::to_string(user_id), "echo",
546 ">/dev/null", "2>/dev/null"},
547 false);
Yabin Cui902f9082020-10-15 17:32:48 -0700548}
549
Yabin Cui1a30a582019-01-10 15:35:39 -0800550class InAppRunner {
551 public:
Yabin Cui902f9082020-10-15 17:32:48 -0700552 InAppRunner(int user_id, const std::string& package_name)
553 : user_id_(std::to_string(user_id)), package_name_(package_name) {}
Yabin Cui1a30a582019-01-10 15:35:39 -0800554 virtual ~InAppRunner() {
555 if (!tracepoint_file_.empty()) {
556 unlink(tracepoint_file_.c_str());
Yabin Cuif8974522017-07-17 14:36:37 -0700557 }
558 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800559 virtual bool Prepare() = 0;
560 bool RunCmdInApp(const std::string& cmd, const std::vector<std::string>& args,
561 size_t workload_args_size, const std::string& output_filepath,
562 bool need_tracepoint_events);
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200563
Yabin Cui1a30a582019-01-10 15:35:39 -0800564 protected:
565 virtual std::vector<std::string> GetPrefixArgs(const std::string& cmd) = 0;
Yabin Cuif8974522017-07-17 14:36:37 -0700566
Yabin Cui902f9082020-10-15 17:32:48 -0700567 const std::string user_id_;
Yabin Cui1a30a582019-01-10 15:35:39 -0800568 const std::string package_name_;
569 std::string tracepoint_file_;
Yabin Cuif8974522017-07-17 14:36:37 -0700570};
571
Yabin Cui1a30a582019-01-10 15:35:39 -0800572bool InAppRunner::RunCmdInApp(const std::string& cmd, const std::vector<std::string>& cmd_args,
573 size_t workload_args_size, const std::string& output_filepath,
574 bool need_tracepoint_events) {
575 // 1. Build cmd args running in app's context.
576 std::vector<std::string> args = GetPrefixArgs(cmd);
577 args.insert(args.end(), {"--in-app", "--log", GetLogSeverityName()});
Yabin Cuia556c562020-02-14 16:50:10 -0800578 if (log_to_android_buffer) {
579 args.emplace_back("--log-to-android-buffer");
580 }
Yabin Cuif8974522017-07-17 14:36:37 -0700581 if (need_tracepoint_events) {
582 // Since we can't read tracepoint events from tracefs in app's context, we need to prepare
583 // them in tracepoint_file in shell's context, and pass the path of tracepoint_file to the
584 // child process using --tracepoint-events option.
Yabin Cui1a30a582019-01-10 15:35:39 -0800585 const std::string tracepoint_file = "/data/local/tmp/tracepoint_events";
Yabin Cui16a6ace2020-10-01 14:56:32 -0700586 if (!EventTypeManager::Instance().WriteTracepointsToFile(tracepoint_file)) {
Yabin Cuif8974522017-07-17 14:36:37 -0700587 PLOG(ERROR) << "Failed to store tracepoint events";
588 return false;
589 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800590 tracepoint_file_ = tracepoint_file;
591 args.insert(args.end(), {"--tracepoint-events", tracepoint_file_});
Yabin Cuif8974522017-07-17 14:36:37 -0700592 }
Yabin Cuia80f8f72017-07-12 15:50:20 -0700593
Yabin Cui1a30a582019-01-10 15:35:39 -0800594 android::base::unique_fd out_fd;
595 if (!output_filepath.empty()) {
596 // A process running in app's context can't open a file outside it's data directory to write.
597 // So pass it a file descriptor to write.
598 out_fd = FileHelper::OpenWriteOnly(output_filepath);
599 if (out_fd == -1) {
600 PLOG(ERROR) << "Failed to open " << output_filepath;
601 return false;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700602 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800603 args.insert(args.end(), {"--out-fd", std::to_string(int(out_fd))});
Yabin Cuia80f8f72017-07-12 15:50:20 -0700604 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800605
606 // We can't send signal to a process running in app's context. So use a pipe file to send stop
607 // signal.
608 android::base::unique_fd stop_signal_rfd;
609 android::base::unique_fd stop_signal_wfd;
610 if (!android::base::Pipe(&stop_signal_rfd, &stop_signal_wfd, 0)) {
611 PLOG(ERROR) << "pipe";
612 return false;
613 }
614 args.insert(args.end(), {"--stop-signal-fd", std::to_string(int(stop_signal_rfd))});
615
616 for (size_t i = 0; i < cmd_args.size(); ++i) {
617 if (i < cmd_args.size() - workload_args_size) {
618 // Omit "-o output_file". It is replaced by "--out-fd fd".
619 if (cmd_args[i] == "-o" || cmd_args[i] == "--app") {
620 i++;
621 continue;
622 }
623 }
624 args.push_back(cmd_args[i]);
625 }
626 char* argv[args.size() + 1];
627 for (size_t i = 0; i < args.size(); ++i) {
628 argv[i] = &args[i][0];
629 }
630 argv[args.size()] = nullptr;
631
632 // 2. Run child process in app's context.
633 auto ChildProcFn = [&]() {
634 stop_signal_wfd.reset();
635 execvp(argv[0], argv);
636 exit(1);
637 };
638 std::unique_ptr<Workload> workload = Workload::CreateWorkload(ChildProcFn);
Yabin Cuia80f8f72017-07-12 15:50:20 -0700639 if (!workload) {
640 return false;
641 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800642 stop_signal_rfd.reset();
Yabin Cuia80f8f72017-07-12 15:50:20 -0700643
Yabin Cui1a30a582019-01-10 15:35:39 -0800644 // Wait on signals.
Yabin Cuia80f8f72017-07-12 15:50:20 -0700645 IOEventLoop loop;
Yabin Cui1a30a582019-01-10 15:35:39 -0800646 bool need_to_stop_child = false;
Yabin Cuid5d9c422018-04-11 17:50:56 -0700647 std::vector<int> stop_signals = {SIGINT, SIGTERM};
648 if (!SignalIsIgnored(SIGHUP)) {
649 stop_signals.push_back(SIGHUP);
650 }
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200651 if (!loop.AddSignalEvents(stop_signals, [&]() {
652 need_to_stop_child = true;
653 return loop.ExitLoop();
654 })) {
Yabin Cuia80f8f72017-07-12 15:50:20 -0700655 return false;
656 }
657 if (!loop.AddSignalEvent(SIGCHLD, [&]() { return loop.ExitLoop(); })) {
658 return false;
659 }
660
Yabin Cuia80f8f72017-07-12 15:50:20 -0700661 if (!workload->Start()) {
662 return false;
663 }
664 if (!loop.RunLoop()) {
665 return false;
666 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800667 if (need_to_stop_child) {
668 stop_signal_wfd.reset();
Yabin Cuia80f8f72017-07-12 15:50:20 -0700669 }
670 int exit_code;
Yabin Cui248ef5e2021-12-16 14:09:39 -0800671 if (!workload->WaitChildProcess(true, &exit_code) || exit_code != 0) {
Yabin Cuia80f8f72017-07-12 15:50:20 -0700672 return false;
673 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800674 return true;
675}
Yabin Cuia80f8f72017-07-12 15:50:20 -0700676
Yabin Cui1a30a582019-01-10 15:35:39 -0800677class RunAs : public InAppRunner {
678 public:
Yabin Cui902f9082020-10-15 17:32:48 -0700679 RunAs(int user_id, const std::string& package_name) : InAppRunner(user_id, package_name) {}
Yabin Cui1a30a582019-01-10 15:35:39 -0800680 virtual ~RunAs() {
681 if (simpleperf_copied_in_app_) {
Yabin Cui902f9082020-10-15 17:32:48 -0700682 Workload::RunCmd({"run-as", package_name_, "--user", user_id_, "rm", "-rf", "simpleperf"});
Yabin Cuia80f8f72017-07-12 15:50:20 -0700683 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800684 }
685 bool Prepare() override;
686
687 protected:
688 std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
Yabin Cui8729bc62021-05-11 11:29:38 -0700689 std::vector<std::string> args = {"run-as",
690 package_name_,
691 "--user",
692 user_id_,
693 simpleperf_copied_in_app_ ? "./simpleperf" : simpleperf_path_,
694 cmd,
695 "--app",
696 package_name_};
697 if (cmd == "record") {
698 if (simpleperf_copied_in_app_ || GetAndroidVersion() >= kAndroidVersionS) {
699 args.emplace_back("--add-meta-info");
700 args.emplace_back("app_type=debuggable");
701 }
702 }
703 return args;
Yabin Cui1a30a582019-01-10 15:35:39 -0800704 }
705
706 bool simpleperf_copied_in_app_ = false;
707 std::string simpleperf_path_;
708};
709
710bool RunAs::Prepare() {
Yabin Cui1a30a582019-01-10 15:35:39 -0800711 // run-as can't run /data/local/tmp/simpleperf directly. So copy simpleperf binary if needed.
712 if (!android::base::Readlink("/proc/self/exe", &simpleperf_path_)) {
713 PLOG(ERROR) << "ReadLink failed";
714 return false;
715 }
Yabin Cuia24cf962019-01-29 17:06:42 -0800716 if (simpleperf_path_.find("CtsSimpleperfTest") != std::string::npos) {
717 simpleperf_path_ = "/system/bin/simpleperf";
718 return true;
719 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800720 if (android::base::StartsWith(simpleperf_path_, "/system")) {
721 return true;
722 }
Yabin Cui902f9082020-10-15 17:32:48 -0700723 if (!Workload::RunCmd(
724 {"run-as", package_name_, "--user", user_id_, "cp", simpleperf_path_, "simpleperf"})) {
Yabin Cui1a30a582019-01-10 15:35:39 -0800725 return false;
726 }
727 simpleperf_copied_in_app_ = true;
728 return true;
729}
730
731class SimpleperfAppRunner : public InAppRunner {
732 public:
Greg Kaiserde124ee2021-05-17 12:54:14 -0700733 SimpleperfAppRunner(int user_id, const std::string& package_name, const std::string& app_type)
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700734 : InAppRunner(user_id, package_name) {
735 // On Android < S, the app type is unknown before running simpleperf_app_runner. Assume it's
736 // profileable.
737 app_type_ = app_type == "unknown" ? "profileable" : app_type;
738 }
Yabin Cui8729bc62021-05-11 11:29:38 -0700739 bool Prepare() override { return GetAndroidVersion() >= kAndroidVersionQ; }
Yabin Cui1a30a582019-01-10 15:35:39 -0800740
741 protected:
742 std::vector<std::string> GetPrefixArgs(const std::string& cmd) {
Yabin Cui92825be2020-12-02 17:06:54 -0800743 std::vector<std::string> args = {"simpleperf_app_runner", package_name_};
744 if (user_id_ != "0") {
745 args.emplace_back("--user");
746 args.emplace_back(user_id_);
747 }
748 args.emplace_back(cmd);
Yabin Cui8729bc62021-05-11 11:29:38 -0700749 if (cmd == "record" && GetAndroidVersion() >= kAndroidVersionS) {
750 args.emplace_back("--add-meta-info");
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700751 args.emplace_back("app_type=" + app_type_);
Yabin Cui8729bc62021-05-11 11:29:38 -0700752 }
Yabin Cui92825be2020-12-02 17:06:54 -0800753 return args;
Yabin Cui1a30a582019-01-10 15:35:39 -0800754 }
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700755
756 std::string app_type_;
Yabin Cui1a30a582019-01-10 15:35:39 -0800757};
758
759} // namespace
760
Yabin Cui94c148d2020-02-18 14:32:33 -0800761static bool allow_run_as = true;
762static bool allow_simpleperf_app_runner = true;
763
764void SetRunInAppToolForTesting(bool run_as, bool simpleperf_app_runner) {
765 allow_run_as = run_as;
766 allow_simpleperf_app_runner = simpleperf_app_runner;
767}
768
Yabin Cui902f9082020-10-15 17:32:48 -0700769static int GetCurrentUserId() {
770 std::unique_ptr<FILE, decltype(&pclose)> fd(popen("am get-current-user", "r"), pclose);
771 if (fd) {
772 char buf[128];
773 if (fgets(buf, sizeof(buf), fd.get()) != nullptr) {
774 int user_id;
775 if (android::base::ParseInt(android::base::Trim(buf), &user_id, 0)) {
776 return user_id;
777 }
778 }
779 }
780 return 0;
781}
782
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700783std::string GetAppType(const std::string& app_package_name) {
784 if (GetAndroidVersion() < kAndroidVersionS) {
785 return "unknown";
786 }
787 std::string cmd = "simpleperf_app_runner " + app_package_name + " --show-app-type";
788 std::unique_ptr<FILE, decltype(&pclose)> fp(popen(cmd.c_str(), "re"), pclose);
789 if (fp) {
790 char buf[128];
791 if (fgets(buf, sizeof(buf), fp.get()) != nullptr) {
792 return android::base::Trim(buf);
793 }
794 }
795 // Can't get app_type. It means the app doesn't exist.
796 return "not_exist";
797}
798
Yabin Cui1a30a582019-01-10 15:35:39 -0800799bool RunInAppContext(const std::string& app_package_name, const std::string& cmd,
800 const std::vector<std::string>& args, size_t workload_args_size,
801 const std::string& output_filepath, bool need_tracepoint_events) {
Yabin Cui902f9082020-10-15 17:32:48 -0700802 int user_id = GetCurrentUserId();
Yabin Cui94c148d2020-02-18 14:32:33 -0800803 std::unique_ptr<InAppRunner> in_app_runner;
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700804
805 std::string app_type = GetAppType(app_package_name);
806 if (app_type == "unknown" && IsAppDebuggable(user_id, app_package_name)) {
807 app_type = "debuggable";
808 }
809
810 if (allow_run_as && app_type == "debuggable") {
Yabin Cui902f9082020-10-15 17:32:48 -0700811 in_app_runner.reset(new RunAs(user_id, app_package_name));
Yabin Cui94c148d2020-02-18 14:32:33 -0800812 if (!in_app_runner->Prepare()) {
813 in_app_runner = nullptr;
814 }
815 }
816 if (!in_app_runner && allow_simpleperf_app_runner) {
Yabin Cuidb19d6d2021-05-12 17:36:02 -0700817 if (app_type == "debuggable" || app_type == "profileable" || app_type == "unknown") {
818 in_app_runner.reset(new SimpleperfAppRunner(user_id, app_package_name, app_type));
819 if (!in_app_runner->Prepare()) {
820 in_app_runner = nullptr;
821 }
Yabin Cuia80f8f72017-07-12 15:50:20 -0700822 }
823 }
Yabin Cui94c148d2020-02-18 14:32:33 -0800824 if (!in_app_runner) {
825 LOG(ERROR) << "Package " << app_package_name
826 << " doesn't exist or isn't debuggable/profileable.";
827 return false;
828 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800829 return in_app_runner->RunCmdInApp(cmd, args, workload_args_size, output_filepath,
830 need_tracepoint_events);
Yabin Cuia80f8f72017-07-12 15:50:20 -0700831}
Yabin Cui616b3a02017-07-14 15:59:56 -0700832
Yabin Cui7c5fe4e2017-12-05 17:44:05 -0800833void AllowMoreOpenedFiles() {
834 // On Android <= O, the hard limit is 4096, and the soft limit is 1024.
835 // On Android >= P, both the hard and soft limit are 32768.
836 rlimit limit;
Yabin Cuic0e1f882023-02-15 10:43:16 -0800837 if (getrlimit(RLIMIT_NOFILE, &limit) != 0) {
838 return;
839 }
840 rlim_t new_limit = limit.rlim_max;
841 if (IsRoot()) {
842 rlim_t sysctl_nr_open = 0;
843 if (ReadUintFromProcFile("/proc/sys/fs/nr_open", &sysctl_nr_open) &&
844 sysctl_nr_open > new_limit) {
845 new_limit = sysctl_nr_open;
846 }
847 }
848 if (limit.rlim_cur < new_limit) {
849 limit.rlim_cur = limit.rlim_max = new_limit;
850 if (setrlimit(RLIMIT_NOFILE, &limit) == 0) {
851 LOG(DEBUG) << "increased open file limit to " << new_limit;
852 }
Yabin Cui7c5fe4e2017-12-05 17:44:05 -0800853 }
854}
Yabin Cui38b6a902017-12-06 14:15:48 -0800855
Yabin Cuic68e66d2018-03-07 15:47:15 -0800856std::string ScopedTempFiles::tmp_dir_;
857std::vector<std::string> ScopedTempFiles::files_to_delete_;
858
Yabin Cui554f3bb2021-05-05 13:34:59 -0700859std::unique_ptr<ScopedTempFiles> ScopedTempFiles::Create(const std::string& tmp_dir) {
860 if (access(tmp_dir.c_str(), W_OK | X_OK) != 0) {
861 return nullptr;
862 }
863 return std::unique_ptr<ScopedTempFiles>(new ScopedTempFiles(tmp_dir));
864}
865
Yabin Cuic68e66d2018-03-07 15:47:15 -0800866ScopedTempFiles::ScopedTempFiles(const std::string& tmp_dir) {
867 CHECK(tmp_dir_.empty()); // No other ScopedTempFiles.
868 tmp_dir_ = tmp_dir;
Yabin Cui38b6a902017-12-06 14:15:48 -0800869}
870
Yabin Cuic68e66d2018-03-07 15:47:15 -0800871ScopedTempFiles::~ScopedTempFiles() {
872 tmp_dir_.clear();
873 for (auto& file : files_to_delete_) {
874 unlink(file.c_str());
875 }
876 files_to_delete_.clear();
877}
878
879std::unique_ptr<TemporaryFile> ScopedTempFiles::CreateTempFile(bool delete_in_destructor) {
880 CHECK(!tmp_dir_.empty());
881 std::unique_ptr<TemporaryFile> tmp_file(new TemporaryFile(tmp_dir_));
Yabin Cuia9cfcde2020-06-29 14:04:44 -0700882 CHECK_NE(tmp_file->fd, -1) << "failed to create tmpfile under " << tmp_dir_;
Yabin Cuic68e66d2018-03-07 15:47:15 -0800883 if (delete_in_destructor) {
884 tmp_file->DoNotRemove();
885 files_to_delete_.push_back(tmp_file->path);
886 }
887 return tmp_file;
Yabin Cui38b6a902017-12-06 14:15:48 -0800888}
Josh Gao30535f22017-12-14 16:10:28 -0800889
Yabin Cuie32ed2b2020-07-23 15:30:14 -0700890void ScopedTempFiles::RegisterTempFile(const std::string& path) {
891 files_to_delete_.emplace_back(path);
892}
893
Josh Gao30535f22017-12-14 16:10:28 -0800894bool SignalIsIgnored(int signo) {
895 struct sigaction act;
896 if (sigaction(signo, nullptr, &act) != 0) {
897 PLOG(FATAL) << "failed to query signal handler for signal " << signo;
898 }
899
900 if ((act.sa_flags & SA_SIGINFO)) {
901 return false;
902 }
903
904 return act.sa_handler == SIG_IGN;
905}
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800906
907int GetAndroidVersion() {
908#if defined(__ANDROID__)
Yabin Cui6e173a42018-08-13 15:58:25 -0700909 static int android_version = -1;
910 if (android_version == -1) {
911 android_version = 0;
Yabin Cui58740ff2021-03-23 13:34:51 -0700912 std::string s = android::base::GetProperty("ro.build.version.codename", "REL");
913 if (s == "REL") {
914 s = android::base::GetProperty("ro.build.version.release", "");
915 }
Yabin Cui6e173a42018-08-13 15:58:25 -0700916 // The release string can be a list of numbers (like 8.1.0), a character (like Q)
917 // or many characters (like OMR1).
918 if (!s.empty()) {
919 // Each Android version has a version number: L is 5, M is 6, N is 7, O is 8, etc.
920 if (s[0] >= 'A' && s[0] <= 'Z') {
921 android_version = s[0] - 'P' + kAndroidVersionP;
922 } else if (isdigit(s[0])) {
923 sscanf(s.c_str(), "%d", &android_version);
924 }
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800925 }
926 }
Yabin Cui6e173a42018-08-13 15:58:25 -0700927 return android_version;
928#else // defined(__ANDROID__)
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800929 return 0;
Yabin Cui6e173a42018-08-13 15:58:25 -0700930#endif
Yabin Cui9e43e9f2018-03-09 15:57:13 -0800931}
Yabin Cui8faa6152018-06-07 15:52:57 -0700932
933std::string GetHardwareFromCpuInfo(const std::string& cpu_info) {
934 for (auto& line : android::base::Split(cpu_info, "\n")) {
935 size_t pos = line.find(':');
936 if (pos != std::string::npos) {
937 std::string key = android::base::Trim(line.substr(0, pos));
938 if (key == "Hardware") {
939 return android::base::Trim(line.substr(pos + 1));
940 }
941 }
942 }
943 return "";
944}
Yabin Cui2db05b42018-07-16 14:04:49 -0700945
946bool MappedFileOnlyExistInMemory(const char* filename) {
947 // Mapped files only existing in memory:
948 // empty name
949 // [anon:???]
950 // [stack]
951 // /dev/*
952 // //anon: generated by kernel/events/core.c.
Yabin Cui739b1542018-10-17 17:19:56 -0700953 // /memfd: created by memfd_create.
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200954 return filename[0] == '\0' || (filename[0] == '[' && strcmp(filename, "[vdso]") != 0) ||
955 strncmp(filename, "//", 2) == 0 || strncmp(filename, "/dev/", 5) == 0 ||
956 strncmp(filename, "/memfd:", 7) == 0;
Yabin Cui2db05b42018-07-16 14:04:49 -0700957}
Yabin Cui38335f42018-07-17 16:06:21 -0700958
959std::string GetCompleteProcessName(pid_t pid) {
Yabin Cui1c6be752023-02-28 11:46:37 -0800960 std::string argv0;
961 if (!android::base::ReadFileToString("/proc/" + std::to_string(pid) + "/cmdline", &argv0)) {
962 // Maybe we don't have permission to read it.
963 return std::string();
Yabin Cui38335f42018-07-17 16:06:21 -0700964 }
Yabin Cui1c6be752023-02-28 11:46:37 -0800965 size_t pos = argv0.find('\0');
966 if (pos != std::string::npos) {
967 argv0.resize(pos);
Yabin Cui38335f42018-07-17 16:06:21 -0700968 }
Yabin Cui504119d2023-03-01 14:02:18 -0800969 // argv0 can be empty if the process is in zombie state. In that case, we don't want to pass argv0
970 // to Basename(), which returns ".".
971 return argv0.empty() ? std::string() : android::base::Basename(argv0);
Yabin Cui38335f42018-07-17 16:06:21 -0700972}
Yabin Cuia22efeb2020-01-29 13:27:33 -0800973
974const char* GetTraceFsDir() {
Yabin Cui142acc82020-10-14 10:24:38 -0700975 static const char* tracefs_dir = nullptr;
976 if (tracefs_dir == nullptr) {
977 for (const char* path : {"/sys/kernel/debug/tracing", "/sys/kernel/tracing"}) {
978 if (IsDir(path)) {
979 tracefs_dir = path;
980 break;
981 }
Yabin Cuia22efeb2020-01-29 13:27:33 -0800982 }
983 }
Yabin Cui142acc82020-10-14 10:24:38 -0700984 return tracefs_dir;
Yabin Cuia22efeb2020-01-29 13:27:33 -0800985}
Yabin Cui84c55ff2020-07-09 14:14:22 -0700986
Yabin Cuid703bb32021-01-05 16:45:52 -0800987std::optional<std::pair<int, int>> GetKernelVersion() {
Yabin Cui71aec162021-11-03 15:23:22 -0700988 static std::optional<std::pair<int, int>> kernel_version;
989 if (!kernel_version.has_value()) {
990 utsname uname_buf;
991 int major;
992 int minor;
993 if (TEMP_FAILURE_RETRY(uname(&uname_buf)) != 0 ||
994 sscanf(uname_buf.release, "%d.%d", &major, &minor) != 2) {
995 return std::nullopt;
996 }
997 kernel_version = std::make_pair(major, minor);
Yabin Cui84c55ff2020-07-09 14:14:22 -0700998 }
Yabin Cui71aec162021-11-03 15:23:22 -0700999 return kernel_version;
Yabin Cui84c55ff2020-07-09 14:14:22 -07001000}
Yabin Cuifaa7b922021-01-11 17:35:57 -08001001
Yabin Cui3485af92021-10-27 10:50:53 -07001002#if defined(__ANDROID__)
1003bool IsInAppUid() {
1004 return getuid() % AID_USER_OFFSET >= AID_APP_START;
1005}
1006#endif
1007
Yabin Cuia89a3742021-02-11 13:14:54 -08001008std::optional<uid_t> GetProcessUid(pid_t pid) {
1009 std::string status_file = "/proc/" + std::to_string(pid) + "/status";
Yabin Cui40eef9e2021-04-13 13:08:31 -07001010 LineReader reader(status_file);
1011 if (!reader.Ok()) {
Yabin Cuia89a3742021-02-11 13:14:54 -08001012 return std::nullopt;
1013 }
1014
Yabin Cui40eef9e2021-04-13 13:08:31 -07001015 std::string* line;
Yabin Cuia89a3742021-02-11 13:14:54 -08001016 while ((line = reader.ReadLine()) != nullptr) {
Yabin Cui40eef9e2021-04-13 13:08:31 -07001017 if (android::base::StartsWith(*line, "Uid:")) {
Yabin Cuia89a3742021-02-11 13:14:54 -08001018 uid_t uid;
Yabin Cui40eef9e2021-04-13 13:08:31 -07001019 if (sscanf(line->data() + strlen("Uid:"), "%u", &uid) == 1) {
Yabin Cuia89a3742021-02-11 13:14:54 -08001020 return uid;
1021 }
1022 }
1023 }
1024 return std::nullopt;
1025}
1026
Yabin Cuifaa7b922021-01-11 17:35:57 -08001027} // namespace simpleperf