blob: f51b07671bf10da2cbc2d023d653429ea634d4d9 [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 Baghdasaryan35078462023-07-25 14:50:18 -0700117const std::string& ProfileAttribute::file_name() const {
118 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
119 return file_name_;
120}
121
122void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name,
123 const std::string& file_v2_name) {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700124 controller_ = controller;
125 file_name_ = file_name;
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700126 file_v2_name_ = file_v2_name;
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700127}
128
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700129bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
130 if (controller()->version() == 2) {
131 // all cgroup v2 attributes use the same process group hierarchy
132 *path = StringPrintf("%s/uid_%u/pid_%d/%s", controller()->path(), uid, pid,
133 file_name().c_str());
134 return true;
135 }
136 return GetPathForTask(pid, path);
137}
138
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800139bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
140 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700141 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800142 return false;
143 }
144
145 if (path == nullptr) {
146 return true;
147 }
148
149 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700150 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800151 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700152 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
153 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800154 }
155 return true;
156}
157
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000158bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
159 if (path == nullptr) {
160 return true;
161 }
162
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700163 *path = StringPrintf("%s/uid_%u/%s", controller()->path(), uid, file_name().c_str());
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000164 return true;
165}
166
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800167bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
168 // TODO: add support when kernel supports util_clamp
169 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
170 return false;
171}
172
173bool SetClampsAction::ExecuteForTask(int) const {
174 // TODO: add support when kernel supports util_clamp
175 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
176 return false;
177}
178
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800179// To avoid issues in sdk_mac build
180#if defined(__ANDROID__)
181
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800182bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
183 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
184
185 return (access(file.c_str(), W_OK) == 0);
186}
187
188bool SetTimerSlackAction::ExecuteForTask(int tid) const {
189 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
190
191 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
192 // TODO: once we've backported this, log if the open(2) fails.
193 if (sys_supports_timerslack) {
194 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
195 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800196 if (errno == ENOENT) {
197 // This happens when process is already dead
198 return true;
199 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800200 PLOG(ERROR) << "set_timerslack_ns write failed";
201 }
202 }
203
204 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
205 if (tid == 0 || tid == GetThreadId()) {
206 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
207 PLOG(ERROR) << "set_timerslack_ns prctl failed";
208 }
209 }
210
211 return true;
212}
213
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000214#else
215
216bool SetTimerSlackAction::ExecuteForTask(int) const {
217 return true;
218};
219
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800220#endif
221
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700222bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800223 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700224 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000225 if (optional_) {
226 return true;
227 } else {
228 LOG(ERROR) << "No such cgroup attribute: " << path;
229 return false;
230 }
231 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700232 // The PLOG() statement below uses the error code stored in `errno` by
233 // WriteStringToFile() because access() only overwrites `errno` if it fails
234 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800235 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
236 return false;
237 }
238
239 return true;
240}
241
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700242bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
243 std::string path;
244
245 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
246 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
247 return false;
248 }
249
250 return WriteValueToFile(path);
251}
252
253bool SetAttributeAction::ExecuteForTask(int tid) const {
254 std::string path;
255
256 if (!attribute_->GetPathForTask(tid, &path)) {
257 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
258 return false;
259 }
260
261 return WriteValueToFile(path);
262}
263
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000264bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
265 std::string path;
266
267 if (!attribute_->GetPathForUID(uid, &path)) {
268 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
269 return false;
270 }
271
272 if (!WriteStringToFile(value_, path)) {
273 if (access(path.c_str(), F_OK) < 0) {
274 if (optional_) {
275 return true;
276 } else {
277 LOG(ERROR) << "No such cgroup attribute: " << path;
278 return false;
279 }
280 }
281 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
282 return false;
283 }
284 return true;
285}
286
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000287bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
288 return IsValidForTask(pid);
289}
290
291bool SetAttributeAction::IsValidForTask(int tid) const {
292 std::string path;
293
294 if (!attribute_->GetPathForTask(tid, &path)) {
295 return false;
296 }
297
298 if (!access(path.c_str(), W_OK)) {
299 // operation will succeed
300 return true;
301 }
302
303 if (!access(path.c_str(), F_OK)) {
304 // file exists but not writable
305 return false;
306 }
307
308 // file does not exist, ignore if optional
309 return optional_;
310}
311
Rick Yiud4c53512021-11-21 15:57:36 +0800312SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
313 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800314 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
315 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
316 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800317}
318
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700319bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800320 if (tid <= 0) {
321 return true;
322 }
323
324 std::string value = std::to_string(tid);
325
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700326 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
327 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800328 }
329
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700330 // If the thread is in the process of exiting, don't flag an error
331 if (errno == ESRCH) {
332 return true;
333 }
334
335 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
336 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
337 // This is an abnormal case happening only in testing, so report it only once
338 static bool empty_cpuset_reported = false;
339
340 if (empty_cpuset_reported) {
341 return true;
342 }
343
344 LOG(ERROR) << "Failed to add task '" << value
345 << "' into cpuset because all cpus in that cpuset are offline";
346 empty_cpuset_reported = true;
347 } else {
348 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
349 }
350
351 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800352}
353
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800354ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
355 int id) const {
356 std::lock_guard<std::mutex> lock(fd_mutex_);
357 if (FdCacheHelper::IsCached(fd_[cache_type])) {
358 // fd is cached, reuse it
359 if (!AddTidToCgroup(id, fd_[cache_type], controller()->name())) {
360 LOG(ERROR) << "Failed to add task into cgroup";
361 return ProfileAction::FAIL;
362 }
363 return ProfileAction::SUCCESS;
364 }
365
366 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
367 // no permissions to access the file, ignore
368 return ProfileAction::SUCCESS;
369 }
370
371 if (cache_type == ResourceCacheType::RCT_TASK &&
372 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
373 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700374 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800375 return ProfileAction::FAIL;
376 }
377
378 return ProfileAction::UNUSED;
379}
380
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800381bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800382 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
383 if (result != ProfileAction::UNUSED) {
384 return result == ProfileAction::SUCCESS;
385 }
386
387 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700388 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800389 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
390 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700391 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800392 return false;
393 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700394 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800395 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800396 return false;
397 }
398
399 return true;
400}
401
402bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800403 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
404 if (result != ProfileAction::UNUSED) {
405 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800406 }
407
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800408 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700409 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800410 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
411 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700412 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800413 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800414 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700415 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800416 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800417 return false;
418 }
419
420 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800421}
422
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800423void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800424 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800425 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
426 // include regex evaluations
427 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
428 return;
429 }
430 switch (cache_type) {
431 case (ProfileAction::RCT_TASK):
432 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
433 break;
434 case (ProfileAction::RCT_PROCESS):
435 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
436 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
437 break;
438 default:
439 LOG(ERROR) << "Invalid cache type is specified!";
440 break;
441 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800442}
443
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800444void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800445 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800446 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800447}
448
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000449bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
450 std::lock_guard<std::mutex> lock(fd_mutex_);
451 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
452 return true;
453 }
454
455 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
456 return false;
457 }
458
459 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
460 return access(procs_path.c_str(), W_OK) == 0;
461}
462
463bool SetCgroupAction::IsValidForTask(int) const {
464 std::lock_guard<std::mutex> lock(fd_mutex_);
465 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
466 return true;
467 }
468
469 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
470 return false;
471 }
472
473 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
474 // application-dependent path can't be used with tid
475 return false;
476 }
477
478 std::string tasks_path = controller()->GetTasksFilePath(path_);
479 return access(tasks_path.c_str(), W_OK) == 0;
480}
481
Rick Yiu9221b1e2022-02-10 16:44:43 +0800482WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
483 const std::string& value, bool logfailures)
484 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
485 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
486 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800487}
Rick Yiubc1ad962020-10-26 20:32:52 +0800488
Rick Yiu9221b1e2022-02-10 16:44:43 +0800489bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
490 int uid, int pid, bool logfailures) const {
491 std::string value(value_);
492
493 value = StringReplace(value, "<uid>", std::to_string(uid), true);
494 value = StringReplace(value, "<pid>", std::to_string(pid), true);
495
496 CacheUseResult result = UseCachedFd(cache_type, value);
497
498 if (result != ProfileAction::UNUSED) {
499 return result == ProfileAction::SUCCESS;
500 }
501
502 std::string path;
503 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
504 path = task_path_;
505 } else {
506 path = proc_path_;
507 }
508
Rick Yiud4c53512021-11-21 15:57:36 +0800509 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
510 // O_TRUNC which causes kernfs_mutex contention
511 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800512
Rick Yiud4c53512021-11-21 15:57:36 +0800513 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700514 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800515 return false;
516 }
517
518 if (!WriteStringToFd(value, tmp_fd)) {
519 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800520 return false;
521 }
522
523 return true;
524}
525
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800526ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
527 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800528 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800529 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800530 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800531 bool ret = WriteStringToFd(value, fd_[cache_type]);
532
533 if (!ret && logfailures_) {
534 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
535 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
536 } else {
537 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
538 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800539 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800540 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800541 }
542
Rick Yiu9221b1e2022-02-10 16:44:43 +0800543 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800544 // no permissions to access the file, ignore
545 return ProfileAction::SUCCESS;
546 }
547
Rick Yiu9221b1e2022-02-10 16:44:43 +0800548 if (cache_type == ResourceCacheType::RCT_TASK &&
549 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800550 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700551 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800552 return ProfileAction::FAIL;
553 }
554 return ProfileAction::UNUSED;
555}
556
557bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800558 if (!proc_path_.empty()) {
559 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800560 }
561
Rick Yiu9221b1e2022-02-10 16:44:43 +0800562 DIR* d;
563 struct dirent* de;
564 char proc_path[255];
565 int t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800566
Rick Yiu9221b1e2022-02-10 16:44:43 +0800567 sprintf(proc_path, "/proc/%d/task", pid);
568 if (!(d = opendir(proc_path))) {
569 return false;
570 }
571
572 while ((de = readdir(d))) {
573 if (de->d_name[0] == '.') {
574 continue;
575 }
576
577 t_pid = atoi(de->d_name);
578
579 if (!t_pid) {
580 continue;
581 }
582
583 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
584 }
585
586 closedir(d);
587
588 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800589}
590
Rick Yiubc1ad962020-10-26 20:32:52 +0800591bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800592 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
593}
Rick Yiubc1ad962020-10-26 20:32:52 +0800594
Rick Yiu9221b1e2022-02-10 16:44:43 +0800595void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
596 std::lock_guard<std::mutex> lock(fd_mutex_);
597 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
598 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800599 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800600 switch (cache_type) {
601 case (ProfileAction::RCT_TASK):
602 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
603 break;
604 case (ProfileAction::RCT_PROCESS):
605 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
606 break;
607 default:
608 LOG(ERROR) << "Invalid cache type is specified!";
609 break;
610 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800611}
612
Rick Yiu9221b1e2022-02-10 16:44:43 +0800613void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800614 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800615 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800616}
617
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000618bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
619 std::lock_guard<std::mutex> lock(fd_mutex_);
620 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
621 return true;
622 }
623
624 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
625 return false;
626 }
627
628 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
629}
630
631bool WriteFileAction::IsValidForTask(int) const {
632 std::lock_guard<std::mutex> lock(fd_mutex_);
633 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
634 return true;
635 }
636
637 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
638 return false;
639 }
640
641 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
642 // application-dependent path can't be used with tid
643 return false;
644 }
645
646 return access(task_path_.c_str(), W_OK) == 0;
647}
648
Rick Yiu0b211fa2019-09-16 19:07:17 +0800649bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
650 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800651 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800652 }
653 return true;
654}
655
656bool ApplyProfileAction::ExecuteForTask(int tid) const {
657 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700658 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800659 }
660 return true;
661}
662
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800663void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800664 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800665 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800666 }
667}
668
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800669void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800670 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800671 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800672 }
673}
674
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000675bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
676 for (const auto& profile : profiles_) {
677 if (!profile->IsValidForProcess(uid, pid)) {
678 return false;
679 }
680 }
681 return true;
682}
683
684bool ApplyProfileAction::IsValidForTask(int tid) const {
685 for (const auto& profile : profiles_) {
686 if (!profile->IsValidForTask(tid)) {
687 return false;
688 }
689 }
690 return true;
691}
692
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800693void TaskProfile::MoveTo(TaskProfile* profile) {
694 profile->elements_ = std::move(elements_);
695 profile->res_cached_ = res_cached_;
696}
697
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800698bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
699 for (const auto& element : elements_) {
700 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000701 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800702 return false;
703 }
704 }
705 return true;
706}
707
708bool TaskProfile::ExecuteForTask(int tid) const {
709 if (tid == 0) {
710 tid = GetThreadId();
711 }
712 for (const auto& element : elements_) {
713 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000714 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800715 return false;
716 }
717 }
718 return true;
719}
720
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000721bool TaskProfile::ExecuteForUID(uid_t uid) const {
722 for (const auto& element : elements_) {
723 if (!element->ExecuteForUID(uid)) {
724 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
725 return false;
726 }
727 }
728 return true;
729}
730
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800731void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800732 if (res_cached_) {
733 return;
734 }
735
736 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800737 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800738 }
739
740 res_cached_ = true;
741}
742
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800743void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600744 if (!res_cached_) {
745 return;
746 }
747
748 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800749 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600750 }
751
752 res_cached_ = false;
753}
754
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000755bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
756 for (const auto& element : elements_) {
757 if (!element->IsValidForProcess(uid, pid)) return false;
758 }
759 return true;
760}
761
762bool TaskProfile::IsValidForTask(int tid) const {
763 for (const auto& element : elements_) {
764 if (!element->IsValidForTask(tid)) return false;
765 }
766 return true;
767}
768
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800769void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600770 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800771 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600772 }
773}
774
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800775TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700776 // Deliberately leak this object to avoid a race between destruction on
777 // process exit and concurrent access from another thread.
778 static auto* instance = new TaskProfiles;
779 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800780}
781
782TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800783 // load system task profiles
784 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
785 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
786 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800787
788 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800789 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800790 if (api_level > 0) {
791 std::string api_profiles_path =
792 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
793 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800794 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800795 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800796 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800797 }
798 }
799
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800800 // load vendor task profiles if the file exists
801 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
802 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
803 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
804 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800805 }
806}
807
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800808bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800809 std::string json_doc;
810
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800811 if (!android::base::ReadFileToString(file_name, &json_doc)) {
812 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800813 return false;
814 }
815
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800816 Json::CharReaderBuilder builder;
817 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800818 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800819 std::string errorMessage;
820 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
821 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800822 return false;
823 }
824
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800825 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800826 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
827 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800828 std::string controller_name = attr[i]["Controller"].asString();
829 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000830 std::string file_v2_attr = attr[i]["FileV2"].asString();
831
832 if (!file_v2_attr.empty() && file_attr.empty()) {
833 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
834 return false;
835 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800836
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700837 auto controller = cg_map.FindController(controller_name);
838 if (controller.HasValue()) {
839 auto iter = attributes_.find(name);
840 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000841 attributes_[name] =
842 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800843 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700844 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800845 }
846 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700847 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800848 }
849 }
850
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800851 const Json::Value& profiles_val = root["Profiles"];
852 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
853 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800854
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800855 std::string profile_name = profile_val["Name"].asString();
856 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000857 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800858
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800859 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
860 const Json::Value& action_val = actions[act_idx];
861 std::string action_name = action_val["Name"].asString();
862 const Json::Value& params_val = action_val["Params"];
863 if (action_name == "JoinCgroup") {
864 std::string controller_name = params_val["Controller"].asString();
865 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800866
Yifan Hong53e0deb2019-03-22 17:01:08 -0700867 auto controller = cg_map.FindController(controller_name);
868 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800869 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
870 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800871 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800872 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800873 } else if (action_name == "SetTimerSlack") {
874 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800875 char* end;
876 unsigned long slack;
877
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800878 slack = strtoul(slack_value.c_str(), &end, 10);
879 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800880 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
881 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800882 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800883 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800884 } else if (action_name == "SetAttribute") {
885 std::string attr_name = params_val["Name"].asString();
886 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000887 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800888
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800889 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800890 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000891 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
892 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800893 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800894 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800895 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800896 } else if (action_name == "SetClamps") {
897 std::string boost_value = params_val["Boost"].asString();
898 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800899 char* end;
900 unsigned long boost;
901
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800902 boost = strtoul(boost_value.c_str(), &end, 10);
903 if (end > boost_value.c_str()) {
904 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
905 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800906 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
907 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800908 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800909 }
910 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800911 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800912 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800913 } else if (action_name == "WriteFile") {
914 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800915 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800916 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800917 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800918 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800919 std::string attr_logfailures = params_val["LogFailures"].asString();
920 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800921 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
922 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800923 } else if (attr_filepath.empty()) {
924 LOG(WARNING) << "WriteFile: invalid parameter: "
925 << "empty filepath";
926 } else if (attr_value.empty()) {
927 LOG(WARNING) << "WriteFile: invalid parameter: "
928 << "empty value";
929 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800930 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800931 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800932 }
933 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800934 auto iter = profiles_.find(profile_name);
935 if (iter == profiles_.end()) {
936 profiles_[profile_name] = profile;
937 } else {
938 // Move the content rather that replace the profile because old profile might be
939 // referenced from an aggregate profile if vendor overrides task profiles
940 profile->MoveTo(iter->second.get());
941 profile.reset();
942 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800943 }
944
945 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
946 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
947 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
948
949 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
950 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
951 std::vector<std::shared_ptr<TaskProfile>> profiles;
952 bool ret = true;
953
954 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
955 std::string profile_name = aggregateprofiles[pf_idx].asString();
956
957 if (profile_name == aggregateprofile_name) {
958 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
959 ret = false;
960 break;
961 } else if (profiles_.find(profile_name) == profiles_.end()) {
962 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
963 ret = false;
964 break;
965 } else {
966 profiles.push_back(profiles_[profile_name]);
967 }
968 }
969 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000970 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800971 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
972 profiles_[aggregateprofile_name] = profile;
973 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800974 }
975
976 return true;
977}
978
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700979TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800980 auto iter = profiles_.find(name);
981
982 if (iter != profiles_.end()) {
983 return iter->second.get();
984 }
985 return nullptr;
986}
987
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700988const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800989 auto iter = attributes_.find(name);
990
991 if (iter != attributes_.end()) {
992 return iter->second.get();
993 }
994 return nullptr;
995}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800996
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700997template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000998bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
999 for (const auto& name : profiles) {
1000 TaskProfile* profile = GetProfile(name);
1001 if (profile != nullptr) {
1002 if (use_fd_cache) {
1003 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1004 }
1005 if (!profile->ExecuteForUID(uid)) {
1006 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1007 }
1008 } else {
1009 PLOG(WARNING) << "Failed to find " << name << "process profile";
1010 }
1011 }
1012 return true;
1013}
1014
1015template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001016bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1017 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001018 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001019 for (const auto& name : profiles) {
1020 TaskProfile* profile = GetProfile(name);
1021 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001022 if (use_fd_cache) {
1023 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1024 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001025 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001026 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001027 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001028 }
1029 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001030 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001031 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001032 }
1033 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001034 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001035}
1036
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001037template <typename T>
1038bool TaskProfiles::SetTaskProfiles(int tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001039 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001040 for (const auto& name : profiles) {
1041 TaskProfile* profile = GetProfile(name);
1042 if (profile != nullptr) {
1043 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001044 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001045 }
1046 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001047 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001048 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001049 }
1050 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001051 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001052 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001053 }
1054 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001055 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001056}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001057
1058template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1059 std::span<const std::string> profiles,
1060 bool use_fd_cache);
1061template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1062 std::span<const std::string_view> profiles,
1063 bool use_fd_cache);
1064template bool TaskProfiles::SetTaskProfiles(int tid, std::span<const std::string> profiles,
1065 bool use_fd_cache);
1066template bool TaskProfiles::SetTaskProfiles(int tid, std::span<const std::string_view> profiles,
1067 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001068template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1069 bool use_fd_cache);