blob: 89ca7f1b4e947a2dc5694e7343a5876934a3bf93 [file] [log] [blame]
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001/*
2 * Copyright (C) 2019 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//#define LOG_NDEBUG 0
18#define LOG_TAG "libprocessgroup"
19
T.J. Mercier39846112024-10-09 22:40:26 +000020#include <task_profiles.h>
21
22#include <map>
23#include <string>
24
T.J. Mercier54bfde02024-06-04 23:25:29 +000025#include <dirent.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080026#include <fcntl.h>
T.J. Mercier39846112024-10-09 22:40:26 +000027#include <sched.h>
28#include <sys/resource.h>
T.J. Mercier54bfde02024-06-04 23:25:29 +000029#include <unistd.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080030
31#include <android-base/file.h>
32#include <android-base/logging.h>
T.J. Mercierba18f502025-01-06 21:47:45 +000033#include <android-base/parseint.h>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080034#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080035#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080036#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080037#include <android-base/threads.h>
38
T.J. Mercier39846112024-10-09 22:40:26 +000039#include <build_flags.h>
40
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080041#include <cutils/android_filesystem_config.h>
42
43#include <json/reader.h>
44#include <json/value.h>
45
46using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080047using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080048using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080049using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080050using android::base::unique_fd;
51using android::base::WriteStringToFile;
52
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080053static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
54static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
55
56static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
57 "/etc/task_profiles/task_profiles_%u.json";
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +000058namespace {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080059
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080060class FdCacheHelper {
61 public:
62 enum FdState {
63 FDS_INACCESSIBLE = -1,
64 FDS_APP_DEPENDENT = -2,
65 FDS_NOT_CACHED = -3,
66 };
67
68 static void Cache(const std::string& path, android::base::unique_fd& fd);
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +000069
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080070 static void Drop(android::base::unique_fd& fd);
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +000071
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080072 static void Init(const std::string& path, android::base::unique_fd& fd);
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +000073
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080074 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
75
76 private:
77 static bool IsAppDependentPath(const std::string& path);
78};
79
80void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
81 // file descriptors for app-dependent paths can't be cached
82 if (IsAppDependentPath(path)) {
83 // file descriptor is not cached
84 fd.reset(FDS_APP_DEPENDENT);
85 return;
86 }
87 // file descriptor can be cached later on request
88 fd.reset(FDS_NOT_CACHED);
89}
90
91void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
92 if (fd != FDS_NOT_CACHED) {
93 return;
94 }
95
96 if (access(path.c_str(), W_OK) != 0) {
97 // file is not accessible
98 fd.reset(FDS_INACCESSIBLE);
99 return;
100 }
101
102 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
103 if (tmp_fd < 0) {
104 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
105 fd.reset(FDS_INACCESSIBLE);
106 return;
107 }
108
109 fd = std::move(tmp_fd);
110}
111
112void FdCacheHelper::Drop(android::base::unique_fd& fd) {
113 if (fd == FDS_NOT_CACHED) {
114 return;
115 }
116
117 fd.reset(FDS_NOT_CACHED);
118}
119
120bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
121 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
122}
123
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +0000124} // namespace
125
Bart Van Assche4c99e962022-02-03 19:50:16 +0000126IProfileAttribute::~IProfileAttribute() = default;
127
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700128const std::string& ProfileAttribute::file_name() const {
129 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
130 return file_name_;
131}
132
T.J. Mercierfcb86662024-08-01 20:52:30 +0000133void ProfileAttribute::Reset(const CgroupControllerWrapper& controller,
134 const std::string& file_name, const std::string& file_v2_name) {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700135 controller_ = controller;
136 file_name_ = file_name;
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700137 file_v2_name_ = file_v2_name;
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700138}
139
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000140static bool isSystemApp(uid_t uid) {
141 return uid < AID_APP_START;
142}
143
T.J. Mercierc897b0a2024-12-11 23:07:19 +0000144std::string ConvertUidToPath(const char* root_cgroup_path, uid_t uid, bool v2_path) {
145 if (android::libprocessgroup_flags::cgroup_v2_sys_app_isolation() && v2_path) {
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000146 if (isSystemApp(uid))
147 return StringPrintf("%s/system/uid_%u", root_cgroup_path, uid);
148 else
149 return StringPrintf("%s/apps/uid_%u", root_cgroup_path, uid);
150 }
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000151 return StringPrintf("%s/uid_%u", root_cgroup_path, uid);
152}
153
T.J. Mercierc897b0a2024-12-11 23:07:19 +0000154std::string ConvertUidPidToPath(const char* root_cgroup_path, uid_t uid, pid_t pid, bool v2_path) {
155 const std::string uid_path = ConvertUidToPath(root_cgroup_path, uid, v2_path);
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000156 return StringPrintf("%s/pid_%d", uid_path.c_str(), pid);
157}
158
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700159bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
160 if (controller()->version() == 2) {
T.J. Mercierc897b0a2024-12-11 23:07:19 +0000161 const std::string cgroup_path = ConvertUidPidToPath(controller()->path(), uid, pid, true);
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000162 *path = cgroup_path + "/" + file_name();
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700163 return true;
164 }
165 return GetPathForTask(pid, path);
166}
167
T.J. Mercier1c007992024-01-25 16:29:54 +0000168bool ProfileAttribute::GetPathForTask(pid_t tid, std::string* path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800169 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700170 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800171 return false;
172 }
173
174 if (path == nullptr) {
175 return true;
176 }
177
178 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700179 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800180 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700181 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
182 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800183 }
184 return true;
185}
186
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000187// NOTE: This function is for cgroup v2 only
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000188bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
189 if (path == nullptr) {
190 return true;
191 }
192
T.J. Mercierc897b0a2024-12-11 23:07:19 +0000193 const std::string cgroup_path = ConvertUidToPath(controller()->path(), uid, true);
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000194 *path = cgroup_path + "/" + file_name();
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000195 return true;
196}
197
T.J. Mercier1c007992024-01-25 16:29:54 +0000198bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
T.J. Mercier07500812024-10-09 17:41:32 +0000199 const auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
200 if (!WriteStringToFile(std::to_string(slack_), file)) {
201 if (errno == ENOENT) {
202 // This happens when process is already dead
203 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800204 }
T.J. Mercier07500812024-10-09 17:41:32 +0000205 PLOG(ERROR) << "set_timerslack_ns write failed";
206 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800207 }
208
209 return true;
210}
211
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700212bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800213 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700214 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000215 if (optional_) {
216 return true;
217 } else {
218 LOG(ERROR) << "No such cgroup attribute: " << path;
219 return false;
220 }
221 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700222 // The PLOG() statement below uses the error code stored in `errno` by
223 // WriteStringToFile() because access() only overwrites `errno` if it fails
224 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800225 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
226 return false;
227 }
228
229 return true;
230}
231
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700232bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
233 std::string path;
234
235 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
236 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
237 return false;
238 }
239
240 return WriteValueToFile(path);
241}
242
T.J. Mercier1c007992024-01-25 16:29:54 +0000243bool SetAttributeAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700244 std::string path;
245
246 if (!attribute_->GetPathForTask(tid, &path)) {
247 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
248 return false;
249 }
250
251 return WriteValueToFile(path);
252}
253
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000254bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
255 std::string path;
256
257 if (!attribute_->GetPathForUID(uid, &path)) {
258 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
259 return false;
260 }
261
262 if (!WriteStringToFile(value_, path)) {
263 if (access(path.c_str(), F_OK) < 0) {
264 if (optional_) {
265 return true;
266 } else {
267 LOG(ERROR) << "No such cgroup attribute: " << path;
268 return false;
269 }
270 }
271 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
272 return false;
273 }
274 return true;
275}
276
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000277bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
278 return IsValidForTask(pid);
279}
280
T.J. Mercier1c007992024-01-25 16:29:54 +0000281bool SetAttributeAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000282 std::string path;
283
284 if (!attribute_->GetPathForTask(tid, &path)) {
285 return false;
286 }
287
288 if (!access(path.c_str(), W_OK)) {
289 // operation will succeed
290 return true;
291 }
292
293 if (!access(path.c_str(), F_OK)) {
294 // file exists but not writable
295 return false;
296 }
297
298 // file does not exist, ignore if optional
299 return optional_;
300}
301
T.J. Mercierfcb86662024-08-01 20:52:30 +0000302SetCgroupAction::SetCgroupAction(const CgroupControllerWrapper& c, const std::string& p)
Rick Yiud4c53512021-11-21 15:57:36 +0800303 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800304 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
305 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
306 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800307}
308
T.J. Mercier1c007992024-01-25 16:29:54 +0000309bool SetCgroupAction::AddTidToCgroup(pid_t tid, int fd, ResourceCacheType cache_type) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800310 if (tid <= 0) {
311 return true;
312 }
313
314 std::string value = std::to_string(tid);
315
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700316 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
317 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800318 }
319
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700320 // If the thread is in the process of exiting, don't flag an error
321 if (errno == ESRCH) {
322 return true;
323 }
324
Bart Van Asschedf985342023-11-13 15:19:43 -0800325 const char* controller_name = controller()->name();
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700326 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
327 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
328 // This is an abnormal case happening only in testing, so report it only once
329 static bool empty_cpuset_reported = false;
330
331 if (empty_cpuset_reported) {
332 return true;
333 }
334
335 LOG(ERROR) << "Failed to add task '" << value
336 << "' into cpuset because all cpus in that cpuset are offline";
337 empty_cpuset_reported = true;
338 } else {
Bart Van Asschedf985342023-11-13 15:19:43 -0800339 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; path=" << path_ << "; "
340 << (cache_type == RCT_TASK ? "task" : "process");
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700341 }
342
343 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800344}
345
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800346ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
347 int id) const {
348 std::lock_guard<std::mutex> lock(fd_mutex_);
349 if (FdCacheHelper::IsCached(fd_[cache_type])) {
350 // fd is cached, reuse it
Bart Van Asschedf985342023-11-13 15:19:43 -0800351 if (!AddTidToCgroup(id, fd_[cache_type], cache_type)) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800352 LOG(ERROR) << "Failed to add task into cgroup";
353 return ProfileAction::FAIL;
354 }
355 return ProfileAction::SUCCESS;
356 }
357
358 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
359 // no permissions to access the file, ignore
360 return ProfileAction::SUCCESS;
361 }
362
363 if (cache_type == ResourceCacheType::RCT_TASK &&
364 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
365 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700366 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800367 return ProfileAction::FAIL;
368 }
369
370 return ProfileAction::UNUSED;
371}
372
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800373bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800374 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
375 if (result != ProfileAction::UNUSED) {
376 return result == ProfileAction::SUCCESS;
377 }
378
379 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700380 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800381 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
382 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700383 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800384 return false;
385 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800386 if (!AddTidToCgroup(pid, tmp_fd, RCT_PROCESS)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800387 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800388 return false;
389 }
390
391 return true;
392}
393
T.J. Mercier1c007992024-01-25 16:29:54 +0000394bool SetCgroupAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800395 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
396 if (result != ProfileAction::UNUSED) {
397 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800398 }
399
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800400 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700401 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800402 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
403 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700404 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800405 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800406 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800407 if (!AddTidToCgroup(tid, tmp_fd, RCT_TASK)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800408 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800409 return false;
410 }
411
412 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800413}
414
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800415void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800416 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800417 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
418 // include regex evaluations
419 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
420 return;
421 }
422 switch (cache_type) {
423 case (ProfileAction::RCT_TASK):
424 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
425 break;
426 case (ProfileAction::RCT_PROCESS):
427 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
428 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
429 break;
430 default:
431 LOG(ERROR) << "Invalid cache type is specified!";
432 break;
433 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800434}
435
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800436void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800437 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800438 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800439}
440
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000441bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
442 std::lock_guard<std::mutex> lock(fd_mutex_);
443 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
444 return true;
445 }
446
447 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
448 return false;
449 }
450
451 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
452 return access(procs_path.c_str(), W_OK) == 0;
453}
454
455bool SetCgroupAction::IsValidForTask(int) const {
456 std::lock_guard<std::mutex> lock(fd_mutex_);
457 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
458 return true;
459 }
460
461 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
462 return false;
463 }
464
465 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
466 // application-dependent path can't be used with tid
467 return false;
468 }
469
470 std::string tasks_path = controller()->GetTasksFilePath(path_);
471 return access(tasks_path.c_str(), W_OK) == 0;
472}
473
Rick Yiu9221b1e2022-02-10 16:44:43 +0800474WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
475 const std::string& value, bool logfailures)
476 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
477 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
478 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800479}
Rick Yiubc1ad962020-10-26 20:32:52 +0800480
Rick Yiu9221b1e2022-02-10 16:44:43 +0800481bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000482 uid_t uid, pid_t pid, bool logfailures) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800483 std::string value(value_);
484
485 value = StringReplace(value, "<uid>", std::to_string(uid), true);
486 value = StringReplace(value, "<pid>", std::to_string(pid), true);
487
488 CacheUseResult result = UseCachedFd(cache_type, value);
489
490 if (result != ProfileAction::UNUSED) {
491 return result == ProfileAction::SUCCESS;
492 }
493
494 std::string path;
495 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
496 path = task_path_;
497 } else {
498 path = proc_path_;
499 }
500
Rick Yiud4c53512021-11-21 15:57:36 +0800501 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
502 // O_TRUNC which causes kernfs_mutex contention
503 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800504
Rick Yiud4c53512021-11-21 15:57:36 +0800505 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700506 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800507 return false;
508 }
509
510 if (!WriteStringToFd(value, tmp_fd)) {
511 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800512 return false;
513 }
514
515 return true;
516}
517
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800518ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
519 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800520 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800521 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800522 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800523 bool ret = WriteStringToFd(value, fd_[cache_type]);
524
525 if (!ret && logfailures_) {
526 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
527 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
528 } else {
529 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
530 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800531 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800532 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800533 }
534
Rick Yiu9221b1e2022-02-10 16:44:43 +0800535 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800536 // no permissions to access the file, ignore
537 return ProfileAction::SUCCESS;
538 }
539
Rick Yiu9221b1e2022-02-10 16:44:43 +0800540 if (cache_type == ResourceCacheType::RCT_TASK &&
541 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800542 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700543 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800544 return ProfileAction::FAIL;
545 }
546 return ProfileAction::UNUSED;
547}
548
549bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800550 if (!proc_path_.empty()) {
551 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800552 }
553
Rick Yiu9221b1e2022-02-10 16:44:43 +0800554 DIR* d;
555 struct dirent* de;
556 char proc_path[255];
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000557 pid_t t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800558
Rick Yiu9221b1e2022-02-10 16:44:43 +0800559 sprintf(proc_path, "/proc/%d/task", pid);
560 if (!(d = opendir(proc_path))) {
561 return false;
562 }
563
564 while ((de = readdir(d))) {
565 if (de->d_name[0] == '.') {
566 continue;
567 }
568
569 t_pid = atoi(de->d_name);
570
571 if (!t_pid) {
572 continue;
573 }
574
575 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
576 }
577
578 closedir(d);
579
580 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800581}
582
T.J. Mercier1c007992024-01-25 16:29:54 +0000583bool WriteFileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800584 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
585}
Rick Yiubc1ad962020-10-26 20:32:52 +0800586
Rick Yiu9221b1e2022-02-10 16:44:43 +0800587void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
588 std::lock_guard<std::mutex> lock(fd_mutex_);
589 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
590 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800591 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800592 switch (cache_type) {
593 case (ProfileAction::RCT_TASK):
594 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
595 break;
596 case (ProfileAction::RCT_PROCESS):
597 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
598 break;
599 default:
600 LOG(ERROR) << "Invalid cache type is specified!";
601 break;
602 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800603}
604
Rick Yiu9221b1e2022-02-10 16:44:43 +0800605void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800606 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800607 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800608}
609
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000610bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
611 std::lock_guard<std::mutex> lock(fd_mutex_);
612 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
613 return true;
614 }
615
616 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
617 return false;
618 }
619
620 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
621}
622
623bool WriteFileAction::IsValidForTask(int) const {
624 std::lock_guard<std::mutex> lock(fd_mutex_);
625 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
626 return true;
627 }
628
629 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
630 return false;
631 }
632
633 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
634 // application-dependent path can't be used with tid
635 return false;
636 }
637
638 return access(task_path_.c_str(), W_OK) == 0;
639}
640
T.J. Mercier39846112024-10-09 22:40:26 +0000641bool SetSchedulerPolicyAction::isNormalPolicy(int policy) {
642 return policy == SCHED_OTHER || policy == SCHED_BATCH || policy == SCHED_IDLE;
643}
644
645bool SetSchedulerPolicyAction::toPriority(int policy, int virtual_priority, int& priority_out) {
646 constexpr int VIRTUAL_PRIORITY_MIN = 1;
647 constexpr int VIRTUAL_PRIORITY_MAX = 99;
648
649 if (virtual_priority < VIRTUAL_PRIORITY_MIN || virtual_priority > VIRTUAL_PRIORITY_MAX) {
650 LOG(WARNING) << "SetSchedulerPolicy: invalid priority (" << virtual_priority
651 << ") for policy (" << policy << ")";
652 return false;
653 }
654
655 const int min = sched_get_priority_min(policy);
656 if (min == -1) {
657 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get min sched priority for policy " << policy;
658 return false;
659 }
660
661 const int max = sched_get_priority_max(policy);
662 if (max == -1) {
663 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get max sched priority for policy " << policy;
664 return false;
665 }
666
667 priority_out = min + (virtual_priority - VIRTUAL_PRIORITY_MIN) * (max - min) /
668 (VIRTUAL_PRIORITY_MAX - VIRTUAL_PRIORITY_MIN);
669
670 return true;
671}
672
673bool SetSchedulerPolicyAction::ExecuteForTask(pid_t tid) const {
674 struct sched_param param = {};
675 param.sched_priority = isNormalPolicy(policy_) ? 0 : *priority_or_nice_;
676 if (sched_setscheduler(tid, policy_, &param) == -1) {
677 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply scheduler policy (" << policy_
678 << ") with priority (" << *priority_or_nice_ << ") to tid " << tid;
679 return false;
680 }
681
682 if (isNormalPolicy(policy_) && priority_or_nice_ &&
683 setpriority(PRIO_PROCESS, tid, *priority_or_nice_) == -1) {
684 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply nice (" << *priority_or_nice_
685 << ") to tid " << tid;
686 return false;
687 }
688
689 return true;
690}
691
Rick Yiu0b211fa2019-09-16 19:07:17 +0800692bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
693 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800694 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800695 }
696 return true;
697}
698
T.J. Mercier1c007992024-01-25 16:29:54 +0000699bool ApplyProfileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800700 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700701 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800702 }
703 return true;
704}
705
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800706void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800707 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800708 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800709 }
710}
711
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800712void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800713 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800714 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800715 }
716}
717
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000718bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
719 for (const auto& profile : profiles_) {
720 if (!profile->IsValidForProcess(uid, pid)) {
721 return false;
722 }
723 }
724 return true;
725}
726
T.J. Mercier1c007992024-01-25 16:29:54 +0000727bool ApplyProfileAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000728 for (const auto& profile : profiles_) {
729 if (!profile->IsValidForTask(tid)) {
730 return false;
731 }
732 }
733 return true;
734}
735
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800736void TaskProfile::MoveTo(TaskProfile* profile) {
737 profile->elements_ = std::move(elements_);
738 profile->res_cached_ = res_cached_;
739}
740
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800741bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
742 for (const auto& element : elements_) {
743 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000744 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800745 return false;
746 }
747 }
748 return true;
749}
750
T.J. Mercier1c007992024-01-25 16:29:54 +0000751bool TaskProfile::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800752 if (tid == 0) {
753 tid = GetThreadId();
754 }
755 for (const auto& element : elements_) {
756 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000757 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800758 return false;
759 }
760 }
761 return true;
762}
763
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000764bool TaskProfile::ExecuteForUID(uid_t uid) const {
765 for (const auto& element : elements_) {
766 if (!element->ExecuteForUID(uid)) {
767 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
768 return false;
769 }
770 }
771 return true;
772}
773
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800774void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800775 if (res_cached_) {
776 return;
777 }
778
779 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800780 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800781 }
782
783 res_cached_ = true;
784}
785
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800786void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600787 if (!res_cached_) {
788 return;
789 }
790
791 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800792 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600793 }
794
795 res_cached_ = false;
796}
797
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000798bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
799 for (const auto& element : elements_) {
800 if (!element->IsValidForProcess(uid, pid)) return false;
801 }
802 return true;
803}
804
T.J. Mercier1c007992024-01-25 16:29:54 +0000805bool TaskProfile::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000806 for (const auto& element : elements_) {
807 if (!element->IsValidForTask(tid)) return false;
808 }
809 return true;
810}
811
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800812void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600813 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800814 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600815 }
816}
817
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800818TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700819 // Deliberately leak this object to avoid a race between destruction on
820 // process exit and concurrent access from another thread.
821 static auto* instance = new TaskProfiles;
822 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800823}
824
825TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800826 // load system task profiles
827 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
828 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
829 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800830
831 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800832 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800833 if (api_level > 0) {
834 std::string api_profiles_path =
835 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
836 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800837 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800838 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800839 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800840 }
841 }
842
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800843 // load vendor task profiles if the file exists
844 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
845 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
846 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
847 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800848 }
849}
850
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800851bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800852 std::string json_doc;
853
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800854 if (!android::base::ReadFileToString(file_name, &json_doc)) {
855 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800856 return false;
857 }
858
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800859 Json::CharReaderBuilder builder;
860 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800861 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800862 std::string errorMessage;
863 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
864 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800865 return false;
866 }
867
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800868 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800869 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
870 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800871 std::string controller_name = attr[i]["Controller"].asString();
872 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000873 std::string file_v2_attr = attr[i]["FileV2"].asString();
874
875 if (!file_v2_attr.empty() && file_attr.empty()) {
876 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
877 return false;
878 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800879
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700880 auto controller = cg_map.FindController(controller_name);
881 if (controller.HasValue()) {
882 auto iter = attributes_.find(name);
883 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000884 attributes_[name] =
885 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800886 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700887 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800888 }
889 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700890 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800891 }
892 }
893
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800894 const Json::Value& profiles_val = root["Profiles"];
895 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
896 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800897
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800898 std::string profile_name = profile_val["Name"].asString();
899 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000900 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800901
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800902 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
903 const Json::Value& action_val = actions[act_idx];
904 std::string action_name = action_val["Name"].asString();
905 const Json::Value& params_val = action_val["Params"];
906 if (action_name == "JoinCgroup") {
907 std::string controller_name = params_val["Controller"].asString();
908 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800909
Yifan Hong53e0deb2019-03-22 17:01:08 -0700910 auto controller = cg_map.FindController(controller_name);
911 if (controller.HasValue()) {
Bart Van Assche2953a922023-11-14 07:33:00 -0800912 if (controller.version() == 1) {
913 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
914 } else {
915 LOG(WARNING) << "A JoinCgroup action in the " << profile_name
916 << " profile is used for controller " << controller_name
917 << " in the cgroup v2 hierarchy and will be ignored";
918 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800919 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800920 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800921 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800922 } else if (action_name == "SetTimerSlack") {
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +0000923 const std::string slack_string = params_val["Slack"].asString();
T.J. Mercierba18f502025-01-06 21:47:45 +0000924 if (long slack; android::base::ParseInt(slack_string, &slack) && slack >= 0) {
925 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800926 } else {
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +0000927 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_string;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800928 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800929 } else if (action_name == "SetAttribute") {
930 std::string attr_name = params_val["Name"].asString();
931 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000932 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800933
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800934 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800935 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000936 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
937 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800938 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800939 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800940 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800941 } else if (action_name == "WriteFile") {
942 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800943 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800944 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800945 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800946 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800947 std::string attr_logfailures = params_val["LogFailures"].asString();
948 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800949 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
950 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800951 } else if (attr_filepath.empty()) {
952 LOG(WARNING) << "WriteFile: invalid parameter: "
953 << "empty filepath";
954 } else if (attr_value.empty()) {
955 LOG(WARNING) << "WriteFile: invalid parameter: "
956 << "empty value";
957 }
T.J. Mercier39846112024-10-09 22:40:26 +0000958 } else if (action_name == "SetSchedulerPolicy") {
959 const std::map<std::string, int> POLICY_MAP = {
960 {"SCHED_OTHER", SCHED_OTHER},
961 {"SCHED_BATCH", SCHED_BATCH},
962 {"SCHED_IDLE", SCHED_IDLE},
963 {"SCHED_FIFO", SCHED_FIFO},
964 {"SCHED_RR", SCHED_RR},
965 };
966 const std::string policy_str = params_val["Policy"].asString();
967
968 const auto it = POLICY_MAP.find(policy_str);
969 if (it == POLICY_MAP.end()) {
970 LOG(WARNING) << "SetSchedulerPolicy: invalid policy " << policy_str;
971 continue;
972 }
973
974 const int policy = it->second;
975
976 if (SetSchedulerPolicyAction::isNormalPolicy(policy)) {
977 if (params_val.isMember("Priority")) {
978 LOG(WARNING) << "SetSchedulerPolicy: Normal policies (" << policy_str
979 << ") use Nice values, not Priority values";
980 }
981
982 if (params_val.isMember("Nice")) {
983 // If present, this optional value will be passed in an additional syscall
984 // to setpriority(), since the sched_priority value must be 0 for calls to
985 // sched_setscheduler() with "normal" policies.
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +0000986 const std::string nice_string = params_val["Nice"].asString();
T.J. Mercierba18f502025-01-06 21:47:45 +0000987 int nice;
988 if (!android::base::ParseInt(nice_string, &nice)) {
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +0000989 LOG(FATAL) << "Invalid nice value specified: " << nice_string;
990 }
T.J. Mercier39846112024-10-09 22:40:26 +0000991 const int LINUX_MIN_NICE = -20;
992 const int LINUX_MAX_NICE = 19;
T.J. Mercierba18f502025-01-06 21:47:45 +0000993 if (nice < LINUX_MIN_NICE || nice > LINUX_MAX_NICE) {
994 LOG(WARNING) << "SetSchedulerPolicy: Provided nice (" << nice
T.J. Mercier39846112024-10-09 22:40:26 +0000995 << ") appears out of range.";
996 }
T.J. Mercierba18f502025-01-06 21:47:45 +0000997 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy, nice));
T.J. Mercier39846112024-10-09 22:40:26 +0000998 } else {
999 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy));
1000 }
1001 } else {
1002 if (params_val.isMember("Nice")) {
1003 LOG(WARNING) << "SetSchedulerPolicy: Real-time policies (" << policy_str
1004 << ") use Priority values, not Nice values";
1005 }
1006
1007 // This is a "virtual priority" as described by `man 2 sched_get_priority_min`
1008 // that will be mapped onto the following range for the provided policy:
1009 // [sched_get_priority_min(), sched_get_priority_max()]
T.J. Mercier39846112024-10-09 22:40:26 +00001010
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +00001011 const std::string priority_string = params_val["Priority"].asString();
T.J. Mercierba18f502025-01-06 21:47:45 +00001012 if (long virtual_priority;
1013 android::base::ParseInt(priority_string, &virtual_priority) &&
1014 virtual_priority > 0) {
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +00001015 int priority;
T.J. Mercierba18f502025-01-06 21:47:45 +00001016 if (SetSchedulerPolicyAction::toPriority(policy, virtual_priority,
Siarhei Vishniakoua3cf8262024-10-31 22:38:50 +00001017 priority)) {
1018 profile->Add(
1019 std::make_unique<SetSchedulerPolicyAction>(policy, priority));
1020 }
1021 } else {
1022 LOG(WARNING) << "Invalid priority value: " << priority_string;
T.J. Mercier39846112024-10-09 22:40:26 +00001023 }
1024 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001025 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -08001026 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001027 }
1028 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -08001029 auto iter = profiles_.find(profile_name);
1030 if (iter == profiles_.end()) {
1031 profiles_[profile_name] = profile;
1032 } else {
1033 // Move the content rather that replace the profile because old profile might be
1034 // referenced from an aggregate profile if vendor overrides task profiles
1035 profile->MoveTo(iter->second.get());
1036 profile.reset();
1037 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001038 }
1039
1040 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
1041 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
1042 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
1043
1044 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
1045 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
1046 std::vector<std::shared_ptr<TaskProfile>> profiles;
1047 bool ret = true;
1048
1049 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
1050 std::string profile_name = aggregateprofiles[pf_idx].asString();
1051
1052 if (profile_name == aggregateprofile_name) {
1053 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
1054 ret = false;
1055 break;
1056 } else if (profiles_.find(profile_name) == profiles_.end()) {
1057 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
1058 ret = false;
1059 break;
1060 } else {
1061 profiles.push_back(profiles_[profile_name]);
1062 }
1063 }
1064 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +00001065 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001066 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
1067 profiles_[aggregateprofile_name] = profile;
1068 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001069 }
1070
1071 return true;
1072}
1073
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001074TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001075 auto iter = profiles_.find(name);
1076
1077 if (iter != profiles_.end()) {
1078 return iter->second.get();
1079 }
1080 return nullptr;
1081}
1082
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001083const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001084 auto iter = attributes_.find(name);
1085
1086 if (iter != attributes_.end()) {
1087 return iter->second.get();
1088 }
1089 return nullptr;
1090}
Rick Yiu0b211fa2019-09-16 19:07:17 +08001091
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001092template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001093bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
1094 for (const auto& name : profiles) {
1095 TaskProfile* profile = GetProfile(name);
1096 if (profile != nullptr) {
1097 if (use_fd_cache) {
1098 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1099 }
1100 if (!profile->ExecuteForUID(uid)) {
1101 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1102 }
1103 } else {
1104 PLOG(WARNING) << "Failed to find " << name << "process profile";
1105 }
1106 }
1107 return true;
1108}
1109
1110template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001111bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1112 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001113 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001114 for (const auto& name : profiles) {
1115 TaskProfile* profile = GetProfile(name);
1116 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001117 if (use_fd_cache) {
1118 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1119 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001120 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001121 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001122 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001123 }
1124 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001125 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001126 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001127 }
1128 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001129 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001130}
1131
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001132template <typename T>
T.J. Mercier1c007992024-01-25 16:29:54 +00001133bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001134 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001135 for (const auto& name : profiles) {
1136 TaskProfile* profile = GetProfile(name);
1137 if (profile != nullptr) {
1138 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001139 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001140 }
1141 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001142 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001143 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001144 }
1145 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001146 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001147 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001148 }
1149 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001150 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001151}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001152
1153template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1154 std::span<const std::string> profiles,
1155 bool use_fd_cache);
1156template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1157 std::span<const std::string_view> profiles,
1158 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001159template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001160 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001161template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001162 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001163template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1164 bool use_fd_cache);