• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2014 Google, Inc
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 <assert.h>
21 #include <dirent.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <signal.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 
32 #include <chrono>
33 #include <map>
34 #include <memory>
35 #include <mutex>
36 #include <set>
37 #include <string>
38 #include <thread>
39 
40 #include <android-base/file.h>
41 #include <android-base/logging.h>
42 #include <android-base/properties.h>
43 #include <android-base/stringprintf.h>
44 #include <android-base/strings.h>
45 #include <cutils/android_filesystem_config.h>
46 #include <processgroup/processgroup.h>
47 #include <task_profiles.h>
48 
49 using android::base::GetBoolProperty;
50 using android::base::StartsWith;
51 using android::base::StringPrintf;
52 using android::base::WriteStringToFile;
53 
54 using namespace std::chrono_literals;
55 
56 #define PROCESSGROUP_CGROUP_PROCS_FILE "/cgroup.procs"
57 
CgroupsAvailable()58 bool CgroupsAvailable() {
59     static bool cgroups_available = access("/proc/cgroups", F_OK) == 0;
60     return cgroups_available;
61 }
62 
CgroupGetControllerPath(const std::string & cgroup_name,std::string * path)63 bool CgroupGetControllerPath(const std::string& cgroup_name, std::string* path) {
64     auto controller = CgroupMap::GetInstance().FindController(cgroup_name);
65 
66     if (!controller.HasValue()) {
67         return false;
68     }
69 
70     if (path) {
71         *path = controller.path();
72     }
73 
74     return true;
75 }
76 
CgroupGetMemcgAppsPath(std::string * path)77 static bool CgroupGetMemcgAppsPath(std::string* path) {
78     CgroupController controller = CgroupMap::GetInstance().FindController("memory");
79 
80     if (!controller.HasValue()) {
81         return false;
82     }
83 
84     if (path) {
85         *path = controller.path();
86         if (controller.version() == 1) {
87             *path += "/apps";
88         }
89     }
90 
91     return true;
92 }
93 
CgroupGetControllerFromPath(const std::string & path,std::string * cgroup_name)94 bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
95     auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
96 
97     if (!controller.HasValue()) {
98         return false;
99     }
100 
101     if (cgroup_name) {
102         *cgroup_name = controller.name();
103     }
104 
105     return true;
106 }
107 
CgroupGetAttributePath(const std::string & attr_name,std::string * path)108 bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
109     const TaskProfiles& tp = TaskProfiles::GetInstance();
110     const IProfileAttribute* attr = tp.GetAttribute(attr_name);
111 
112     if (attr == nullptr) {
113         return false;
114     }
115 
116     if (path) {
117         *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
118     }
119 
120     return true;
121 }
122 
CgroupGetAttributePathForTask(const std::string & attr_name,int tid,std::string * path)123 bool CgroupGetAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
124     const TaskProfiles& tp = TaskProfiles::GetInstance();
125     const IProfileAttribute* attr = tp.GetAttribute(attr_name);
126 
127     if (attr == nullptr) {
128         return false;
129     }
130 
131     if (!attr->GetPathForTask(tid, path)) {
132         PLOG(ERROR) << "Failed to find cgroup for tid " << tid;
133         return false;
134     }
135 
136     return true;
137 }
138 
UsePerAppMemcg()139 bool UsePerAppMemcg() {
140     bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
141     return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
142 }
143 
isMemoryCgroupSupported()144 static bool isMemoryCgroupSupported() {
145     static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
146 
147     return memcg_supported;
148 }
149 
DropTaskProfilesResourceCaching()150 void DropTaskProfilesResourceCaching() {
151     TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
152     TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
153 }
154 
SetProcessProfiles(uid_t uid,pid_t pid,const std::vector<std::string> & profiles)155 bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
156     return TaskProfiles::GetInstance().SetProcessProfiles(
157             uid, pid, std::span<const std::string>(profiles), false);
158 }
159 
SetProcessProfiles(uid_t uid,pid_t pid,std::initializer_list<std::string_view> profiles)160 bool SetProcessProfiles(uid_t uid, pid_t pid, std::initializer_list<std::string_view> profiles) {
161     return TaskProfiles::GetInstance().SetProcessProfiles(
162             uid, pid, std::span<const std::string_view>(profiles), false);
163 }
164 
SetProcessProfiles(uid_t uid,pid_t pid,std::span<const std::string_view> profiles)165 bool SetProcessProfiles(uid_t uid, pid_t pid, std::span<const std::string_view> profiles) {
166     return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
167 }
168 
SetProcessProfilesCached(uid_t uid,pid_t pid,const std::vector<std::string> & profiles)169 bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
170     return TaskProfiles::GetInstance().SetProcessProfiles(
171             uid, pid, std::span<const std::string>(profiles), true);
172 }
173 
SetTaskProfiles(int tid,const std::vector<std::string> & profiles,bool use_fd_cache)174 bool SetTaskProfiles(int tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
175     return TaskProfiles::GetInstance().SetTaskProfiles(tid, std::span<const std::string>(profiles),
176                                                        use_fd_cache);
177 }
178 
SetTaskProfiles(int tid,std::initializer_list<std::string_view> profiles,bool use_fd_cache)179 bool SetTaskProfiles(int tid, std::initializer_list<std::string_view> profiles, bool use_fd_cache) {
180     return TaskProfiles::GetInstance().SetTaskProfiles(
181             tid, std::span<const std::string_view>(profiles), use_fd_cache);
182 }
183 
SetTaskProfiles(int tid,std::span<const std::string_view> profiles,bool use_fd_cache)184 bool SetTaskProfiles(int tid, std::span<const std::string_view> profiles, bool use_fd_cache) {
185     return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
186 }
187 
188 // C wrapper for SetProcessProfiles.
189 // No need to have this in the header file because this function is specifically for crosvm. Crosvm
190 // which is written in Rust has its own declaration of this foreign function and doesn't rely on the
191 // header. See
192 // https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
android_set_process_profiles(uid_t uid,pid_t pid,size_t num_profiles,const char * profiles[])193 extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
194                                              const char* profiles[]) {
195     std::vector<std::string_view> profiles_;
196     profiles_.reserve(num_profiles);
197     for (size_t i = 0; i < num_profiles; i++) {
198         profiles_.emplace_back(profiles[i]);
199     }
200     return SetProcessProfiles(uid, pid, std::span<const std::string_view>(profiles_));
201 }
202 
SetUserProfiles(uid_t uid,const std::vector<std::string> & profiles)203 bool SetUserProfiles(uid_t uid, const std::vector<std::string>& profiles) {
204     return TaskProfiles::GetInstance().SetUserProfiles(uid, std::span<const std::string>(profiles),
205                                                        false);
206 }
207 
ConvertUidToPath(const char * cgroup,uid_t uid)208 static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
209     return StringPrintf("%s/uid_%d", cgroup, uid);
210 }
211 
ConvertUidPidToPath(const char * cgroup,uid_t uid,int pid)212 static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, int pid) {
213     return StringPrintf("%s/uid_%d/pid_%d", cgroup, uid, pid);
214 }
215 
RemoveProcessGroup(const char * cgroup,uid_t uid,int pid,unsigned int retries)216 static int RemoveProcessGroup(const char* cgroup, uid_t uid, int pid, unsigned int retries) {
217     int ret = 0;
218     auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, pid);
219     auto uid_path = ConvertUidToPath(cgroup, uid);
220 
221     while (retries--) {
222         ret = rmdir(uid_pid_path.c_str());
223         if (!ret || errno != EBUSY) break;
224         std::this_thread::sleep_for(5ms);
225     }
226 
227     return ret;
228 }
229 
RemoveUidProcessGroups(const std::string & uid_path,bool empty_only)230 static bool RemoveUidProcessGroups(const std::string& uid_path, bool empty_only) {
231     std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
232     bool empty = true;
233     if (uid != NULL) {
234         dirent* dir;
235         while ((dir = readdir(uid.get())) != nullptr) {
236             if (dir->d_type != DT_DIR) {
237                 continue;
238             }
239 
240             if (!StartsWith(dir->d_name, "pid_")) {
241                 continue;
242             }
243 
244             auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
245             if (empty_only) {
246                 struct stat st;
247                 auto procs_file = StringPrintf("%s/%s", path.c_str(),
248                                                PROCESSGROUP_CGROUP_PROCS_FILE);
249                 if (stat(procs_file.c_str(), &st) == -1) {
250                     PLOG(ERROR) << "Failed to get stats for " << procs_file;
251                     continue;
252                 }
253                 if (st.st_size > 0) {
254                     // skip non-empty groups
255                     LOG(VERBOSE) << "Skipping non-empty group " << path;
256                     empty = false;
257                     continue;
258                 }
259             }
260             LOG(VERBOSE) << "Removing " << path;
261             if (rmdir(path.c_str()) == -1) {
262                 if (errno != EBUSY) {
263                     PLOG(WARNING) << "Failed to remove " << path;
264                 }
265                 empty = false;
266             }
267         }
268     }
269     return empty;
270 }
271 
removeAllProcessGroupsInternal(bool empty_only)272 void removeAllProcessGroupsInternal(bool empty_only) {
273     std::vector<std::string> cgroups;
274     std::string path, memcg_apps_path;
275 
276     if (CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &path)) {
277         cgroups.push_back(path);
278     }
279     if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
280         cgroups.push_back(memcg_apps_path);
281     }
282 
283     for (std::string cgroup_root_path : cgroups) {
284         std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
285         if (root == NULL) {
286             PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
287         } else {
288             dirent* dir;
289             while ((dir = readdir(root.get())) != nullptr) {
290                 if (dir->d_type != DT_DIR) {
291                     continue;
292                 }
293 
294                 if (!StartsWith(dir->d_name, "uid_")) {
295                     continue;
296                 }
297 
298                 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
299                 if (!RemoveUidProcessGroups(path, empty_only)) {
300                     LOG(VERBOSE) << "Skip removing " << path;
301                     continue;
302                 }
303                 LOG(VERBOSE) << "Removing " << path;
304                 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
305                     PLOG(WARNING) << "Failed to remove " << path;
306                 }
307             }
308         }
309     }
310 }
311 
removeAllProcessGroups()312 void removeAllProcessGroups() {
313     LOG(VERBOSE) << "removeAllProcessGroups()";
314     removeAllProcessGroupsInternal(false);
315 }
316 
removeAllEmptyProcessGroups()317 void removeAllEmptyProcessGroups() {
318     LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
319     removeAllProcessGroupsInternal(true);
320 }
321 
322 /**
323  * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
324  * the user root. Ownership for the newly created cgroup and all of its files must thus be
325  * transferred for the user/group passed as uid/gid before system_server can properly access them.
326  */
MkdirAndChown(const std::string & path,mode_t mode,uid_t uid,gid_t gid)327 static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
328     if (mkdir(path.c_str(), mode) == -1) {
329         if (errno == EEXIST) {
330             // Directory already exists and permissions have been set at the time it was created
331             return true;
332         }
333         return false;
334     }
335 
336     auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
337 
338     if (dir == NULL) {
339         PLOG(ERROR) << "opendir failed for " << path;
340         goto err;
341     }
342 
343     struct dirent* dir_entry;
344     while ((dir_entry = readdir(dir.get()))) {
345         if (!strcmp("..", dir_entry->d_name)) {
346             continue;
347         }
348 
349         std::string file_path = path + "/" + dir_entry->d_name;
350 
351         if (lchown(file_path.c_str(), uid, gid) < 0) {
352             PLOG(ERROR) << "lchown failed for " << file_path;
353             goto err;
354         }
355 
356         if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
357             PLOG(ERROR) << "fchmodat failed for " << file_path;
358             goto err;
359         }
360     }
361 
362     return true;
363 err:
364     int saved_errno = errno;
365     rmdir(path.c_str());
366     errno = saved_errno;
367 
368     return false;
369 }
370 
371 // Returns number of processes killed on success
372 // Returns 0 if there are no processes in the process cgroup left to kill
373 // Returns -1 on error
DoKillProcessGroupOnce(const char * cgroup,uid_t uid,int initialPid,int signal)374 static int DoKillProcessGroupOnce(const char* cgroup, uid_t uid, int initialPid, int signal) {
375     // We separate all of the pids in the cgroup into those pids that are also the leaders of
376     // process groups (stored in the pgids set) and those that are not (stored in the pids set).
377     std::set<pid_t> pgids;
378     pgids.emplace(initialPid);
379     std::set<pid_t> pids;
380     int processes = 0;
381 
382     std::unique_ptr<FILE, decltype(&fclose)> fd(nullptr, fclose);
383 
384     if (CgroupsAvailable()) {
385         auto path = ConvertUidPidToPath(cgroup, uid, initialPid) + PROCESSGROUP_CGROUP_PROCS_FILE;
386         fd.reset(fopen(path.c_str(), "re"));
387         if (!fd) {
388             if (errno == ENOENT) {
389                 // This happens when process is already dead
390                 return 0;
391             }
392             PLOG(WARNING) << __func__ << " failed to open process cgroup uid " << uid << " pid "
393                           << initialPid;
394             return -1;
395         }
396         pid_t pid;
397         bool file_is_empty = true;
398         while (fscanf(fd.get(), "%d\n", &pid) == 1 && pid >= 0) {
399             processes++;
400             file_is_empty = false;
401             if (pid == 0) {
402                 // Should never happen...  but if it does, trying to kill this
403                 // will boomerang right back and kill us!  Let's not let that happen.
404                 LOG(WARNING)
405                         << "Yikes, we've been told to kill pid 0!  How about we don't do that?";
406                 continue;
407             }
408             pid_t pgid = getpgid(pid);
409             if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
410             if (pgid == pid) {
411                 pgids.emplace(pid);
412             } else {
413                 pids.emplace(pid);
414             }
415         }
416         if (!file_is_empty) {
417             // Erase all pids that will be killed when we kill the process groups.
418             for (auto it = pids.begin(); it != pids.end();) {
419                 pid_t pgid = getpgid(*it);
420                 if (pgids.count(pgid) == 1) {
421                     it = pids.erase(it);
422                 } else {
423                     ++it;
424                 }
425             }
426         }
427     }
428 
429     // Kill all process groups.
430     for (const auto pgid : pgids) {
431         LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
432                      << " as part of process cgroup " << initialPid;
433 
434         if (kill(-pgid, signal) == -1 && errno != ESRCH) {
435             PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
436         }
437     }
438 
439     // Kill remaining pids.
440     for (const auto pid : pids) {
441         LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
442                      << initialPid;
443 
444         if (kill(pid, signal) == -1 && errno != ESRCH) {
445             PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
446         }
447     }
448 
449     return (!fd || feof(fd.get())) ? processes : -1;
450 }
451 
KillProcessGroup(uid_t uid,int initialPid,int signal,int retries,int * max_processes)452 static int KillProcessGroup(uid_t uid, int initialPid, int signal, int retries,
453                             int* max_processes) {
454     CHECK_GE(uid, 0);
455     CHECK_GT(initialPid, 0);
456 
457     std::string hierarchy_root_path;
458     if (CgroupsAvailable()) {
459         CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &hierarchy_root_path);
460     }
461     const char* cgroup = hierarchy_root_path.c_str();
462 
463     std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
464 
465     if (max_processes != nullptr) {
466         *max_processes = 0;
467     }
468 
469     int retry = retries;
470     int processes;
471     while ((processes = DoKillProcessGroupOnce(cgroup, uid, initialPid, signal)) > 0) {
472         if (max_processes != nullptr && processes > *max_processes) {
473             *max_processes = processes;
474         }
475         LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
476         if (!CgroupsAvailable()) {
477             // makes no sense to retry, because there are no cgroup_procs file
478             processes = 0;  // no remaining processes
479             break;
480         }
481         if (retry > 0) {
482             std::this_thread::sleep_for(5ms);
483             --retry;
484         } else {
485             break;
486         }
487     }
488 
489     if (processes < 0) {
490         PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
491                     << initialPid;
492         return -1;
493     }
494 
495     std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
496     auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
497 
498     // We only calculate the number of 'processes' when killing the processes.
499     // In the retries == 0 case, we only kill the processes once and therefore
500     // will not have waited then recalculated how many processes are remaining
501     // after the first signals have been sent.
502     // Logging anything regarding the number of 'processes' here does not make sense.
503 
504     if (processes == 0) {
505         if (retries > 0) {
506             LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
507                       << " in " << static_cast<int>(ms) << "ms";
508         }
509 
510         if (!CgroupsAvailable()) {
511             // nothing to do here, if cgroups isn't available
512             return 0;
513         }
514 
515         // 400 retries correspond to 2 secs max timeout
516         int err = RemoveProcessGroup(cgroup, uid, initialPid, 400);
517 
518         if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
519             std::string memcg_apps_path;
520             if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
521                 RemoveProcessGroup(memcg_apps_path.c_str(), uid, initialPid, 400) < 0) {
522                 return -1;
523             }
524         }
525 
526         return err;
527     } else {
528         if (retries > 0) {
529             LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
530                        << " in " << static_cast<int>(ms) << "ms, " << processes
531                        << " processes remain";
532         }
533         return -1;
534     }
535 }
536 
killProcessGroup(uid_t uid,int initialPid,int signal,int * max_processes)537 int killProcessGroup(uid_t uid, int initialPid, int signal, int* max_processes) {
538     return KillProcessGroup(uid, initialPid, signal, 40 /*retries*/, max_processes);
539 }
540 
killProcessGroupOnce(uid_t uid,int initialPid,int signal,int * max_processes)541 int killProcessGroupOnce(uid_t uid, int initialPid, int signal, int* max_processes) {
542     return KillProcessGroup(uid, initialPid, signal, 0 /*retries*/, max_processes);
543 }
544 
sendSignalToProcessGroup(uid_t uid,int initialPid,int signal)545 int sendSignalToProcessGroup(uid_t uid, int initialPid, int signal) {
546     std::string hierarchy_root_path;
547     if (CgroupsAvailable()) {
548         CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &hierarchy_root_path);
549     }
550     const char* cgroup = hierarchy_root_path.c_str();
551     return DoKillProcessGroupOnce(cgroup, uid, initialPid, signal);
552 }
553 
createProcessGroupInternal(uid_t uid,int initialPid,std::string cgroup,bool activate_controllers)554 static int createProcessGroupInternal(uid_t uid, int initialPid, std::string cgroup,
555                                       bool activate_controllers) {
556     auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
557 
558     struct stat cgroup_stat;
559     mode_t cgroup_mode = 0750;
560     uid_t cgroup_uid = AID_SYSTEM;
561     gid_t cgroup_gid = AID_SYSTEM;
562     int ret = 0;
563 
564     if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
565         PLOG(ERROR) << "Failed to get stats for " << cgroup;
566     } else {
567         cgroup_mode = cgroup_stat.st_mode;
568         cgroup_uid = cgroup_stat.st_uid;
569         cgroup_gid = cgroup_stat.st_gid;
570     }
571 
572     if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
573         PLOG(ERROR) << "Failed to make and chown " << uid_path;
574         return -errno;
575     }
576     if (activate_controllers) {
577         ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
578         if (ret) {
579             LOG(ERROR) << "Failed to activate controllers in " << uid_path;
580             return ret;
581         }
582     }
583 
584     auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
585 
586     if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
587         PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
588         return -errno;
589     }
590 
591     auto uid_pid_procs_file = uid_pid_path + PROCESSGROUP_CGROUP_PROCS_FILE;
592 
593     if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
594         ret = -errno;
595         PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
596     }
597 
598     return ret;
599 }
600 
createProcessGroup(uid_t uid,int initialPid,bool memControl)601 int createProcessGroup(uid_t uid, int initialPid, bool memControl) {
602     CHECK_GE(uid, 0);
603     CHECK_GT(initialPid, 0);
604 
605     if (memControl && !UsePerAppMemcg()) {
606         PLOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
607         return -EINVAL;
608     }
609 
610     if (std::string memcg_apps_path;
611         isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
612         // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
613         // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
614         // v1 hierarchy is used.
615         int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
616         if (ret != 0) {
617             return ret;
618         }
619     }
620 
621     std::string cgroup;
622     CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cgroup);
623     return createProcessGroupInternal(uid, initialPid, cgroup, true);
624 }
625 
SetProcessGroupValue(int tid,const std::string & attr_name,int64_t value)626 static bool SetProcessGroupValue(int tid, const std::string& attr_name, int64_t value) {
627     if (!isMemoryCgroupSupported()) {
628         PLOG(ERROR) << "Memcg is not mounted.";
629         return false;
630     }
631 
632     std::string path;
633     if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
634         PLOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
635         return false;
636     }
637 
638     if (!WriteStringToFile(std::to_string(value), path)) {
639         PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
640         return false;
641     }
642     return true;
643 }
644 
setProcessGroupSwappiness(uid_t,int pid,int swappiness)645 bool setProcessGroupSwappiness(uid_t, int pid, int swappiness) {
646     return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
647 }
648 
setProcessGroupSoftLimit(uid_t,int pid,int64_t soft_limit_in_bytes)649 bool setProcessGroupSoftLimit(uid_t, int pid, int64_t soft_limit_in_bytes) {
650     return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
651 }
652 
setProcessGroupLimit(uid_t,int pid,int64_t limit_in_bytes)653 bool setProcessGroupLimit(uid_t, int pid, int64_t limit_in_bytes) {
654     return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
655 }
656 
getAttributePathForTask(const std::string & attr_name,int tid,std::string * path)657 bool getAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
658     return CgroupGetAttributePathForTask(attr_name, tid, path);
659 }
660 
isProfileValidForProcess(const std::string & profile_name,int uid,int pid)661 bool isProfileValidForProcess(const std::string& profile_name, int uid, int pid) {
662     const TaskProfile* tp = TaskProfiles::GetInstance().GetProfile(profile_name);
663 
664     if (tp == nullptr) {
665         return false;
666     }
667 
668     return tp->IsValidForProcess(uid, pid);
669 }