blob: 7e27d75440d3d626775f54354349efb14a169ff7 [file] [log] [blame]
Colin Crosscf8d1c22014-06-03 13:24:21 -07001/*
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>
Elliott Hughes0badbd62014-12-29 12:24:25 -080022#include <errno.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070023#include <fcntl.h>
Chih-Hung Hsiehfcc81152014-11-20 17:05:15 -080024#include <inttypes.h>
T.J. Mercier4928b6e2023-12-14 21:38:23 +000025#include <poll.h>
Tom Cherry574a0812018-02-23 13:04:40 -080026#include <signal.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070027#include <stdio.h>
28#include <stdlib.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070029#include <sys/stat.h>
30#include <sys/types.h>
Tom Cherry70a5ed42017-06-05 19:20:17 -070031#include <unistd.h>
Collin Mullinerf7e79b92016-06-01 21:03:55 +000032
33#include <chrono>
T.J. Mercier4928b6e2023-12-14 21:38:23 +000034#include <cstring>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080035#include <map>
James Hawkins588a2ca2016-02-18 14:52:46 -080036#include <memory>
Elliott Hughes8d532e42016-06-06 21:19:55 -070037#include <mutex>
Tom Cherry70a5ed42017-06-05 19:20:17 -070038#include <set>
Tom Cherry574a0812018-02-23 13:04:40 -080039#include <string>
Elliott Hughes290a2282016-11-14 17:08:47 -080040#include <thread>
Colin Crosscf8d1c22014-06-03 13:24:21 -070041
Robert Benead4852262017-07-16 19:38:11 -070042#include <android-base/file.h>
Elliott Hughes171df0a2016-08-02 13:30:30 -070043#include <android-base/logging.h>
Suren Baghdasaryanbc131c32018-05-23 12:30:44 -070044#include <android-base/properties.h>
Tom Cherry574a0812018-02-23 13:04:40 -080045#include <android-base/stringprintf.h>
46#include <android-base/strings.h>
Suren Baghdasaryan7bf43812019-01-25 05:29:55 +000047#include <cutils/android_filesystem_config.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070048#include <processgroup/processgroup.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080049#include <task_profiles.h>
Martijn Coenenb82bab62016-01-20 16:39:16 -080050
Suren Baghdasaryanbc131c32018-05-23 12:30:44 -070051using android::base::GetBoolProperty;
Tom Cherry574a0812018-02-23 13:04:40 -080052using android::base::StartsWith;
53using android::base::StringPrintf;
Robert Benead4852262017-07-16 19:38:11 -070054using android::base::WriteStringToFile;
55
Elliott Hughes290a2282016-11-14 17:08:47 -080056using namespace std::chrono_literals;
57
T.J. Mercier4928b6e2023-12-14 21:38:23 +000058#define PROCESSGROUP_CGROUP_PROCS_FILE "cgroup.procs"
59#define PROCESSGROUP_CGROUP_EVENTS_FILE "cgroup.events"
Martijn Coenenb82bab62016-01-20 16:39:16 -080060
Nikita Ioffec2b16542022-10-20 14:14:39 +010061bool CgroupsAvailable() {
62 static bool cgroups_available = access("/proc/cgroups", F_OK) == 0;
63 return cgroups_available;
64}
65
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080066bool CgroupGetControllerPath(const std::string& cgroup_name, std::string* path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070067 auto controller = CgroupMap::GetInstance().FindController(cgroup_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080068
Yifan Hong53e0deb2019-03-22 17:01:08 -070069 if (!controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080070 return false;
71 }
72
73 if (path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070074 *path = controller.path();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080075 }
76
77 return true;
78}
79
Bart Van Assche4c957122022-02-04 18:19:45 +000080static bool CgroupGetMemcgAppsPath(std::string* path) {
81 CgroupController controller = CgroupMap::GetInstance().FindController("memory");
82
83 if (!controller.HasValue()) {
84 return false;
85 }
86
87 if (path) {
88 *path = controller.path();
89 if (controller.version() == 1) {
90 *path += "/apps";
91 }
92 }
93
94 return true;
95}
96
Suren Baghdasaryan9e3ace52021-06-16 17:01:19 -070097bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
98 auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
99
100 if (!controller.HasValue()) {
101 return false;
102 }
103
104 if (cgroup_name) {
105 *cgroup_name = controller.name();
106 }
107
108 return true;
109}
110
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800111bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
112 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000113 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800114
115 if (attr == nullptr) {
116 return false;
117 }
118
119 if (path) {
120 *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
121 }
122
123 return true;
124}
125
126bool CgroupGetAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
127 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000128 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800129
130 if (attr == nullptr) {
131 return false;
132 }
133
134 if (!attr->GetPathForTask(tid, path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000135 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800136 return false;
137 }
138
139 return true;
140}
141
142bool UsePerAppMemcg() {
143 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
144 return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
145}
146
Peter Collingbourned7157c22018-10-30 15:49:33 -0700147static bool isMemoryCgroupSupported() {
Suren Baghdasaryanfa7a05f2019-05-08 17:59:55 -0700148 static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800149
Peter Collingbourned7157c22018-10-30 15:49:33 -0700150 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -0800151}
152
Riddle Hsua6abd822019-06-18 15:53:53 -0600153void DropTaskProfilesResourceCaching() {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800154 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
155 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
Riddle Hsua6abd822019-06-18 15:53:53 -0600156}
157
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800158bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700159 return TaskProfiles::GetInstance().SetProcessProfiles(
160 uid, pid, std::span<const std::string>(profiles), false);
161}
162
163bool SetProcessProfiles(uid_t uid, pid_t pid, std::initializer_list<std::string_view> profiles) {
164 return TaskProfiles::GetInstance().SetProcessProfiles(
165 uid, pid, std::span<const std::string_view>(profiles), false);
166}
167
168bool SetProcessProfiles(uid_t uid, pid_t pid, std::span<const std::string_view> profiles) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800169 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
170}
171
172bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700173 return TaskProfiles::GetInstance().SetProcessProfiles(
174 uid, pid, std::span<const std::string>(profiles), true);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800175}
176
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800177bool SetTaskProfiles(int tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700178 return TaskProfiles::GetInstance().SetTaskProfiles(tid, std::span<const std::string>(profiles),
179 use_fd_cache);
180}
181
182bool SetTaskProfiles(int tid, std::initializer_list<std::string_view> profiles, bool use_fd_cache) {
183 return TaskProfiles::GetInstance().SetTaskProfiles(
184 tid, std::span<const std::string_view>(profiles), use_fd_cache);
185}
186
187bool SetTaskProfiles(int tid, std::span<const std::string_view> profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800188 return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800189}
190
Jiyong Park8bf59402022-04-01 12:24:22 +0900191// C wrapper for SetProcessProfiles.
192// No need to have this in the header file because this function is specifically for crosvm. Crosvm
193// which is written in Rust has its own declaration of this foreign function and doesn't rely on the
194// header. See
195// https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
196extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
197 const char* profiles[]) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700198 std::vector<std::string_view> profiles_;
Jiyong Parkcc9932b2022-04-20 17:11:42 +0900199 profiles_.reserve(num_profiles);
Jiyong Park8bf59402022-04-01 12:24:22 +0900200 for (size_t i = 0; i < num_profiles; i++) {
201 profiles_.emplace_back(profiles[i]);
202 }
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700203 return SetProcessProfiles(uid, pid, std::span<const std::string_view>(profiles_));
Jiyong Park8bf59402022-04-01 12:24:22 +0900204}
205
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000206bool SetUserProfiles(uid_t uid, const std::vector<std::string>& profiles) {
207 return TaskProfiles::GetInstance().SetUserProfiles(uid, std::span<const std::string>(profiles),
208 false);
209}
210
Android Culprit Assistantc0ce1782023-12-08 01:48:25 +0000211static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
212 return StringPrintf("%s/uid_%u", cgroup, uid);
213}
214
215static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, int pid) {
216 return StringPrintf("%s/uid_%u/pid_%d", cgroup, uid, pid);
217}
218
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000219static int RemoveCgroup(const char* cgroup, uid_t uid, int pid) {
220 auto path = ConvertUidPidToPath(cgroup, uid, pid);
221 int ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
Marco Ballesio4dac8162021-02-10 16:35:44 -0800222
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000223 if (!ret && uid >= AID_ISOLATED_START && uid <= AID_ISOLATED_END) {
224 // Isolated UIDs are unlikely to be reused soon after removal,
225 // so free up the kernel resources for the UID level cgroup.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000226 path = ConvertUidToPath(cgroup, uid);
227 ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
228 }
229
230 if (ret < 0 && errno == ENOENT) {
231 // This function is idempoetent, but still warn here.
232 LOG(WARNING) << "RemoveCgroup: " << path << " does not exist.";
233 ret = 0;
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000234 }
235
Colin Crosscf8d1c22014-06-03 13:24:21 -0700236 return ret;
237}
238
Bart Van Assche30488122023-11-15 09:11:20 -0800239static bool RemoveEmptyUidCgroups(const std::string& uid_path) {
Tom Cherry574a0812018-02-23 13:04:40 -0800240 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Wei Wang858f3e52019-02-21 11:25:16 -0800241 bool empty = true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700242 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700243 dirent* dir;
244 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700245 if (dir->d_type != DT_DIR) {
246 continue;
247 }
248
Tom Cherry574a0812018-02-23 13:04:40 -0800249 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700250 continue;
251 }
252
Tom Cherry574a0812018-02-23 13:04:40 -0800253 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700254 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800255 if (rmdir(path.c_str()) == -1) {
256 if (errno != EBUSY) {
257 PLOG(WARNING) << "Failed to remove " << path;
258 }
259 empty = false;
260 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700261 }
262 }
Wei Wang858f3e52019-02-21 11:25:16 -0800263 return empty;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700264}
265
Bart Van Assche30488122023-11-15 09:11:20 -0800266void removeAllEmptyProcessGroups() {
267 LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
268
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800269 std::vector<std::string> cgroups;
Bart Van Assche4c957122022-02-04 18:19:45 +0000270 std::string path, memcg_apps_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800271
T.J. Merciera99e7d82023-10-27 17:29:01 +0000272 if (CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &path)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800273 cgroups.push_back(path);
274 }
Bart Van Assche4c957122022-02-04 18:19:45 +0000275 if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
276 cgroups.push_back(memcg_apps_path);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800277 }
278
279 for (std::string cgroup_root_path : cgroups) {
280 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700281 if (root == NULL) {
Bart Van Assche6e814b02022-02-03 19:24:42 +0000282 PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700283 } else {
284 dirent* dir;
285 while ((dir = readdir(root.get())) != nullptr) {
286 if (dir->d_type != DT_DIR) {
287 continue;
288 }
Tom Cherry574a0812018-02-23 13:04:40 -0800289
Peter Collingbourned7157c22018-10-30 15:49:33 -0700290 if (!StartsWith(dir->d_name, "uid_")) {
291 continue;
292 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700293
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800294 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
Bart Van Assche30488122023-11-15 09:11:20 -0800295 if (!RemoveEmptyUidCgroups(path)) {
Wei Wang858f3e52019-02-21 11:25:16 -0800296 LOG(VERBOSE) << "Skip removing " << path;
297 continue;
298 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700299 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800300 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
301 PLOG(WARNING) << "Failed to remove " << path;
302 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700303 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700304 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700305 }
306}
307
Marco Ballesio4dac8162021-02-10 16:35:44 -0800308/**
309 * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
310 * the user root. Ownership for the newly created cgroup and all of its files must thus be
311 * transferred for the user/group passed as uid/gid before system_server can properly access them.
312 */
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800313static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Suren Baghdasaryan29c9e262021-07-07 10:59:59 -0700314 if (mkdir(path.c_str(), mode) == -1) {
315 if (errno == EEXIST) {
316 // Directory already exists and permissions have been set at the time it was created
317 return true;
318 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800319 return false;
320 }
321
Marco Ballesio4dac8162021-02-10 16:35:44 -0800322 auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
323
324 if (dir == NULL) {
325 PLOG(ERROR) << "opendir failed for " << path;
326 goto err;
327 }
328
329 struct dirent* dir_entry;
330 while ((dir_entry = readdir(dir.get()))) {
331 if (!strcmp("..", dir_entry->d_name)) {
332 continue;
333 }
334
335 std::string file_path = path + "/" + dir_entry->d_name;
336
337 if (lchown(file_path.c_str(), uid, gid) < 0) {
338 PLOG(ERROR) << "lchown failed for " << file_path;
339 goto err;
340 }
341
342 if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
343 PLOG(ERROR) << "fchmodat failed for " << file_path;
344 goto err;
345 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800346 }
347
348 return true;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800349err:
350 int saved_errno = errno;
351 rmdir(path.c_str());
352 errno = saved_errno;
353
354 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800355}
356
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000357bool sendSignalToProcessGroup(uid_t uid, int initialPid, int signal) {
358 std::set<pid_t> pgids, pids;
Inseob Kima049a992022-11-17 23:42:12 +0900359
360 if (CgroupsAvailable()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000361 std::string hierarchy_root_path, cgroup_v2_path;
362 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
363 cgroup_v2_path = ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
364
365 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_PROCS_FILE << " to signal (" << signal
366 << ") " << cgroup_v2_path;
367
368 // We separate all of the pids in the cgroup into those pids that are also the leaders of
369 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
370 const auto procsfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
371 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(procsfilepath.c_str(), "re"), fclose);
372 if (!fp) {
373 // This should only happen if the cgroup has already been removed with a successful call
374 // to killProcessGroup. Callers should only retry sendSignalToProcessGroup or
375 // killProcessGroup calls if they fail without ENOENT.
376 PLOG(ERROR) << "Failed to open " << procsfilepath;
377 kill(-initialPid, signal);
378 return false;
Inseob Kima049a992022-11-17 23:42:12 +0900379 }
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000380
Inseob Kima049a992022-11-17 23:42:12 +0900381 pid_t pid;
382 bool file_is_empty = true;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000383 while (fscanf(fp.get(), "%d\n", &pid) == 1 && pid >= 0) {
Inseob Kima049a992022-11-17 23:42:12 +0900384 file_is_empty = false;
385 if (pid == 0) {
386 // Should never happen... but if it does, trying to kill this
387 // will boomerang right back and kill us! Let's not let that happen.
388 LOG(WARNING)
389 << "Yikes, we've been told to kill pid 0! How about we don't do that?";
390 continue;
391 }
392 pid_t pgid = getpgid(pid);
393 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
394 if (pgid == pid) {
395 pgids.emplace(pid);
396 } else {
397 pids.emplace(pid);
398 }
399 }
Jing Ji304c0f12023-02-27 21:58:19 -0800400 if (!file_is_empty) {
401 // Erase all pids that will be killed when we kill the process groups.
402 for (auto it = pids.begin(); it != pids.end();) {
403 pid_t pgid = getpgid(*it);
404 if (pgids.count(pgid) == 1) {
405 it = pids.erase(it);
406 } else {
407 ++it;
408 }
Inseob Kima049a992022-11-17 23:42:12 +0900409 }
410 }
411 }
412
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000413 pgids.emplace(initialPid);
414
Tom Cherry70a5ed42017-06-05 19:20:17 -0700415 // Kill all process groups.
416 for (const auto pgid : pgids) {
417 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
418 << " as part of process cgroup " << initialPid;
419
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800420 if (kill(-pgid, signal) == -1 && errno != ESRCH) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700421 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
422 }
423 }
424
425 // Kill remaining pids.
426 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700427 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
428 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700429
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800430 if (kill(pid, signal) == -1 && errno != ESRCH) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700431 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700432 }
433 }
434
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000435 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700436}
437
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000438template <typename T>
439static std::chrono::milliseconds toMillisec(T&& duration) {
440 return std::chrono::duration_cast<std::chrono::milliseconds>(duration);
441}
442
443enum class populated_status
444{
445 populated,
446 not_populated,
447 error
448};
449
450static populated_status cgroupIsPopulated(int events_fd) {
451 const std::string POPULATED_KEY("populated ");
452 const std::string::size_type MAX_EVENTS_FILE_SIZE = 32;
453
454 std::string buf;
455 buf.resize(MAX_EVENTS_FILE_SIZE);
456 ssize_t len = TEMP_FAILURE_RETRY(pread(events_fd, buf.data(), buf.size(), 0));
457 if (len == -1) {
458 PLOG(ERROR) << "Could not read cgroup.events: ";
459 // Potentially ENODEV if the cgroup has been removed since we opened this file, but that
460 // shouldn't have happened yet.
461 return populated_status::error;
462 }
463
464 if (len == 0) {
465 LOG(ERROR) << "cgroup.events EOF";
466 return populated_status::error;
467 }
468
469 buf.resize(len);
470
471 const std::string::size_type pos = buf.find(POPULATED_KEY);
472 if (pos == std::string::npos) {
473 LOG(ERROR) << "Could not find populated key in cgroup.events";
474 return populated_status::error;
475 }
476
477 if (pos + POPULATED_KEY.size() + 1 > len) {
478 LOG(ERROR) << "Partial read of cgroup.events";
479 return populated_status::error;
480 }
481
482 return buf[pos + POPULATED_KEY.size()] == '1' ?
483 populated_status::populated : populated_status::not_populated;
484}
485
486// The default timeout of 2200ms comes from the default number of retries in a previous
487// implementation of this function. The default retry value was 40 for killing and 400 for cgroup
488// removal with 5ms sleeps between each retry.
489static int KillProcessGroup(
490 uid_t uid, int initialPid, int signal, bool once = false,
491 std::chrono::steady_clock::time_point until = std::chrono::steady_clock::now() + 2200ms) {
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700492 CHECK_GE(uid, 0);
493 CHECK_GT(initialPid, 0);
494
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000495 // Always attempt to send a kill signal to at least the initialPid, at least once, regardless of
496 // whether its cgroup exists or not. This should only be necessary if a bug results in the
497 // migration of the targeted process out of its cgroup, which we will also attempt to kill.
498 const bool signal_ret = sendSignalToProcessGroup(uid, initialPid, signal);
499
500 if (!CgroupsAvailable() || !signal_ret) return signal_ret ? 0 : -1;
501
Marco Ballesio4dac8162021-02-10 16:35:44 -0800502 std::string hierarchy_root_path;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000503 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700504
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000505 const std::string cgroup_v2_path =
506 ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700507
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000508 const std::string eventsfile = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_EVENTS_FILE;
509 android::base::unique_fd events_fd(open(eventsfile.c_str(), O_RDONLY));
510 if (events_fd.get() == -1) {
511 PLOG(WARNING) << "Error opening " << eventsfile << " for KillProcessGroup";
Tom Cherry20514c42017-04-21 13:48:49 -0700512 return -1;
513 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000514
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000515 struct pollfd fds = {
516 .fd = events_fd,
517 .events = POLLPRI,
518 };
Tom Cherry20514c42017-04-21 13:48:49 -0700519
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000520 const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700521
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000522 // The primary reason to loop here is to capture any new forks or migrations that could occur
523 // after we send signals to the original set of processes, but before all of those processes
524 // exit and the cgroup becomes unpopulated, or before we remove the cgroup. We try hard to
525 // ensure this completes successfully to avoid permanent memory leaks, but we still place a
526 // large default upper bound on the amount of time we spend in this loop. The amount of CPU
527 // contention, and the amount of work that needs to be done in do_exit for each process
528 // determines how long this will take.
529 int ret;
530 do {
531 populated_status populated;
532 while ((populated = cgroupIsPopulated(events_fd.get())) == populated_status::populated &&
533 std::chrono::steady_clock::now() < until) {
534
535 sendSignalToProcessGroup(uid, initialPid, signal);
536 if (once) {
537 populated = cgroupIsPopulated(events_fd.get());
538 break;
539 }
540
541 const std::chrono::steady_clock::time_point poll_start =
542 std::chrono::steady_clock::now();
543
544 if (poll_start < until)
545 ret = TEMP_FAILURE_RETRY(poll(&fds, 1, toMillisec(until - poll_start).count()));
546
547 if (ret == -1) {
548 // Fallback to 5ms sleeps if poll fails
549 PLOG(ERROR) << "Poll on " << eventsfile << "failed";
550 const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
551 if (now < until)
552 std::this_thread::sleep_for(std::min(5ms, toMillisec(until - now)));
553 }
554
555 LOG(VERBOSE) << "Waited "
556 << toMillisec(std::chrono::steady_clock::now() - poll_start).count()
557 << " ms for " << eventsfile << " poll";
Tom Cherry20514c42017-04-21 13:48:49 -0700558 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800559
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000560 const std::chrono::milliseconds kill_duration =
561 toMillisec(std::chrono::steady_clock::now() - start);
562
563 if (populated == populated_status::populated) {
564 LOG(WARNING) << "Still waiting on process(es) to exit for cgroup " << cgroup_v2_path
565 << " after " << kill_duration.count() << " ms";
566 // We'll still try the cgroup removal below which we expect to log an error.
567 } else if (populated == populated_status::not_populated) {
568 LOG(VERBOSE) << "Killed all processes under cgroup " << cgroup_v2_path
569 << " after " << kill_duration.count() << " ms";
Inseob Kima049a992022-11-17 23:42:12 +0900570 }
571
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000572 ret = RemoveCgroup(hierarchy_root_path.c_str(), uid, initialPid);
573 if (ret)
574 PLOG(ERROR) << "Unable to remove cgroup " << cgroup_v2_path;
575 else
576 LOG(INFO) << "Removed cgroup " << cgroup_v2_path;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800577
578 if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000579 // This per-application memcg v1 case should eventually be removed after migration to
580 // memcg v2.
Bart Van Assche4c957122022-02-04 18:19:45 +0000581 std::string memcg_apps_path;
582 if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000583 (ret = RemoveCgroup(memcg_apps_path.c_str(), uid, initialPid)) < 0) {
584 const auto memcg_v1_cgroup_path =
585 ConvertUidPidToPath(memcg_apps_path.c_str(), uid, initialPid);
586 PLOG(ERROR) << "Unable to remove memcg v1 cgroup " << memcg_v1_cgroup_path;
Bart Van Assche4c957122022-02-04 18:19:45 +0000587 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800588 }
589
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000590 if (once) break;
591 if (std::chrono::steady_clock::now() >= until) break;
592 } while (ret && errno == EBUSY);
593
594 return ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700595}
596
T.J. Mercier599d9792023-10-26 20:46:21 +0000597int killProcessGroup(uid_t uid, int initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000598 return KillProcessGroup(uid, initialPid, signal);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700599}
600
T.J. Mercier599d9792023-10-26 20:46:21 +0000601int killProcessGroupOnce(uid_t uid, int initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000602 return KillProcessGroup(uid, initialPid, signal, true);
T.J. Mercier22006bf2023-04-13 21:48:55 +0000603}
604
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700605static int createProcessGroupInternal(uid_t uid, int initialPid, std::string cgroup,
606 bool activate_controllers) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800607 auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700608
Marco Ballesio9e628a62021-02-11 14:44:53 -0800609 struct stat cgroup_stat;
610 mode_t cgroup_mode = 0750;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000611 uid_t cgroup_uid = AID_SYSTEM;
Bart Van Assche32a9b1c2022-03-10 21:42:40 +0000612 gid_t cgroup_gid = AID_SYSTEM;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700613 int ret = 0;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800614
Bart Van Assche55a9b1e2022-03-23 10:13:18 -0700615 if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
Marco Ballesio9e628a62021-02-11 14:44:53 -0800616 PLOG(ERROR) << "Failed to get stats for " << cgroup;
617 } else {
618 cgroup_mode = cgroup_stat.st_mode;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000619 cgroup_uid = cgroup_stat.st_uid;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800620 cgroup_gid = cgroup_stat.st_gid;
621 }
622
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000623 if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800624 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700625 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700626 }
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700627 if (activate_controllers) {
628 ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
629 if (ret) {
630 LOG(ERROR) << "Failed to activate controllers in " << uid_path;
631 return ret;
632 }
633 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700634
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800635 auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700636
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000637 if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800638 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700639 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700640 }
641
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000642 auto uid_pid_procs_file = uid_pid_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700643
Tom Cherry574a0812018-02-23 13:04:40 -0800644 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700645 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800646 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700647 }
648
Colin Crosscf8d1c22014-06-03 13:24:21 -0700649 return ret;
650}
Robert Benead4852262017-07-16 19:38:11 -0700651
Marco Ballesio4dac8162021-02-10 16:35:44 -0800652int createProcessGroup(uid_t uid, int initialPid, bool memControl) {
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700653 CHECK_GE(uid, 0);
654 CHECK_GT(initialPid, 0);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800655
656 if (memControl && !UsePerAppMemcg()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000657 LOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
Marco Ballesio4dac8162021-02-10 16:35:44 -0800658 return -EINVAL;
659 }
660
Bart Van Assche4c957122022-02-04 18:19:45 +0000661 if (std::string memcg_apps_path;
662 isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
663 // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
664 // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
665 // v1 hierarchy is used.
666 int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800667 if (ret != 0) {
668 return ret;
669 }
670 }
671
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700672 std::string cgroup;
T.J. Merciera99e7d82023-10-27 17:29:01 +0000673 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cgroup);
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700674 return createProcessGroupInternal(uid, initialPid, cgroup, true);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800675}
676
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800677static bool SetProcessGroupValue(int tid, const std::string& attr_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700678 if (!isMemoryCgroupSupported()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000679 LOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700680 return false;
681 }
682
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800683 std::string path;
684 if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000685 LOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800686 return false;
687 }
Robert Benead4852262017-07-16 19:38:11 -0700688
689 if (!WriteStringToFile(std::to_string(value), path)) {
690 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
691 return false;
692 }
693 return true;
694}
695
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800696bool setProcessGroupSwappiness(uid_t, int pid, int swappiness) {
697 return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700698}
699
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800700bool setProcessGroupSoftLimit(uid_t, int pid, int64_t soft_limit_in_bytes) {
701 return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700702}
703
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800704bool setProcessGroupLimit(uid_t, int pid, int64_t limit_in_bytes) {
705 return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700706}
Marco Ballesio4e644c42021-02-24 16:30:50 -0800707
708bool getAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
709 return CgroupGetAttributePathForTask(attr_name, tid, path);
710}
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000711
712bool isProfileValidForProcess(const std::string& profile_name, int uid, int pid) {
713 const TaskProfile* tp = TaskProfiles::GetInstance().GetProfile(profile_name);
714
715 if (tp == nullptr) {
716 return false;
717 }
718
719 return tp->IsValidForProcess(uid, pid);
T.J. Merciera99e7d82023-10-27 17:29:01 +0000720}