blob: 7c555708e002f0f17a2a5433593a389e54fd76aa [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"
T.J. Merciera1036302023-11-07 14:36:46 +000059#define PROCESSGROUP_CGROUP_KILL_FILE "cgroup.kill"
T.J. Mercier4928b6e2023-12-14 21:38:23 +000060#define PROCESSGROUP_CGROUP_EVENTS_FILE "cgroup.events"
Martijn Coenenb82bab62016-01-20 16:39:16 -080061
Nikita Ioffec2b16542022-10-20 14:14:39 +010062bool CgroupsAvailable() {
63 static bool cgroups_available = access("/proc/cgroups", F_OK) == 0;
64 return cgroups_available;
65}
66
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080067bool CgroupGetControllerPath(const std::string& cgroup_name, std::string* path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070068 auto controller = CgroupMap::GetInstance().FindController(cgroup_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080069
Yifan Hong53e0deb2019-03-22 17:01:08 -070070 if (!controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080071 return false;
72 }
73
74 if (path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070075 *path = controller.path();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080076 }
77
78 return true;
79}
80
T.J. Merciera1036302023-11-07 14:36:46 +000081static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
82 return StringPrintf("%s/uid_%u", cgroup, uid);
83}
84
T.J. Mercierd6fb2252024-01-24 23:42:39 +000085static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, pid_t pid) {
T.J. Merciera1036302023-11-07 14:36:46 +000086 return StringPrintf("%s/uid_%u/pid_%d", cgroup, uid, pid);
87}
88
89static bool CgroupKillAvailable() {
90 static std::once_flag f;
91 static bool cgroup_kill_available = false;
92 std::call_once(f, []() {
93 std::string cg_kill;
94 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cg_kill);
95 // cgroup.kill is not on the root cgroup, so check a non-root cgroup that should always
96 // exist
97 cg_kill = ConvertUidToPath(cg_kill.c_str(), AID_ROOT) + '/' + PROCESSGROUP_CGROUP_KILL_FILE;
98 cgroup_kill_available = access(cg_kill.c_str(), F_OK) == 0;
99 });
100
101 return cgroup_kill_available;
102}
103
Bart Van Assche4c957122022-02-04 18:19:45 +0000104static bool CgroupGetMemcgAppsPath(std::string* path) {
105 CgroupController controller = CgroupMap::GetInstance().FindController("memory");
106
107 if (!controller.HasValue()) {
108 return false;
109 }
110
111 if (path) {
112 *path = controller.path();
113 if (controller.version() == 1) {
114 *path += "/apps";
115 }
116 }
117
118 return true;
119}
120
Suren Baghdasaryan9e3ace52021-06-16 17:01:19 -0700121bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
122 auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
123
124 if (!controller.HasValue()) {
125 return false;
126 }
127
128 if (cgroup_name) {
129 *cgroup_name = controller.name();
130 }
131
132 return true;
133}
134
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800135bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
136 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000137 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800138
139 if (attr == nullptr) {
140 return false;
141 }
142
143 if (path) {
144 *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
145 }
146
147 return true;
148}
149
T.J. Mercier1c007992024-01-25 16:29:54 +0000150bool CgroupGetAttributePathForTask(const std::string& attr_name, pid_t tid, std::string* path) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800151 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000152 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800153
154 if (attr == nullptr) {
155 return false;
156 }
157
158 if (!attr->GetPathForTask(tid, path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000159 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800160 return false;
161 }
162
163 return true;
164}
165
166bool UsePerAppMemcg() {
167 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
168 return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
169}
170
Peter Collingbourned7157c22018-10-30 15:49:33 -0700171static bool isMemoryCgroupSupported() {
Suren Baghdasaryanfa7a05f2019-05-08 17:59:55 -0700172 static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800173
Peter Collingbourned7157c22018-10-30 15:49:33 -0700174 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -0800175}
176
Riddle Hsua6abd822019-06-18 15:53:53 -0600177void DropTaskProfilesResourceCaching() {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800178 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
179 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
Riddle Hsua6abd822019-06-18 15:53:53 -0600180}
181
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800182bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700183 return TaskProfiles::GetInstance().SetProcessProfiles(
184 uid, pid, std::span<const std::string>(profiles), false);
185}
186
187bool SetProcessProfiles(uid_t uid, pid_t pid, std::initializer_list<std::string_view> profiles) {
188 return TaskProfiles::GetInstance().SetProcessProfiles(
189 uid, pid, std::span<const std::string_view>(profiles), false);
190}
191
192bool SetProcessProfiles(uid_t uid, pid_t pid, std::span<const std::string_view> profiles) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800193 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
194}
195
196bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700197 return TaskProfiles::GetInstance().SetProcessProfiles(
198 uid, pid, std::span<const std::string>(profiles), true);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800199}
200
T.J. Mercier1c007992024-01-25 16:29:54 +0000201bool SetTaskProfiles(pid_t tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700202 return TaskProfiles::GetInstance().SetTaskProfiles(tid, std::span<const std::string>(profiles),
203 use_fd_cache);
204}
205
T.J. Mercier1c007992024-01-25 16:29:54 +0000206bool SetTaskProfiles(pid_t tid, std::initializer_list<std::string_view> profiles,
207 bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700208 return TaskProfiles::GetInstance().SetTaskProfiles(
209 tid, std::span<const std::string_view>(profiles), use_fd_cache);
210}
211
T.J. Mercier1c007992024-01-25 16:29:54 +0000212bool SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800213 return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800214}
215
Jiyong Park8bf59402022-04-01 12:24:22 +0900216// C wrapper for SetProcessProfiles.
217// No need to have this in the header file because this function is specifically for crosvm. Crosvm
218// which is written in Rust has its own declaration of this foreign function and doesn't rely on the
219// header. See
220// https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
221extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
222 const char* profiles[]) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700223 std::vector<std::string_view> profiles_;
Jiyong Parkcc9932b2022-04-20 17:11:42 +0900224 profiles_.reserve(num_profiles);
Jiyong Park8bf59402022-04-01 12:24:22 +0900225 for (size_t i = 0; i < num_profiles; i++) {
226 profiles_.emplace_back(profiles[i]);
227 }
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700228 return SetProcessProfiles(uid, pid, std::span<const std::string_view>(profiles_));
Jiyong Park8bf59402022-04-01 12:24:22 +0900229}
230
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000231bool SetUserProfiles(uid_t uid, const std::vector<std::string>& profiles) {
232 return TaskProfiles::GetInstance().SetUserProfiles(uid, std::span<const std::string>(profiles),
233 false);
234}
235
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000236static int RemoveCgroup(const char* cgroup, uid_t uid, pid_t pid) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000237 auto path = ConvertUidPidToPath(cgroup, uid, pid);
238 int ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
Marco Ballesio4dac8162021-02-10 16:35:44 -0800239
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000240 if (!ret && uid >= AID_ISOLATED_START && uid <= AID_ISOLATED_END) {
241 // Isolated UIDs are unlikely to be reused soon after removal,
242 // so free up the kernel resources for the UID level cgroup.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000243 path = ConvertUidToPath(cgroup, uid);
244 ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
245 }
246
247 if (ret < 0 && errno == ENOENT) {
248 // This function is idempoetent, but still warn here.
249 LOG(WARNING) << "RemoveCgroup: " << path << " does not exist.";
250 ret = 0;
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000251 }
252
Colin Crosscf8d1c22014-06-03 13:24:21 -0700253 return ret;
254}
255
Bart Van Assche30488122023-11-15 09:11:20 -0800256static bool RemoveEmptyUidCgroups(const std::string& uid_path) {
Tom Cherry574a0812018-02-23 13:04:40 -0800257 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Wei Wang858f3e52019-02-21 11:25:16 -0800258 bool empty = true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700259 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700260 dirent* dir;
261 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700262 if (dir->d_type != DT_DIR) {
263 continue;
264 }
265
Tom Cherry574a0812018-02-23 13:04:40 -0800266 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700267 continue;
268 }
269
Tom Cherry574a0812018-02-23 13:04:40 -0800270 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700271 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800272 if (rmdir(path.c_str()) == -1) {
273 if (errno != EBUSY) {
274 PLOG(WARNING) << "Failed to remove " << path;
275 }
276 empty = false;
277 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700278 }
279 }
Wei Wang858f3e52019-02-21 11:25:16 -0800280 return empty;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700281}
282
Bart Van Assche30488122023-11-15 09:11:20 -0800283void removeAllEmptyProcessGroups() {
284 LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
285
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800286 std::vector<std::string> cgroups;
Bart Van Assche4c957122022-02-04 18:19:45 +0000287 std::string path, memcg_apps_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800288
T.J. Merciera99e7d82023-10-27 17:29:01 +0000289 if (CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &path)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800290 cgroups.push_back(path);
291 }
Bart Van Assche4c957122022-02-04 18:19:45 +0000292 if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
293 cgroups.push_back(memcg_apps_path);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800294 }
295
296 for (std::string cgroup_root_path : cgroups) {
297 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700298 if (root == NULL) {
Bart Van Assche6e814b02022-02-03 19:24:42 +0000299 PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700300 } else {
301 dirent* dir;
302 while ((dir = readdir(root.get())) != nullptr) {
303 if (dir->d_type != DT_DIR) {
304 continue;
305 }
Tom Cherry574a0812018-02-23 13:04:40 -0800306
Peter Collingbourned7157c22018-10-30 15:49:33 -0700307 if (!StartsWith(dir->d_name, "uid_")) {
308 continue;
309 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700310
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800311 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
Bart Van Assche30488122023-11-15 09:11:20 -0800312 if (!RemoveEmptyUidCgroups(path)) {
Wei Wang858f3e52019-02-21 11:25:16 -0800313 LOG(VERBOSE) << "Skip removing " << path;
314 continue;
315 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700316 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800317 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
318 PLOG(WARNING) << "Failed to remove " << path;
319 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700320 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700321 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700322 }
323}
324
Marco Ballesio4dac8162021-02-10 16:35:44 -0800325/**
326 * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
327 * the user root. Ownership for the newly created cgroup and all of its files must thus be
328 * transferred for the user/group passed as uid/gid before system_server can properly access them.
329 */
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800330static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Suren Baghdasaryan29c9e262021-07-07 10:59:59 -0700331 if (mkdir(path.c_str(), mode) == -1) {
332 if (errno == EEXIST) {
333 // Directory already exists and permissions have been set at the time it was created
334 return true;
335 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800336 return false;
337 }
338
Marco Ballesio4dac8162021-02-10 16:35:44 -0800339 auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
340
341 if (dir == NULL) {
342 PLOG(ERROR) << "opendir failed for " << path;
343 goto err;
344 }
345
346 struct dirent* dir_entry;
347 while ((dir_entry = readdir(dir.get()))) {
348 if (!strcmp("..", dir_entry->d_name)) {
349 continue;
350 }
351
352 std::string file_path = path + "/" + dir_entry->d_name;
353
354 if (lchown(file_path.c_str(), uid, gid) < 0) {
355 PLOG(ERROR) << "lchown failed for " << file_path;
356 goto err;
357 }
358
359 if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
360 PLOG(ERROR) << "fchmodat failed for " << file_path;
361 goto err;
362 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800363 }
364
365 return true;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800366err:
367 int saved_errno = errno;
368 rmdir(path.c_str());
369 errno = saved_errno;
370
371 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800372}
373
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000374bool sendSignalToProcessGroup(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000375 std::set<pid_t> pgids, pids;
Inseob Kima049a992022-11-17 23:42:12 +0900376
377 if (CgroupsAvailable()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000378 std::string hierarchy_root_path, cgroup_v2_path;
379 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
380 cgroup_v2_path = ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
381
T.J. Merciera1036302023-11-07 14:36:46 +0000382 if (signal == SIGKILL && CgroupKillAvailable()) {
383 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_KILL_FILE << " to SIGKILL "
384 << cgroup_v2_path;
385
386 // We need to kill the process group in addition to the cgroup. For normal apps they
387 // should completely overlap, but system_server kills depend on process group kills to
388 // take down apps which are in their own cgroups and not individually targeted.
389 if (kill(-initialPid, signal) == -1 && errno != ESRCH) {
390 PLOG(WARNING) << "kill(" << -initialPid << ", " << signal << ") failed";
391 }
392
393 const std::string killfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_KILL_FILE;
394 if (WriteStringToFile("1", killfilepath)) {
395 return true;
396 } else {
397 PLOG(ERROR) << "Failed to write 1 to " << killfilepath;
398 // Fallback to cgroup.procs below
399 }
400 }
401
402 // Since cgroup.kill only sends SIGKILLs, we read cgroup.procs to find each process to
403 // signal individually. This is more costly than using cgroup.kill for SIGKILLs.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000404 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_PROCS_FILE << " to signal (" << signal
405 << ") " << cgroup_v2_path;
406
407 // We separate all of the pids in the cgroup into those pids that are also the leaders of
408 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
409 const auto procsfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
410 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(procsfilepath.c_str(), "re"), fclose);
411 if (!fp) {
412 // This should only happen if the cgroup has already been removed with a successful call
413 // to killProcessGroup. Callers should only retry sendSignalToProcessGroup or
414 // killProcessGroup calls if they fail without ENOENT.
415 PLOG(ERROR) << "Failed to open " << procsfilepath;
416 kill(-initialPid, signal);
417 return false;
Inseob Kima049a992022-11-17 23:42:12 +0900418 }
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000419
Inseob Kima049a992022-11-17 23:42:12 +0900420 pid_t pid;
421 bool file_is_empty = true;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000422 while (fscanf(fp.get(), "%d\n", &pid) == 1 && pid >= 0) {
Inseob Kima049a992022-11-17 23:42:12 +0900423 file_is_empty = false;
424 if (pid == 0) {
425 // Should never happen... but if it does, trying to kill this
426 // will boomerang right back and kill us! Let's not let that happen.
427 LOG(WARNING)
428 << "Yikes, we've been told to kill pid 0! How about we don't do that?";
429 continue;
430 }
431 pid_t pgid = getpgid(pid);
432 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
433 if (pgid == pid) {
434 pgids.emplace(pid);
435 } else {
436 pids.emplace(pid);
437 }
438 }
Jing Ji304c0f12023-02-27 21:58:19 -0800439 if (!file_is_empty) {
440 // Erase all pids that will be killed when we kill the process groups.
441 for (auto it = pids.begin(); it != pids.end();) {
442 pid_t pgid = getpgid(*it);
443 if (pgids.count(pgid) == 1) {
444 it = pids.erase(it);
445 } else {
446 ++it;
447 }
Inseob Kima049a992022-11-17 23:42:12 +0900448 }
449 }
450 }
451
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000452 pgids.emplace(initialPid);
453
Tom Cherry70a5ed42017-06-05 19:20:17 -0700454 // Kill all process groups.
455 for (const auto pgid : pgids) {
456 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
457 << " as part of process cgroup " << initialPid;
458
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800459 if (kill(-pgid, signal) == -1 && errno != ESRCH) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700460 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
461 }
462 }
463
464 // Kill remaining pids.
465 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700466 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
467 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700468
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800469 if (kill(pid, signal) == -1 && errno != ESRCH) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700470 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700471 }
472 }
473
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000474 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700475}
476
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000477template <typename T>
478static std::chrono::milliseconds toMillisec(T&& duration) {
479 return std::chrono::duration_cast<std::chrono::milliseconds>(duration);
480}
481
482enum class populated_status
483{
484 populated,
485 not_populated,
486 error
487};
488
489static populated_status cgroupIsPopulated(int events_fd) {
490 const std::string POPULATED_KEY("populated ");
491 const std::string::size_type MAX_EVENTS_FILE_SIZE = 32;
492
493 std::string buf;
494 buf.resize(MAX_EVENTS_FILE_SIZE);
495 ssize_t len = TEMP_FAILURE_RETRY(pread(events_fd, buf.data(), buf.size(), 0));
496 if (len == -1) {
497 PLOG(ERROR) << "Could not read cgroup.events: ";
498 // Potentially ENODEV if the cgroup has been removed since we opened this file, but that
499 // shouldn't have happened yet.
500 return populated_status::error;
501 }
502
503 if (len == 0) {
504 LOG(ERROR) << "cgroup.events EOF";
505 return populated_status::error;
506 }
507
508 buf.resize(len);
509
510 const std::string::size_type pos = buf.find(POPULATED_KEY);
511 if (pos == std::string::npos) {
512 LOG(ERROR) << "Could not find populated key in cgroup.events";
513 return populated_status::error;
514 }
515
516 if (pos + POPULATED_KEY.size() + 1 > len) {
517 LOG(ERROR) << "Partial read of cgroup.events";
518 return populated_status::error;
519 }
520
521 return buf[pos + POPULATED_KEY.size()] == '1' ?
522 populated_status::populated : populated_status::not_populated;
523}
524
525// The default timeout of 2200ms comes from the default number of retries in a previous
526// implementation of this function. The default retry value was 40 for killing and 400 for cgroup
527// removal with 5ms sleeps between each retry.
528static int KillProcessGroup(
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000529 uid_t uid, pid_t initialPid, int signal, bool once = false,
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000530 std::chrono::steady_clock::time_point until = std::chrono::steady_clock::now() + 2200ms) {
T.J. Mercier29e30f22024-04-18 16:00:11 +0000531 if (uid < 0) {
532 LOG(ERROR) << __func__ << ": invalid UID " << uid;
533 return -1;
534 }
535 if (initialPid <= 0) {
536 LOG(ERROR) << __func__ << ": invalid PID " << initialPid;
537 return -1;
538 }
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700539
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000540 // Always attempt to send a kill signal to at least the initialPid, at least once, regardless of
541 // whether its cgroup exists or not. This should only be necessary if a bug results in the
542 // migration of the targeted process out of its cgroup, which we will also attempt to kill.
543 const bool signal_ret = sendSignalToProcessGroup(uid, initialPid, signal);
544
545 if (!CgroupsAvailable() || !signal_ret) return signal_ret ? 0 : -1;
546
Marco Ballesio4dac8162021-02-10 16:35:44 -0800547 std::string hierarchy_root_path;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000548 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700549
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000550 const std::string cgroup_v2_path =
551 ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700552
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000553 const std::string eventsfile = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_EVENTS_FILE;
554 android::base::unique_fd events_fd(open(eventsfile.c_str(), O_RDONLY));
555 if (events_fd.get() == -1) {
556 PLOG(WARNING) << "Error opening " << eventsfile << " for KillProcessGroup";
Tom Cherry20514c42017-04-21 13:48:49 -0700557 return -1;
558 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000559
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000560 struct pollfd fds = {
561 .fd = events_fd,
562 .events = POLLPRI,
563 };
Tom Cherry20514c42017-04-21 13:48:49 -0700564
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000565 const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700566
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000567 // The primary reason to loop here is to capture any new forks or migrations that could occur
568 // after we send signals to the original set of processes, but before all of those processes
569 // exit and the cgroup becomes unpopulated, or before we remove the cgroup. We try hard to
570 // ensure this completes successfully to avoid permanent memory leaks, but we still place a
571 // large default upper bound on the amount of time we spend in this loop. The amount of CPU
572 // contention, and the amount of work that needs to be done in do_exit for each process
573 // determines how long this will take.
574 int ret;
575 do {
576 populated_status populated;
577 while ((populated = cgroupIsPopulated(events_fd.get())) == populated_status::populated &&
578 std::chrono::steady_clock::now() < until) {
579
580 sendSignalToProcessGroup(uid, initialPid, signal);
581 if (once) {
582 populated = cgroupIsPopulated(events_fd.get());
583 break;
584 }
585
586 const std::chrono::steady_clock::time_point poll_start =
587 std::chrono::steady_clock::now();
588
589 if (poll_start < until)
590 ret = TEMP_FAILURE_RETRY(poll(&fds, 1, toMillisec(until - poll_start).count()));
591
592 if (ret == -1) {
593 // Fallback to 5ms sleeps if poll fails
594 PLOG(ERROR) << "Poll on " << eventsfile << "failed";
595 const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
596 if (now < until)
597 std::this_thread::sleep_for(std::min(5ms, toMillisec(until - now)));
598 }
599
600 LOG(VERBOSE) << "Waited "
601 << toMillisec(std::chrono::steady_clock::now() - poll_start).count()
602 << " ms for " << eventsfile << " poll";
Tom Cherry20514c42017-04-21 13:48:49 -0700603 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800604
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000605 const std::chrono::milliseconds kill_duration =
606 toMillisec(std::chrono::steady_clock::now() - start);
607
608 if (populated == populated_status::populated) {
609 LOG(WARNING) << "Still waiting on process(es) to exit for cgroup " << cgroup_v2_path
610 << " after " << kill_duration.count() << " ms";
611 // We'll still try the cgroup removal below which we expect to log an error.
612 } else if (populated == populated_status::not_populated) {
613 LOG(VERBOSE) << "Killed all processes under cgroup " << cgroup_v2_path
614 << " after " << kill_duration.count() << " ms";
Inseob Kima049a992022-11-17 23:42:12 +0900615 }
616
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000617 ret = RemoveCgroup(hierarchy_root_path.c_str(), uid, initialPid);
618 if (ret)
619 PLOG(ERROR) << "Unable to remove cgroup " << cgroup_v2_path;
620 else
621 LOG(INFO) << "Removed cgroup " << cgroup_v2_path;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800622
623 if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000624 // This per-application memcg v1 case should eventually be removed after migration to
625 // memcg v2.
Bart Van Assche4c957122022-02-04 18:19:45 +0000626 std::string memcg_apps_path;
627 if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000628 (ret = RemoveCgroup(memcg_apps_path.c_str(), uid, initialPid)) < 0) {
629 const auto memcg_v1_cgroup_path =
630 ConvertUidPidToPath(memcg_apps_path.c_str(), uid, initialPid);
631 PLOG(ERROR) << "Unable to remove memcg v1 cgroup " << memcg_v1_cgroup_path;
Bart Van Assche4c957122022-02-04 18:19:45 +0000632 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800633 }
634
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000635 if (once) break;
636 if (std::chrono::steady_clock::now() >= until) break;
637 } while (ret && errno == EBUSY);
638
639 return ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700640}
641
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000642int killProcessGroup(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000643 return KillProcessGroup(uid, initialPid, signal);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700644}
645
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000646int killProcessGroupOnce(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000647 return KillProcessGroup(uid, initialPid, signal, true);
T.J. Mercier22006bf2023-04-13 21:48:55 +0000648}
649
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000650static int createProcessGroupInternal(uid_t uid, pid_t initialPid, std::string cgroup,
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700651 bool activate_controllers) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800652 auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700653
Marco Ballesio9e628a62021-02-11 14:44:53 -0800654 struct stat cgroup_stat;
655 mode_t cgroup_mode = 0750;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000656 uid_t cgroup_uid = AID_SYSTEM;
Bart Van Assche32a9b1c2022-03-10 21:42:40 +0000657 gid_t cgroup_gid = AID_SYSTEM;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700658 int ret = 0;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800659
Bart Van Assche55a9b1e2022-03-23 10:13:18 -0700660 if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
Marco Ballesio9e628a62021-02-11 14:44:53 -0800661 PLOG(ERROR) << "Failed to get stats for " << cgroup;
662 } else {
663 cgroup_mode = cgroup_stat.st_mode;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000664 cgroup_uid = cgroup_stat.st_uid;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800665 cgroup_gid = cgroup_stat.st_gid;
666 }
667
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000668 if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800669 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700670 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700671 }
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700672 if (activate_controllers) {
673 ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
674 if (ret) {
675 LOG(ERROR) << "Failed to activate controllers in " << uid_path;
676 return ret;
677 }
678 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700679
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800680 auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700681
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000682 if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800683 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700684 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700685 }
686
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000687 auto uid_pid_procs_file = uid_pid_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700688
Tom Cherry574a0812018-02-23 13:04:40 -0800689 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700690 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800691 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700692 }
693
Colin Crosscf8d1c22014-06-03 13:24:21 -0700694 return ret;
695}
Robert Benead4852262017-07-16 19:38:11 -0700696
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000697int createProcessGroup(uid_t uid, pid_t initialPid, bool memControl) {
Marco Ballesio4dac8162021-02-10 16:35:44 -0800698 if (memControl && !UsePerAppMemcg()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000699 LOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
Marco Ballesio4dac8162021-02-10 16:35:44 -0800700 return -EINVAL;
701 }
702
Bart Van Assche4c957122022-02-04 18:19:45 +0000703 if (std::string memcg_apps_path;
704 isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
705 // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
706 // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
707 // v1 hierarchy is used.
708 int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800709 if (ret != 0) {
710 return ret;
711 }
712 }
713
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700714 std::string cgroup;
T.J. Merciera99e7d82023-10-27 17:29:01 +0000715 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cgroup);
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700716 return createProcessGroupInternal(uid, initialPid, cgroup, true);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800717}
718
T.J. Mercier1c007992024-01-25 16:29:54 +0000719static bool SetProcessGroupValue(pid_t tid, const std::string& attr_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700720 if (!isMemoryCgroupSupported()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000721 LOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700722 return false;
723 }
724
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800725 std::string path;
726 if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000727 LOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800728 return false;
729 }
Robert Benead4852262017-07-16 19:38:11 -0700730
731 if (!WriteStringToFile(std::to_string(value), path)) {
732 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
733 return false;
734 }
735 return true;
736}
737
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000738bool setProcessGroupSwappiness(uid_t, pid_t pid, int swappiness) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800739 return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700740}
741
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000742bool setProcessGroupSoftLimit(uid_t, pid_t pid, int64_t soft_limit_in_bytes) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800743 return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700744}
745
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000746bool setProcessGroupLimit(uid_t, pid_t pid, int64_t limit_in_bytes) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800747 return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700748}
Marco Ballesio4e644c42021-02-24 16:30:50 -0800749
T.J. Mercier1c007992024-01-25 16:29:54 +0000750bool getAttributePathForTask(const std::string& attr_name, pid_t tid, std::string* path) {
Marco Ballesio4e644c42021-02-24 16:30:50 -0800751 return CgroupGetAttributePathForTask(attr_name, tid, path);
752}
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000753
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000754bool isProfileValidForProcess(const std::string& profile_name, uid_t uid, pid_t pid) {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000755 const TaskProfile* tp = TaskProfiles::GetInstance().GetProfile(profile_name);
756
757 if (tp == nullptr) {
758 return false;
759 }
760
761 return tp->IsValidForProcess(uid, pid);
T.J. Merciera99e7d82023-10-27 17:29:01 +0000762}