blob: 17318289fb99fd904ee70f1b27ff52fe0fba9c73 [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
20#include <fcntl.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080021#include <task_profiles.h>
22#include <string>
23
24#include <android-base/file.h>
25#include <android-base/logging.h>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080026#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080027#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080028#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080029#include <android-base/threads.h>
30
31#include <cutils/android_filesystem_config.h>
32
33#include <json/reader.h>
34#include <json/value.h>
35
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080036// To avoid issues in sdk_mac build
37#if defined(__ANDROID__)
38#include <sys/prctl.h>
39#endif
40
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080041using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080042using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080043using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080044using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080045using android::base::unique_fd;
46using android::base::WriteStringToFile;
47
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080048static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
49static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
50
51static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
52 "/etc/task_profiles/task_profiles_%u.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080053
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080054class FdCacheHelper {
55 public:
56 enum FdState {
57 FDS_INACCESSIBLE = -1,
58 FDS_APP_DEPENDENT = -2,
59 FDS_NOT_CACHED = -3,
60 };
61
62 static void Cache(const std::string& path, android::base::unique_fd& fd);
63 static void Drop(android::base::unique_fd& fd);
64 static void Init(const std::string& path, android::base::unique_fd& fd);
65 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
66
67 private:
68 static bool IsAppDependentPath(const std::string& path);
69};
70
71void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
72 // file descriptors for app-dependent paths can't be cached
73 if (IsAppDependentPath(path)) {
74 // file descriptor is not cached
75 fd.reset(FDS_APP_DEPENDENT);
76 return;
77 }
78 // file descriptor can be cached later on request
79 fd.reset(FDS_NOT_CACHED);
80}
81
82void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
83 if (fd != FDS_NOT_CACHED) {
84 return;
85 }
86
87 if (access(path.c_str(), W_OK) != 0) {
88 // file is not accessible
89 fd.reset(FDS_INACCESSIBLE);
90 return;
91 }
92
93 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
94 if (tmp_fd < 0) {
95 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
96 fd.reset(FDS_INACCESSIBLE);
97 return;
98 }
99
100 fd = std::move(tmp_fd);
101}
102
103void FdCacheHelper::Drop(android::base::unique_fd& fd) {
104 if (fd == FDS_NOT_CACHED) {
105 return;
106 }
107
108 fd.reset(FDS_NOT_CACHED);
109}
110
111bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
112 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
113}
114
Bart Van Assche4c99e962022-02-03 19:50:16 +0000115IProfileAttribute::~IProfileAttribute() = default;
116
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700117void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name) {
118 controller_ = controller;
119 file_name_ = file_name;
120}
121
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800122bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
123 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700124 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800125 return false;
126 }
127
128 if (path == nullptr) {
129 return true;
130 }
131
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000132 const std::string& file_name =
133 controller()->version() == 2 && !file_v2_name_.empty() ? file_v2_name_ : file_name_;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800134 if (subgroup.empty()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000135 *path = StringPrintf("%s/%s", controller()->path(), file_name.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800136 } else {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000137 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(), file_name.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800138 }
139 return true;
140}
141
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000142bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
143 if (path == nullptr) {
144 return true;
145 }
146
147 const std::string& file_name =
148 controller()->version() == 2 && !file_v2_name_.empty() ? file_v2_name_ : file_name_;
149 *path = StringPrintf("%s/uid_%d/%s", controller()->path(), uid, file_name.c_str());
150 return true;
151}
152
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800153bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
154 // TODO: add support when kernel supports util_clamp
155 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
156 return false;
157}
158
159bool SetClampsAction::ExecuteForTask(int) const {
160 // TODO: add support when kernel supports util_clamp
161 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
162 return false;
163}
164
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800165// To avoid issues in sdk_mac build
166#if defined(__ANDROID__)
167
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800168bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
169 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
170
171 return (access(file.c_str(), W_OK) == 0);
172}
173
174bool SetTimerSlackAction::ExecuteForTask(int tid) const {
175 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
176
177 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
178 // TODO: once we've backported this, log if the open(2) fails.
179 if (sys_supports_timerslack) {
180 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
181 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800182 if (errno == ENOENT) {
183 // This happens when process is already dead
184 return true;
185 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800186 PLOG(ERROR) << "set_timerslack_ns write failed";
187 }
188 }
189
190 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
191 if (tid == 0 || tid == GetThreadId()) {
192 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
193 PLOG(ERROR) << "set_timerslack_ns prctl failed";
194 }
195 }
196
197 return true;
198}
199
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000200#else
201
202bool SetTimerSlackAction::ExecuteForTask(int) const {
203 return true;
204};
205
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800206#endif
207
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800208bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
209 return ExecuteForTask(pid);
210}
211
212bool SetAttributeAction::ExecuteForTask(int tid) const {
213 std::string path;
214
215 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800216 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800217 return false;
218 }
219
220 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700221 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000222 if (optional_) {
223 return true;
224 } else {
225 LOG(ERROR) << "No such cgroup attribute: " << path;
226 return false;
227 }
228 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700229 // The PLOG() statement below uses the error code stored in `errno` by
230 // WriteStringToFile() because access() only overwrites `errno` if it fails
231 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800232 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
233 return false;
234 }
235
236 return true;
237}
238
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000239bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
240 std::string path;
241
242 if (!attribute_->GetPathForUID(uid, &path)) {
243 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
244 return false;
245 }
246
247 if (!WriteStringToFile(value_, path)) {
248 if (access(path.c_str(), F_OK) < 0) {
249 if (optional_) {
250 return true;
251 } else {
252 LOG(ERROR) << "No such cgroup attribute: " << path;
253 return false;
254 }
255 }
256 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
257 return false;
258 }
259 return true;
260}
261
Rick Yiud4c53512021-11-21 15:57:36 +0800262SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
263 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800264 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
265 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
266 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800267}
268
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700269bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800270 if (tid <= 0) {
271 return true;
272 }
273
274 std::string value = std::to_string(tid);
275
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700276 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
277 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800278 }
279
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700280 // If the thread is in the process of exiting, don't flag an error
281 if (errno == ESRCH) {
282 return true;
283 }
284
285 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
286 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
287 // This is an abnormal case happening only in testing, so report it only once
288 static bool empty_cpuset_reported = false;
289
290 if (empty_cpuset_reported) {
291 return true;
292 }
293
294 LOG(ERROR) << "Failed to add task '" << value
295 << "' into cpuset because all cpus in that cpuset are offline";
296 empty_cpuset_reported = true;
297 } else {
298 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
299 }
300
301 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800302}
303
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800304ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
305 int id) const {
306 std::lock_guard<std::mutex> lock(fd_mutex_);
307 if (FdCacheHelper::IsCached(fd_[cache_type])) {
308 // fd is cached, reuse it
309 if (!AddTidToCgroup(id, fd_[cache_type], controller()->name())) {
310 LOG(ERROR) << "Failed to add task into cgroup";
311 return ProfileAction::FAIL;
312 }
313 return ProfileAction::SUCCESS;
314 }
315
316 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
317 // no permissions to access the file, ignore
318 return ProfileAction::SUCCESS;
319 }
320
321 if (cache_type == ResourceCacheType::RCT_TASK &&
322 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
323 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700324 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800325 return ProfileAction::FAIL;
326 }
327
328 return ProfileAction::UNUSED;
329}
330
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800331bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800332 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
333 if (result != ProfileAction::UNUSED) {
334 return result == ProfileAction::SUCCESS;
335 }
336
337 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700338 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800339 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
340 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700341 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800342 return false;
343 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700344 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800345 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800346 return false;
347 }
348
349 return true;
350}
351
352bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800353 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
354 if (result != ProfileAction::UNUSED) {
355 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800356 }
357
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800358 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700359 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800360 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
361 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700362 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800363 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800364 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700365 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800366 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800367 return false;
368 }
369
370 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800371}
372
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800373void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800374 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800375 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
376 // include regex evaluations
377 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
378 return;
379 }
380 switch (cache_type) {
381 case (ProfileAction::RCT_TASK):
382 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
383 break;
384 case (ProfileAction::RCT_PROCESS):
385 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
386 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
387 break;
388 default:
389 LOG(ERROR) << "Invalid cache type is specified!";
390 break;
391 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800392}
393
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800394void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800395 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800396 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800397}
398
Rick Yiu9221b1e2022-02-10 16:44:43 +0800399WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
400 const std::string& value, bool logfailures)
401 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
402 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
403 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800404}
Rick Yiubc1ad962020-10-26 20:32:52 +0800405
Rick Yiu9221b1e2022-02-10 16:44:43 +0800406bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
407 int uid, int pid, bool logfailures) const {
408 std::string value(value_);
409
410 value = StringReplace(value, "<uid>", std::to_string(uid), true);
411 value = StringReplace(value, "<pid>", std::to_string(pid), true);
412
413 CacheUseResult result = UseCachedFd(cache_type, value);
414
415 if (result != ProfileAction::UNUSED) {
416 return result == ProfileAction::SUCCESS;
417 }
418
419 std::string path;
420 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
421 path = task_path_;
422 } else {
423 path = proc_path_;
424 }
425
Rick Yiud4c53512021-11-21 15:57:36 +0800426 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
427 // O_TRUNC which causes kernfs_mutex contention
428 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800429
Rick Yiud4c53512021-11-21 15:57:36 +0800430 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700431 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800432 return false;
433 }
434
435 if (!WriteStringToFd(value, tmp_fd)) {
436 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800437 return false;
438 }
439
440 return true;
441}
442
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800443ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
444 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800445 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800446 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800447 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800448 bool ret = WriteStringToFd(value, fd_[cache_type]);
449
450 if (!ret && logfailures_) {
451 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
452 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
453 } else {
454 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
455 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800456 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800457 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800458 }
459
Rick Yiu9221b1e2022-02-10 16:44:43 +0800460 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800461 // no permissions to access the file, ignore
462 return ProfileAction::SUCCESS;
463 }
464
Rick Yiu9221b1e2022-02-10 16:44:43 +0800465 if (cache_type == ResourceCacheType::RCT_TASK &&
466 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800467 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700468 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800469 return ProfileAction::FAIL;
470 }
471 return ProfileAction::UNUSED;
472}
473
474bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800475 if (!proc_path_.empty()) {
476 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800477 }
478
Rick Yiu9221b1e2022-02-10 16:44:43 +0800479 DIR* d;
480 struct dirent* de;
481 char proc_path[255];
482 int t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800483
Rick Yiu9221b1e2022-02-10 16:44:43 +0800484 sprintf(proc_path, "/proc/%d/task", pid);
485 if (!(d = opendir(proc_path))) {
486 return false;
487 }
488
489 while ((de = readdir(d))) {
490 if (de->d_name[0] == '.') {
491 continue;
492 }
493
494 t_pid = atoi(de->d_name);
495
496 if (!t_pid) {
497 continue;
498 }
499
500 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
501 }
502
503 closedir(d);
504
505 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800506}
507
Rick Yiubc1ad962020-10-26 20:32:52 +0800508bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800509 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
510}
Rick Yiubc1ad962020-10-26 20:32:52 +0800511
Rick Yiu9221b1e2022-02-10 16:44:43 +0800512void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
513 std::lock_guard<std::mutex> lock(fd_mutex_);
514 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
515 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800516 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800517 switch (cache_type) {
518 case (ProfileAction::RCT_TASK):
519 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
520 break;
521 case (ProfileAction::RCT_PROCESS):
522 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
523 break;
524 default:
525 LOG(ERROR) << "Invalid cache type is specified!";
526 break;
527 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800528}
529
Rick Yiu9221b1e2022-02-10 16:44:43 +0800530void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800531 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800532 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800533}
534
Rick Yiu0b211fa2019-09-16 19:07:17 +0800535bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
536 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800537 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800538 }
539 return true;
540}
541
542bool ApplyProfileAction::ExecuteForTask(int tid) const {
543 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700544 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800545 }
546 return true;
547}
548
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800549void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800550 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800551 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800552 }
553}
554
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800555void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800556 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800557 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800558 }
559}
560
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800561void TaskProfile::MoveTo(TaskProfile* profile) {
562 profile->elements_ = std::move(elements_);
563 profile->res_cached_ = res_cached_;
564}
565
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800566bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
567 for (const auto& element : elements_) {
568 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000569 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800570 return false;
571 }
572 }
573 return true;
574}
575
576bool TaskProfile::ExecuteForTask(int tid) const {
577 if (tid == 0) {
578 tid = GetThreadId();
579 }
580 for (const auto& element : elements_) {
581 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000582 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800583 return false;
584 }
585 }
586 return true;
587}
588
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000589bool TaskProfile::ExecuteForUID(uid_t uid) const {
590 for (const auto& element : elements_) {
591 if (!element->ExecuteForUID(uid)) {
592 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
593 return false;
594 }
595 }
596 return true;
597}
598
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800599void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800600 if (res_cached_) {
601 return;
602 }
603
604 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800605 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800606 }
607
608 res_cached_ = true;
609}
610
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800611void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600612 if (!res_cached_) {
613 return;
614 }
615
616 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800617 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600618 }
619
620 res_cached_ = false;
621}
622
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800623void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600624 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800625 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600626 }
627}
628
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800629TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700630 // Deliberately leak this object to avoid a race between destruction on
631 // process exit and concurrent access from another thread.
632 static auto* instance = new TaskProfiles;
633 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800634}
635
636TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800637 // load system task profiles
638 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
639 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
640 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800641
642 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800643 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800644 if (api_level > 0) {
645 std::string api_profiles_path =
646 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
647 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800648 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800649 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800650 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800651 }
652 }
653
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800654 // load vendor task profiles if the file exists
655 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
656 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
657 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
658 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800659 }
660}
661
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800662bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800663 std::string json_doc;
664
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800665 if (!android::base::ReadFileToString(file_name, &json_doc)) {
666 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800667 return false;
668 }
669
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800670 Json::CharReaderBuilder builder;
671 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800672 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800673 std::string errorMessage;
674 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
675 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800676 return false;
677 }
678
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800679 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800680 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
681 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800682 std::string controller_name = attr[i]["Controller"].asString();
683 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000684 std::string file_v2_attr = attr[i]["FileV2"].asString();
685
686 if (!file_v2_attr.empty() && file_attr.empty()) {
687 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
688 return false;
689 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800690
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700691 auto controller = cg_map.FindController(controller_name);
692 if (controller.HasValue()) {
693 auto iter = attributes_.find(name);
694 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000695 attributes_[name] =
696 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800697 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700698 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800699 }
700 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700701 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800702 }
703 }
704
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800705 const Json::Value& profiles_val = root["Profiles"];
706 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
707 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800708
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800709 std::string profile_name = profile_val["Name"].asString();
710 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000711 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800712
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800713 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
714 const Json::Value& action_val = actions[act_idx];
715 std::string action_name = action_val["Name"].asString();
716 const Json::Value& params_val = action_val["Params"];
717 if (action_name == "JoinCgroup") {
718 std::string controller_name = params_val["Controller"].asString();
719 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800720
Yifan Hong53e0deb2019-03-22 17:01:08 -0700721 auto controller = cg_map.FindController(controller_name);
722 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800723 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
724 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800725 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800726 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800727 } else if (action_name == "SetTimerSlack") {
728 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800729 char* end;
730 unsigned long slack;
731
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800732 slack = strtoul(slack_value.c_str(), &end, 10);
733 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800734 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
735 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800736 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800737 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800738 } else if (action_name == "SetAttribute") {
739 std::string attr_name = params_val["Name"].asString();
740 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000741 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800742
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800743 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800744 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000745 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
746 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800747 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800748 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800749 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800750 } else if (action_name == "SetClamps") {
751 std::string boost_value = params_val["Boost"].asString();
752 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800753 char* end;
754 unsigned long boost;
755
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800756 boost = strtoul(boost_value.c_str(), &end, 10);
757 if (end > boost_value.c_str()) {
758 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
759 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800760 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
761 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800762 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800763 }
764 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800765 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800766 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800767 } else if (action_name == "WriteFile") {
768 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800769 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800770 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800771 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800772 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800773 std::string attr_logfailures = params_val["LogFailures"].asString();
774 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800775 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
776 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800777 } else if (attr_filepath.empty()) {
778 LOG(WARNING) << "WriteFile: invalid parameter: "
779 << "empty filepath";
780 } else if (attr_value.empty()) {
781 LOG(WARNING) << "WriteFile: invalid parameter: "
782 << "empty value";
783 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800784 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800785 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800786 }
787 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800788 auto iter = profiles_.find(profile_name);
789 if (iter == profiles_.end()) {
790 profiles_[profile_name] = profile;
791 } else {
792 // Move the content rather that replace the profile because old profile might be
793 // referenced from an aggregate profile if vendor overrides task profiles
794 profile->MoveTo(iter->second.get());
795 profile.reset();
796 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800797 }
798
799 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
800 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
801 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
802
803 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
804 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
805 std::vector<std::shared_ptr<TaskProfile>> profiles;
806 bool ret = true;
807
808 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
809 std::string profile_name = aggregateprofiles[pf_idx].asString();
810
811 if (profile_name == aggregateprofile_name) {
812 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
813 ret = false;
814 break;
815 } else if (profiles_.find(profile_name) == profiles_.end()) {
816 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
817 ret = false;
818 break;
819 } else {
820 profiles.push_back(profiles_[profile_name]);
821 }
822 }
823 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000824 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800825 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
826 profiles_[aggregateprofile_name] = profile;
827 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800828 }
829
830 return true;
831}
832
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700833TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800834 auto iter = profiles_.find(name);
835
836 if (iter != profiles_.end()) {
837 return iter->second.get();
838 }
839 return nullptr;
840}
841
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700842const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800843 auto iter = attributes_.find(name);
844
845 if (iter != attributes_.end()) {
846 return iter->second.get();
847 }
848 return nullptr;
849}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800850
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700851template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000852bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
853 for (const auto& name : profiles) {
854 TaskProfile* profile = GetProfile(name);
855 if (profile != nullptr) {
856 if (use_fd_cache) {
857 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
858 }
859 if (!profile->ExecuteForUID(uid)) {
860 PLOG(WARNING) << "Failed to apply " << name << " process profile";
861 }
862 } else {
863 PLOG(WARNING) << "Failed to find " << name << "process profile";
864 }
865 }
866 return true;
867}
868
869template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700870bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
871 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +0000872 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800873 for (const auto& name : profiles) {
874 TaskProfile* profile = GetProfile(name);
875 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800876 if (use_fd_cache) {
877 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
878 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800879 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +0000880 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +0000881 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800882 }
883 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +0000884 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +0000885 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800886 }
887 }
Inseob Kim538fc1f2022-04-13 18:50:12 +0000888 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800889}
890
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700891template <typename T>
892bool TaskProfiles::SetTaskProfiles(int tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +0000893 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800894 for (const auto& name : profiles) {
895 TaskProfile* profile = GetProfile(name);
896 if (profile != nullptr) {
897 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800898 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800899 }
900 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +0000901 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +0000902 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800903 }
904 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +0000905 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +0000906 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800907 }
908 }
Inseob Kim538fc1f2022-04-13 18:50:12 +0000909 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800910}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700911
912template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
913 std::span<const std::string> profiles,
914 bool use_fd_cache);
915template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
916 std::span<const std::string_view> profiles,
917 bool use_fd_cache);
918template bool TaskProfiles::SetTaskProfiles(int tid, std::span<const std::string> profiles,
919 bool use_fd_cache);
920template bool TaskProfiles::SetTaskProfiles(int tid, std::span<const std::string_view> profiles,
921 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000922template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
923 bool use_fd_cache);