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 
CgroupGetControllerPath(const std::string & cgroup_name,std::string * path)58 bool CgroupGetControllerPath(const std::string& cgroup_name, std::string* path) {
59     auto controller = CgroupMap::GetInstance().FindController(cgroup_name);
60 
61     if (!controller.HasValue()) {
62         return false;
63     }
64 
65     if (path) {
66         *path = controller.path();
67     }
68 
69     return true;
70 }
71 
CgroupGetAttributePath(const std::string & attr_name,std::string * path)72 bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
73     const TaskProfiles& tp = TaskProfiles::GetInstance();
74     const ProfileAttribute* attr = tp.GetAttribute(attr_name);
75 
76     if (attr == nullptr) {
77         return false;
78     }
79 
80     if (path) {
81         *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
82     }
83 
84     return true;
85 }
86 
CgroupGetAttributePathForTask(const std::string & attr_name,int tid,std::string * path)87 bool CgroupGetAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
88     const TaskProfiles& tp = TaskProfiles::GetInstance();
89     const ProfileAttribute* attr = tp.GetAttribute(attr_name);
90 
91     if (attr == nullptr) {
92         return false;
93     }
94 
95     if (!attr->GetPathForTask(tid, path)) {
96         PLOG(ERROR) << "Failed to find cgroup for tid " << tid;
97         return false;
98     }
99 
100     return true;
101 }
102 
UsePerAppMemcg()103 bool UsePerAppMemcg() {
104     bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
105     return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
106 }
107 
isMemoryCgroupSupported()108 static bool isMemoryCgroupSupported() {
109     static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
110 
111     return memcg_supported;
112 }
113 
DropTaskProfilesResourceCaching()114 void DropTaskProfilesResourceCaching() {
115     TaskProfiles::GetInstance().DropResourceCaching();
116 }
117 
SetProcessProfiles(uid_t uid,pid_t pid,const std::vector<std::string> & profiles)118 bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
119     return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles);
120 }
121 
SetTaskProfiles(int tid,const std::vector<std::string> & profiles,bool use_fd_cache)122 bool SetTaskProfiles(int tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
123     return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
124 }
125 
ConvertUidToPath(const char * cgroup,uid_t uid)126 static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
127     return StringPrintf("%s/uid_%d", cgroup, uid);
128 }
129 
ConvertUidPidToPath(const char * cgroup,uid_t uid,int pid)130 static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, int pid) {
131     return StringPrintf("%s/uid_%d/pid_%d", cgroup, uid, pid);
132 }
133 
RemoveProcessGroup(const char * cgroup,uid_t uid,int pid)134 static int RemoveProcessGroup(const char* cgroup, uid_t uid, int pid) {
135     int ret;
136 
137     auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, pid);
138     ret = rmdir(uid_pid_path.c_str());
139 
140     auto uid_path = ConvertUidToPath(cgroup, uid);
141     rmdir(uid_path.c_str());
142 
143     return ret;
144 }
145 
RemoveUidProcessGroups(const std::string & uid_path)146 static bool RemoveUidProcessGroups(const std::string& uid_path) {
147     std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
148     bool empty = true;
149     if (uid != NULL) {
150         dirent* dir;
151         while ((dir = readdir(uid.get())) != nullptr) {
152             if (dir->d_type != DT_DIR) {
153                 continue;
154             }
155 
156             if (!StartsWith(dir->d_name, "pid_")) {
157                 continue;
158             }
159 
160             auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
161             LOG(VERBOSE) << "Removing " << path;
162             if (rmdir(path.c_str()) == -1) {
163                 if (errno != EBUSY) {
164                     PLOG(WARNING) << "Failed to remove " << path;
165                 }
166                 empty = false;
167             }
168         }
169     }
170     return empty;
171 }
172 
removeAllProcessGroups()173 void removeAllProcessGroups() {
174     LOG(VERBOSE) << "removeAllProcessGroups()";
175 
176     std::vector<std::string> cgroups;
177     std::string path;
178 
179     if (CgroupGetControllerPath("cpuacct", &path)) {
180         cgroups.push_back(path);
181     }
182     if (CgroupGetControllerPath("memory", &path)) {
183         cgroups.push_back(path + "/apps");
184     }
185 
186     for (std::string cgroup_root_path : cgroups) {
187         std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
188         if (root == NULL) {
189             PLOG(ERROR) << "Failed to open " << cgroup_root_path;
190         } else {
191             dirent* dir;
192             while ((dir = readdir(root.get())) != nullptr) {
193                 if (dir->d_type != DT_DIR) {
194                     continue;
195                 }
196 
197                 if (!StartsWith(dir->d_name, "uid_")) {
198                     continue;
199                 }
200 
201                 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
202                 if (!RemoveUidProcessGroups(path)) {
203                     LOG(VERBOSE) << "Skip removing " << path;
204                     continue;
205                 }
206                 LOG(VERBOSE) << "Removing " << path;
207                 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
208                     PLOG(WARNING) << "Failed to remove " << path;
209                 }
210             }
211         }
212     }
213 }
214 
MkdirAndChown(const std::string & path,mode_t mode,uid_t uid,gid_t gid)215 static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
216     if (mkdir(path.c_str(), mode) == -1 && errno != EEXIST) {
217         return false;
218     }
219 
220     if (chown(path.c_str(), uid, gid) == -1) {
221         int saved_errno = errno;
222         rmdir(path.c_str());
223         errno = saved_errno;
224         return false;
225     }
226 
227     return true;
228 }
229 
230 // Returns number of processes killed on success
231 // Returns 0 if there are no processes in the process cgroup left to kill
232 // Returns -1 on error
DoKillProcessGroupOnce(const char * cgroup,uid_t uid,int initialPid,int signal)233 static int DoKillProcessGroupOnce(const char* cgroup, uid_t uid, int initialPid, int signal) {
234     auto path = ConvertUidPidToPath(cgroup, uid, initialPid) + PROCESSGROUP_CGROUP_PROCS_FILE;
235     std::unique_ptr<FILE, decltype(&fclose)> fd(fopen(path.c_str(), "re"), fclose);
236     if (!fd) {
237         if (errno == ENOENT) {
238             // This happens when process is already dead
239             return 0;
240         }
241         PLOG(WARNING) << "Failed to open process cgroup uid " << uid << " pid " << initialPid;
242         return -1;
243     }
244 
245     // We separate all of the pids in the cgroup into those pids that are also the leaders of
246     // process groups (stored in the pgids set) and those that are not (stored in the pids set).
247     std::set<pid_t> pgids;
248     pgids.emplace(initialPid);
249     std::set<pid_t> pids;
250 
251     pid_t pid;
252     int processes = 0;
253     while (fscanf(fd.get(), "%d\n", &pid) == 1 && pid >= 0) {
254         processes++;
255         if (pid == 0) {
256             // Should never happen...  but if it does, trying to kill this
257             // will boomerang right back and kill us!  Let's not let that happen.
258             LOG(WARNING) << "Yikes, we've been told to kill pid 0!  How about we don't do that?";
259             continue;
260         }
261         pid_t pgid = getpgid(pid);
262         if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
263         if (pgid == pid) {
264             pgids.emplace(pid);
265         } else {
266             pids.emplace(pid);
267         }
268     }
269 
270     // Erase all pids that will be killed when we kill the process groups.
271     for (auto it = pids.begin(); it != pids.end();) {
272         pid_t pgid = getpgid(*it);
273         if (pgids.count(pgid) == 1) {
274             it = pids.erase(it);
275         } else {
276             ++it;
277         }
278     }
279 
280     // Kill all process groups.
281     for (const auto pgid : pgids) {
282         LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
283                      << " as part of process cgroup " << initialPid;
284 
285         if (kill(-pgid, signal) == -1 && errno != ESRCH) {
286             PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
287         }
288     }
289 
290     // Kill remaining pids.
291     for (const auto pid : pids) {
292         LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
293                      << initialPid;
294 
295         if (kill(pid, signal) == -1 && errno != ESRCH) {
296             PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
297         }
298     }
299 
300     return feof(fd.get()) ? processes : -1;
301 }
302 
KillProcessGroup(uid_t uid,int initialPid,int signal,int retries,int * max_processes)303 static int KillProcessGroup(uid_t uid, int initialPid, int signal, int retries,
304                             int* max_processes) {
305     std::string cpuacct_path;
306     std::string memory_path;
307 
308     CgroupGetControllerPath("cpuacct", &cpuacct_path);
309     CgroupGetControllerPath("memory", &memory_path);
310     memory_path += "/apps";
311 
312     const char* cgroup =
313             (!access(ConvertUidPidToPath(cpuacct_path.c_str(), uid, initialPid).c_str(), F_OK))
314                     ? cpuacct_path.c_str()
315                     : memory_path.c_str();
316 
317     std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
318 
319     if (max_processes != nullptr) {
320         *max_processes = 0;
321     }
322 
323     int retry = retries;
324     int processes;
325     while ((processes = DoKillProcessGroupOnce(cgroup, uid, initialPid, signal)) > 0) {
326         if (max_processes != nullptr && processes > *max_processes) {
327             *max_processes = processes;
328         }
329         LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
330         if (retry > 0) {
331             std::this_thread::sleep_for(5ms);
332             --retry;
333         } else {
334             break;
335         }
336     }
337 
338     if (processes < 0) {
339         PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
340                     << initialPid;
341         return -1;
342     }
343 
344     std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
345     auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
346 
347     // We only calculate the number of 'processes' when killing the processes.
348     // In the retries == 0 case, we only kill the processes once and therefore
349     // will not have waited then recalculated how many processes are remaining
350     // after the first signals have been sent.
351     // Logging anything regarding the number of 'processes' here does not make sense.
352 
353     if (processes == 0) {
354         if (retries > 0) {
355             LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
356                       << " in " << static_cast<int>(ms) << "ms";
357         }
358         return RemoveProcessGroup(cgroup, uid, initialPid);
359     } else {
360         if (retries > 0) {
361             LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
362                        << " in " << static_cast<int>(ms) << "ms, " << processes
363                        << " processes remain";
364         }
365         return -1;
366     }
367 }
368 
killProcessGroup(uid_t uid,int initialPid,int signal,int * max_processes)369 int killProcessGroup(uid_t uid, int initialPid, int signal, int* max_processes) {
370     return KillProcessGroup(uid, initialPid, signal, 40 /*retries*/, max_processes);
371 }
372 
killProcessGroupOnce(uid_t uid,int initialPid,int signal,int * max_processes)373 int killProcessGroupOnce(uid_t uid, int initialPid, int signal, int* max_processes) {
374     return KillProcessGroup(uid, initialPid, signal, 0 /*retries*/, max_processes);
375 }
376 
createProcessGroup(uid_t uid,int initialPid,bool memControl)377 int createProcessGroup(uid_t uid, int initialPid, bool memControl) {
378     std::string cgroup;
379     if (isMemoryCgroupSupported() && (memControl || UsePerAppMemcg())) {
380         CgroupGetControllerPath("memory", &cgroup);
381         cgroup += "/apps";
382     } else {
383         CgroupGetControllerPath("cpuacct", &cgroup);
384     }
385 
386     auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
387 
388     if (!MkdirAndChown(uid_path, 0750, AID_SYSTEM, AID_SYSTEM)) {
389         PLOG(ERROR) << "Failed to make and chown " << uid_path;
390         return -errno;
391     }
392 
393     auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
394 
395     if (!MkdirAndChown(uid_pid_path, 0750, AID_SYSTEM, AID_SYSTEM)) {
396         PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
397         return -errno;
398     }
399 
400     auto uid_pid_procs_file = uid_pid_path + PROCESSGROUP_CGROUP_PROCS_FILE;
401 
402     int ret = 0;
403     if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
404         ret = -errno;
405         PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
406     }
407 
408     return ret;
409 }
410 
SetProcessGroupValue(int tid,const std::string & attr_name,int64_t value)411 static bool SetProcessGroupValue(int tid, const std::string& attr_name, int64_t value) {
412     if (!isMemoryCgroupSupported()) {
413         PLOG(ERROR) << "Memcg is not mounted.";
414         return false;
415     }
416 
417     std::string path;
418     if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
419         PLOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
420         return false;
421     }
422 
423     if (!WriteStringToFile(std::to_string(value), path)) {
424         PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
425         return false;
426     }
427     return true;
428 }
429 
setProcessGroupSwappiness(uid_t,int pid,int swappiness)430 bool setProcessGroupSwappiness(uid_t, int pid, int swappiness) {
431     return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
432 }
433 
setProcessGroupSoftLimit(uid_t,int pid,int64_t soft_limit_in_bytes)434 bool setProcessGroupSoftLimit(uid_t, int pid, int64_t soft_limit_in_bytes) {
435     return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
436 }
437 
setProcessGroupLimit(uid_t,int pid,int64_t limit_in_bytes)438 bool setProcessGroupLimit(uid_t, int pid, int64_t limit_in_bytes) {
439     return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
440 }
441