blob: 95221594b6be7f4545ae406a9190388cd5ac3150 [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>
T.J. Mercier9611c182024-10-25 17:11:02 +000040#include <string_view>
Elliott Hughes290a2282016-11-14 17:08:47 -080041#include <thread>
Colin Crosscf8d1c22014-06-03 13:24:21 -070042
Robert Benead4852262017-07-16 19:38:11 -070043#include <android-base/file.h>
Elliott Hughes171df0a2016-08-02 13:30:30 -070044#include <android-base/logging.h>
Suren Baghdasaryanbc131c32018-05-23 12:30:44 -070045#include <android-base/properties.h>
Tom Cherry574a0812018-02-23 13:04:40 -080046#include <android-base/stringprintf.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::StringPrintf;
Robert Benead4852262017-07-16 19:38:11 -070053using android::base::WriteStringToFile;
54
Elliott Hughes290a2282016-11-14 17:08:47 -080055using namespace std::chrono_literals;
56
T.J. Mercier4928b6e2023-12-14 21:38:23 +000057#define PROCESSGROUP_CGROUP_PROCS_FILE "cgroup.procs"
T.J. Merciera1036302023-11-07 14:36:46 +000058#define PROCESSGROUP_CGROUP_KILL_FILE "cgroup.kill"
T.J. Mercier4928b6e2023-12-14 21:38:23 +000059#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
T.J. Merciera1036302023-11-07 14:36:46 +000080static bool CgroupKillAvailable() {
81 static std::once_flag f;
82 static bool cgroup_kill_available = false;
83 std::call_once(f, []() {
84 std::string cg_kill;
85 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cg_kill);
86 // cgroup.kill is not on the root cgroup, so check a non-root cgroup that should always
87 // exist
88 cg_kill = ConvertUidToPath(cg_kill.c_str(), AID_ROOT) + '/' + PROCESSGROUP_CGROUP_KILL_FILE;
89 cgroup_kill_available = access(cg_kill.c_str(), F_OK) == 0;
90 });
91
92 return cgroup_kill_available;
93}
94
Bart Van Assche4c957122022-02-04 18:19:45 +000095static bool CgroupGetMemcgAppsPath(std::string* path) {
T.J. Mercierfcb86662024-08-01 20:52:30 +000096 CgroupControllerWrapper controller = CgroupMap::GetInstance().FindController("memory");
Bart Van Assche4c957122022-02-04 18:19:45 +000097
98 if (!controller.HasValue()) {
99 return false;
100 }
101
102 if (path) {
103 *path = controller.path();
104 if (controller.version() == 1) {
105 *path += "/apps";
106 }
107 }
108
109 return true;
110}
111
Suren Baghdasaryan9e3ace52021-06-16 17:01:19 -0700112bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
113 auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
114
115 if (!controller.HasValue()) {
116 return false;
117 }
118
119 if (cgroup_name) {
120 *cgroup_name = controller.name();
121 }
122
123 return true;
124}
125
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800126bool CgroupGetAttributePath(const std::string& attr_name, 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 (path) {
135 *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
136 }
137
138 return true;
139}
140
T.J. Mercier1c007992024-01-25 16:29:54 +0000141bool CgroupGetAttributePathForTask(const std::string& attr_name, pid_t tid, std::string* path) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800142 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000143 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800144
145 if (attr == nullptr) {
146 return false;
147 }
148
149 if (!attr->GetPathForTask(tid, path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000150 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800151 return false;
152 }
153
154 return true;
155}
156
157bool UsePerAppMemcg() {
158 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
159 return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
160}
161
Peter Collingbourned7157c22018-10-30 15:49:33 -0700162static bool isMemoryCgroupSupported() {
Suren Baghdasaryanfa7a05f2019-05-08 17:59:55 -0700163 static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800164
Peter Collingbourned7157c22018-10-30 15:49:33 -0700165 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -0800166}
167
Riddle Hsua6abd822019-06-18 15:53:53 -0600168void DropTaskProfilesResourceCaching() {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800169 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
170 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
Riddle Hsua6abd822019-06-18 15:53:53 -0600171}
172
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800173bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700174 return TaskProfiles::GetInstance().SetProcessProfiles(
175 uid, pid, std::span<const std::string>(profiles), false);
176}
177
178bool SetProcessProfiles(uid_t uid, pid_t pid, std::initializer_list<std::string_view> profiles) {
179 return TaskProfiles::GetInstance().SetProcessProfiles(
180 uid, pid, std::span<const std::string_view>(profiles), false);
181}
182
183bool SetProcessProfiles(uid_t uid, pid_t pid, std::span<const std::string_view> profiles) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800184 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
185}
186
187bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700188 return TaskProfiles::GetInstance().SetProcessProfiles(
189 uid, pid, std::span<const std::string>(profiles), true);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800190}
191
T.J. Mercier1c007992024-01-25 16:29:54 +0000192bool SetTaskProfiles(pid_t tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700193 return TaskProfiles::GetInstance().SetTaskProfiles(tid, std::span<const std::string>(profiles),
194 use_fd_cache);
195}
196
T.J. Mercier1c007992024-01-25 16:29:54 +0000197bool SetTaskProfiles(pid_t tid, std::initializer_list<std::string_view> profiles,
198 bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700199 return TaskProfiles::GetInstance().SetTaskProfiles(
200 tid, std::span<const std::string_view>(profiles), use_fd_cache);
201}
202
T.J. Mercier1c007992024-01-25 16:29:54 +0000203bool SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800204 return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800205}
206
Jiyong Park8bf59402022-04-01 12:24:22 +0900207// C wrapper for SetProcessProfiles.
208// No need to have this in the header file because this function is specifically for crosvm. Crosvm
209// which is written in Rust has its own declaration of this foreign function and doesn't rely on the
210// header. See
211// https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
212extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
213 const char* profiles[]) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700214 std::vector<std::string_view> profiles_;
Jiyong Parkcc9932b2022-04-20 17:11:42 +0900215 profiles_.reserve(num_profiles);
Jiyong Park8bf59402022-04-01 12:24:22 +0900216 for (size_t i = 0; i < num_profiles; i++) {
217 profiles_.emplace_back(profiles[i]);
218 }
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700219 return SetProcessProfiles(uid, pid, std::span<const std::string_view>(profiles_));
Jiyong Park8bf59402022-04-01 12:24:22 +0900220}
221
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000222bool SetUserProfiles(uid_t uid, const std::vector<std::string>& profiles) {
223 return TaskProfiles::GetInstance().SetUserProfiles(uid, std::span<const std::string>(profiles),
224 false);
225}
226
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000227static int RemoveCgroup(const char* cgroup, uid_t uid, pid_t pid) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000228 auto path = ConvertUidPidToPath(cgroup, uid, pid);
229 int ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
Marco Ballesio4dac8162021-02-10 16:35:44 -0800230
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000231 if (!ret && uid >= AID_ISOLATED_START && uid <= AID_ISOLATED_END) {
232 // Isolated UIDs are unlikely to be reused soon after removal,
233 // so free up the kernel resources for the UID level cgroup.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000234 path = ConvertUidToPath(cgroup, uid);
235 ret = TEMP_FAILURE_RETRY(rmdir(path.c_str()));
236 }
237
238 if (ret < 0 && errno == ENOENT) {
239 // This function is idempoetent, but still warn here.
240 LOG(WARNING) << "RemoveCgroup: " << path << " does not exist.";
241 ret = 0;
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000242 }
243
Colin Crosscf8d1c22014-06-03 13:24:21 -0700244 return ret;
245}
246
Bart Van Assche30488122023-11-15 09:11:20 -0800247static bool RemoveEmptyUidCgroups(const std::string& uid_path) {
Tom Cherry574a0812018-02-23 13:04:40 -0800248 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Wei Wang858f3e52019-02-21 11:25:16 -0800249 bool empty = true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700250 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700251 dirent* dir;
252 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700253 if (dir->d_type != DT_DIR) {
254 continue;
255 }
256
T.J. Mercier9611c182024-10-25 17:11:02 +0000257 if (!std::string_view(dir->d_name).starts_with("pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700258 continue;
259 }
260
Tom Cherry574a0812018-02-23 13:04:40 -0800261 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700262 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800263 if (rmdir(path.c_str()) == -1) {
264 if (errno != EBUSY) {
265 PLOG(WARNING) << "Failed to remove " << path;
266 }
267 empty = false;
268 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700269 }
270 }
Wei Wang858f3e52019-02-21 11:25:16 -0800271 return empty;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700272}
273
Bart Van Assche30488122023-11-15 09:11:20 -0800274void removeAllEmptyProcessGroups() {
275 LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
276
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800277 std::vector<std::string> cgroups;
Bart Van Assche4c957122022-02-04 18:19:45 +0000278 std::string path, memcg_apps_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800279
T.J. Merciera99e7d82023-10-27 17:29:01 +0000280 if (CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &path)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800281 cgroups.push_back(path);
282 }
Bart Van Assche4c957122022-02-04 18:19:45 +0000283 if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
284 cgroups.push_back(memcg_apps_path);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800285 }
286
287 for (std::string cgroup_root_path : cgroups) {
288 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700289 if (root == NULL) {
Bart Van Assche6e814b02022-02-03 19:24:42 +0000290 PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700291 } else {
292 dirent* dir;
293 while ((dir = readdir(root.get())) != nullptr) {
294 if (dir->d_type != DT_DIR) {
295 continue;
296 }
Tom Cherry574a0812018-02-23 13:04:40 -0800297
T.J. Mercier9611c182024-10-25 17:11:02 +0000298 if (!std::string_view(dir->d_name).starts_with("uid_")) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700299 continue;
300 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700301
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800302 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
Bart Van Assche30488122023-11-15 09:11:20 -0800303 if (!RemoveEmptyUidCgroups(path)) {
Wei Wang858f3e52019-02-21 11:25:16 -0800304 LOG(VERBOSE) << "Skip removing " << path;
305 continue;
306 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700307 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800308 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
309 PLOG(WARNING) << "Failed to remove " << path;
310 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700311 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700312 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700313 }
314}
315
Marco Ballesio4dac8162021-02-10 16:35:44 -0800316/**
317 * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
318 * the user root. Ownership for the newly created cgroup and all of its files must thus be
319 * transferred for the user/group passed as uid/gid before system_server can properly access them.
320 */
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800321static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Suren Baghdasaryan29c9e262021-07-07 10:59:59 -0700322 if (mkdir(path.c_str(), mode) == -1) {
323 if (errno == EEXIST) {
324 // Directory already exists and permissions have been set at the time it was created
325 return true;
326 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800327 return false;
328 }
329
Marco Ballesio4dac8162021-02-10 16:35:44 -0800330 auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
331
332 if (dir == NULL) {
333 PLOG(ERROR) << "opendir failed for " << path;
334 goto err;
335 }
336
337 struct dirent* dir_entry;
338 while ((dir_entry = readdir(dir.get()))) {
339 if (!strcmp("..", dir_entry->d_name)) {
340 continue;
341 }
342
343 std::string file_path = path + "/" + dir_entry->d_name;
344
345 if (lchown(file_path.c_str(), uid, gid) < 0) {
346 PLOG(ERROR) << "lchown failed for " << file_path;
347 goto err;
348 }
349
350 if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
351 PLOG(ERROR) << "fchmodat failed for " << file_path;
352 goto err;
353 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800354 }
355
356 return true;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800357err:
358 int saved_errno = errno;
359 rmdir(path.c_str());
360 errno = saved_errno;
361
362 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800363}
364
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000365bool sendSignalToProcessGroup(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000366 std::set<pid_t> pgids, pids;
Inseob Kima049a992022-11-17 23:42:12 +0900367
368 if (CgroupsAvailable()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000369 std::string hierarchy_root_path, cgroup_v2_path;
370 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
371 cgroup_v2_path = ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
372
T.J. Merciera1036302023-11-07 14:36:46 +0000373 if (signal == SIGKILL && CgroupKillAvailable()) {
374 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_KILL_FILE << " to SIGKILL "
375 << cgroup_v2_path;
376
377 // We need to kill the process group in addition to the cgroup. For normal apps they
378 // should completely overlap, but system_server kills depend on process group kills to
379 // take down apps which are in their own cgroups and not individually targeted.
380 if (kill(-initialPid, signal) == -1 && errno != ESRCH) {
381 PLOG(WARNING) << "kill(" << -initialPid << ", " << signal << ") failed";
382 }
383
384 const std::string killfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_KILL_FILE;
385 if (WriteStringToFile("1", killfilepath)) {
386 return true;
387 } else {
388 PLOG(ERROR) << "Failed to write 1 to " << killfilepath;
389 // Fallback to cgroup.procs below
390 }
391 }
392
393 // Since cgroup.kill only sends SIGKILLs, we read cgroup.procs to find each process to
394 // signal individually. This is more costly than using cgroup.kill for SIGKILLs.
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000395 LOG(VERBOSE) << "Using " << PROCESSGROUP_CGROUP_PROCS_FILE << " to signal (" << signal
396 << ") " << cgroup_v2_path;
397
398 // We separate all of the pids in the cgroup into those pids that are also the leaders of
399 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
400 const auto procsfilepath = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
401 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(procsfilepath.c_str(), "re"), fclose);
402 if (!fp) {
403 // This should only happen if the cgroup has already been removed with a successful call
404 // to killProcessGroup. Callers should only retry sendSignalToProcessGroup or
405 // killProcessGroup calls if they fail without ENOENT.
406 PLOG(ERROR) << "Failed to open " << procsfilepath;
407 kill(-initialPid, signal);
408 return false;
Inseob Kima049a992022-11-17 23:42:12 +0900409 }
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000410
Inseob Kima049a992022-11-17 23:42:12 +0900411 pid_t pid;
412 bool file_is_empty = true;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000413 while (fscanf(fp.get(), "%d\n", &pid) == 1 && pid >= 0) {
Inseob Kima049a992022-11-17 23:42:12 +0900414 file_is_empty = false;
415 if (pid == 0) {
416 // Should never happen... but if it does, trying to kill this
417 // will boomerang right back and kill us! Let's not let that happen.
418 LOG(WARNING)
419 << "Yikes, we've been told to kill pid 0! How about we don't do that?";
420 continue;
421 }
422 pid_t pgid = getpgid(pid);
423 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
424 if (pgid == pid) {
425 pgids.emplace(pid);
426 } else {
427 pids.emplace(pid);
428 }
429 }
Jing Ji304c0f12023-02-27 21:58:19 -0800430 if (!file_is_empty) {
431 // Erase all pids that will be killed when we kill the process groups.
432 for (auto it = pids.begin(); it != pids.end();) {
433 pid_t pgid = getpgid(*it);
434 if (pgids.count(pgid) == 1) {
435 it = pids.erase(it);
436 } else {
437 ++it;
438 }
Inseob Kima049a992022-11-17 23:42:12 +0900439 }
440 }
441 }
442
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000443 pgids.emplace(initialPid);
444
Tom Cherry70a5ed42017-06-05 19:20:17 -0700445 // Kill all process groups.
446 for (const auto pgid : pgids) {
447 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
448 << " as part of process cgroup " << initialPid;
449
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800450 if (kill(-pgid, signal) == -1 && errno != ESRCH) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700451 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
452 }
453 }
454
455 // Kill remaining pids.
456 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700457 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
458 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700459
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800460 if (kill(pid, signal) == -1 && errno != ESRCH) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700461 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700462 }
463 }
464
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000465 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700466}
467
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000468template <typename T>
469static std::chrono::milliseconds toMillisec(T&& duration) {
470 return std::chrono::duration_cast<std::chrono::milliseconds>(duration);
471}
472
473enum class populated_status
474{
475 populated,
476 not_populated,
477 error
478};
479
480static populated_status cgroupIsPopulated(int events_fd) {
481 const std::string POPULATED_KEY("populated ");
482 const std::string::size_type MAX_EVENTS_FILE_SIZE = 32;
483
484 std::string buf;
485 buf.resize(MAX_EVENTS_FILE_SIZE);
486 ssize_t len = TEMP_FAILURE_RETRY(pread(events_fd, buf.data(), buf.size(), 0));
487 if (len == -1) {
488 PLOG(ERROR) << "Could not read cgroup.events: ";
489 // Potentially ENODEV if the cgroup has been removed since we opened this file, but that
490 // shouldn't have happened yet.
491 return populated_status::error;
492 }
493
494 if (len == 0) {
495 LOG(ERROR) << "cgroup.events EOF";
496 return populated_status::error;
497 }
498
499 buf.resize(len);
500
501 const std::string::size_type pos = buf.find(POPULATED_KEY);
502 if (pos == std::string::npos) {
503 LOG(ERROR) << "Could not find populated key in cgroup.events";
504 return populated_status::error;
505 }
506
507 if (pos + POPULATED_KEY.size() + 1 > len) {
508 LOG(ERROR) << "Partial read of cgroup.events";
509 return populated_status::error;
510 }
511
512 return buf[pos + POPULATED_KEY.size()] == '1' ?
513 populated_status::populated : populated_status::not_populated;
514}
515
516// The default timeout of 2200ms comes from the default number of retries in a previous
517// implementation of this function. The default retry value was 40 for killing and 400 for cgroup
518// removal with 5ms sleeps between each retry.
519static int KillProcessGroup(
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000520 uid_t uid, pid_t initialPid, int signal, bool once = false,
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000521 std::chrono::steady_clock::time_point until = std::chrono::steady_clock::now() + 2200ms) {
T.J. Mercier29e30f22024-04-18 16:00:11 +0000522 if (uid < 0) {
523 LOG(ERROR) << __func__ << ": invalid UID " << uid;
524 return -1;
525 }
526 if (initialPid <= 0) {
527 LOG(ERROR) << __func__ << ": invalid PID " << initialPid;
528 return -1;
529 }
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700530
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000531 // Always attempt to send a kill signal to at least the initialPid, at least once, regardless of
532 // whether its cgroup exists or not. This should only be necessary if a bug results in the
533 // migration of the targeted process out of its cgroup, which we will also attempt to kill.
534 const bool signal_ret = sendSignalToProcessGroup(uid, initialPid, signal);
535
536 if (!CgroupsAvailable() || !signal_ret) return signal_ret ? 0 : -1;
537
Marco Ballesio4dac8162021-02-10 16:35:44 -0800538 std::string hierarchy_root_path;
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000539 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700540
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000541 const std::string cgroup_v2_path =
542 ConvertUidPidToPath(hierarchy_root_path.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700543
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000544 const std::string eventsfile = cgroup_v2_path + '/' + PROCESSGROUP_CGROUP_EVENTS_FILE;
545 android::base::unique_fd events_fd(open(eventsfile.c_str(), O_RDONLY));
546 if (events_fd.get() == -1) {
547 PLOG(WARNING) << "Error opening " << eventsfile << " for KillProcessGroup";
Tom Cherry20514c42017-04-21 13:48:49 -0700548 return -1;
549 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000550
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000551 struct pollfd fds = {
552 .fd = events_fd,
553 .events = POLLPRI,
554 };
Tom Cherry20514c42017-04-21 13:48:49 -0700555
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000556 const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700557
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000558 // The primary reason to loop here is to capture any new forks or migrations that could occur
559 // after we send signals to the original set of processes, but before all of those processes
560 // exit and the cgroup becomes unpopulated, or before we remove the cgroup. We try hard to
561 // ensure this completes successfully to avoid permanent memory leaks, but we still place a
562 // large default upper bound on the amount of time we spend in this loop. The amount of CPU
563 // contention, and the amount of work that needs to be done in do_exit for each process
564 // determines how long this will take.
565 int ret;
566 do {
567 populated_status populated;
568 while ((populated = cgroupIsPopulated(events_fd.get())) == populated_status::populated &&
569 std::chrono::steady_clock::now() < until) {
570
571 sendSignalToProcessGroup(uid, initialPid, signal);
572 if (once) {
573 populated = cgroupIsPopulated(events_fd.get());
574 break;
575 }
576
577 const std::chrono::steady_clock::time_point poll_start =
578 std::chrono::steady_clock::now();
579
580 if (poll_start < until)
581 ret = TEMP_FAILURE_RETRY(poll(&fds, 1, toMillisec(until - poll_start).count()));
582
583 if (ret == -1) {
584 // Fallback to 5ms sleeps if poll fails
585 PLOG(ERROR) << "Poll on " << eventsfile << "failed";
586 const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
587 if (now < until)
588 std::this_thread::sleep_for(std::min(5ms, toMillisec(until - now)));
589 }
590
591 LOG(VERBOSE) << "Waited "
592 << toMillisec(std::chrono::steady_clock::now() - poll_start).count()
593 << " ms for " << eventsfile << " poll";
Tom Cherry20514c42017-04-21 13:48:49 -0700594 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800595
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000596 const std::chrono::milliseconds kill_duration =
597 toMillisec(std::chrono::steady_clock::now() - start);
598
599 if (populated == populated_status::populated) {
600 LOG(WARNING) << "Still waiting on process(es) to exit for cgroup " << cgroup_v2_path
601 << " after " << kill_duration.count() << " ms";
602 // We'll still try the cgroup removal below which we expect to log an error.
603 } else if (populated == populated_status::not_populated) {
604 LOG(VERBOSE) << "Killed all processes under cgroup " << cgroup_v2_path
605 << " after " << kill_duration.count() << " ms";
Inseob Kima049a992022-11-17 23:42:12 +0900606 }
607
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000608 ret = RemoveCgroup(hierarchy_root_path.c_str(), uid, initialPid);
609 if (ret)
610 PLOG(ERROR) << "Unable to remove cgroup " << cgroup_v2_path;
611 else
612 LOG(INFO) << "Removed cgroup " << cgroup_v2_path;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800613
614 if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000615 // This per-application memcg v1 case should eventually be removed after migration to
616 // memcg v2.
Bart Van Assche4c957122022-02-04 18:19:45 +0000617 std::string memcg_apps_path;
618 if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000619 (ret = RemoveCgroup(memcg_apps_path.c_str(), uid, initialPid)) < 0) {
620 const auto memcg_v1_cgroup_path =
621 ConvertUidPidToPath(memcg_apps_path.c_str(), uid, initialPid);
622 PLOG(ERROR) << "Unable to remove memcg v1 cgroup " << memcg_v1_cgroup_path;
Bart Van Assche4c957122022-02-04 18:19:45 +0000623 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800624 }
625
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000626 if (once) break;
627 if (std::chrono::steady_clock::now() >= until) break;
628 } while (ret && errno == EBUSY);
629
630 return ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700631}
632
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000633int killProcessGroup(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000634 return KillProcessGroup(uid, initialPid, signal);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700635}
636
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000637int killProcessGroupOnce(uid_t uid, pid_t initialPid, int signal) {
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000638 return KillProcessGroup(uid, initialPid, signal, true);
T.J. Mercier22006bf2023-04-13 21:48:55 +0000639}
640
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000641static int createProcessGroupInternal(uid_t uid, pid_t initialPid, std::string cgroup,
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700642 bool activate_controllers) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800643 auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700644
Marco Ballesio9e628a62021-02-11 14:44:53 -0800645 struct stat cgroup_stat;
646 mode_t cgroup_mode = 0750;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000647 uid_t cgroup_uid = AID_SYSTEM;
Bart Van Assche32a9b1c2022-03-10 21:42:40 +0000648 gid_t cgroup_gid = AID_SYSTEM;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700649 int ret = 0;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800650
Bart Van Assche55a9b1e2022-03-23 10:13:18 -0700651 if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
Marco Ballesio9e628a62021-02-11 14:44:53 -0800652 PLOG(ERROR) << "Failed to get stats for " << cgroup;
653 } else {
654 cgroup_mode = cgroup_stat.st_mode;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000655 cgroup_uid = cgroup_stat.st_uid;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800656 cgroup_gid = cgroup_stat.st_gid;
657 }
658
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000659 if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800660 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700661 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700662 }
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700663 if (activate_controllers) {
T.J. Mercier787ddbc2024-10-08 23:41:34 +0000664 if (!CgroupMap::GetInstance().ActivateControllers(uid_path)) {
665 PLOG(ERROR) << "Failed to activate controllers in " << uid_path;
666 return -errno;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700667 }
668 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700669
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800670 auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700671
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000672 if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800673 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700674 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700675 }
676
T.J. Mercier4928b6e2023-12-14 21:38:23 +0000677 auto uid_pid_procs_file = uid_pid_path + '/' + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700678
Tom Cherry574a0812018-02-23 13:04:40 -0800679 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700680 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800681 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700682 }
683
Colin Crosscf8d1c22014-06-03 13:24:21 -0700684 return ret;
685}
Robert Benead4852262017-07-16 19:38:11 -0700686
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000687int createProcessGroup(uid_t uid, pid_t initialPid, bool memControl) {
T.J. Mercier7d9d1712024-04-18 16:05:56 +0000688 if (uid < 0) {
689 LOG(ERROR) << __func__ << ": invalid UID " << uid;
690 return -1;
691 }
692 if (initialPid <= 0) {
693 LOG(ERROR) << __func__ << ": invalid PID " << initialPid;
694 return -1;
695 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800696
697 if (memControl && !UsePerAppMemcg()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000698 LOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
Marco Ballesio4dac8162021-02-10 16:35:44 -0800699 return -EINVAL;
700 }
701
Bart Van Assche4c957122022-02-04 18:19:45 +0000702 if (std::string memcg_apps_path;
703 isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
704 // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
705 // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
706 // v1 hierarchy is used.
707 int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800708 if (ret != 0) {
709 return ret;
710 }
711 }
712
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700713 std::string cgroup;
T.J. Merciera99e7d82023-10-27 17:29:01 +0000714 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cgroup);
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700715 return createProcessGroupInternal(uid, initialPid, cgroup, true);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800716}
717
T.J. Mercier1c007992024-01-25 16:29:54 +0000718static bool SetProcessGroupValue(pid_t tid, const std::string& attr_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700719 if (!isMemoryCgroupSupported()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000720 LOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700721 return false;
722 }
723
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800724 std::string path;
725 if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000726 LOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800727 return false;
728 }
Robert Benead4852262017-07-16 19:38:11 -0700729
730 if (!WriteStringToFile(std::to_string(value), path)) {
731 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
732 return false;
733 }
734 return true;
735}
736
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000737bool setProcessGroupSwappiness(uid_t, pid_t pid, int swappiness) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800738 return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700739}
740
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000741bool setProcessGroupSoftLimit(uid_t, pid_t pid, int64_t soft_limit_in_bytes) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800742 return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700743}
744
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000745bool setProcessGroupLimit(uid_t, pid_t pid, int64_t limit_in_bytes) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800746 return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700747}
Marco Ballesio4e644c42021-02-24 16:30:50 -0800748
T.J. Mercier1c007992024-01-25 16:29:54 +0000749bool getAttributePathForTask(const std::string& attr_name, pid_t tid, std::string* path) {
Marco Ballesio4e644c42021-02-24 16:30:50 -0800750 return CgroupGetAttributePathForTask(attr_name, tid, path);
751}
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000752
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000753bool isProfileValidForProcess(const std::string& profile_name, uid_t uid, pid_t pid) {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000754 const TaskProfile* tp = TaskProfiles::GetInstance().GetProfile(profile_name);
755
756 if (tp == nullptr) {
757 return false;
758 }
759
760 return tp->IsValidForProcess(uid, pid);
T.J. Merciera99e7d82023-10-27 17:29:01 +0000761}