1 /*
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 <task_profiles.h>
21
22 #include <map>
23 #include <string>
24
25 #include <dirent.h>
26 #include <fcntl.h>
27 #include <sched.h>
28 #include <sys/resource.h>
29 #include <unistd.h>
30
31 #include <android-base/file.h>
32 #include <android-base/logging.h>
33 #include <android-base/parseint.h>
34 #include <android-base/properties.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <android-base/threads.h>
38
39 #include <build_flags.h>
40
41 #include <cutils/android_filesystem_config.h>
42
43 #include <json/reader.h>
44 #include <json/value.h>
45
46 using android::base::GetThreadId;
47 using android::base::GetUintProperty;
48 using android::base::StringPrintf;
49 using android::base::StringReplace;
50 using android::base::unique_fd;
51 using android::base::WriteStringToFile;
52
53 static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
54 static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
55
56 static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
57 "/etc/task_profiles/task_profiles_%u.json";
58 namespace {
59
60 class FdCacheHelper {
61 public:
62 enum FdState {
63 FDS_INACCESSIBLE = -1,
64 FDS_APP_DEPENDENT = -2,
65 FDS_NOT_CACHED = -3,
66 };
67
68 static void Cache(const std::string& path, android::base::unique_fd& fd);
69
70 static void Drop(android::base::unique_fd& fd);
71
72 static void Init(const std::string& path, android::base::unique_fd& fd);
73
IsCached(const android::base::unique_fd & fd)74 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
75
76 private:
77 static bool IsAppDependentPath(const std::string& path);
78 };
79
Init(const std::string & path,android::base::unique_fd & fd)80 void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
81 // file descriptors for app-dependent paths can't be cached
82 if (IsAppDependentPath(path)) {
83 // file descriptor is not cached
84 fd.reset(FDS_APP_DEPENDENT);
85 return;
86 }
87 // file descriptor can be cached later on request
88 fd.reset(FDS_NOT_CACHED);
89 }
90
Cache(const std::string & path,android::base::unique_fd & fd)91 void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
92 if (fd != FDS_NOT_CACHED) {
93 return;
94 }
95
96 if (access(path.c_str(), W_OK) != 0) {
97 // file is not accessible
98 fd.reset(FDS_INACCESSIBLE);
99 return;
100 }
101
102 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
103 if (tmp_fd < 0) {
104 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
105 fd.reset(FDS_INACCESSIBLE);
106 return;
107 }
108
109 fd = std::move(tmp_fd);
110 }
111
Drop(android::base::unique_fd & fd)112 void FdCacheHelper::Drop(android::base::unique_fd& fd) {
113 if (fd == FDS_NOT_CACHED) {
114 return;
115 }
116
117 fd.reset(FDS_NOT_CACHED);
118 }
119
IsAppDependentPath(const std::string & path)120 bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
121 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
122 }
123
124 } // namespace
125
126 IProfileAttribute::~IProfileAttribute() = default;
127
file_name() const128 const std::string& ProfileAttribute::file_name() const {
129 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
130 return file_name_;
131 }
132
Reset(const CgroupControllerWrapper & controller,const std::string & file_name,const std::string & file_v2_name)133 void ProfileAttribute::Reset(const CgroupControllerWrapper& controller,
134 const std::string& file_name, const std::string& file_v2_name) {
135 controller_ = controller;
136 file_name_ = file_name;
137 file_v2_name_ = file_v2_name;
138 }
139
isSystemApp(uid_t uid)140 static bool isSystemApp(uid_t uid) {
141 return uid < AID_APP_START;
142 }
143
ConvertUidToPath(const char * root_cgroup_path,uid_t uid,bool v2_path)144 std::string ConvertUidToPath(const char* root_cgroup_path, uid_t uid, bool v2_path) {
145 if (android::libprocessgroup_flags::cgroup_v2_sys_app_isolation() && v2_path) {
146 if (isSystemApp(uid))
147 return StringPrintf("%s/system/uid_%u", root_cgroup_path, uid);
148 else
149 return StringPrintf("%s/apps/uid_%u", root_cgroup_path, uid);
150 }
151 return StringPrintf("%s/uid_%u", root_cgroup_path, uid);
152 }
153
ConvertUidPidToPath(const char * root_cgroup_path,uid_t uid,pid_t pid,bool v2_path)154 std::string ConvertUidPidToPath(const char* root_cgroup_path, uid_t uid, pid_t pid, bool v2_path) {
155 const std::string uid_path = ConvertUidToPath(root_cgroup_path, uid, v2_path);
156 return StringPrintf("%s/pid_%d", uid_path.c_str(), pid);
157 }
158
GetPathForProcess(uid_t uid,pid_t pid,std::string * path) const159 bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
160 if (controller()->version() == 2) {
161 const std::string cgroup_path = ConvertUidPidToPath(controller()->path(), uid, pid, true);
162 *path = cgroup_path + "/" + file_name();
163 return true;
164 }
165 return GetPathForTask(pid, path);
166 }
167
GetPathForTask(pid_t tid,std::string * path) const168 bool ProfileAttribute::GetPathForTask(pid_t tid, std::string* path) const {
169 std::string subgroup;
170 if (!controller()->GetTaskGroup(tid, &subgroup)) {
171 return false;
172 }
173
174 if (path == nullptr) {
175 return true;
176 }
177
178 if (subgroup.empty()) {
179 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
180 } else {
181 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
182 file_name().c_str());
183 }
184 return true;
185 }
186
187 // NOTE: This function is for cgroup v2 only
GetPathForUID(uid_t uid,std::string * path) const188 bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
189 if (path == nullptr) {
190 return true;
191 }
192
193 const std::string cgroup_path = ConvertUidToPath(controller()->path(), uid, true);
194 *path = cgroup_path + "/" + file_name();
195 return true;
196 }
197
ExecuteForTask(pid_t tid) const198 bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
199 const auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
200 if (!WriteStringToFile(std::to_string(slack_), file)) {
201 if (errno == ENOENT) {
202 // This happens when process is already dead
203 return true;
204 }
205 PLOG(ERROR) << "set_timerslack_ns write failed";
206 return false;
207 }
208
209 return true;
210 }
211
WriteValueToFile(const std::string & path) const212 bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
213 if (!WriteStringToFile(value_, path)) {
214 if (access(path.c_str(), F_OK) < 0) {
215 if (optional_) {
216 return true;
217 } else {
218 LOG(ERROR) << "No such cgroup attribute: " << path;
219 return false;
220 }
221 }
222 // The PLOG() statement below uses the error code stored in `errno` by
223 // WriteStringToFile() because access() only overwrites `errno` if it fails
224 // and because this code is only reached if the access() function returns 0.
225 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
226 return false;
227 }
228
229 return true;
230 }
231
ExecuteForProcess(uid_t uid,pid_t pid) const232 bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
233 std::string path;
234
235 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
236 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
237 return false;
238 }
239
240 return WriteValueToFile(path);
241 }
242
ExecuteForTask(pid_t tid) const243 bool SetAttributeAction::ExecuteForTask(pid_t tid) const {
244 std::string path;
245
246 if (!attribute_->GetPathForTask(tid, &path)) {
247 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
248 return false;
249 }
250
251 return WriteValueToFile(path);
252 }
253
ExecuteForUID(uid_t uid) const254 bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
255 std::string path;
256
257 if (!attribute_->GetPathForUID(uid, &path)) {
258 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
259 return false;
260 }
261
262 if (!WriteStringToFile(value_, path)) {
263 if (access(path.c_str(), F_OK) < 0) {
264 if (optional_) {
265 return true;
266 } else {
267 LOG(ERROR) << "No such cgroup attribute: " << path;
268 return false;
269 }
270 }
271 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
272 return false;
273 }
274 return true;
275 }
276
IsValidForProcess(uid_t,pid_t pid) const277 bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
278 return IsValidForTask(pid);
279 }
280
IsValidForTask(pid_t tid) const281 bool SetAttributeAction::IsValidForTask(pid_t tid) const {
282 std::string path;
283
284 if (!attribute_->GetPathForTask(tid, &path)) {
285 return false;
286 }
287
288 if (!access(path.c_str(), W_OK)) {
289 // operation will succeed
290 return true;
291 }
292
293 if (!access(path.c_str(), F_OK)) {
294 // file exists but not writable
295 return false;
296 }
297
298 // file does not exist, ignore if optional
299 return optional_;
300 }
301
SetCgroupAction(const CgroupControllerWrapper & c,const std::string & p)302 SetCgroupAction::SetCgroupAction(const CgroupControllerWrapper& c, const std::string& p)
303 : controller_(c), path_(p) {
304 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
305 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
306 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
307 }
308
AddTidToCgroup(pid_t tid,int fd,ResourceCacheType cache_type) const309 bool SetCgroupAction::AddTidToCgroup(pid_t tid, int fd, ResourceCacheType cache_type) const {
310 if (tid <= 0) {
311 return true;
312 }
313
314 std::string value = std::to_string(tid);
315
316 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
317 return true;
318 }
319
320 // If the thread is in the process of exiting, don't flag an error
321 if (errno == ESRCH) {
322 return true;
323 }
324
325 const char* controller_name = controller()->name();
326 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
327 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
328 // This is an abnormal case happening only in testing, so report it only once
329 static bool empty_cpuset_reported = false;
330
331 if (empty_cpuset_reported) {
332 return true;
333 }
334
335 LOG(ERROR) << "Failed to add task '" << value
336 << "' into cpuset because all cpus in that cpuset are offline";
337 empty_cpuset_reported = true;
338 } else {
339 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; path=" << path_ << "; "
340 << (cache_type == RCT_TASK ? "task" : "process");
341 }
342
343 return false;
344 }
345
UseCachedFd(ResourceCacheType cache_type,int id) const346 ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
347 int id) const {
348 std::lock_guard<std::mutex> lock(fd_mutex_);
349 if (FdCacheHelper::IsCached(fd_[cache_type])) {
350 // fd is cached, reuse it
351 if (!AddTidToCgroup(id, fd_[cache_type], cache_type)) {
352 LOG(ERROR) << "Failed to add task into cgroup";
353 return ProfileAction::FAIL;
354 }
355 return ProfileAction::SUCCESS;
356 }
357
358 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
359 // no permissions to access the file, ignore
360 return ProfileAction::SUCCESS;
361 }
362
363 if (cache_type == ResourceCacheType::RCT_TASK &&
364 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
365 // application-dependent path can't be used with tid
366 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
367 return ProfileAction::FAIL;
368 }
369
370 return ProfileAction::UNUSED;
371 }
372
ExecuteForProcess(uid_t uid,pid_t pid) const373 bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
374 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
375 if (result != ProfileAction::UNUSED) {
376 return result == ProfileAction::SUCCESS;
377 }
378
379 // fd was not cached or cached fd can't be used
380 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
381 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
382 if (tmp_fd < 0) {
383 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
384 return false;
385 }
386 if (!AddTidToCgroup(pid, tmp_fd, RCT_PROCESS)) {
387 LOG(ERROR) << "Failed to add task into cgroup";
388 return false;
389 }
390
391 return true;
392 }
393
ExecuteForTask(pid_t tid) const394 bool SetCgroupAction::ExecuteForTask(pid_t tid) const {
395 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
396 if (result != ProfileAction::UNUSED) {
397 return result == ProfileAction::SUCCESS;
398 }
399
400 // fd was not cached or cached fd can't be used
401 std::string tasks_path = controller()->GetTasksFilePath(path_);
402 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
403 if (tmp_fd < 0) {
404 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
405 return false;
406 }
407 if (!AddTidToCgroup(tid, tmp_fd, RCT_TASK)) {
408 LOG(ERROR) << "Failed to add task into cgroup";
409 return false;
410 }
411
412 return true;
413 }
414
EnableResourceCaching(ResourceCacheType cache_type)415 void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
416 std::lock_guard<std::mutex> lock(fd_mutex_);
417 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
418 // include regex evaluations
419 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
420 return;
421 }
422 switch (cache_type) {
423 case (ProfileAction::RCT_TASK):
424 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
425 break;
426 case (ProfileAction::RCT_PROCESS):
427 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
428 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
429 break;
430 default:
431 LOG(ERROR) << "Invalid cache type is specified!";
432 break;
433 }
434 }
435
DropResourceCaching(ResourceCacheType cache_type)436 void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
437 std::lock_guard<std::mutex> lock(fd_mutex_);
438 FdCacheHelper::Drop(fd_[cache_type]);
439 }
440
IsValidForProcess(uid_t uid,pid_t pid) const441 bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
442 std::lock_guard<std::mutex> lock(fd_mutex_);
443 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
444 return true;
445 }
446
447 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
448 return false;
449 }
450
451 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
452 return access(procs_path.c_str(), W_OK) == 0;
453 }
454
IsValidForTask(int) const455 bool SetCgroupAction::IsValidForTask(int) const {
456 std::lock_guard<std::mutex> lock(fd_mutex_);
457 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
458 return true;
459 }
460
461 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
462 return false;
463 }
464
465 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
466 // application-dependent path can't be used with tid
467 return false;
468 }
469
470 std::string tasks_path = controller()->GetTasksFilePath(path_);
471 return access(tasks_path.c_str(), W_OK) == 0;
472 }
473
WriteFileAction(const std::string & task_path,const std::string & proc_path,const std::string & value,bool logfailures)474 WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
475 const std::string& value, bool logfailures)
476 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
477 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
478 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
479 }
480
WriteValueToFile(const std::string & value_,ResourceCacheType cache_type,uid_t uid,pid_t pid,bool logfailures) const481 bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
482 uid_t uid, pid_t pid, bool logfailures) const {
483 std::string value(value_);
484
485 value = StringReplace(value, "<uid>", std::to_string(uid), true);
486 value = StringReplace(value, "<pid>", std::to_string(pid), true);
487
488 CacheUseResult result = UseCachedFd(cache_type, value);
489
490 if (result != ProfileAction::UNUSED) {
491 return result == ProfileAction::SUCCESS;
492 }
493
494 std::string path;
495 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
496 path = task_path_;
497 } else {
498 path = proc_path_;
499 }
500
501 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
502 // O_TRUNC which causes kernfs_mutex contention
503 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
504
505 if (tmp_fd < 0) {
506 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
507 return false;
508 }
509
510 if (!WriteStringToFd(value, tmp_fd)) {
511 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
512 return false;
513 }
514
515 return true;
516 }
517
UseCachedFd(ResourceCacheType cache_type,const std::string & value) const518 ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
519 const std::string& value) const {
520 std::lock_guard<std::mutex> lock(fd_mutex_);
521 if (FdCacheHelper::IsCached(fd_[cache_type])) {
522 // fd is cached, reuse it
523 bool ret = WriteStringToFd(value, fd_[cache_type]);
524
525 if (!ret && logfailures_) {
526 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
527 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
528 } else {
529 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
530 }
531 }
532 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
533 }
534
535 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
536 // no permissions to access the file, ignore
537 return ProfileAction::SUCCESS;
538 }
539
540 if (cache_type == ResourceCacheType::RCT_TASK &&
541 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
542 // application-dependent path can't be used with tid
543 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
544 return ProfileAction::FAIL;
545 }
546 return ProfileAction::UNUSED;
547 }
548
ExecuteForProcess(uid_t uid,pid_t pid) const549 bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
550 if (!proc_path_.empty()) {
551 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
552 }
553
554 DIR* d;
555 struct dirent* de;
556 char proc_path[255];
557 pid_t t_pid;
558
559 sprintf(proc_path, "/proc/%d/task", pid);
560 if (!(d = opendir(proc_path))) {
561 return false;
562 }
563
564 while ((de = readdir(d))) {
565 if (de->d_name[0] == '.') {
566 continue;
567 }
568
569 t_pid = atoi(de->d_name);
570
571 if (!t_pid) {
572 continue;
573 }
574
575 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
576 }
577
578 closedir(d);
579
580 return true;
581 }
582
ExecuteForTask(pid_t tid) const583 bool WriteFileAction::ExecuteForTask(pid_t tid) const {
584 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
585 }
586
EnableResourceCaching(ResourceCacheType cache_type)587 void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
588 std::lock_guard<std::mutex> lock(fd_mutex_);
589 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
590 return;
591 }
592 switch (cache_type) {
593 case (ProfileAction::RCT_TASK):
594 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
595 break;
596 case (ProfileAction::RCT_PROCESS):
597 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
598 break;
599 default:
600 LOG(ERROR) << "Invalid cache type is specified!";
601 break;
602 }
603 }
604
DropResourceCaching(ResourceCacheType cache_type)605 void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
606 std::lock_guard<std::mutex> lock(fd_mutex_);
607 FdCacheHelper::Drop(fd_[cache_type]);
608 }
609
IsValidForProcess(uid_t,pid_t) const610 bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
611 std::lock_guard<std::mutex> lock(fd_mutex_);
612 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
613 return true;
614 }
615
616 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
617 return false;
618 }
619
620 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
621 }
622
IsValidForTask(int) const623 bool WriteFileAction::IsValidForTask(int) const {
624 std::lock_guard<std::mutex> lock(fd_mutex_);
625 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
626 return true;
627 }
628
629 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
630 return false;
631 }
632
633 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
634 // application-dependent path can't be used with tid
635 return false;
636 }
637
638 return access(task_path_.c_str(), W_OK) == 0;
639 }
640
isNormalPolicy(int policy)641 bool SetSchedulerPolicyAction::isNormalPolicy(int policy) {
642 return policy == SCHED_OTHER || policy == SCHED_BATCH || policy == SCHED_IDLE;
643 }
644
toPriority(int policy,int virtual_priority,int & priority_out)645 bool SetSchedulerPolicyAction::toPriority(int policy, int virtual_priority, int& priority_out) {
646 constexpr int VIRTUAL_PRIORITY_MIN = 1;
647 constexpr int VIRTUAL_PRIORITY_MAX = 99;
648
649 if (virtual_priority < VIRTUAL_PRIORITY_MIN || virtual_priority > VIRTUAL_PRIORITY_MAX) {
650 LOG(WARNING) << "SetSchedulerPolicy: invalid priority (" << virtual_priority
651 << ") for policy (" << policy << ")";
652 return false;
653 }
654
655 const int min = sched_get_priority_min(policy);
656 if (min == -1) {
657 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get min sched priority for policy " << policy;
658 return false;
659 }
660
661 const int max = sched_get_priority_max(policy);
662 if (max == -1) {
663 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get max sched priority for policy " << policy;
664 return false;
665 }
666
667 priority_out = min + (virtual_priority - VIRTUAL_PRIORITY_MIN) * (max - min) /
668 (VIRTUAL_PRIORITY_MAX - VIRTUAL_PRIORITY_MIN);
669
670 return true;
671 }
672
ExecuteForTask(pid_t tid) const673 bool SetSchedulerPolicyAction::ExecuteForTask(pid_t tid) const {
674 struct sched_param param = {};
675 param.sched_priority = isNormalPolicy(policy_) ? 0 : *priority_or_nice_;
676 if (sched_setscheduler(tid, policy_, ¶m) == -1) {
677 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply scheduler policy (" << policy_
678 << ") with priority (" << *priority_or_nice_ << ") to tid " << tid;
679 return false;
680 }
681
682 if (isNormalPolicy(policy_) && priority_or_nice_ &&
683 setpriority(PRIO_PROCESS, tid, *priority_or_nice_) == -1) {
684 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply nice (" << *priority_or_nice_
685 << ") to tid " << tid;
686 return false;
687 }
688
689 return true;
690 }
691
ExecuteForProcess(uid_t uid,pid_t pid) const692 bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
693 for (const auto& profile : profiles_) {
694 profile->ExecuteForProcess(uid, pid);
695 }
696 return true;
697 }
698
ExecuteForTask(pid_t tid) const699 bool ApplyProfileAction::ExecuteForTask(pid_t tid) const {
700 for (const auto& profile : profiles_) {
701 profile->ExecuteForTask(tid);
702 }
703 return true;
704 }
705
EnableResourceCaching(ResourceCacheType cache_type)706 void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
707 for (const auto& profile : profiles_) {
708 profile->EnableResourceCaching(cache_type);
709 }
710 }
711
DropResourceCaching(ResourceCacheType cache_type)712 void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
713 for (const auto& profile : profiles_) {
714 profile->DropResourceCaching(cache_type);
715 }
716 }
717
IsValidForProcess(uid_t uid,pid_t pid) const718 bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
719 for (const auto& profile : profiles_) {
720 if (!profile->IsValidForProcess(uid, pid)) {
721 return false;
722 }
723 }
724 return true;
725 }
726
IsValidForTask(pid_t tid) const727 bool ApplyProfileAction::IsValidForTask(pid_t tid) const {
728 for (const auto& profile : profiles_) {
729 if (!profile->IsValidForTask(tid)) {
730 return false;
731 }
732 }
733 return true;
734 }
735
MoveTo(TaskProfile * profile)736 void TaskProfile::MoveTo(TaskProfile* profile) {
737 profile->elements_ = std::move(elements_);
738 profile->res_cached_ = res_cached_;
739 }
740
ExecuteForProcess(uid_t uid,pid_t pid) const741 bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
742 for (const auto& element : elements_) {
743 if (!element->ExecuteForProcess(uid, pid)) {
744 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
745 return false;
746 }
747 }
748 return true;
749 }
750
ExecuteForTask(pid_t tid) const751 bool TaskProfile::ExecuteForTask(pid_t tid) const {
752 if (tid == 0) {
753 tid = GetThreadId();
754 }
755 for (const auto& element : elements_) {
756 if (!element->ExecuteForTask(tid)) {
757 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
758 return false;
759 }
760 }
761 return true;
762 }
763
ExecuteForUID(uid_t uid) const764 bool TaskProfile::ExecuteForUID(uid_t uid) const {
765 for (const auto& element : elements_) {
766 if (!element->ExecuteForUID(uid)) {
767 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
768 return false;
769 }
770 }
771 return true;
772 }
773
EnableResourceCaching(ProfileAction::ResourceCacheType cache_type)774 void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
775 if (res_cached_) {
776 return;
777 }
778
779 for (auto& element : elements_) {
780 element->EnableResourceCaching(cache_type);
781 }
782
783 res_cached_ = true;
784 }
785
DropResourceCaching(ProfileAction::ResourceCacheType cache_type)786 void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
787 if (!res_cached_) {
788 return;
789 }
790
791 for (auto& element : elements_) {
792 element->DropResourceCaching(cache_type);
793 }
794
795 res_cached_ = false;
796 }
797
IsValidForProcess(uid_t uid,pid_t pid) const798 bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
799 for (const auto& element : elements_) {
800 if (!element->IsValidForProcess(uid, pid)) return false;
801 }
802 return true;
803 }
804
IsValidForTask(pid_t tid) const805 bool TaskProfile::IsValidForTask(pid_t tid) const {
806 for (const auto& element : elements_) {
807 if (!element->IsValidForTask(tid)) return false;
808 }
809 return true;
810 }
811
DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const812 void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
813 for (auto& iter : profiles_) {
814 iter.second->DropResourceCaching(cache_type);
815 }
816 }
817
GetInstance()818 TaskProfiles& TaskProfiles::GetInstance() {
819 // Deliberately leak this object to avoid a race between destruction on
820 // process exit and concurrent access from another thread.
821 static auto* instance = new TaskProfiles;
822 return *instance;
823 }
824
TaskProfiles()825 TaskProfiles::TaskProfiles() {
826 // load system task profiles
827 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
828 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
829 }
830
831 // load API-level specific system task profiles if available
832 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
833 if (api_level > 0) {
834 std::string api_profiles_path =
835 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
836 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
837 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
838 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
839 }
840 }
841 }
842
843 // load vendor task profiles if the file exists
844 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
845 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
846 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
847 << "] failed";
848 }
849 }
850
Load(const CgroupMap & cg_map,const std::string & file_name)851 bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
852 std::string json_doc;
853
854 if (!android::base::ReadFileToString(file_name, &json_doc)) {
855 LOG(ERROR) << "Failed to read task profiles from " << file_name;
856 return false;
857 }
858
859 Json::CharReaderBuilder builder;
860 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
861 Json::Value root;
862 std::string errorMessage;
863 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
864 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
865 return false;
866 }
867
868 const Json::Value& attr = root["Attributes"];
869 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
870 std::string name = attr[i]["Name"].asString();
871 std::string controller_name = attr[i]["Controller"].asString();
872 std::string file_attr = attr[i]["File"].asString();
873 std::string file_v2_attr = attr[i]["FileV2"].asString();
874
875 if (!file_v2_attr.empty() && file_attr.empty()) {
876 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
877 return false;
878 }
879
880 auto controller = cg_map.FindController(controller_name);
881 if (controller.HasValue()) {
882 auto iter = attributes_.find(name);
883 if (iter == attributes_.end()) {
884 attributes_[name] =
885 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
886 } else {
887 iter->second->Reset(controller, file_attr, file_v2_attr);
888 }
889 } else {
890 LOG(WARNING) << "Controller " << controller_name << " is not found";
891 }
892 }
893
894 const Json::Value& profiles_val = root["Profiles"];
895 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
896 const Json::Value& profile_val = profiles_val[i];
897
898 std::string profile_name = profile_val["Name"].asString();
899 const Json::Value& actions = profile_val["Actions"];
900 auto profile = std::make_shared<TaskProfile>(profile_name);
901
902 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
903 const Json::Value& action_val = actions[act_idx];
904 std::string action_name = action_val["Name"].asString();
905 const Json::Value& params_val = action_val["Params"];
906 if (action_name == "JoinCgroup") {
907 std::string controller_name = params_val["Controller"].asString();
908 std::string path = params_val["Path"].asString();
909
910 auto controller = cg_map.FindController(controller_name);
911 if (controller.HasValue()) {
912 if (controller.version() == 1) {
913 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
914 } else {
915 LOG(WARNING) << "A JoinCgroup action in the " << profile_name
916 << " profile is used for controller " << controller_name
917 << " in the cgroup v2 hierarchy and will be ignored";
918 }
919 } else {
920 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
921 }
922 } else if (action_name == "SetTimerSlack") {
923 const std::string slack_string = params_val["Slack"].asString();
924 if (long slack; android::base::ParseInt(slack_string, &slack) && slack >= 0) {
925 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
926 } else {
927 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_string;
928 }
929 } else if (action_name == "SetAttribute") {
930 std::string attr_name = params_val["Name"].asString();
931 std::string attr_value = params_val["Value"].asString();
932 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
933
934 auto iter = attributes_.find(attr_name);
935 if (iter != attributes_.end()) {
936 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
937 attr_value, optional));
938 } else {
939 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
940 }
941 } else if (action_name == "WriteFile") {
942 std::string attr_filepath = params_val["FilePath"].asString();
943 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
944 std::string attr_value = params_val["Value"].asString();
945 // FilePath and Value are mandatory
946 if (!attr_filepath.empty() && !attr_value.empty()) {
947 std::string attr_logfailures = params_val["LogFailures"].asString();
948 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
949 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
950 attr_value, logfailures));
951 } else if (attr_filepath.empty()) {
952 LOG(WARNING) << "WriteFile: invalid parameter: "
953 << "empty filepath";
954 } else if (attr_value.empty()) {
955 LOG(WARNING) << "WriteFile: invalid parameter: "
956 << "empty value";
957 }
958 } else if (action_name == "SetSchedulerPolicy") {
959 const std::map<std::string, int> POLICY_MAP = {
960 {"SCHED_OTHER", SCHED_OTHER},
961 {"SCHED_BATCH", SCHED_BATCH},
962 {"SCHED_IDLE", SCHED_IDLE},
963 {"SCHED_FIFO", SCHED_FIFO},
964 {"SCHED_RR", SCHED_RR},
965 };
966 const std::string policy_str = params_val["Policy"].asString();
967
968 const auto it = POLICY_MAP.find(policy_str);
969 if (it == POLICY_MAP.end()) {
970 LOG(WARNING) << "SetSchedulerPolicy: invalid policy " << policy_str;
971 continue;
972 }
973
974 const int policy = it->second;
975
976 if (SetSchedulerPolicyAction::isNormalPolicy(policy)) {
977 if (params_val.isMember("Priority")) {
978 LOG(WARNING) << "SetSchedulerPolicy: Normal policies (" << policy_str
979 << ") use Nice values, not Priority values";
980 }
981
982 if (params_val.isMember("Nice")) {
983 // If present, this optional value will be passed in an additional syscall
984 // to setpriority(), since the sched_priority value must be 0 for calls to
985 // sched_setscheduler() with "normal" policies.
986 const std::string nice_string = params_val["Nice"].asString();
987 int nice;
988 if (!android::base::ParseInt(nice_string, &nice)) {
989 LOG(FATAL) << "Invalid nice value specified: " << nice_string;
990 }
991 const int LINUX_MIN_NICE = -20;
992 const int LINUX_MAX_NICE = 19;
993 if (nice < LINUX_MIN_NICE || nice > LINUX_MAX_NICE) {
994 LOG(WARNING) << "SetSchedulerPolicy: Provided nice (" << nice
995 << ") appears out of range.";
996 }
997 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy, nice));
998 } else {
999 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy));
1000 }
1001 } else {
1002 if (params_val.isMember("Nice")) {
1003 LOG(WARNING) << "SetSchedulerPolicy: Real-time policies (" << policy_str
1004 << ") use Priority values, not Nice values";
1005 }
1006
1007 // This is a "virtual priority" as described by `man 2 sched_get_priority_min`
1008 // that will be mapped onto the following range for the provided policy:
1009 // [sched_get_priority_min(), sched_get_priority_max()]
1010
1011 const std::string priority_string = params_val["Priority"].asString();
1012 if (long virtual_priority;
1013 android::base::ParseInt(priority_string, &virtual_priority) &&
1014 virtual_priority > 0) {
1015 int priority;
1016 if (SetSchedulerPolicyAction::toPriority(policy, virtual_priority,
1017 priority)) {
1018 profile->Add(
1019 std::make_unique<SetSchedulerPolicyAction>(policy, priority));
1020 }
1021 } else {
1022 LOG(WARNING) << "Invalid priority value: " << priority_string;
1023 }
1024 }
1025 } else {
1026 LOG(WARNING) << "Unknown profile action: " << action_name;
1027 }
1028 }
1029 auto iter = profiles_.find(profile_name);
1030 if (iter == profiles_.end()) {
1031 profiles_[profile_name] = profile;
1032 } else {
1033 // Move the content rather that replace the profile because old profile might be
1034 // referenced from an aggregate profile if vendor overrides task profiles
1035 profile->MoveTo(iter->second.get());
1036 profile.reset();
1037 }
1038 }
1039
1040 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
1041 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
1042 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
1043
1044 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
1045 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
1046 std::vector<std::shared_ptr<TaskProfile>> profiles;
1047 bool ret = true;
1048
1049 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
1050 std::string profile_name = aggregateprofiles[pf_idx].asString();
1051
1052 if (profile_name == aggregateprofile_name) {
1053 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
1054 ret = false;
1055 break;
1056 } else if (profiles_.find(profile_name) == profiles_.end()) {
1057 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
1058 ret = false;
1059 break;
1060 } else {
1061 profiles.push_back(profiles_[profile_name]);
1062 }
1063 }
1064 if (ret) {
1065 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
1066 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
1067 profiles_[aggregateprofile_name] = profile;
1068 }
1069 }
1070
1071 return true;
1072 }
1073
GetProfile(std::string_view name) const1074 TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
1075 auto iter = profiles_.find(name);
1076
1077 if (iter != profiles_.end()) {
1078 return iter->second.get();
1079 }
1080 return nullptr;
1081 }
1082
GetAttribute(std::string_view name) const1083 const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
1084 auto iter = attributes_.find(name);
1085
1086 if (iter != attributes_.end()) {
1087 return iter->second.get();
1088 }
1089 return nullptr;
1090 }
1091
1092 template <typename T>
SetUserProfiles(uid_t uid,std::span<const T> profiles,bool use_fd_cache)1093 bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
1094 for (const auto& name : profiles) {
1095 TaskProfile* profile = GetProfile(name);
1096 if (profile != nullptr) {
1097 if (use_fd_cache) {
1098 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1099 }
1100 if (!profile->ExecuteForUID(uid)) {
1101 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1102 }
1103 } else {
1104 PLOG(WARNING) << "Failed to find " << name << "process profile";
1105 }
1106 }
1107 return true;
1108 }
1109
1110 template <typename T>
SetProcessProfiles(uid_t uid,pid_t pid,std::span<const T> profiles,bool use_fd_cache)1111 bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1112 bool use_fd_cache) {
1113 bool success = true;
1114 for (const auto& name : profiles) {
1115 TaskProfile* profile = GetProfile(name);
1116 if (profile != nullptr) {
1117 if (use_fd_cache) {
1118 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1119 }
1120 if (!profile->ExecuteForProcess(uid, pid)) {
1121 LOG(WARNING) << "Failed to apply " << name << " process profile";
1122 success = false;
1123 }
1124 } else {
1125 LOG(WARNING) << "Failed to find " << name << " process profile";
1126 success = false;
1127 }
1128 }
1129 return success;
1130 }
1131
1132 template <typename T>
SetTaskProfiles(pid_t tid,std::span<const T> profiles,bool use_fd_cache)1133 bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const T> profiles, bool use_fd_cache) {
1134 bool success = true;
1135 for (const auto& name : profiles) {
1136 TaskProfile* profile = GetProfile(name);
1137 if (profile != nullptr) {
1138 if (use_fd_cache) {
1139 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
1140 }
1141 if (!profile->ExecuteForTask(tid)) {
1142 LOG(WARNING) << "Failed to apply " << name << " task profile";
1143 success = false;
1144 }
1145 } else {
1146 LOG(WARNING) << "Failed to find " << name << " task profile";
1147 success = false;
1148 }
1149 }
1150 return success;
1151 }
1152
1153 template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1154 std::span<const std::string> profiles,
1155 bool use_fd_cache);
1156 template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1157 std::span<const std::string_view> profiles,
1158 bool use_fd_cache);
1159 template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string> profiles,
1160 bool use_fd_cache);
1161 template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles,
1162 bool use_fd_cache);
1163 template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1164 bool use_fd_cache);
1165