blob: c96feb3140f4150d30aaf9b761a10922df7b2737 [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>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080033#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080034#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080035#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080036#include <android-base/threads.h>
37
T.J. Mercier39846112024-10-09 22:40:26 +000038#include <build_flags.h>
39
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080040#include <cutils/android_filesystem_config.h>
41
42#include <json/reader.h>
43#include <json/value.h>
44
45using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080046using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080047using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080048using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080049using android::base::unique_fd;
50using android::base::WriteStringToFile;
51
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080052static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
53static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
54
55static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
56 "/etc/task_profiles/task_profiles_%u.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080057
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080058class FdCacheHelper {
59 public:
60 enum FdState {
61 FDS_INACCESSIBLE = -1,
62 FDS_APP_DEPENDENT = -2,
63 FDS_NOT_CACHED = -3,
64 };
65
66 static void Cache(const std::string& path, android::base::unique_fd& fd);
67 static void Drop(android::base::unique_fd& fd);
68 static void Init(const std::string& path, android::base::unique_fd& fd);
69 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
70
71 private:
72 static bool IsAppDependentPath(const std::string& path);
73};
74
75void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
76 // file descriptors for app-dependent paths can't be cached
77 if (IsAppDependentPath(path)) {
78 // file descriptor is not cached
79 fd.reset(FDS_APP_DEPENDENT);
80 return;
81 }
82 // file descriptor can be cached later on request
83 fd.reset(FDS_NOT_CACHED);
84}
85
86void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
87 if (fd != FDS_NOT_CACHED) {
88 return;
89 }
90
91 if (access(path.c_str(), W_OK) != 0) {
92 // file is not accessible
93 fd.reset(FDS_INACCESSIBLE);
94 return;
95 }
96
97 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
98 if (tmp_fd < 0) {
99 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
100 fd.reset(FDS_INACCESSIBLE);
101 return;
102 }
103
104 fd = std::move(tmp_fd);
105}
106
107void FdCacheHelper::Drop(android::base::unique_fd& fd) {
108 if (fd == FDS_NOT_CACHED) {
109 return;
110 }
111
112 fd.reset(FDS_NOT_CACHED);
113}
114
115bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
116 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
117}
118
Bart Van Assche4c99e962022-02-03 19:50:16 +0000119IProfileAttribute::~IProfileAttribute() = default;
120
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700121const std::string& ProfileAttribute::file_name() const {
122 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
123 return file_name_;
124}
125
T.J. Mercierfcb86662024-08-01 20:52:30 +0000126void ProfileAttribute::Reset(const CgroupControllerWrapper& controller,
127 const std::string& file_name, const std::string& file_v2_name) {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700128 controller_ = controller;
129 file_name_ = file_name;
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700130 file_v2_name_ = file_v2_name;
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700131}
132
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000133static bool isSystemApp(uid_t uid) {
134 return uid < AID_APP_START;
135}
136
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000137std::string ConvertUidToPath(const char* root_cgroup_path, uid_t uid) {
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000138 if (android::libprocessgroup_flags::cgroup_v2_sys_app_isolation()) {
139 if (isSystemApp(uid))
140 return StringPrintf("%s/system/uid_%u", root_cgroup_path, uid);
141 else
142 return StringPrintf("%s/apps/uid_%u", root_cgroup_path, uid);
143 }
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000144 return StringPrintf("%s/uid_%u", root_cgroup_path, uid);
145}
146
147std::string ConvertUidPidToPath(const char* root_cgroup_path, uid_t uid, pid_t pid) {
148 const std::string uid_path = ConvertUidToPath(root_cgroup_path, uid);
149 return StringPrintf("%s/pid_%d", uid_path.c_str(), pid);
150}
151
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700152bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
153 if (controller()->version() == 2) {
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000154 const std::string cgroup_path = ConvertUidPidToPath(controller()->path(), uid, pid);
155 *path = cgroup_path + "/" + file_name();
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700156 return true;
157 }
158 return GetPathForTask(pid, path);
159}
160
T.J. Mercier1c007992024-01-25 16:29:54 +0000161bool ProfileAttribute::GetPathForTask(pid_t tid, std::string* path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800162 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700163 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800164 return false;
165 }
166
167 if (path == nullptr) {
168 return true;
169 }
170
171 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700172 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800173 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700174 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
175 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800176 }
177 return true;
178}
179
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000180// NOTE: This function is for cgroup v2 only
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000181bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
182 if (path == nullptr) {
183 return true;
184 }
185
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000186 const std::string cgroup_path = ConvertUidToPath(controller()->path(), uid);
187 *path = cgroup_path + "/" + file_name();
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000188 return true;
189}
190
T.J. Mercier1c007992024-01-25 16:29:54 +0000191bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
T.J. Mercier07500812024-10-09 17:41:32 +0000192 const auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
193 if (!WriteStringToFile(std::to_string(slack_), file)) {
194 if (errno == ENOENT) {
195 // This happens when process is already dead
196 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800197 }
T.J. Mercier07500812024-10-09 17:41:32 +0000198 PLOG(ERROR) << "set_timerslack_ns write failed";
199 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800200 }
201
202 return true;
203}
204
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700205bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800206 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700207 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000208 if (optional_) {
209 return true;
210 } else {
211 LOG(ERROR) << "No such cgroup attribute: " << path;
212 return false;
213 }
214 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700215 // The PLOG() statement below uses the error code stored in `errno` by
216 // WriteStringToFile() because access() only overwrites `errno` if it fails
217 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800218 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
219 return false;
220 }
221
222 return true;
223}
224
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700225bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
226 std::string path;
227
228 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
229 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
230 return false;
231 }
232
233 return WriteValueToFile(path);
234}
235
T.J. Mercier1c007992024-01-25 16:29:54 +0000236bool SetAttributeAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700237 std::string path;
238
239 if (!attribute_->GetPathForTask(tid, &path)) {
240 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
241 return false;
242 }
243
244 return WriteValueToFile(path);
245}
246
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000247bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
248 std::string path;
249
250 if (!attribute_->GetPathForUID(uid, &path)) {
251 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
252 return false;
253 }
254
255 if (!WriteStringToFile(value_, path)) {
256 if (access(path.c_str(), F_OK) < 0) {
257 if (optional_) {
258 return true;
259 } else {
260 LOG(ERROR) << "No such cgroup attribute: " << path;
261 return false;
262 }
263 }
264 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
265 return false;
266 }
267 return true;
268}
269
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000270bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
271 return IsValidForTask(pid);
272}
273
T.J. Mercier1c007992024-01-25 16:29:54 +0000274bool SetAttributeAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000275 std::string path;
276
277 if (!attribute_->GetPathForTask(tid, &path)) {
278 return false;
279 }
280
281 if (!access(path.c_str(), W_OK)) {
282 // operation will succeed
283 return true;
284 }
285
286 if (!access(path.c_str(), F_OK)) {
287 // file exists but not writable
288 return false;
289 }
290
291 // file does not exist, ignore if optional
292 return optional_;
293}
294
T.J. Mercierfcb86662024-08-01 20:52:30 +0000295SetCgroupAction::SetCgroupAction(const CgroupControllerWrapper& c, const std::string& p)
Rick Yiud4c53512021-11-21 15:57:36 +0800296 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800297 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
298 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
299 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800300}
301
T.J. Mercier1c007992024-01-25 16:29:54 +0000302bool SetCgroupAction::AddTidToCgroup(pid_t tid, int fd, ResourceCacheType cache_type) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800303 if (tid <= 0) {
304 return true;
305 }
306
307 std::string value = std::to_string(tid);
308
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700309 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
310 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800311 }
312
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700313 // If the thread is in the process of exiting, don't flag an error
314 if (errno == ESRCH) {
315 return true;
316 }
317
Bart Van Asschedf985342023-11-13 15:19:43 -0800318 const char* controller_name = controller()->name();
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700319 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
320 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
321 // This is an abnormal case happening only in testing, so report it only once
322 static bool empty_cpuset_reported = false;
323
324 if (empty_cpuset_reported) {
325 return true;
326 }
327
328 LOG(ERROR) << "Failed to add task '" << value
329 << "' into cpuset because all cpus in that cpuset are offline";
330 empty_cpuset_reported = true;
331 } else {
Bart Van Asschedf985342023-11-13 15:19:43 -0800332 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; path=" << path_ << "; "
333 << (cache_type == RCT_TASK ? "task" : "process");
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700334 }
335
336 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800337}
338
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800339ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
340 int id) const {
341 std::lock_guard<std::mutex> lock(fd_mutex_);
342 if (FdCacheHelper::IsCached(fd_[cache_type])) {
343 // fd is cached, reuse it
Bart Van Asschedf985342023-11-13 15:19:43 -0800344 if (!AddTidToCgroup(id, fd_[cache_type], cache_type)) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800345 LOG(ERROR) << "Failed to add task into cgroup";
346 return ProfileAction::FAIL;
347 }
348 return ProfileAction::SUCCESS;
349 }
350
351 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
352 // no permissions to access the file, ignore
353 return ProfileAction::SUCCESS;
354 }
355
356 if (cache_type == ResourceCacheType::RCT_TASK &&
357 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
358 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700359 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800360 return ProfileAction::FAIL;
361 }
362
363 return ProfileAction::UNUSED;
364}
365
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800366bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800367 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
368 if (result != ProfileAction::UNUSED) {
369 return result == ProfileAction::SUCCESS;
370 }
371
372 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700373 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800374 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
375 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700376 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800377 return false;
378 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800379 if (!AddTidToCgroup(pid, tmp_fd, RCT_PROCESS)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800380 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800381 return false;
382 }
383
384 return true;
385}
386
T.J. Mercier1c007992024-01-25 16:29:54 +0000387bool SetCgroupAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800388 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
389 if (result != ProfileAction::UNUSED) {
390 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800391 }
392
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800393 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700394 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800395 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
396 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700397 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800398 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800399 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800400 if (!AddTidToCgroup(tid, tmp_fd, RCT_TASK)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800401 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800402 return false;
403 }
404
405 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800406}
407
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800408void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800409 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800410 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
411 // include regex evaluations
412 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
413 return;
414 }
415 switch (cache_type) {
416 case (ProfileAction::RCT_TASK):
417 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
418 break;
419 case (ProfileAction::RCT_PROCESS):
420 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
421 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
422 break;
423 default:
424 LOG(ERROR) << "Invalid cache type is specified!";
425 break;
426 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800427}
428
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800429void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800430 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800431 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800432}
433
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000434bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
435 std::lock_guard<std::mutex> lock(fd_mutex_);
436 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
437 return true;
438 }
439
440 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
441 return false;
442 }
443
444 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
445 return access(procs_path.c_str(), W_OK) == 0;
446}
447
448bool SetCgroupAction::IsValidForTask(int) const {
449 std::lock_guard<std::mutex> lock(fd_mutex_);
450 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
451 return true;
452 }
453
454 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
455 return false;
456 }
457
458 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
459 // application-dependent path can't be used with tid
460 return false;
461 }
462
463 std::string tasks_path = controller()->GetTasksFilePath(path_);
464 return access(tasks_path.c_str(), W_OK) == 0;
465}
466
Rick Yiu9221b1e2022-02-10 16:44:43 +0800467WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
468 const std::string& value, bool logfailures)
469 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
470 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
471 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800472}
Rick Yiubc1ad962020-10-26 20:32:52 +0800473
Rick Yiu9221b1e2022-02-10 16:44:43 +0800474bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000475 uid_t uid, pid_t pid, bool logfailures) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800476 std::string value(value_);
477
478 value = StringReplace(value, "<uid>", std::to_string(uid), true);
479 value = StringReplace(value, "<pid>", std::to_string(pid), true);
480
481 CacheUseResult result = UseCachedFd(cache_type, value);
482
483 if (result != ProfileAction::UNUSED) {
484 return result == ProfileAction::SUCCESS;
485 }
486
487 std::string path;
488 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
489 path = task_path_;
490 } else {
491 path = proc_path_;
492 }
493
Rick Yiud4c53512021-11-21 15:57:36 +0800494 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
495 // O_TRUNC which causes kernfs_mutex contention
496 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800497
Rick Yiud4c53512021-11-21 15:57:36 +0800498 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700499 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800500 return false;
501 }
502
503 if (!WriteStringToFd(value, tmp_fd)) {
504 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800505 return false;
506 }
507
508 return true;
509}
510
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800511ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
512 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800513 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800514 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800515 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800516 bool ret = WriteStringToFd(value, fd_[cache_type]);
517
518 if (!ret && logfailures_) {
519 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
520 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
521 } else {
522 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
523 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800524 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800525 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800526 }
527
Rick Yiu9221b1e2022-02-10 16:44:43 +0800528 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800529 // no permissions to access the file, ignore
530 return ProfileAction::SUCCESS;
531 }
532
Rick Yiu9221b1e2022-02-10 16:44:43 +0800533 if (cache_type == ResourceCacheType::RCT_TASK &&
534 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800535 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700536 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800537 return ProfileAction::FAIL;
538 }
539 return ProfileAction::UNUSED;
540}
541
542bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800543 if (!proc_path_.empty()) {
544 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800545 }
546
Rick Yiu9221b1e2022-02-10 16:44:43 +0800547 DIR* d;
548 struct dirent* de;
549 char proc_path[255];
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000550 pid_t t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800551
Rick Yiu9221b1e2022-02-10 16:44:43 +0800552 sprintf(proc_path, "/proc/%d/task", pid);
553 if (!(d = opendir(proc_path))) {
554 return false;
555 }
556
557 while ((de = readdir(d))) {
558 if (de->d_name[0] == '.') {
559 continue;
560 }
561
562 t_pid = atoi(de->d_name);
563
564 if (!t_pid) {
565 continue;
566 }
567
568 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
569 }
570
571 closedir(d);
572
573 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800574}
575
T.J. Mercier1c007992024-01-25 16:29:54 +0000576bool WriteFileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800577 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
578}
Rick Yiubc1ad962020-10-26 20:32:52 +0800579
Rick Yiu9221b1e2022-02-10 16:44:43 +0800580void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
581 std::lock_guard<std::mutex> lock(fd_mutex_);
582 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
583 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800584 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800585 switch (cache_type) {
586 case (ProfileAction::RCT_TASK):
587 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
588 break;
589 case (ProfileAction::RCT_PROCESS):
590 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
591 break;
592 default:
593 LOG(ERROR) << "Invalid cache type is specified!";
594 break;
595 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800596}
597
Rick Yiu9221b1e2022-02-10 16:44:43 +0800598void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800599 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800600 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800601}
602
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000603bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
604 std::lock_guard<std::mutex> lock(fd_mutex_);
605 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
606 return true;
607 }
608
609 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
610 return false;
611 }
612
613 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
614}
615
616bool WriteFileAction::IsValidForTask(int) const {
617 std::lock_guard<std::mutex> lock(fd_mutex_);
618 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
619 return true;
620 }
621
622 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
623 return false;
624 }
625
626 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
627 // application-dependent path can't be used with tid
628 return false;
629 }
630
631 return access(task_path_.c_str(), W_OK) == 0;
632}
633
T.J. Mercier39846112024-10-09 22:40:26 +0000634bool SetSchedulerPolicyAction::isNormalPolicy(int policy) {
635 return policy == SCHED_OTHER || policy == SCHED_BATCH || policy == SCHED_IDLE;
636}
637
638bool SetSchedulerPolicyAction::toPriority(int policy, int virtual_priority, int& priority_out) {
639 constexpr int VIRTUAL_PRIORITY_MIN = 1;
640 constexpr int VIRTUAL_PRIORITY_MAX = 99;
641
642 if (virtual_priority < VIRTUAL_PRIORITY_MIN || virtual_priority > VIRTUAL_PRIORITY_MAX) {
643 LOG(WARNING) << "SetSchedulerPolicy: invalid priority (" << virtual_priority
644 << ") for policy (" << policy << ")";
645 return false;
646 }
647
648 const int min = sched_get_priority_min(policy);
649 if (min == -1) {
650 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get min sched priority for policy " << policy;
651 return false;
652 }
653
654 const int max = sched_get_priority_max(policy);
655 if (max == -1) {
656 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get max sched priority for policy " << policy;
657 return false;
658 }
659
660 priority_out = min + (virtual_priority - VIRTUAL_PRIORITY_MIN) * (max - min) /
661 (VIRTUAL_PRIORITY_MAX - VIRTUAL_PRIORITY_MIN);
662
663 return true;
664}
665
666bool SetSchedulerPolicyAction::ExecuteForTask(pid_t tid) const {
667 struct sched_param param = {};
668 param.sched_priority = isNormalPolicy(policy_) ? 0 : *priority_or_nice_;
669 if (sched_setscheduler(tid, policy_, &param) == -1) {
670 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply scheduler policy (" << policy_
671 << ") with priority (" << *priority_or_nice_ << ") to tid " << tid;
672 return false;
673 }
674
675 if (isNormalPolicy(policy_) && priority_or_nice_ &&
676 setpriority(PRIO_PROCESS, tid, *priority_or_nice_) == -1) {
677 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply nice (" << *priority_or_nice_
678 << ") to tid " << tid;
679 return false;
680 }
681
682 return true;
683}
684
Rick Yiu0b211fa2019-09-16 19:07:17 +0800685bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
686 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800687 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800688 }
689 return true;
690}
691
T.J. Mercier1c007992024-01-25 16:29:54 +0000692bool ApplyProfileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800693 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700694 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800695 }
696 return true;
697}
698
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800699void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800700 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800701 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800702 }
703}
704
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800705void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800706 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800707 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800708 }
709}
710
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000711bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
712 for (const auto& profile : profiles_) {
713 if (!profile->IsValidForProcess(uid, pid)) {
714 return false;
715 }
716 }
717 return true;
718}
719
T.J. Mercier1c007992024-01-25 16:29:54 +0000720bool ApplyProfileAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000721 for (const auto& profile : profiles_) {
722 if (!profile->IsValidForTask(tid)) {
723 return false;
724 }
725 }
726 return true;
727}
728
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800729void TaskProfile::MoveTo(TaskProfile* profile) {
730 profile->elements_ = std::move(elements_);
731 profile->res_cached_ = res_cached_;
732}
733
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800734bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
735 for (const auto& element : elements_) {
736 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000737 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800738 return false;
739 }
740 }
741 return true;
742}
743
T.J. Mercier1c007992024-01-25 16:29:54 +0000744bool TaskProfile::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800745 if (tid == 0) {
746 tid = GetThreadId();
747 }
748 for (const auto& element : elements_) {
749 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000750 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800751 return false;
752 }
753 }
754 return true;
755}
756
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000757bool TaskProfile::ExecuteForUID(uid_t uid) const {
758 for (const auto& element : elements_) {
759 if (!element->ExecuteForUID(uid)) {
760 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
761 return false;
762 }
763 }
764 return true;
765}
766
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800767void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800768 if (res_cached_) {
769 return;
770 }
771
772 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800773 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800774 }
775
776 res_cached_ = true;
777}
778
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800779void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600780 if (!res_cached_) {
781 return;
782 }
783
784 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800785 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600786 }
787
788 res_cached_ = false;
789}
790
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000791bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
792 for (const auto& element : elements_) {
793 if (!element->IsValidForProcess(uid, pid)) return false;
794 }
795 return true;
796}
797
T.J. Mercier1c007992024-01-25 16:29:54 +0000798bool TaskProfile::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000799 for (const auto& element : elements_) {
800 if (!element->IsValidForTask(tid)) return false;
801 }
802 return true;
803}
804
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800805void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600806 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800807 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600808 }
809}
810
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800811TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700812 // Deliberately leak this object to avoid a race between destruction on
813 // process exit and concurrent access from another thread.
814 static auto* instance = new TaskProfiles;
815 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800816}
817
818TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800819 // load system task profiles
820 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
821 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
822 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800823
824 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800825 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800826 if (api_level > 0) {
827 std::string api_profiles_path =
828 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
829 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800830 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800831 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800832 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800833 }
834 }
835
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800836 // load vendor task profiles if the file exists
837 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
838 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
839 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
840 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800841 }
842}
843
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800844bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800845 std::string json_doc;
846
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800847 if (!android::base::ReadFileToString(file_name, &json_doc)) {
848 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800849 return false;
850 }
851
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800852 Json::CharReaderBuilder builder;
853 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800854 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800855 std::string errorMessage;
856 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
857 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800858 return false;
859 }
860
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800861 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800862 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
863 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800864 std::string controller_name = attr[i]["Controller"].asString();
865 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000866 std::string file_v2_attr = attr[i]["FileV2"].asString();
867
868 if (!file_v2_attr.empty() && file_attr.empty()) {
869 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
870 return false;
871 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800872
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700873 auto controller = cg_map.FindController(controller_name);
874 if (controller.HasValue()) {
875 auto iter = attributes_.find(name);
876 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000877 attributes_[name] =
878 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800879 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700880 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800881 }
882 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700883 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800884 }
885 }
886
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800887 const Json::Value& profiles_val = root["Profiles"];
888 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
889 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800890
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800891 std::string profile_name = profile_val["Name"].asString();
892 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000893 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800894
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800895 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
896 const Json::Value& action_val = actions[act_idx];
897 std::string action_name = action_val["Name"].asString();
898 const Json::Value& params_val = action_val["Params"];
899 if (action_name == "JoinCgroup") {
900 std::string controller_name = params_val["Controller"].asString();
901 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800902
Yifan Hong53e0deb2019-03-22 17:01:08 -0700903 auto controller = cg_map.FindController(controller_name);
904 if (controller.HasValue()) {
Bart Van Assche2953a922023-11-14 07:33:00 -0800905 if (controller.version() == 1) {
906 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
907 } else {
908 LOG(WARNING) << "A JoinCgroup action in the " << profile_name
909 << " profile is used for controller " << controller_name
910 << " in the cgroup v2 hierarchy and will be ignored";
911 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800912 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800913 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800914 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800915 } else if (action_name == "SetTimerSlack") {
916 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800917 char* end;
918 unsigned long slack;
919
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800920 slack = strtoul(slack_value.c_str(), &end, 10);
921 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800922 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
923 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800924 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800925 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800926 } else if (action_name == "SetAttribute") {
927 std::string attr_name = params_val["Name"].asString();
928 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000929 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800930
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800931 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800932 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000933 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
934 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800935 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800936 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800937 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800938 } else if (action_name == "WriteFile") {
939 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800940 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800941 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800942 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800943 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800944 std::string attr_logfailures = params_val["LogFailures"].asString();
945 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800946 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
947 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800948 } else if (attr_filepath.empty()) {
949 LOG(WARNING) << "WriteFile: invalid parameter: "
950 << "empty filepath";
951 } else if (attr_value.empty()) {
952 LOG(WARNING) << "WriteFile: invalid parameter: "
953 << "empty value";
954 }
T.J. Mercier39846112024-10-09 22:40:26 +0000955 } else if (action_name == "SetSchedulerPolicy") {
956 const std::map<std::string, int> POLICY_MAP = {
957 {"SCHED_OTHER", SCHED_OTHER},
958 {"SCHED_BATCH", SCHED_BATCH},
959 {"SCHED_IDLE", SCHED_IDLE},
960 {"SCHED_FIFO", SCHED_FIFO},
961 {"SCHED_RR", SCHED_RR},
962 };
963 const std::string policy_str = params_val["Policy"].asString();
964
965 const auto it = POLICY_MAP.find(policy_str);
966 if (it == POLICY_MAP.end()) {
967 LOG(WARNING) << "SetSchedulerPolicy: invalid policy " << policy_str;
968 continue;
969 }
970
971 const int policy = it->second;
972
973 if (SetSchedulerPolicyAction::isNormalPolicy(policy)) {
974 if (params_val.isMember("Priority")) {
975 LOG(WARNING) << "SetSchedulerPolicy: Normal policies (" << policy_str
976 << ") use Nice values, not Priority values";
977 }
978
979 if (params_val.isMember("Nice")) {
980 // If present, this optional value will be passed in an additional syscall
981 // to setpriority(), since the sched_priority value must be 0 for calls to
982 // sched_setscheduler() with "normal" policies.
983 const int nice = params_val["Nice"].asInt();
984
985 const int LINUX_MIN_NICE = -20;
986 const int LINUX_MAX_NICE = 19;
987 if (nice < LINUX_MIN_NICE || nice > LINUX_MAX_NICE) {
988 LOG(WARNING) << "SetSchedulerPolicy: Provided nice (" << nice
989 << ") appears out of range.";
990 }
991 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy, nice));
992 } else {
993 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy));
994 }
995 } else {
996 if (params_val.isMember("Nice")) {
997 LOG(WARNING) << "SetSchedulerPolicy: Real-time policies (" << policy_str
998 << ") use Priority values, not Nice values";
999 }
1000
1001 // This is a "virtual priority" as described by `man 2 sched_get_priority_min`
1002 // that will be mapped onto the following range for the provided policy:
1003 // [sched_get_priority_min(), sched_get_priority_max()]
1004 const int virtual_priority = params_val["Priority"].asInt();
1005
1006 int priority;
1007 if (SetSchedulerPolicyAction::toPriority(policy, virtual_priority, priority)) {
1008 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy, priority));
1009 }
1010 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001011 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -08001012 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001013 }
1014 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -08001015 auto iter = profiles_.find(profile_name);
1016 if (iter == profiles_.end()) {
1017 profiles_[profile_name] = profile;
1018 } else {
1019 // Move the content rather that replace the profile because old profile might be
1020 // referenced from an aggregate profile if vendor overrides task profiles
1021 profile->MoveTo(iter->second.get());
1022 profile.reset();
1023 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001024 }
1025
1026 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
1027 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
1028 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
1029
1030 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
1031 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
1032 std::vector<std::shared_ptr<TaskProfile>> profiles;
1033 bool ret = true;
1034
1035 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
1036 std::string profile_name = aggregateprofiles[pf_idx].asString();
1037
1038 if (profile_name == aggregateprofile_name) {
1039 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
1040 ret = false;
1041 break;
1042 } else if (profiles_.find(profile_name) == profiles_.end()) {
1043 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
1044 ret = false;
1045 break;
1046 } else {
1047 profiles.push_back(profiles_[profile_name]);
1048 }
1049 }
1050 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +00001051 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001052 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
1053 profiles_[aggregateprofile_name] = profile;
1054 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001055 }
1056
1057 return true;
1058}
1059
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001060TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001061 auto iter = profiles_.find(name);
1062
1063 if (iter != profiles_.end()) {
1064 return iter->second.get();
1065 }
1066 return nullptr;
1067}
1068
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001069const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001070 auto iter = attributes_.find(name);
1071
1072 if (iter != attributes_.end()) {
1073 return iter->second.get();
1074 }
1075 return nullptr;
1076}
Rick Yiu0b211fa2019-09-16 19:07:17 +08001077
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001078template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001079bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
1080 for (const auto& name : profiles) {
1081 TaskProfile* profile = GetProfile(name);
1082 if (profile != nullptr) {
1083 if (use_fd_cache) {
1084 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1085 }
1086 if (!profile->ExecuteForUID(uid)) {
1087 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1088 }
1089 } else {
1090 PLOG(WARNING) << "Failed to find " << name << "process profile";
1091 }
1092 }
1093 return true;
1094}
1095
1096template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001097bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1098 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001099 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001100 for (const auto& name : profiles) {
1101 TaskProfile* profile = GetProfile(name);
1102 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001103 if (use_fd_cache) {
1104 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1105 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001106 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001107 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001108 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001109 }
1110 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001111 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001112 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001113 }
1114 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001115 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001116}
1117
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001118template <typename T>
T.J. Mercier1c007992024-01-25 16:29:54 +00001119bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001120 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001121 for (const auto& name : profiles) {
1122 TaskProfile* profile = GetProfile(name);
1123 if (profile != nullptr) {
1124 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001125 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001126 }
1127 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001128 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001129 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001130 }
1131 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001132 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001133 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001134 }
1135 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001136 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001137}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001138
1139template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1140 std::span<const std::string> profiles,
1141 bool use_fd_cache);
1142template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1143 std::span<const std::string_view> profiles,
1144 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001145template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001146 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001147template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001148 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001149template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1150 bool use_fd_cache);