blob: 387c104ff4c598e8eab11a7d52c929bae29ad4e8 [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 bool CgroupKillAvailable() {
82 static std::once_flag f;
83 static bool cgroup_kill_available = false;
84 std::call_once(f, []() {
85 std::string cg_kill;
86 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cg_kill);
87 // cgroup.kill is not on the root cgroup, so check a non-root cgroup that should always
88 // exist
89 cg_kill = ConvertUidToPath(cg_kill.c_str(), AID_ROOT) + '/' + PROCESSGROUP_CGROUP_KILL_FILE;
90 cgroup_kill_available = access(cg_kill.c_str(), F_OK) == 0;
91 });
92
93 return cgroup_kill_available;
94}
95
Bart Van Assche4c957122022-02-04 18:19:45 +000096static bool CgroupGetMemcgAppsPath(std::string* path) {
97 CgroupController controller = CgroupMap::GetInstance().FindController("memory");
98
99 if (!controller.HasValue()) {
100 return false;
101 }
102
103 if (path) {
104 *path = controller.path();
105 if (controller.version() == 1) {
106 *path += "/apps";
107 }
108 }
109
110 return true;
111}
112
Suren Baghdasaryan9e3ace52021-06-16 17:01:19 -0700113bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
114 auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
115
116 if (!controller.HasValue()) {
117 return false;
118 }
119
120 if (cgroup_name) {
121 *cgroup_name = controller.name();
122 }
123
124 return true;
125}
126
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800127bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
128 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000129 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800130
131 if (attr == nullptr) {
132 return false;
133 }
134
135 if (path) {
136 *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
137 }
138
139 return true;
140}
141
T.J. Mercier1c007992024-01-25 16:29:54 +0000142bool CgroupGetAttributePathForTask(const std::string& attr_name, pid_t tid, std::string* path) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800143 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000144 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800145
146 if (attr == nullptr) {
147 return false;
148 }
149
150 if (!attr->GetPathForTask(tid, path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000151 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800152 return false;
153 }
154
155 return true;
156}
157
158bool UsePerAppMemcg() {
159 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
160 return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
161}
162
Peter Collingbourned7157c22018-10-30 15:49:33 -0700163static bool isMemoryCgroupSupported() {
Suren Baghdasaryanfa7a05f2019-05-08 17:59:55 -0700164 static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800165
Peter Collingbourned7157c22018-10-30 15:49:33 -0700166 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -0800167}
168
Riddle Hsua6abd822019-06-18 15:53:53 -0600169void DropTaskProfilesResourceCaching() {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800170 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
171 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
Riddle Hsua6abd822019-06-18 15:53:53 -0600172}
173
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800174bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700175 return TaskProfiles::GetInstance().SetProcessProfiles(
176 uid, pid, std::span<const std::string>(profiles), false);
177}
178
179bool SetProcessProfiles(uid_t uid, pid_t pid, std::initializer_list<std::string_view> profiles) {
180 return TaskProfiles::GetInstance().SetProcessProfiles(
181 uid, pid, std::span<const std::string_view>(profiles), false);
182}
183
184bool SetProcessProfiles(uid_t uid, pid_t pid, std::span<const std::string_view> profiles) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800185 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
186}
187
188bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700189 return TaskProfiles::GetInstance().SetProcessProfiles(
190 uid, pid, std::span<const std::string>(profiles), true);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800191}
192
T.J. Mercier1c007992024-01-25 16:29:54 +0000193bool SetTaskProfiles(pid_t tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700194 return TaskProfiles::GetInstance().SetTaskProfiles(tid, std::span<const std::string>(profiles),
195 use_fd_cache);
196}
197
T.J. Mercier1c007992024-01-25 16:29:54 +0000198bool SetTaskProfiles(pid_t tid, std::initializer_list<std::string_view> profiles,
199 bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700200 return TaskProfiles::GetInstance().SetTaskProfiles(
201 tid, std::span<const std::string_view>(profiles), use_fd_cache);
202}
203
T.J. Mercier1c007992024-01-25 16:29:54 +0000204bool SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800205 return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800206}
207
Jiyong Park8bf59402022-04-01 12:24:22 +0900208// C wrapper for SetProcessProfiles.
209// No need to have this in the header file because this function is specifically for crosvm. Crosvm
210// which is written in Rust has its own declaration of this foreign function and doesn't rely on the
211// header. See
212// https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
213extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
214 const char* profiles[]) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700215 std::vector<std::string_view> profiles_;
Jiyong Parkcc9932b2022-04-20 17:11:42 +0900216 profiles_.reserve(num_profiles);
Jiyong Park8bf59402022-04-01 12:24:22 +0900217 for (size_t i = 0; i < num_profiles; i++) {
218 profiles_.emplace_back(profiles[i]);
219 }
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700220 return SetProcessProfiles(uid, pid, std::span<const std::string_view>(profiles_));
Jiyong Park8bf59402022-04-01 12:24:22 +0900221}
222
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000223bool SetUserProfiles(uid_t uid, const std::vector<std::string>& profiles) {
224 return TaskProfiles::GetInstance().SetUserProfiles(uid, std::span<const std::string>(profiles),
225 false);
226}
227
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000228static int RemoveCgroup(const char* cgroup, uid_t uid, pid_t pid) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000229 auto path = ConvertUidPidToPath(cgroup, uid, pid);
230 int ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
Marco Ballesio4dac8162021-02-10 16:35:44 -0800231
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000232 if (!ret && uid >= AID_ISOLATED_START && uid <= AID_ISOLATED_END) {
233 // Isolated UIDs are unlikely to be reused soon after removal,
234 // so free up the kernel resources for the UID level cgroup.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000235 path = ConvertUidToPath(cgroup, uid);
236 ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
237 }
238
239 if (ret < 0 && errno == ENOENT) {
240 // This function is idempoetent, but still warn here.
241 LOG(WARNING) << "RemoveCgroup: " << path << " does not exist.";
242 ret = 0;
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000243 }
244
Colin Crosscf8d1c22014-06-03 13:24:21 -0700245 return ret;
246}
247
Bart Van Assche30488122023-11-15 09:11:20 -0800248static bool RemoveEmptyUidCgroups(const std::string& uid_path) {
Tom Cherry574a0812018-02-23 13:04:40 -0800249 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Wei Wang858f3e52019-02-21 11:25:16 -0800250 bool empty = true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700251 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700252 dirent* dir;
253 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700254 if (dir->d_type != DT_DIR) {
255 continue;
256 }
257
Tom Cherry574a0812018-02-23 13:04:40 -0800258 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700259 continue;
260 }
261
Tom Cherry574a0812018-02-23 13:04:40 -0800262 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700263 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800264 if (rmdir(path.c_str()) == -1) {
265 if (errno != EBUSY) {
266 PLOG(WARNING) << "Failed to remove " << path;
267 }
268 empty = false;
269 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700270 }
271 }
Wei Wang858f3e52019-02-21 11:25:16 -0800272 return empty;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700273}
274
Bart Van Assche30488122023-11-15 09:11:20 -0800275void removeAllEmptyProcessGroups() {
276 LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
277
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800278 std::vector<std::string> cgroups;
Bart Van Assche4c957122022-02-04 18:19:45 +0000279 std::string path, memcg_apps_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800280
T.J. Merciera99e7d82023-10-27 17:29:01 +0000281 if (CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &path)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800282 cgroups.push_back(path);
283 }
Bart Van Assche4c957122022-02-04 18:19:45 +0000284 if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
285 cgroups.push_back(memcg_apps_path);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800286 }
287
288 for (std::string cgroup_root_path : cgroups) {
289 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700290 if (root == NULL) {
Bart Van Assche6e814b02022-02-03 19:24:42 +0000291 PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700292 } else {
293 dirent* dir;
294 while ((dir = readdir(root.get())) != nullptr) {
295 if (dir->d_type != DT_DIR) {
296 continue;
297 }
Tom Cherry574a0812018-02-23 13:04:40 -0800298
Peter Collingbourned7157c22018-10-30 15:49:33 -0700299 if (!StartsWith(dir->d_name, "uid_")) {
300 continue;
301 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700302
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800303 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
Bart Van Assche30488122023-11-15 09:11:20 -0800304 if (!RemoveEmptyUidCgroups(path)) {
Wei Wang858f3e52019-02-21 11:25:16 -0800305 LOG(VERBOSE) << "Skip removing " << path;
306 continue;
307 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700308 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800309 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
310 PLOG(WARNING) << "Failed to remove " << path;
311 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700312 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700313 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700314 }
315}
316
Marco Ballesio4dac8162021-02-10 16:35:44 -0800317/**
318 * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
319 * the user root. Ownership for the newly created cgroup and all of its files must thus be
320 * transferred for the user/group passed as uid/gid before system_server can properly access them.
321 */
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800322static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Suren Baghdasaryan29c9e262021-07-07 10:59:59 -0700323 if (mkdir(path.c_str(), mode) == -1) {
324 if (errno == EEXIST) {
325 // Directory already exists and permissions have been set at the time it was created
326 return true;
327 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800328 return false;
329 }
330
Marco Ballesio4dac8162021-02-10 16:35:44 -0800331 auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
332
333 if (dir == NULL) {
334 PLOG(ERROR) << "opendir failed for " << path;
335 goto err;
336 }
337
338 struct dirent* dir_entry;
339 while ((dir_entry = readdir(dir.get()))) {
340 if (!strcmp("..", dir_entry->d_name)) {
341 continue;
342 }
343
344 std::string file_path = path + "/" + dir_entry->d_name;
345
346 if (lchown(file_path.c_str(), uid, gid) < 0) {
347 PLOG(ERROR) << "lchown failed for " << file_path;
348 goto err;
349 }
350
351 if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
352 PLOG(ERROR) << "fchmodat failed for " << file_path;
353 goto err;
354 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800355 }
356
357 return true;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800358err:
359 int saved_errno = errno;
360 rmdir(path.c_str());
361 errno = saved_errno;
362
363 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800364}
365
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000366bool sendSignalToProcessGroup(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000367 std::set<pid_t> pgids, pids;
Inseob Kima049a992022-11-17 23:42:12 +0900368
369 if (CgroupsAvailable()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000370 std::string hierarchy_root_path, cgroup_v2_path;
371 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
372 cgroup_v2_path = ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
373
T.J. Merciera1036302023-11-07 14:36:46 +0000374 if (signal == SIGKILL && CgroupKillAvailable()) {
375 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_KILL_FILE << " to SIGKILL "
376 << cgroup_v2_path;
377
378 // We need to kill the process group in addition to the cgroup. For normal apps they
379 // should completely overlap, but system_server kills depend on process group kills to
380 // take down apps which are in their own cgroups and not individually targeted.
381 if (kill(-initialPid, signal) == -1 && errno != ESRCH) {
382 PLOG(WARNING) << "kill(" << -initialPid << ", " << signal << ") failed";
383 }
384
385 const std::string killfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_KILL_FILE;
386 if (WriteStringToFile("1", killfilepath)) {
387 return true;
388 } else {
389 PLOG(ERROR) << "Failed to write 1 to " << killfilepath;
390 // Fallback to cgroup.procs below
391 }
392 }
393
394 // Since cgroup.kill only sends SIGKILLs, we read cgroup.procs to find each process to
395 // signal individually. This is more costly than using cgroup.kill for SIGKILLs.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000396 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_PROCS_FILE << " to signal (" << signal
397 << ") " << cgroup_v2_path;
398
399 // We separate all of the pids in the cgroup into those pids that are also the leaders of
400 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
401 const auto procsfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
402 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(procsfilepath.c_str(), "re"), fclose);
403 if (!fp) {
404 // This should only happen if the cgroup has already been removed with a successful call
405 // to killProcessGroup. Callers should only retry sendSignalToProcessGroup or
406 // killProcessGroup calls if they fail without ENOENT.
407 PLOG(ERROR) << "Failed to open " << procsfilepath;
408 kill(-initialPid, signal);
409 return false;
Inseob Kima049a992022-11-17 23:42:12 +0900410 }
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000411
Inseob Kima049a992022-11-17 23:42:12 +0900412 pid_t pid;
413 bool file_is_empty = true;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000414 while (fscanf(fp.get(), "%d\n", &pid) == 1 && pid >= 0) {
Inseob Kima049a992022-11-17 23:42:12 +0900415 file_is_empty = false;
416 if (pid == 0) {
417 // Should never happen... but if it does, trying to kill this
418 // will boomerang right back and kill us! Let's not let that happen.
419 LOG(WARNING)
420 << "Yikes, we've been told to kill pid 0! How about we don't do that?";
421 continue;
422 }
423 pid_t pgid = getpgid(pid);
424 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
425 if (pgid == pid) {
426 pgids.emplace(pid);
427 } else {
428 pids.emplace(pid);
429 }
430 }
Jing Ji304c0f12023-02-27 21:58:19 -0800431 if (!file_is_empty) {
432 // Erase all pids that will be killed when we kill the process groups.
433 for (auto it = pids.begin(); it != pids.end();) {
434 pid_t pgid = getpgid(*it);
435 if (pgids.count(pgid) == 1) {
436 it = pids.erase(it);
437 } else {
438 ++it;
439 }
Inseob Kima049a992022-11-17 23:42:12 +0900440 }
441 }
442 }
443
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000444 pgids.emplace(initialPid);
445
Tom Cherry70a5ed42017-06-05 19:20:17 -0700446 // Kill all process groups.
447 for (const auto pgid : pgids) {
448 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
449 << " as part of process cgroup " << initialPid;
450
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800451 if (kill(-pgid, signal) == -1 && errno != ESRCH) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700452 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
453 }
454 }
455
456 // Kill remaining pids.
457 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700458 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
459 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700460
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800461 if (kill(pid, signal) == -1 && errno != ESRCH) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700462 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700463 }
464 }
465
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000466 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700467}
468
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000469template <typename T>
470static std::chrono::milliseconds toMillisec(T&& duration) {
471 return std::chrono::duration_cast<std::chrono::milliseconds>(duration);
472}
473
474enum class populated_status
475{
476 populated,
477 not_populated,
478 error
479};
480
481static populated_status cgroupIsPopulated(int events_fd) {
482 const std::string POPULATED_KEY("populated ");
483 const std::string::size_type MAX_EVENTS_FILE_SIZE = 32;
484
485 std::string buf;
486 buf.resize(MAX_EVENTS_FILE_SIZE);
487 ssize_t len = TEMP_FAILURE_RETRY(pread(events_fd, buf.data(), buf.size(), 0));
488 if (len == -1) {
489 PLOG(ERROR) << "Could not read cgroup.events: ";
490 // Potentially ENODEV if the cgroup has been removed since we opened this file, but that
491 // shouldn't have happened yet.
492 return populated_status::error;
493 }
494
495 if (len == 0) {
496 LOG(ERROR) << "cgroup.events EOF";
497 return populated_status::error;
498 }
499
500 buf.resize(len);
501
502 const std::string::size_type pos = buf.find(POPULATED_KEY);
503 if (pos == std::string::npos) {
504 LOG(ERROR) << "Could not find populated key in cgroup.events";
505 return populated_status::error;
506 }
507
508 if (pos + POPULATED_KEY.size() + 1 > len) {
509 LOG(ERROR) << "Partial read of cgroup.events";
510 return populated_status::error;
511 }
512
513 return buf[pos + POPULATED_KEY.size()] == '1' ?
514 populated_status::populated : populated_status::not_populated;
515}
516
517// The default timeout of 2200ms comes from the default number of retries in a previous
518// implementation of this function. The default retry value was 40 for killing and 400 for cgroup
519// removal with 5ms sleeps between each retry.
520static int KillProcessGroup(
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000521 uid_t uid, pid_t initialPid, int signal, bool once = false,
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000522 std::chrono::steady_clock::time_point until = std::chrono::steady_clock::now() + 2200ms) {
T.J. Mercier29e30f22024-04-18 16:00:11 +0000523 if (uid < 0) {
524 LOG(ERROR) << __func__ << ": invalid UID " << uid;
525 return -1;
526 }
527 if (initialPid <= 0) {
528 LOG(ERROR) << __func__ << ": invalid PID " << initialPid;
529 return -1;
530 }
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700531
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000532 // Always attempt to send a kill signal to at least the initialPid, at least once, regardless of
533 // whether its cgroup exists or not. This should only be necessary if a bug results in the
534 // migration of the targeted process out of its cgroup, which we will also attempt to kill.
535 const bool signal_ret = sendSignalToProcessGroup(uid, initialPid, signal);
536
537 if (!CgroupsAvailable() || !signal_ret) return signal_ret ? 0 : -1;
538
Marco Ballesio4dac8162021-02-10 16:35:44 -0800539 std::string hierarchy_root_path;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000540 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700541
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000542 const std::string cgroup_v2_path =
543 ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700544
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000545 const std::string eventsfile = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_EVENTS_FILE;
546 android::base::unique_fd events_fd(open(eventsfile.c_str(), O_RDONLY));
547 if (events_fd.get() == -1) {
548 PLOG(WARNING) << "Error opening " << eventsfile << " for KillProcessGroup";
Tom Cherry20514c42017-04-21 13:48:49 -0700549 return -1;
550 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000551
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000552 struct pollfd fds = {
553 .fd = events_fd,
554 .events = POLLPRI,
555 };
Tom Cherry20514c42017-04-21 13:48:49 -0700556
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000557 const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700558
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000559 // The primary reason to loop here is to capture any new forks or migrations that could occur
560 // after we send signals to the original set of processes, but before all of those processes
561 // exit and the cgroup becomes unpopulated, or before we remove the cgroup. We try hard to
562 // ensure this completes successfully to avoid permanent memory leaks, but we still place a
563 // large default upper bound on the amount of time we spend in this loop. The amount of CPU
564 // contention, and the amount of work that needs to be done in do_exit for each process
565 // determines how long this will take.
566 int ret;
567 do {
568 populated_status populated;
569 while ((populated = cgroupIsPopulated(events_fd.get())) == populated_status::populated &&
570 std::chrono::steady_clock::now() < until) {
571
572 sendSignalToProcessGroup(uid, initialPid, signal);
573 if (once) {
574 populated = cgroupIsPopulated(events_fd.get());
575 break;
576 }
577
578 const std::chrono::steady_clock::time_point poll_start =
579 std::chrono::steady_clock::now();
580
581 if (poll_start < until)
582 ret = TEMP_FAILURE_RETRY(poll(&fds, 1, toMillisec(until - poll_start).count()));
583
584 if (ret == -1) {
585 // Fallback to 5ms sleeps if poll fails
586 PLOG(ERROR) << "Poll on " << eventsfile << "failed";
587 const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
588 if (now < until)
589 std::this_thread::sleep_for(std::min(5ms, toMillisec(until - now)));
590 }
591
592 LOG(VERBOSE) << "Waited "
593 << toMillisec(std::chrono::steady_clock::now() - poll_start).count()
594 << " ms for " << eventsfile << " poll";
Tom Cherry20514c42017-04-21 13:48:49 -0700595 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800596
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000597 const std::chrono::milliseconds kill_duration =
598 toMillisec(std::chrono::steady_clock::now() - start);
599
600 if (populated == populated_status::populated) {
601 LOG(WARNING) << "Still waiting on process(es) to exit for cgroup " << cgroup_v2_path
602 << " after " << kill_duration.count() << " ms";
603 // We'll still try the cgroup removal below which we expect to log an error.
604 } else if (populated == populated_status::not_populated) {
605 LOG(VERBOSE) << "Killed all processes under cgroup " << cgroup_v2_path
606 << " after " << kill_duration.count() << " ms";
Inseob Kima049a992022-11-17 23:42:12 +0900607 }
608
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000609 ret = RemoveCgroup(hierarchy_root_path.c_str(), uid, initialPid);
610 if (ret)
611 PLOG(ERROR) << "Unable to remove cgroup " << cgroup_v2_path;
612 else
613 LOG(INFO) << "Removed cgroup " << cgroup_v2_path;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800614
615 if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000616 // This per-application memcg v1 case should eventually be removed after migration to
617 // memcg v2.
Bart Van Assche4c957122022-02-04 18:19:45 +0000618 std::string memcg_apps_path;
619 if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000620 (ret = RemoveCgroup(memcg_apps_path.c_str(), uid, initialPid)) < 0) {
621 const auto memcg_v1_cgroup_path =
622 ConvertUidPidToPath(memcg_apps_path.c_str(), uid, initialPid);
623 PLOG(ERROR) << "Unable to remove memcg v1 cgroup " << memcg_v1_cgroup_path;
Bart Van Assche4c957122022-02-04 18:19:45 +0000624 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800625 }
626
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000627 if (once) break;
628 if (std::chrono::steady_clock::now() >= until) break;
629 } while (ret && errno == EBUSY);
630
631 return ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700632}
633
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000634int killProcessGroup(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000635 return KillProcessGroup(uid, initialPid, signal);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700636}
637
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000638int killProcessGroupOnce(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000639 return KillProcessGroup(uid, initialPid, signal, true);
T.J. Mercier22006bf2023-04-13 21:48:55 +0000640}
641
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000642static int createProcessGroupInternal(uid_t uid, pid_t initialPid, std::string cgroup,
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700643 bool activate_controllers) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800644 auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700645
Marco Ballesio9e628a62021-02-11 14:44:53 -0800646 struct stat cgroup_stat;
647 mode_t cgroup_mode = 0750;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000648 uid_t cgroup_uid = AID_SYSTEM;
Bart Van Assche32a9b1c2022-03-10 21:42:40 +0000649 gid_t cgroup_gid = AID_SYSTEM;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700650 int ret = 0;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800651
Bart Van Assche55a9b1e2022-03-23 10:13:18 -0700652 if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
Marco Ballesio9e628a62021-02-11 14:44:53 -0800653 PLOG(ERROR) << "Failed to get stats for " << cgroup;
654 } else {
655 cgroup_mode = cgroup_stat.st_mode;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000656 cgroup_uid = cgroup_stat.st_uid;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800657 cgroup_gid = cgroup_stat.st_gid;
658 }
659
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000660 if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800661 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700662 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700663 }
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700664 if (activate_controllers) {
665 ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
666 if (ret) {
667 LOG(ERROR) << "Failed to activate controllers in " << uid_path;
668 return ret;
669 }
670 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700671
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800672 auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700673
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000674 if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800675 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700676 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700677 }
678
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000679 auto uid_pid_procs_file = uid_pid_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700680
Tom Cherry574a0812018-02-23 13:04:40 -0800681 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700682 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800683 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700684 }
685
Colin Crosscf8d1c22014-06-03 13:24:21 -0700686 return ret;
687}
Robert Benead4852262017-07-16 19:38:11 -0700688
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000689int createProcessGroup(uid_t uid, pid_t initialPid, bool memControl) {
T.J. Mercier7d9d1712024-04-18 16:05:56 +0000690 if (uid < 0) {
691 LOG(ERROR) << __func__ << ": invalid UID " << uid;
692 return -1;
693 }
694 if (initialPid <= 0) {
695 LOG(ERROR) << __func__ << ": invalid PID " << initialPid;
696 return -1;
697 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800698
699 if (memControl && !UsePerAppMemcg()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000700 LOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
Marco Ballesio4dac8162021-02-10 16:35:44 -0800701 return -EINVAL;
702 }
703
Bart Van Assche4c957122022-02-04 18:19:45 +0000704 if (std::string memcg_apps_path;
705 isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
706 // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
707 // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
708 // v1 hierarchy is used.
709 int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800710 if (ret != 0) {
711 return ret;
712 }
713 }
714
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700715 std::string cgroup;
T.J. Merciera99e7d82023-10-27 17:29:01 +0000716 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cgroup);
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700717 return createProcessGroupInternal(uid, initialPid, cgroup, true);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800718}
719
T.J. Mercier1c007992024-01-25 16:29:54 +0000720static bool SetProcessGroupValue(pid_t tid, const std::string& attr_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700721 if (!isMemoryCgroupSupported()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000722 LOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700723 return false;
724 }
725
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800726 std::string path;
727 if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000728 LOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800729 return false;
730 }
Robert Benead4852262017-07-16 19:38:11 -0700731
732 if (!WriteStringToFile(std::to_string(value), path)) {
733 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
734 return false;
735 }
736 return true;
737}
738
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000739bool setProcessGroupSwappiness(uid_t, pid_t pid, int swappiness) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800740 return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700741}
742
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000743bool setProcessGroupSoftLimit(uid_t, pid_t pid, int64_t soft_limit_in_bytes) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800744 return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700745}
746
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000747bool setProcessGroupLimit(uid_t, pid_t pid, int64_t limit_in_bytes) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800748 return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700749}
Marco Ballesio4e644c42021-02-24 16:30:50 -0800750
T.J. Mercier1c007992024-01-25 16:29:54 +0000751bool getAttributePathForTask(const std::string& attr_name, pid_t tid, std::string* path) {
Marco Ballesio4e644c42021-02-24 16:30:50 -0800752 return CgroupGetAttributePathForTask(attr_name, tid, path);
753}
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000754
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000755bool isProfileValidForProcess(const std::string& profile_name, uid_t uid, pid_t pid) {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000756 const TaskProfile* tp = TaskProfiles::GetInstance().GetProfile(profile_name);
757
758 if (tp == nullptr) {
759 return false;
760 }
761
762 return tp->IsValidForProcess(uid, pid);
T.J. Merciera99e7d82023-10-27 17:29:01 +0000763}