blob: 59b135013326bb69fa94f345f6c2339d28580a8f [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 Baghdasaryan82b72a52018-12-21 11:41:50 -0800129bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
130 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700131 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800132 return false;
133 }
134
135 if (path == nullptr) {
136 return true;
137 }
138
139 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700140 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800141 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700142 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
143 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800144 }
145 return true;
146}
147
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000148bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
149 if (path == nullptr) {
150 return true;
151 }
152
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700153 *path = StringPrintf("%s/uid_%u/%s", controller()->path(), uid, file_name().c_str());
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000154 return true;
155}
156
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800157bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
158 // TODO: add support when kernel supports util_clamp
159 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
160 return false;
161}
162
163bool SetClampsAction::ExecuteForTask(int) const {
164 // TODO: add support when kernel supports util_clamp
165 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
166 return false;
167}
168
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800169// To avoid issues in sdk_mac build
170#if defined(__ANDROID__)
171
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800172bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
173 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
174
175 return (access(file.c_str(), W_OK) == 0);
176}
177
178bool SetTimerSlackAction::ExecuteForTask(int tid) const {
179 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
180
181 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
182 // TODO: once we've backported this, log if the open(2) fails.
183 if (sys_supports_timerslack) {
184 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
185 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800186 if (errno == ENOENT) {
187 // This happens when process is already dead
188 return true;
189 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800190 PLOG(ERROR) << "set_timerslack_ns write failed";
191 }
192 }
193
194 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
195 if (tid == 0 || tid == GetThreadId()) {
196 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
197 PLOG(ERROR) << "set_timerslack_ns prctl failed";
198 }
199 }
200
201 return true;
202}
203
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000204#else
205
206bool SetTimerSlackAction::ExecuteForTask(int) const {
207 return true;
208};
209
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800210#endif
211
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800212bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
213 return ExecuteForTask(pid);
214}
215
216bool SetAttributeAction::ExecuteForTask(int tid) const {
217 std::string path;
218
219 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800220 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800221 return false;
222 }
223
224 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
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000243bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
244 std::string path;
245
246 if (!attribute_->GetPathForUID(uid, &path)) {
247 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
248 return false;
249 }
250
251 if (!WriteStringToFile(value_, path)) {
252 if (access(path.c_str(), F_OK) < 0) {
253 if (optional_) {
254 return true;
255 } else {
256 LOG(ERROR) << "No such cgroup attribute: " << path;
257 return false;
258 }
259 }
260 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
261 return false;
262 }
263 return true;
264}
265
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000266bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
267 return IsValidForTask(pid);
268}
269
270bool SetAttributeAction::IsValidForTask(int tid) const {
271 std::string path;
272
273 if (!attribute_->GetPathForTask(tid, &path)) {
274 return false;
275 }
276
277 if (!access(path.c_str(), W_OK)) {
278 // operation will succeed
279 return true;
280 }
281
282 if (!access(path.c_str(), F_OK)) {
283 // file exists but not writable
284 return false;
285 }
286
287 // file does not exist, ignore if optional
288 return optional_;
289}
290
Rick Yiud4c53512021-11-21 15:57:36 +0800291SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
292 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800293 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
294 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
295 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800296}
297
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700298bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800299 if (tid <= 0) {
300 return true;
301 }
302
303 std::string value = std::to_string(tid);
304
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700305 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
306 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800307 }
308
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700309 // If the thread is in the process of exiting, don't flag an error
310 if (errno == ESRCH) {
311 return true;
312 }
313
314 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
315 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
316 // This is an abnormal case happening only in testing, so report it only once
317 static bool empty_cpuset_reported = false;
318
319 if (empty_cpuset_reported) {
320 return true;
321 }
322
323 LOG(ERROR) << "Failed to add task '" << value
324 << "' into cpuset because all cpus in that cpuset are offline";
325 empty_cpuset_reported = true;
326 } else {
327 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
328 }
329
330 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800331}
332
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800333ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
334 int id) const {
335 std::lock_guard<std::mutex> lock(fd_mutex_);
336 if (FdCacheHelper::IsCached(fd_[cache_type])) {
337 // fd is cached, reuse it
338 if (!AddTidToCgroup(id, fd_[cache_type], controller()->name())) {
339 LOG(ERROR) << "Failed to add task into cgroup";
340 return ProfileAction::FAIL;
341 }
342 return ProfileAction::SUCCESS;
343 }
344
345 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
346 // no permissions to access the file, ignore
347 return ProfileAction::SUCCESS;
348 }
349
350 if (cache_type == ResourceCacheType::RCT_TASK &&
351 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
352 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700353 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800354 return ProfileAction::FAIL;
355 }
356
357 return ProfileAction::UNUSED;
358}
359
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800360bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800361 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
362 if (result != ProfileAction::UNUSED) {
363 return result == ProfileAction::SUCCESS;
364 }
365
366 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700367 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800368 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
369 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700370 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800371 return false;
372 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700373 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800374 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800375 return false;
376 }
377
378 return true;
379}
380
381bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800382 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
383 if (result != ProfileAction::UNUSED) {
384 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800385 }
386
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800387 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700388 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800389 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_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 " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800392 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800393 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700394 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800395 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800396 return false;
397 }
398
399 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800400}
401
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800402void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800403 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800404 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
405 // include regex evaluations
406 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
407 return;
408 }
409 switch (cache_type) {
410 case (ProfileAction::RCT_TASK):
411 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
412 break;
413 case (ProfileAction::RCT_PROCESS):
414 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
415 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
416 break;
417 default:
418 LOG(ERROR) << "Invalid cache type is specified!";
419 break;
420 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800421}
422
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800423void SetCgroupAction::DropResourceCaching(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 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800426}
427
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000428bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
429 std::lock_guard<std::mutex> lock(fd_mutex_);
430 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
431 return true;
432 }
433
434 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
435 return false;
436 }
437
438 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
439 return access(procs_path.c_str(), W_OK) == 0;
440}
441
442bool SetCgroupAction::IsValidForTask(int) const {
443 std::lock_guard<std::mutex> lock(fd_mutex_);
444 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
445 return true;
446 }
447
448 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
449 return false;
450 }
451
452 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
453 // application-dependent path can't be used with tid
454 return false;
455 }
456
457 std::string tasks_path = controller()->GetTasksFilePath(path_);
458 return access(tasks_path.c_str(), W_OK) == 0;
459}
460
Rick Yiu9221b1e2022-02-10 16:44:43 +0800461WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
462 const std::string& value, bool logfailures)
463 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
464 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
465 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800466}
Rick Yiubc1ad962020-10-26 20:32:52 +0800467
Rick Yiu9221b1e2022-02-10 16:44:43 +0800468bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
469 int uid, int pid, bool logfailures) const {
470 std::string value(value_);
471
472 value = StringReplace(value, "<uid>", std::to_string(uid), true);
473 value = StringReplace(value, "<pid>", std::to_string(pid), true);
474
475 CacheUseResult result = UseCachedFd(cache_type, value);
476
477 if (result != ProfileAction::UNUSED) {
478 return result == ProfileAction::SUCCESS;
479 }
480
481 std::string path;
482 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
483 path = task_path_;
484 } else {
485 path = proc_path_;
486 }
487
Rick Yiud4c53512021-11-21 15:57:36 +0800488 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
489 // O_TRUNC which causes kernfs_mutex contention
490 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800491
Rick Yiud4c53512021-11-21 15:57:36 +0800492 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700493 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800494 return false;
495 }
496
497 if (!WriteStringToFd(value, tmp_fd)) {
498 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800499 return false;
500 }
501
502 return true;
503}
504
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800505ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
506 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800507 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800508 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800509 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800510 bool ret = WriteStringToFd(value, fd_[cache_type]);
511
512 if (!ret && logfailures_) {
513 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
514 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
515 } else {
516 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
517 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800518 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800519 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800520 }
521
Rick Yiu9221b1e2022-02-10 16:44:43 +0800522 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800523 // no permissions to access the file, ignore
524 return ProfileAction::SUCCESS;
525 }
526
Rick Yiu9221b1e2022-02-10 16:44:43 +0800527 if (cache_type == ResourceCacheType::RCT_TASK &&
528 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800529 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700530 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800531 return ProfileAction::FAIL;
532 }
533 return ProfileAction::UNUSED;
534}
535
536bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800537 if (!proc_path_.empty()) {
538 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800539 }
540
Rick Yiu9221b1e2022-02-10 16:44:43 +0800541 DIR* d;
542 struct dirent* de;
543 char proc_path[255];
544 int t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800545
Rick Yiu9221b1e2022-02-10 16:44:43 +0800546 sprintf(proc_path, "/proc/%d/task", pid);
547 if (!(d = opendir(proc_path))) {
548 return false;
549 }
550
551 while ((de = readdir(d))) {
552 if (de->d_name[0] == '.') {
553 continue;
554 }
555
556 t_pid = atoi(de->d_name);
557
558 if (!t_pid) {
559 continue;
560 }
561
562 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
563 }
564
565 closedir(d);
566
567 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800568}
569
Rick Yiubc1ad962020-10-26 20:32:52 +0800570bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800571 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
572}
Rick Yiubc1ad962020-10-26 20:32:52 +0800573
Rick Yiu9221b1e2022-02-10 16:44:43 +0800574void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
575 std::lock_guard<std::mutex> lock(fd_mutex_);
576 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
577 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800578 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800579 switch (cache_type) {
580 case (ProfileAction::RCT_TASK):
581 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
582 break;
583 case (ProfileAction::RCT_PROCESS):
584 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
585 break;
586 default:
587 LOG(ERROR) << "Invalid cache type is specified!";
588 break;
589 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800590}
591
Rick Yiu9221b1e2022-02-10 16:44:43 +0800592void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800593 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800594 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800595}
596
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000597bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
598 std::lock_guard<std::mutex> lock(fd_mutex_);
599 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
600 return true;
601 }
602
603 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
604 return false;
605 }
606
607 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
608}
609
610bool WriteFileAction::IsValidForTask(int) const {
611 std::lock_guard<std::mutex> lock(fd_mutex_);
612 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
613 return true;
614 }
615
616 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
617 return false;
618 }
619
620 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
621 // application-dependent path can't be used with tid
622 return false;
623 }
624
625 return access(task_path_.c_str(), W_OK) == 0;
626}
627
Rick Yiu0b211fa2019-09-16 19:07:17 +0800628bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
629 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800630 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800631 }
632 return true;
633}
634
635bool ApplyProfileAction::ExecuteForTask(int tid) const {
636 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700637 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800638 }
639 return true;
640}
641
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800642void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800643 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800644 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800645 }
646}
647
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800648void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800649 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800650 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800651 }
652}
653
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000654bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
655 for (const auto& profile : profiles_) {
656 if (!profile->IsValidForProcess(uid, pid)) {
657 return false;
658 }
659 }
660 return true;
661}
662
663bool ApplyProfileAction::IsValidForTask(int tid) const {
664 for (const auto& profile : profiles_) {
665 if (!profile->IsValidForTask(tid)) {
666 return false;
667 }
668 }
669 return true;
670}
671
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800672void TaskProfile::MoveTo(TaskProfile* profile) {
673 profile->elements_ = std::move(elements_);
674 profile->res_cached_ = res_cached_;
675}
676
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800677bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
678 for (const auto& element : elements_) {
679 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000680 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800681 return false;
682 }
683 }
684 return true;
685}
686
687bool TaskProfile::ExecuteForTask(int tid) const {
688 if (tid == 0) {
689 tid = GetThreadId();
690 }
691 for (const auto& element : elements_) {
692 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000693 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800694 return false;
695 }
696 }
697 return true;
698}
699
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000700bool TaskProfile::ExecuteForUID(uid_t uid) const {
701 for (const auto& element : elements_) {
702 if (!element->ExecuteForUID(uid)) {
703 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
704 return false;
705 }
706 }
707 return true;
708}
709
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800710void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800711 if (res_cached_) {
712 return;
713 }
714
715 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800716 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800717 }
718
719 res_cached_ = true;
720}
721
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800722void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600723 if (!res_cached_) {
724 return;
725 }
726
727 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800728 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600729 }
730
731 res_cached_ = false;
732}
733
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000734bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
735 for (const auto& element : elements_) {
736 if (!element->IsValidForProcess(uid, pid)) return false;
737 }
738 return true;
739}
740
741bool TaskProfile::IsValidForTask(int tid) const {
742 for (const auto& element : elements_) {
743 if (!element->IsValidForTask(tid)) return false;
744 }
745 return true;
746}
747
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800748void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600749 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800750 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600751 }
752}
753
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800754TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700755 // Deliberately leak this object to avoid a race between destruction on
756 // process exit and concurrent access from another thread.
757 static auto* instance = new TaskProfiles;
758 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800759}
760
761TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800762 // load system task profiles
763 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
764 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
765 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800766
767 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800768 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800769 if (api_level > 0) {
770 std::string api_profiles_path =
771 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
772 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800773 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800774 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800775 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800776 }
777 }
778
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800779 // load vendor task profiles if the file exists
780 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
781 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
782 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
783 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800784 }
785}
786
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800787bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800788 std::string json_doc;
789
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800790 if (!android::base::ReadFileToString(file_name, &json_doc)) {
791 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800792 return false;
793 }
794
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800795 Json::CharReaderBuilder builder;
796 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800797 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800798 std::string errorMessage;
799 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
800 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800801 return false;
802 }
803
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800804 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800805 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
806 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800807 std::string controller_name = attr[i]["Controller"].asString();
808 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000809 std::string file_v2_attr = attr[i]["FileV2"].asString();
810
811 if (!file_v2_attr.empty() && file_attr.empty()) {
812 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
813 return false;
814 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800815
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700816 auto controller = cg_map.FindController(controller_name);
817 if (controller.HasValue()) {
818 auto iter = attributes_.find(name);
819 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000820 attributes_[name] =
821 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800822 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700823 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800824 }
825 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700826 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800827 }
828 }
829
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800830 const Json::Value& profiles_val = root["Profiles"];
831 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
832 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800833
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800834 std::string profile_name = profile_val["Name"].asString();
835 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000836 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800837
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800838 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
839 const Json::Value& action_val = actions[act_idx];
840 std::string action_name = action_val["Name"].asString();
841 const Json::Value& params_val = action_val["Params"];
842 if (action_name == "JoinCgroup") {
843 std::string controller_name = params_val["Controller"].asString();
844 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800845
Yifan Hong53e0deb2019-03-22 17:01:08 -0700846 auto controller = cg_map.FindController(controller_name);
847 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800848 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
849 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800850 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800851 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800852 } else if (action_name == "SetTimerSlack") {
853 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800854 char* end;
855 unsigned long slack;
856
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800857 slack = strtoul(slack_value.c_str(), &end, 10);
858 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800859 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
860 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800861 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800862 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800863 } else if (action_name == "SetAttribute") {
864 std::string attr_name = params_val["Name"].asString();
865 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000866 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800867
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800868 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800869 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000870 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
871 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800872 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800873 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800874 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800875 } else if (action_name == "SetClamps") {
876 std::string boost_value = params_val["Boost"].asString();
877 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800878 char* end;
879 unsigned long boost;
880
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800881 boost = strtoul(boost_value.c_str(), &end, 10);
882 if (end > boost_value.c_str()) {
883 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
884 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800885 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
886 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800887 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800888 }
889 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800890 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800891 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800892 } else if (action_name == "WriteFile") {
893 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800894 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800895 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800896 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800897 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800898 std::string attr_logfailures = params_val["LogFailures"].asString();
899 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800900 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
901 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800902 } else if (attr_filepath.empty()) {
903 LOG(WARNING) << "WriteFile: invalid parameter: "
904 << "empty filepath";
905 } else if (attr_value.empty()) {
906 LOG(WARNING) << "WriteFile: invalid parameter: "
907 << "empty value";
908 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800909 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800910 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800911 }
912 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800913 auto iter = profiles_.find(profile_name);
914 if (iter == profiles_.end()) {
915 profiles_[profile_name] = profile;
916 } else {
917 // Move the content rather that replace the profile because old profile might be
918 // referenced from an aggregate profile if vendor overrides task profiles
919 profile->MoveTo(iter->second.get());
920 profile.reset();
921 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800922 }
923
924 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
925 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
926 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
927
928 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
929 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
930 std::vector<std::shared_ptr<TaskProfile>> profiles;
931 bool ret = true;
932
933 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
934 std::string profile_name = aggregateprofiles[pf_idx].asString();
935
936 if (profile_name == aggregateprofile_name) {
937 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
938 ret = false;
939 break;
940 } else if (profiles_.find(profile_name) == profiles_.end()) {
941 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
942 ret = false;
943 break;
944 } else {
945 profiles.push_back(profiles_[profile_name]);
946 }
947 }
948 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000949 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800950 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
951 profiles_[aggregateprofile_name] = profile;
952 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800953 }
954
955 return true;
956}
957
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700958TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800959 auto iter = profiles_.find(name);
960
961 if (iter != profiles_.end()) {
962 return iter->second.get();
963 }
964 return nullptr;
965}
966
Bart Van Assched0b8ce22022-08-02 13:06:26 -0700967const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800968 auto iter = attributes_.find(name);
969
970 if (iter != attributes_.end()) {
971 return iter->second.get();
972 }
973 return nullptr;
974}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800975
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700976template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000977bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
978 for (const auto& name : profiles) {
979 TaskProfile* profile = GetProfile(name);
980 if (profile != nullptr) {
981 if (use_fd_cache) {
982 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
983 }
984 if (!profile->ExecuteForUID(uid)) {
985 PLOG(WARNING) << "Failed to apply " << name << " process profile";
986 }
987 } else {
988 PLOG(WARNING) << "Failed to find " << name << "process profile";
989 }
990 }
991 return true;
992}
993
994template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700995bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
996 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +0000997 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +0800998 for (const auto& name : profiles) {
999 TaskProfile* profile = GetProfile(name);
1000 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001001 if (use_fd_cache) {
1002 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1003 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001004 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001005 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001006 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001007 }
1008 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001009 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001010 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001011 }
1012 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001013 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001014}
1015
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001016template <typename T>
1017bool TaskProfiles::SetTaskProfiles(int tid, std::span<const T> profiles, 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) {
1022 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001023 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001024 }
1025 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001026 LOG(WARNING) << "Failed to apply " << name << " task 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 << " task 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}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001036
1037template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1038 std::span<const std::string> profiles,
1039 bool use_fd_cache);
1040template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1041 std::span<const std::string_view> profiles,
1042 bool use_fd_cache);
1043template bool TaskProfiles::SetTaskProfiles(int tid, std::span<const std::string> profiles,
1044 bool use_fd_cache);
1045template bool TaskProfiles::SetTaskProfiles(int tid, std::span<const std::string_view> profiles,
1046 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001047template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1048 bool use_fd_cache);