blob: 7f33d4a40ebedbb9c2c492eb98d7dc2bd65d79a8 [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. Mercier54bfde02024-06-04 23:25:29 +000020#include <dirent.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080021#include <fcntl.h>
T.J. Mercier54bfde02024-06-04 23:25:29 +000022#include <unistd.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080023#include <task_profiles.h>
24#include <string>
25
26#include <android-base/file.h>
27#include <android-base/logging.h>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080028#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080029#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080030#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080031#include <android-base/threads.h>
32
33#include <cutils/android_filesystem_config.h>
34
35#include <json/reader.h>
36#include <json/value.h>
37
T.J. Mercier1cfa2c42024-04-08 21:14:32 +000038#include <build_flags.h>
39
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080040using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080041using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080042using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080043using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080044using android::base::unique_fd;
45using android::base::WriteStringToFile;
46
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080047static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
48static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
49
50static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
51 "/etc/task_profiles/task_profiles_%u.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080052
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080053class FdCacheHelper {
54 public:
55 enum FdState {
56 FDS_INACCESSIBLE = -1,
57 FDS_APP_DEPENDENT = -2,
58 FDS_NOT_CACHED = -3,
59 };
60
61 static void Cache(const std::string& path, android::base::unique_fd& fd);
62 static void Drop(android::base::unique_fd& fd);
63 static void Init(const std::string& path, android::base::unique_fd& fd);
64 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
65
66 private:
67 static bool IsAppDependentPath(const std::string& path);
68};
69
70void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
71 // file descriptors for app-dependent paths can't be cached
72 if (IsAppDependentPath(path)) {
73 // file descriptor is not cached
74 fd.reset(FDS_APP_DEPENDENT);
75 return;
76 }
77 // file descriptor can be cached later on request
78 fd.reset(FDS_NOT_CACHED);
79}
80
81void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
82 if (fd != FDS_NOT_CACHED) {
83 return;
84 }
85
86 if (access(path.c_str(), W_OK) != 0) {
87 // file is not accessible
88 fd.reset(FDS_INACCESSIBLE);
89 return;
90 }
91
92 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
93 if (tmp_fd < 0) {
94 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
95 fd.reset(FDS_INACCESSIBLE);
96 return;
97 }
98
99 fd = std::move(tmp_fd);
100}
101
102void FdCacheHelper::Drop(android::base::unique_fd& fd) {
103 if (fd == FDS_NOT_CACHED) {
104 return;
105 }
106
107 fd.reset(FDS_NOT_CACHED);
108}
109
110bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
111 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
112}
113
Bart Van Assche4c99e962022-02-03 19:50:16 +0000114IProfileAttribute::~IProfileAttribute() = default;
115
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700116const std::string& ProfileAttribute::file_name() const {
117 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
118 return file_name_;
119}
120
T.J. Mercierfcb86662024-08-01 20:52:30 +0000121void ProfileAttribute::Reset(const CgroupControllerWrapper& controller,
122 const std::string& file_name, const std::string& file_v2_name) {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700123 controller_ = controller;
124 file_name_ = file_name;
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700125 file_v2_name_ = file_v2_name;
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700126}
127
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000128static bool isSystemApp(uid_t uid) {
129 return uid < AID_APP_START;
130}
131
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000132std::string ConvertUidToPath(const char* root_cgroup_path, uid_t uid) {
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000133 if (android::libprocessgroup_flags::cgroup_v2_sys_app_isolation()) {
134 if (isSystemApp(uid))
135 return StringPrintf("%s/system/uid_%u", root_cgroup_path, uid);
136 else
137 return StringPrintf("%s/apps/uid_%u", root_cgroup_path, uid);
138 }
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000139 return StringPrintf("%s/uid_%u", root_cgroup_path, uid);
140}
141
142std::string ConvertUidPidToPath(const char* root_cgroup_path, uid_t uid, pid_t pid) {
143 const std::string uid_path = ConvertUidToPath(root_cgroup_path, uid);
144 return StringPrintf("%s/pid_%d", uid_path.c_str(), pid);
145}
146
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700147bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
148 if (controller()->version() == 2) {
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000149 const std::string cgroup_path = ConvertUidPidToPath(controller()->path(), uid, pid);
150 *path = cgroup_path + "/" + file_name();
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700151 return true;
152 }
153 return GetPathForTask(pid, path);
154}
155
T.J. Mercier1c007992024-01-25 16:29:54 +0000156bool ProfileAttribute::GetPathForTask(pid_t tid, std::string* path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800157 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700158 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800159 return false;
160 }
161
162 if (path == nullptr) {
163 return true;
164 }
165
166 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700167 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800168 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700169 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
170 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800171 }
172 return true;
173}
174
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000175// NOTE: This function is for cgroup v2 only
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000176bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
177 if (path == nullptr) {
178 return true;
179 }
180
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000181 const std::string cgroup_path = ConvertUidToPath(controller()->path(), uid);
182 *path = cgroup_path + "/" + file_name();
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000183 return true;
184}
185
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800186bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
187 // TODO: add support when kernel supports util_clamp
188 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
189 return false;
190}
191
192bool SetClampsAction::ExecuteForTask(int) const {
193 // TODO: add support when kernel supports util_clamp
194 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
195 return false;
196}
197
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800198// To avoid issues in sdk_mac build
199#if defined(__ANDROID__)
200
T.J. Mercier1c007992024-01-25 16:29:54 +0000201bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
T.J. Mercier07500812024-10-09 17:41:32 +0000202 const auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
203 if (!WriteStringToFile(std::to_string(slack_), file)) {
204 if (errno == ENOENT) {
205 // This happens when process is already dead
206 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800207 }
T.J. Mercier07500812024-10-09 17:41:32 +0000208 PLOG(ERROR) << "set_timerslack_ns write failed";
209 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800210 }
211
212 return true;
213}
214
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000215#else
216
217bool SetTimerSlackAction::ExecuteForTask(int) const {
218 return true;
219};
220
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800221#endif
222
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700223bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800224 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700225 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000226 if (optional_) {
227 return true;
228 } else {
229 LOG(ERROR) << "No such cgroup attribute: " << path;
230 return false;
231 }
232 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700233 // The PLOG() statement below uses the error code stored in `errno` by
234 // WriteStringToFile() because access() only overwrites `errno` if it fails
235 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800236 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
237 return false;
238 }
239
240 return true;
241}
242
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700243bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
244 std::string path;
245
246 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
247 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
248 return false;
249 }
250
251 return WriteValueToFile(path);
252}
253
T.J. Mercier1c007992024-01-25 16:29:54 +0000254bool SetAttributeAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700255 std::string path;
256
257 if (!attribute_->GetPathForTask(tid, &path)) {
258 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
259 return false;
260 }
261
262 return WriteValueToFile(path);
263}
264
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000265bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
266 std::string path;
267
268 if (!attribute_->GetPathForUID(uid, &path)) {
269 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
270 return false;
271 }
272
273 if (!WriteStringToFile(value_, path)) {
274 if (access(path.c_str(), F_OK) < 0) {
275 if (optional_) {
276 return true;
277 } else {
278 LOG(ERROR) << "No such cgroup attribute: " << path;
279 return false;
280 }
281 }
282 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
283 return false;
284 }
285 return true;
286}
287
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000288bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
289 return IsValidForTask(pid);
290}
291
T.J. Mercier1c007992024-01-25 16:29:54 +0000292bool SetAttributeAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000293 std::string path;
294
295 if (!attribute_->GetPathForTask(tid, &path)) {
296 return false;
297 }
298
299 if (!access(path.c_str(), W_OK)) {
300 // operation will succeed
301 return true;
302 }
303
304 if (!access(path.c_str(), F_OK)) {
305 // file exists but not writable
306 return false;
307 }
308
309 // file does not exist, ignore if optional
310 return optional_;
311}
312
T.J. Mercierfcb86662024-08-01 20:52:30 +0000313SetCgroupAction::SetCgroupAction(const CgroupControllerWrapper& c, const std::string& p)
Rick Yiud4c53512021-11-21 15:57:36 +0800314 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800315 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
316 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
317 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800318}
319
T.J. Mercier1c007992024-01-25 16:29:54 +0000320bool SetCgroupAction::AddTidToCgroup(pid_t tid, int fd, ResourceCacheType cache_type) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800321 if (tid <= 0) {
322 return true;
323 }
324
325 std::string value = std::to_string(tid);
326
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700327 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
328 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800329 }
330
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700331 // If the thread is in the process of exiting, don't flag an error
332 if (errno == ESRCH) {
333 return true;
334 }
335
Bart Van Asschedf985342023-11-13 15:19:43 -0800336 const char* controller_name = controller()->name();
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700337 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
338 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
339 // This is an abnormal case happening only in testing, so report it only once
340 static bool empty_cpuset_reported = false;
341
342 if (empty_cpuset_reported) {
343 return true;
344 }
345
346 LOG(ERROR) << "Failed to add task '" << value
347 << "' into cpuset because all cpus in that cpuset are offline";
348 empty_cpuset_reported = true;
349 } else {
Bart Van Asschedf985342023-11-13 15:19:43 -0800350 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; path=" << path_ << "; "
351 << (cache_type == RCT_TASK ? "task" : "process");
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700352 }
353
354 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800355}
356
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800357ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
358 int id) const {
359 std::lock_guard<std::mutex> lock(fd_mutex_);
360 if (FdCacheHelper::IsCached(fd_[cache_type])) {
361 // fd is cached, reuse it
Bart Van Asschedf985342023-11-13 15:19:43 -0800362 if (!AddTidToCgroup(id, fd_[cache_type], cache_type)) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800363 LOG(ERROR) << "Failed to add task into cgroup";
364 return ProfileAction::FAIL;
365 }
366 return ProfileAction::SUCCESS;
367 }
368
369 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
370 // no permissions to access the file, ignore
371 return ProfileAction::SUCCESS;
372 }
373
374 if (cache_type == ResourceCacheType::RCT_TASK &&
375 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
376 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700377 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800378 return ProfileAction::FAIL;
379 }
380
381 return ProfileAction::UNUSED;
382}
383
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800384bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800385 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
386 if (result != ProfileAction::UNUSED) {
387 return result == ProfileAction::SUCCESS;
388 }
389
390 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700391 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800392 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
393 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700394 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800395 return false;
396 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800397 if (!AddTidToCgroup(pid, tmp_fd, RCT_PROCESS)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800398 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800399 return false;
400 }
401
402 return true;
403}
404
T.J. Mercier1c007992024-01-25 16:29:54 +0000405bool SetCgroupAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800406 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
407 if (result != ProfileAction::UNUSED) {
408 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800409 }
410
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800411 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700412 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800413 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
414 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700415 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800416 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800417 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800418 if (!AddTidToCgroup(tid, tmp_fd, RCT_TASK)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800419 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800420 return false;
421 }
422
423 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800424}
425
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800426void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800427 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800428 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
429 // include regex evaluations
430 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
431 return;
432 }
433 switch (cache_type) {
434 case (ProfileAction::RCT_TASK):
435 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
436 break;
437 case (ProfileAction::RCT_PROCESS):
438 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
439 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
440 break;
441 default:
442 LOG(ERROR) << "Invalid cache type is specified!";
443 break;
444 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800445}
446
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800447void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800448 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800449 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800450}
451
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000452bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
453 std::lock_guard<std::mutex> lock(fd_mutex_);
454 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
455 return true;
456 }
457
458 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
459 return false;
460 }
461
462 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
463 return access(procs_path.c_str(), W_OK) == 0;
464}
465
466bool SetCgroupAction::IsValidForTask(int) const {
467 std::lock_guard<std::mutex> lock(fd_mutex_);
468 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
469 return true;
470 }
471
472 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
473 return false;
474 }
475
476 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
477 // application-dependent path can't be used with tid
478 return false;
479 }
480
481 std::string tasks_path = controller()->GetTasksFilePath(path_);
482 return access(tasks_path.c_str(), W_OK) == 0;
483}
484
Rick Yiu9221b1e2022-02-10 16:44:43 +0800485WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
486 const std::string& value, bool logfailures)
487 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
488 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
489 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800490}
Rick Yiubc1ad962020-10-26 20:32:52 +0800491
Rick Yiu9221b1e2022-02-10 16:44:43 +0800492bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000493 uid_t uid, pid_t pid, bool logfailures) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800494 std::string value(value_);
495
496 value = StringReplace(value, "<uid>", std::to_string(uid), true);
497 value = StringReplace(value, "<pid>", std::to_string(pid), true);
498
499 CacheUseResult result = UseCachedFd(cache_type, value);
500
501 if (result != ProfileAction::UNUSED) {
502 return result == ProfileAction::SUCCESS;
503 }
504
505 std::string path;
506 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
507 path = task_path_;
508 } else {
509 path = proc_path_;
510 }
511
Rick Yiud4c53512021-11-21 15:57:36 +0800512 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
513 // O_TRUNC which causes kernfs_mutex contention
514 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800515
Rick Yiud4c53512021-11-21 15:57:36 +0800516 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700517 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800518 return false;
519 }
520
521 if (!WriteStringToFd(value, tmp_fd)) {
522 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800523 return false;
524 }
525
526 return true;
527}
528
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800529ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
530 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800531 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800532 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800533 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800534 bool ret = WriteStringToFd(value, fd_[cache_type]);
535
536 if (!ret && logfailures_) {
537 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
538 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
539 } else {
540 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
541 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800542 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800543 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800544 }
545
Rick Yiu9221b1e2022-02-10 16:44:43 +0800546 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800547 // no permissions to access the file, ignore
548 return ProfileAction::SUCCESS;
549 }
550
Rick Yiu9221b1e2022-02-10 16:44:43 +0800551 if (cache_type == ResourceCacheType::RCT_TASK &&
552 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800553 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700554 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800555 return ProfileAction::FAIL;
556 }
557 return ProfileAction::UNUSED;
558}
559
560bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800561 if (!proc_path_.empty()) {
562 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800563 }
564
Rick Yiu9221b1e2022-02-10 16:44:43 +0800565 DIR* d;
566 struct dirent* de;
567 char proc_path[255];
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000568 pid_t t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800569
Rick Yiu9221b1e2022-02-10 16:44:43 +0800570 sprintf(proc_path, "/proc/%d/task", pid);
571 if (!(d = opendir(proc_path))) {
572 return false;
573 }
574
575 while ((de = readdir(d))) {
576 if (de->d_name[0] == '.') {
577 continue;
578 }
579
580 t_pid = atoi(de->d_name);
581
582 if (!t_pid) {
583 continue;
584 }
585
586 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
587 }
588
589 closedir(d);
590
591 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800592}
593
T.J. Mercier1c007992024-01-25 16:29:54 +0000594bool WriteFileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800595 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
596}
Rick Yiubc1ad962020-10-26 20:32:52 +0800597
Rick Yiu9221b1e2022-02-10 16:44:43 +0800598void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
599 std::lock_guard<std::mutex> lock(fd_mutex_);
600 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
601 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800602 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800603 switch (cache_type) {
604 case (ProfileAction::RCT_TASK):
605 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
606 break;
607 case (ProfileAction::RCT_PROCESS):
608 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
609 break;
610 default:
611 LOG(ERROR) << "Invalid cache type is specified!";
612 break;
613 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800614}
615
Rick Yiu9221b1e2022-02-10 16:44:43 +0800616void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800617 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800618 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800619}
620
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000621bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
622 std::lock_guard<std::mutex> lock(fd_mutex_);
623 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
624 return true;
625 }
626
627 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
628 return false;
629 }
630
631 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
632}
633
634bool WriteFileAction::IsValidForTask(int) const {
635 std::lock_guard<std::mutex> lock(fd_mutex_);
636 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
637 return true;
638 }
639
640 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
641 return false;
642 }
643
644 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
645 // application-dependent path can't be used with tid
646 return false;
647 }
648
649 return access(task_path_.c_str(), W_OK) == 0;
650}
651
Rick Yiu0b211fa2019-09-16 19:07:17 +0800652bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
653 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800654 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800655 }
656 return true;
657}
658
T.J. Mercier1c007992024-01-25 16:29:54 +0000659bool ApplyProfileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800660 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700661 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800662 }
663 return true;
664}
665
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800666void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800667 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800668 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800669 }
670}
671
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800672void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800673 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800674 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800675 }
676}
677
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000678bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
679 for (const auto& profile : profiles_) {
680 if (!profile->IsValidForProcess(uid, pid)) {
681 return false;
682 }
683 }
684 return true;
685}
686
T.J. Mercier1c007992024-01-25 16:29:54 +0000687bool ApplyProfileAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000688 for (const auto& profile : profiles_) {
689 if (!profile->IsValidForTask(tid)) {
690 return false;
691 }
692 }
693 return true;
694}
695
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800696void TaskProfile::MoveTo(TaskProfile* profile) {
697 profile->elements_ = std::move(elements_);
698 profile->res_cached_ = res_cached_;
699}
700
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800701bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
702 for (const auto& element : elements_) {
703 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000704 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800705 return false;
706 }
707 }
708 return true;
709}
710
T.J. Mercier1c007992024-01-25 16:29:54 +0000711bool TaskProfile::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800712 if (tid == 0) {
713 tid = GetThreadId();
714 }
715 for (const auto& element : elements_) {
716 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000717 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800718 return false;
719 }
720 }
721 return true;
722}
723
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000724bool TaskProfile::ExecuteForUID(uid_t uid) const {
725 for (const auto& element : elements_) {
726 if (!element->ExecuteForUID(uid)) {
727 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
728 return false;
729 }
730 }
731 return true;
732}
733
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800734void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800735 if (res_cached_) {
736 return;
737 }
738
739 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800740 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800741 }
742
743 res_cached_ = true;
744}
745
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800746void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600747 if (!res_cached_) {
748 return;
749 }
750
751 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800752 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600753 }
754
755 res_cached_ = false;
756}
757
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000758bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
759 for (const auto& element : elements_) {
760 if (!element->IsValidForProcess(uid, pid)) return false;
761 }
762 return true;
763}
764
T.J. Mercier1c007992024-01-25 16:29:54 +0000765bool TaskProfile::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000766 for (const auto& element : elements_) {
767 if (!element->IsValidForTask(tid)) return false;
768 }
769 return true;
770}
771
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800772void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600773 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800774 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600775 }
776}
777
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800778TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700779 // Deliberately leak this object to avoid a race between destruction on
780 // process exit and concurrent access from another thread.
781 static auto* instance = new TaskProfiles;
782 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800783}
784
785TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800786 // load system task profiles
787 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
788 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
789 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800790
791 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800792 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800793 if (api_level > 0) {
794 std::string api_profiles_path =
795 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
796 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800797 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800798 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800799 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800800 }
801 }
802
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800803 // load vendor task profiles if the file exists
804 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
805 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
806 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
807 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800808 }
809}
810
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800811bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800812 std::string json_doc;
813
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800814 if (!android::base::ReadFileToString(file_name, &json_doc)) {
815 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800816 return false;
817 }
818
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800819 Json::CharReaderBuilder builder;
820 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800821 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800822 std::string errorMessage;
823 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
824 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800825 return false;
826 }
827
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800828 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800829 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
830 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800831 std::string controller_name = attr[i]["Controller"].asString();
832 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000833 std::string file_v2_attr = attr[i]["FileV2"].asString();
834
835 if (!file_v2_attr.empty() && file_attr.empty()) {
836 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
837 return false;
838 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800839
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700840 auto controller = cg_map.FindController(controller_name);
841 if (controller.HasValue()) {
842 auto iter = attributes_.find(name);
843 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000844 attributes_[name] =
845 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800846 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700847 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800848 }
849 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700850 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800851 }
852 }
853
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800854 const Json::Value& profiles_val = root["Profiles"];
855 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
856 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800857
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800858 std::string profile_name = profile_val["Name"].asString();
859 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000860 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800861
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800862 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
863 const Json::Value& action_val = actions[act_idx];
864 std::string action_name = action_val["Name"].asString();
865 const Json::Value& params_val = action_val["Params"];
866 if (action_name == "JoinCgroup") {
867 std::string controller_name = params_val["Controller"].asString();
868 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800869
Yifan Hong53e0deb2019-03-22 17:01:08 -0700870 auto controller = cg_map.FindController(controller_name);
871 if (controller.HasValue()) {
Bart Van Assche2953a922023-11-14 07:33:00 -0800872 if (controller.version() == 1) {
873 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
874 } else {
875 LOG(WARNING) << "A JoinCgroup action in the " << profile_name
876 << " profile is used for controller " << controller_name
877 << " in the cgroup v2 hierarchy and will be ignored";
878 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800879 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800880 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800881 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800882 } else if (action_name == "SetTimerSlack") {
883 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800884 char* end;
885 unsigned long slack;
886
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800887 slack = strtoul(slack_value.c_str(), &end, 10);
888 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800889 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
890 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800891 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800892 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800893 } else if (action_name == "SetAttribute") {
894 std::string attr_name = params_val["Name"].asString();
895 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000896 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800897
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800898 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800899 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000900 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
901 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800902 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800903 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800904 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800905 } else if (action_name == "SetClamps") {
906 std::string boost_value = params_val["Boost"].asString();
907 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800908 char* end;
909 unsigned long boost;
910
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800911 boost = strtoul(boost_value.c_str(), &end, 10);
912 if (end > boost_value.c_str()) {
913 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
914 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800915 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
916 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800917 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800918 }
919 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800920 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800921 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800922 } else if (action_name == "WriteFile") {
923 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800924 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800925 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800926 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800927 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800928 std::string attr_logfailures = params_val["LogFailures"].asString();
929 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800930 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
931 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800932 } else if (attr_filepath.empty()) {
933 LOG(WARNING) << "WriteFile: invalid parameter: "
934 << "empty filepath";
935 } else if (attr_value.empty()) {
936 LOG(WARNING) << "WriteFile: invalid parameter: "
937 << "empty value";
938 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800939 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800940 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800941 }
942 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800943 auto iter = profiles_.find(profile_name);
944 if (iter == profiles_.end()) {
945 profiles_[profile_name] = profile;
946 } else {
947 // Move the content rather that replace the profile because old profile might be
948 // referenced from an aggregate profile if vendor overrides task profiles
949 profile->MoveTo(iter->second.get());
950 profile.reset();
951 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800952 }
953
954 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
955 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
956 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
957
958 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
959 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
960 std::vector<std::shared_ptr<TaskProfile>> profiles;
961 bool ret = true;
962
963 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
964 std::string profile_name = aggregateprofiles[pf_idx].asString();
965
966 if (profile_name == aggregateprofile_name) {
967 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
968 ret = false;
969 break;
970 } else if (profiles_.find(profile_name) == profiles_.end()) {
971 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
972 ret = false;
973 break;
974 } else {
975 profiles.push_back(profiles_[profile_name]);
976 }
977 }
978 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000979 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800980 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
981 profiles_[aggregateprofile_name] = profile;
982 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800983 }
984
985 return true;
986}
987
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700988TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800989 auto iter = profiles_.find(name);
990
991 if (iter != profiles_.end()) {
992 return iter->second.get();
993 }
994 return nullptr;
995}
996
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700997const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800998 auto iter = attributes_.find(name);
999
1000 if (iter != attributes_.end()) {
1001 return iter->second.get();
1002 }
1003 return nullptr;
1004}
Rick Yiu0b211fa2019-09-16 19:07:17 +08001005
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001006template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001007bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
1008 for (const auto& name : profiles) {
1009 TaskProfile* profile = GetProfile(name);
1010 if (profile != nullptr) {
1011 if (use_fd_cache) {
1012 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1013 }
1014 if (!profile->ExecuteForUID(uid)) {
1015 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1016 }
1017 } else {
1018 PLOG(WARNING) << "Failed to find " << name << "process profile";
1019 }
1020 }
1021 return true;
1022}
1023
1024template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001025bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1026 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001027 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001028 for (const auto& name : profiles) {
1029 TaskProfile* profile = GetProfile(name);
1030 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001031 if (use_fd_cache) {
1032 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1033 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001034 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001035 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001036 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001037 }
1038 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001039 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001040 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001041 }
1042 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001043 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001044}
1045
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001046template <typename T>
T.J. Mercier1c007992024-01-25 16:29:54 +00001047bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001048 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001049 for (const auto& name : profiles) {
1050 TaskProfile* profile = GetProfile(name);
1051 if (profile != nullptr) {
1052 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001053 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001054 }
1055 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001056 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001057 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001058 }
1059 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001060 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001061 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001062 }
1063 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001064 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001065}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001066
1067template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1068 std::span<const std::string> profiles,
1069 bool use_fd_cache);
1070template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1071 std::span<const std::string_view> profiles,
1072 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001073template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001074 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001075template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001076 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001077template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1078 bool use_fd_cache);