• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 17886459190

20 Sep 2025 06:41AM UTC coverage: 72.176% (-0.1%) from 72.323%
17886459190

push

github

poettering
meson: fix type in comment

As per https://github.com/systemd/systemd/pull/38999#discussion_r2363704203

302286 of 418815 relevant lines covered (72.18%)

1047325.96 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.97
/src/basic/cgroup-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <linux/fs.h>
4
#include <linux/magic.h>
5
#include <signal.h>
6
#include <stdlib.h>
7
#include <sys/xattr.h>
8
#include <threads.h>
9
#include <unistd.h>
10

11
#include "alloc-util.h"
12
#include "capsule-util.h"
13
#include "cgroup-util.h"
14
#include "dirent-util.h"
15
#include "errno-util.h"
16
#include "extract-word.h"
17
#include "fd-util.h"
18
#include "fileio.h"
19
#include "format-util.h"
20
#include "fs-util.h"
21
#include "log.h"
22
#include "login-util.h"
23
#include "parse-util.h"
24
#include "path-util.h"
25
#include "pidref.h"
26
#include "process-util.h"
27
#include "set.h"
28
#include "special.h"
29
#include "stat-util.h"
30
#include "string-table.h"
31
#include "string-util.h"
32
#include "strv.h"
33
#include "unaligned.h"
34
#include "unit-name.h"
35
#include "user-util.h"
36
#include "xattr-util.h"
37

38
/* The structure to pass to name_to_handle_at() on cgroupfs2 */
39
typedef union {
40
        struct file_handle file_handle;
41
        uint8_t space[offsetof(struct file_handle, f_handle) + sizeof(uint64_t)];
42
} cg_file_handle;
43

44
#define CG_FILE_HANDLE_INIT                                     \
45
        (cg_file_handle) {                                      \
46
                .file_handle.handle_bytes = sizeof(uint64_t),   \
47
                .file_handle.handle_type = FILEID_KERNFS,       \
48
        }
49

50
/* The .f_handle field is not aligned to 64bit on some archs, hence read it via an unaligned accessor */
51
#define CG_FILE_HANDLE_CGROUPID(fh) unaligned_read_ne64(fh.file_handle.f_handle)
52

53
int cg_path_open(const char *controller, const char *path) {
828✔
54
        _cleanup_free_ char *fs = NULL;
828✔
55
        int r;
828✔
56

57
        r = cg_get_path(controller, path, /* suffix=*/ NULL, &fs);
828✔
58
        if (r < 0)
828✔
59
                return r;
60

61
        return RET_NERRNO(open(fs, O_DIRECTORY|O_CLOEXEC));
828✔
62
}
63

64
int cg_cgroupid_open(int cgroupfs_fd, uint64_t id) {
1✔
65
        _cleanup_close_ int fsfd = -EBADF;
1✔
66

67
        if (cgroupfs_fd < 0) {
1✔
68
                fsfd = open("/sys/fs/cgroup", O_CLOEXEC|O_DIRECTORY);
×
69
                if (fsfd < 0)
×
70
                        return -errno;
×
71

72
                cgroupfs_fd = fsfd;
73
        }
74

75
        cg_file_handle fh = CG_FILE_HANDLE_INIT;
1✔
76
        unaligned_write_ne64(fh.file_handle.f_handle, id);
1✔
77

78
        return RET_NERRNO(open_by_handle_at(cgroupfs_fd, &fh.file_handle, O_DIRECTORY|O_CLOEXEC));
2✔
79
}
80

81
int cg_path_from_cgroupid(int cgroupfs_fd, uint64_t id, char **ret) {
×
82
        _cleanup_close_ int cgfd = -EBADF;
×
83
        int r;
×
84

85
        cgfd = cg_cgroupid_open(cgroupfs_fd, id);
×
86
        if (cgfd < 0)
×
87
                return cgfd;
88

89
        _cleanup_free_ char *path = NULL;
×
90
        r = fd_get_path(cgfd, &path);
×
91
        if (r < 0)
×
92
                return r;
93

94
        if (!path_startswith(path, "/sys/fs/cgroup/"))
×
95
                return -EXDEV; /* recognizable error */
96

97
        if (ret)
×
98
                *ret = TAKE_PTR(path);
×
99
        return 0;
100
}
101

102
int cg_get_cgroupid_at(int dfd, const char *path, uint64_t *ret) {
4,711✔
103
        cg_file_handle fh = CG_FILE_HANDLE_INIT;
4,711✔
104
        int mnt_id;
4,711✔
105

106
        assert(dfd >= 0 || (dfd == AT_FDCWD && path_is_absolute(path)));
9,395✔
107
        assert(ret);
4,711✔
108

109
        /* This is cgroupfs so we know the size of the handle, thus no need to loop around like
110
         * name_to_handle_at_loop() does in mountpoint-util.c */
111
        if (name_to_handle_at(dfd, strempty(path), &fh.file_handle, &mnt_id, isempty(path) ? AT_EMPTY_PATH : 0) < 0) {
9,422✔
112
                assert(errno != EOVERFLOW);
×
113
                return -errno;
×
114
        }
115

116
        *ret = CG_FILE_HANDLE_CGROUPID(fh);
4,711✔
117
        return 0;
4,711✔
118
}
119

120
int cg_enumerate_processes(const char *controller, const char *path, FILE **ret) {
14,174✔
121
        _cleanup_free_ char *fs = NULL;
14,174✔
122
        FILE *f;
14,174✔
123
        int r;
14,174✔
124

125
        assert(ret);
14,174✔
126

127
        r = cg_get_path(controller, path, "cgroup.procs", &fs);
14,174✔
128
        if (r < 0)
14,174✔
129
                return r;
130

131
        f = fopen(fs, "re");
14,174✔
132
        if (!f)
14,174✔
133
                return -errno;
9,088✔
134

135
        *ret = f;
5,086✔
136
        return 0;
5,086✔
137
}
138

139
int cg_read_pid(FILE *f, pid_t *ret, CGroupFlags flags) {
9,246✔
140
        unsigned long ul;
9,246✔
141

142
        /* Note that the cgroup.procs might contain duplicates! See cgroups.txt for details. */
143

144
        assert(f);
9,246✔
145
        assert(ret);
9,246✔
146

147
        /* NB: The kernel returns ENODEV if we tried to read from cgroup.procs of a cgroup that has been
148
         * removed already. Callers should handle that! */
149

150
        for (;;) {
9,246✔
151
                errno = 0;
9,246✔
152
                if (fscanf(f, "%lu", &ul) != 1) {
9,246✔
153

154
                        if (feof(f)) {
5,301✔
155
                                *ret = 0;
5,301✔
156
                                return 0;
5,301✔
157
                        }
158

159
                        return errno_or_else(EIO);
×
160
                }
161

162
                if (ul > PID_T_MAX)
3,945✔
163
                        return -EIO;
164

165
                /* In some circumstances (e.g. WSL), cgroups might contain unmappable PIDs from other
166
                 * contexts. These show up as zeros, and depending on the caller, can either be plain
167
                 * skipped over, or returned as-is. */
168
                if (ul == 0 && !FLAGS_SET(flags, CGROUP_DONT_SKIP_UNMAPPED))
3,945✔
169
                        continue;
×
170

171
                *ret = (pid_t) ul;
3,945✔
172
                return 1;
3,945✔
173
        }
174
}
175

176
int cg_read_pidref(FILE *f, PidRef *ret, CGroupFlags flags) {
6,310✔
177
        int r;
6,310✔
178

179
        assert(f);
6,310✔
180
        assert(ret);
6,310✔
181

182
        for (;;) {
×
183
                pid_t pid;
6,310✔
184

185
                r = cg_read_pid(f, &pid, flags);
6,310✔
186
                if (r < 0)
6,310✔
187
                        return log_debug_errno(r, "Failed to read pid from cgroup item: %m");
×
188
                if (r == 0) {
6,310✔
189
                        *ret = PIDREF_NULL;
4,710✔
190
                        return 0;
4,710✔
191
                }
192

193
                if (pid == 0)
1,600✔
194
                        return -EREMOTE;
195

196
                r = pidref_set_pid(ret, pid);
1,600✔
197
                if (r >= 0)
1,600✔
198
                        return 1;
199
                if (r != -ESRCH)
×
200
                        return r;
201

202
                /* ESRCH → gone by now? just skip over it, read the next */
203
        }
204
}
205

206
bool cg_kill_supported(void) {
×
207
        static thread_local int supported = -1;
×
208

209
        if (supported >= 0)
×
210
                return supported;
×
211

212
        if (cg_all_unified() <= 0)
×
213
                return (supported = false);
×
214

215
        if (access("/sys/fs/cgroup/init.scope/cgroup.kill", F_OK) >= 0)
×
216
                return (supported = true);
×
217
        if (errno != ENOENT)
×
218
                log_debug_errno(errno, "Failed to check whether cgroup.kill is available, assuming not: %m");
×
219
        return (supported = false);
×
220
}
221

222
int cg_enumerate_subgroups(const char *controller, const char *path, DIR **ret) {
13,753✔
223
        _cleanup_free_ char *fs = NULL;
13,753✔
224
        DIR *d;
13,753✔
225
        int r;
13,753✔
226

227
        assert(ret);
13,753✔
228

229
        /* This is not recursive! */
230

231
        r = cg_get_path(controller, path, NULL, &fs);
13,753✔
232
        if (r < 0)
13,753✔
233
                return r;
234

235
        d = opendir(fs);
13,753✔
236
        if (!d)
13,753✔
237
                return -errno;
9,088✔
238

239
        *ret = d;
4,665✔
240
        return 0;
4,665✔
241
}
242

243
int cg_read_subgroup(DIR *d, char **ret) {
6,027✔
244
        assert(d);
6,027✔
245
        assert(ret);
6,027✔
246

247
        FOREACH_DIRENT_ALL(de, d, return -errno) {
224,705✔
248
                if (de->d_type != DT_DIR)
219,825✔
249
                        continue;
208,918✔
250

251
                if (dot_or_dot_dot(de->d_name))
10,907✔
252
                        continue;
9,760✔
253

254
                return strdup_to_full(ret, de->d_name);
1,147✔
255
        }
256

257
        *ret = NULL;
4,880✔
258
        return 0;
4,880✔
259
}
260

261
int cg_kill(
13,679✔
262
                const char *path,
263
                int sig,
264
                CGroupFlags flags,
265
                Set *killed_pids,
266
                cg_kill_log_func_t log_kill,
267
                void *userdata) {
268

269
        _cleanup_set_free_ Set *allocated_set = NULL;
13,679✔
270
        int r, ret = 0;
13,679✔
271

272
        assert(path);
13,679✔
273
        assert(sig >= 0);
13,679✔
274

275
         /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence
276
          * don't send SIGCONT on SIGKILL. */
277
        if (IN_SET(sig, SIGCONT, SIGKILL))
13,679✔
278
                flags &= ~CGROUP_SIGCONT;
1,965✔
279

280
        /* This goes through the tasks list and kills them all. This is repeated until no further processes
281
         * are added to the tasks list, to properly handle forking processes.
282
         *
283
         * When sending SIGKILL, prefer cg_kill_kernel_sigkill(), which is fully atomic. */
284

285
        if (!killed_pids) {
13,679✔
286
                killed_pids = allocated_set = set_new(NULL);
668✔
287
                if (!killed_pids)
668✔
288
                        return -ENOMEM;
289
        }
290

291
        bool done;
13,759✔
292
        do {
13,759✔
293
                _cleanup_fclose_ FILE *f = NULL;
9,088✔
294
                int ret_log_kill;
13,759✔
295

296
                done = true;
13,759✔
297

298
                r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
13,759✔
299
                if (r == -ENOENT)
13,759✔
300
                        break;
301
                if (r < 0)
4,671✔
302
                        return RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup items: %m"));
×
303

304
                for (;;) {
6,181✔
305
                        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
6,181✔
306

307
                        r = cg_read_pidref(f, &pidref, flags);
6,181✔
308
                        if (r == -ENODEV) {
6,181✔
309
                                /* reading from cgroup.pids will result in ENODEV if the cgroup is
310
                                 * concurrently removed. Just leave in that case, because a removed cgroup
311
                                 * contains no processes anymore. */
312
                                done = true;
313
                                break;
314
                        }
315
                        if (r < 0)
6,181✔
316
                                return RET_GATHER(ret, log_debug_errno(r, "Failed to read pidref from cgroup '%s': %m", path));
×
317
                        if (r == 0)
6,181✔
318
                                break;
319

320
                        if ((flags & CGROUP_IGNORE_SELF) && pidref_is_self(&pidref))
1,510✔
321
                                continue;
669✔
322

323
                        if (set_contains(killed_pids, PID_TO_PTR(pidref.pid)))
841✔
324
                                continue;
603✔
325

326
                        /* Ignore kernel threads to mimic the behavior of cgroup.kill. */
327
                        if (pidref_is_kernel_thread(&pidref) > 0) {
238✔
328
                                log_debug("Ignoring kernel thread with pid " PID_FMT " in cgroup '%s'", pidref.pid, path);
×
329
                                continue;
×
330
                        }
331

332
                        if (log_kill)
238✔
333
                                ret_log_kill = log_kill(&pidref, sig, userdata);
92✔
334

335
                        /* If we haven't killed this process yet, kill it */
336
                        r = pidref_kill(&pidref, sig);
238✔
337
                        if (r < 0 && r != -ESRCH)
238✔
338
                                RET_GATHER(ret, log_debug_errno(r, "Failed to kill process with pid " PID_FMT " from cgroup '%s': %m", pidref.pid, path));
×
339
                        if (r >= 0) {
238✔
340
                                if (flags & CGROUP_SIGCONT)
238✔
341
                                        (void) pidref_kill(&pidref, SIGCONT);
140✔
342

343
                                if (ret == 0) {
238✔
344
                                        if (log_kill)
149✔
345
                                                ret = ret_log_kill;
346
                                        else
347
                                                ret = 1;
57✔
348
                                }
349
                        }
350

351
                        done = false;
238✔
352

353
                        r = set_put(killed_pids, PID_TO_PTR(pidref.pid));
238✔
354
                        if (r < 0)
238✔
355
                                return RET_GATHER(ret, r);
×
356
                }
357

358
                /* To avoid racing against processes which fork quicker than we can kill them, we repeat this
359
                 * until no new pids need to be killed. */
360

361
        } while (!done);
4,671✔
362

363
        return ret;
364
}
365

366
int cg_kill_recursive(
13,009✔
367
                const char *path,
368
                int sig,
369
                CGroupFlags flags,
370
                Set *killed_pids,
371
                cg_kill_log_func_t log_kill,
372
                void *userdata) {
373

374
        _cleanup_set_free_ Set *allocated_set = NULL;
×
375
        _cleanup_closedir_ DIR *d = NULL;
13,009✔
376
        int r, ret;
13,009✔
377

378
        assert(path);
13,009✔
379
        assert(sig >= 0);
13,009✔
380

381
        if (!killed_pids) {
13,009✔
382
                killed_pids = allocated_set = set_new(NULL);
12,529✔
383
                if (!killed_pids)
12,529✔
384
                        return -ENOMEM;
385
        }
386

387
        ret = cg_kill(path, sig, flags, killed_pids, log_kill, userdata);
13,009✔
388

389
        r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
13,009✔
390
        if (r < 0) {
13,009✔
391
                if (r != -ENOENT)
9,088✔
392
                        RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup '%s' subgroups: %m", path));
×
393

394
                return ret;
9,088✔
395
        }
396

397
        for (;;) {
4,141✔
398
                _cleanup_free_ char *fn = NULL, *p = NULL;
4,031✔
399

400
                r = cg_read_subgroup(d, &fn);
4,031✔
401
                if (r < 0) {
4,031✔
402
                        RET_GATHER(ret, log_debug_errno(r, "Failed to read subgroup from cgroup '%s': %m", path));
×
403
                        break;
404
                }
405
                if (r == 0)
4,031✔
406
                        break;
407

408
                p = path_join(empty_to_root(path), fn);
110✔
409
                if (!p)
110✔
410
                        return -ENOMEM;
×
411

412
                r = cg_kill_recursive(p, sig, flags, killed_pids, log_kill, userdata);
110✔
413
                if (r < 0)
110✔
414
                        log_debug_errno(r, "Failed to recursively kill processes in cgroup '%s': %m", p);
×
415
                if (r != 0 && ret >= 0)
110✔
416
                        ret = r;
17✔
417
        }
418

419
        return ret;
3,921✔
420
}
421

422
int cg_kill_kernel_sigkill(const char *path) {
×
423
        _cleanup_free_ char *killfile = NULL;
×
424
        int r;
×
425

426
        /* Kills the cgroup at `path` directly by writing to its cgroup.kill file.  This sends SIGKILL to all
427
         * processes in the cgroup and has the advantage of being completely atomic, unlike cg_kill_items(). */
428

429
        assert(path);
×
430

431
        if (!cg_kill_supported())
×
432
                return -EOPNOTSUPP;
433

434
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.kill", &killfile);
×
435
        if (r < 0)
×
436
                return r;
437

438
        r = write_string_file(killfile, "1", WRITE_STRING_FILE_DISABLE_BUFFER);
×
439
        if (r < 0)
×
440
                return log_debug_errno(r, "Failed to write to cgroup.kill for cgroup '%s': %m", path);
×
441

442
        return 0;
443
}
444

445
static const char *controller_to_dirname(const char *controller) {
×
446
        assert(controller);
×
447

448
        /* Converts a controller name to the directory name below /sys/fs/cgroup/ we want to mount it
449
         * to. Effectively, this just cuts off the name= prefixed used for named hierarchies, if it is
450
         * specified. */
451

452
        if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
×
453
                if (cg_hybrid_unified() > 0)
×
454
                        controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
455
                else
456
                        controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
×
457
        }
458

459
        return startswith(controller, "name=") ?: controller;
×
460
}
461

462
static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **ret) {
×
463
        const char *dn;
×
464
        char *t = NULL;
×
465

466
        assert(ret);
×
467
        assert(controller);
×
468

469
        dn = controller_to_dirname(controller);
×
470

471
        if (isempty(path) && isempty(suffix))
×
472
                t = path_join("/sys/fs/cgroup", dn);
×
473
        else if (isempty(path))
×
474
                t = path_join("/sys/fs/cgroup", dn, suffix);
×
475
        else if (isempty(suffix))
×
476
                t = path_join("/sys/fs/cgroup", dn, path);
×
477
        else
478
                t = path_join("/sys/fs/cgroup", dn, path, suffix);
×
479
        if (!t)
×
480
                return -ENOMEM;
481

482
        *ret = t;
×
483
        return 0;
×
484
}
485

486
static int join_path_unified(const char *path, const char *suffix, char **ret) {
224,900✔
487
        char *t;
224,900✔
488

489
        assert(ret);
224,900✔
490

491
        if (isempty(path) && isempty(suffix))
238,424✔
492
                t = strdup("/sys/fs/cgroup");
1,387✔
493
        else if (isempty(path))
223,513✔
494
                t = path_join("/sys/fs/cgroup", suffix);
12,137✔
495
        else if (isempty(suffix))
211,376✔
496
                t = path_join("/sys/fs/cgroup", path);
83,483✔
497
        else
498
                t = path_join("/sys/fs/cgroup", path, suffix);
127,893✔
499
        if (!t)
224,900✔
500
                return -ENOMEM;
501

502
        *ret = t;
224,900✔
503
        return 0;
224,900✔
504
}
505

506
int cg_get_path(const char *controller, const char *path, const char *suffix, char **ret) {
225,146✔
507
        int r;
225,146✔
508

509
        assert(ret);
225,146✔
510

511
        if (!controller) {
225,146✔
512
                char *t;
246✔
513

514
                /* If no controller is specified, we return the path *below* the controllers, without any
515
                 * prefix. */
516

517
                if (isempty(path) && isempty(suffix))
246✔
518
                        return -EINVAL;
519

520
                if (isempty(suffix))
246✔
521
                        t = strdup(path);
×
522
                else if (isempty(path))
246✔
523
                        t = strdup(suffix);
×
524
                else
525
                        t = path_join(path, suffix);
246✔
526
                if (!t)
246✔
527
                        return -ENOMEM;
528

529
                *ret = path_simplify(t);
246✔
530
                return 0;
246✔
531
        }
532

533
        if (!cg_controller_is_valid(controller))
224,900✔
534
                return -EINVAL;
535

536
        r = cg_all_unified();
224,900✔
537
        if (r < 0)
224,900✔
538
                return r;
539
        if (r > 0)
224,900✔
540
                r = join_path_unified(path, suffix, ret);
224,900✔
541
        else
542
                r = join_path_legacy(controller, path, suffix, ret);
×
543
        if (r < 0)
224,900✔
544
                return r;
545

546
        path_simplify(*ret);
224,900✔
547
        return 0;
224,900✔
548
}
549

550
static int controller_is_v1_accessible(const char *root, const char *controller) {
×
551
        const char *cpath, *dn;
×
552

553
        assert(controller);
×
554

555
        dn = controller_to_dirname(controller);
×
556

557
        /* If root if specified, we check that:
558
         * - possible subcgroup is created at root,
559
         * - we can modify the hierarchy. */
560

561
        cpath = strjoina("/sys/fs/cgroup/", dn, root, root ? "/cgroup.procs" : NULL);
×
562
        return access_nofollow(cpath, root ? W_OK : F_OK);
×
563
}
564

565
int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **ret) {
20,002✔
566
        int r;
20,002✔
567

568
        assert(controller);
20,002✔
569
        assert(ret);
20,002✔
570

571
        if (!cg_controller_is_valid(controller))
20,002✔
572
                return -EINVAL;
573

574
        r = cg_all_unified();
20,002✔
575
        if (r < 0)
20,002✔
576
                return r;
577
        if (r > 0) {
20,002✔
578
                /* In the unified hierarchy all controllers are considered accessible,
579
                 * except for the named hierarchies */
580
                if (startswith(controller, "name="))
20,002✔
581
                        return -EOPNOTSUPP;
582
        } else {
583
                /* Check if the specified controller is actually accessible */
584
                r = controller_is_v1_accessible(NULL, controller);
×
585
                if (r < 0)
×
586
                        return r;
587
        }
588

589
        return cg_get_path(controller, path, suffix, ret);
20,002✔
590
}
591

592
int cg_set_xattr(const char *path, const char *name, const void *value, size_t size, int flags) {
5,989✔
593
        _cleanup_free_ char *fs = NULL;
5,989✔
594
        int r;
5,989✔
595

596
        assert(path);
5,989✔
597
        assert(name);
5,989✔
598
        assert(value || size <= 0);
5,989✔
599

600
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
5,989✔
601
        if (r < 0)
5,989✔
602
                return r;
603

604
        return RET_NERRNO(setxattr(fs, name, value, size, flags));
5,989✔
605
}
606

607
int cg_get_xattr(const char *path, const char *name, char **ret, size_t *ret_size) {
15,761✔
608
        _cleanup_free_ char *fs = NULL;
15,761✔
609
        int r;
15,761✔
610

611
        assert(path);
15,761✔
612
        assert(name);
15,761✔
613

614
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
15,761✔
615
        if (r < 0)
15,761✔
616
                return r;
617

618
        return lgetxattr_malloc(fs, name, ret, ret_size);
15,761✔
619
}
620

621
int cg_get_xattr_bool(const char *path, const char *name) {
167✔
622
        _cleanup_free_ char *fs = NULL;
167✔
623
        int r;
167✔
624

625
        assert(path);
167✔
626
        assert(name);
167✔
627

628
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
167✔
629
        if (r < 0)
167✔
630
                return r;
631

632
        return getxattr_at_bool(AT_FDCWD, fs, name, /* at_flags= */ 0);
167✔
633
}
634

635
int cg_remove_xattr(const char *path, const char *name) {
29,806✔
636
        _cleanup_free_ char *fs = NULL;
29,806✔
637
        int r;
29,806✔
638

639
        assert(path);
29,806✔
640
        assert(name);
29,806✔
641

642
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
29,806✔
643
        if (r < 0)
29,806✔
644
                return r;
645

646
        return RET_NERRNO(removexattr(fs, name));
59,612✔
647
}
648

649
int cg_pid_get_path(const char *controller, pid_t pid, char **ret_path) {
40,354✔
650
        _cleanup_fclose_ FILE *f = NULL;
40,354✔
651
        const char *fs, *controller_str = NULL;  /* avoid false maybe-uninitialized warning */
40,354✔
652
        int unified, r;
40,354✔
653

654
        assert(pid >= 0);
40,354✔
655
        assert(ret_path);
40,354✔
656

657
        if (controller) {
40,354✔
658
                if (!cg_controller_is_valid(controller))
40,158✔
659
                        return -EINVAL;
660
        } else
661
                controller = SYSTEMD_CGROUP_CONTROLLER;
662

663
        unified = cg_unified_controller(controller);
40,354✔
664
        if (unified < 0)
40,354✔
665
                return unified;
666
        if (unified == 0) {
40,354✔
667
                if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
×
668
                        controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
669
                else
670
                        controller_str = controller;
×
671
        }
672

673
        fs = procfs_file_alloca(pid, "cgroup");
46,590✔
674
        r = fopen_unlocked(fs, "re", &f);
40,354✔
675
        if (r == -ENOENT)
40,354✔
676
                return -ESRCH;
677
        if (r < 0)
36,113✔
678
                return r;
679

680
        for (;;) {
36,113✔
681
                _cleanup_free_ char *line = NULL;
36,113✔
682
                char *e;
36,113✔
683

684
                r = read_line(f, LONG_LINE_MAX, &line);
36,113✔
685
                if (r < 0)
36,113✔
686
                        return r;
687
                if (r == 0)
36,106✔
688
                        return -ENODATA;
689

690
                if (unified) {
36,106✔
691
                        e = startswith(line, "0:");
36,106✔
692
                        if (!e)
36,106✔
693
                                continue;
×
694

695
                        e = strchr(e, ':');
36,106✔
696
                        if (!e)
36,106✔
697
                                continue;
×
698
                } else {
699
                        char *l;
×
700

701
                        l = strchr(line, ':');
×
702
                        if (!l)
×
703
                                continue;
×
704

705
                        l++;
×
706
                        e = strchr(l, ':');
×
707
                        if (!e)
×
708
                                continue;
×
709
                        *e = 0;
×
710

711
                        assert(controller_str);
×
712
                        r = string_contains_word(l, ",", controller_str);
×
713
                        if (r < 0)
×
714
                                return r;
715
                        if (r == 0)
×
716
                                continue;
×
717
                }
718

719
                _cleanup_free_ char *path = strdup(e + 1);
36,106✔
720
                if (!path)
36,106✔
721
                        return -ENOMEM;
722

723
                /* Refuse cgroup paths from outside our cgroup namespace */
724
                if (startswith(path, "/../"))
36,106✔
725
                        return -EUNATCH;
726

727
                /* Truncate suffix indicating the process is a zombie */
728
                e = endswith(path, " (deleted)");
36,106✔
729
                if (e)
36,106✔
730
                        *e = 0;
140✔
731

732
                *ret_path = TAKE_PTR(path);
36,106✔
733
                return 0;
36,106✔
734
        }
735
}
736

737
int cg_pidref_get_path(const char *controller, const PidRef *pidref, char **ret_path) {
9,924✔
738
        _cleanup_free_ char *path = NULL;
9,924✔
739
        int r;
9,924✔
740

741
        assert(ret_path);
9,924✔
742

743
        if (!pidref_is_set(pidref))
9,924✔
744
                return -ESRCH;
745
        if (pidref_is_remote(pidref))
19,848✔
746
                return -EREMOTE;
747

748
        // XXX: Ideally we'd use pidfd_get_cgroupid() + cg_path_from_cgroupid() here, to extract this
749
        // bit of information from pidfd directly. However, the latter requires privilege and it's
750
        // not entirely clear how to handle cgroups from outer namespace.
751

752
        r = cg_pid_get_path(controller, pidref->pid, &path);
9,924✔
753
        if (r < 0)
9,924✔
754
                return r;
755

756
        /* Before we return the path, make sure the procfs entry for this pid still matches the pidref */
757
        r = pidref_verify(pidref);
9,922✔
758
        if (r < 0)
9,922✔
759
                return r;
760

761
        *ret_path = TAKE_PTR(path);
9,922✔
762
        return 0;
9,922✔
763
}
764

765
int cg_is_empty(const char *controller, const char *path) {
2,406✔
766
        _cleanup_free_ char *t = NULL;
2,406✔
767
        int r;
2,406✔
768

769
        /* Check if the cgroup hierarchy under 'path' is empty. On cgroup v2 it's exposed via the "populated"
770
         * attribute of "cgroup.events". */
771

772
        assert(path);
2,406✔
773

774
        /* The root cgroup is always populated */
775
        if (empty_or_root(path))
2,406✔
776
                return false;
777

778
        r = cg_get_keyed_attribute(controller, path, "cgroup.events", STRV_MAKE("populated"), &t);
2,406✔
779
        if (r == -ENOENT)
2,406✔
780
                return true;
781
        if (r < 0)
277✔
782
                return r;
783

784
        return streq(t, "0");
277✔
785
}
786

787
int cg_split_spec(const char *spec, char **ret_controller, char **ret_path) {
23✔
788
        _cleanup_free_ char *controller = NULL, *path = NULL;
23✔
789
        int r;
23✔
790

791
        assert(spec);
23✔
792

793
        if (*spec == '/') {
23✔
794
                if (!path_is_normalized(spec))
15✔
795
                        return -EINVAL;
796

797
                if (ret_path) {
15✔
798
                        r = path_simplify_alloc(spec, &path);
15✔
799
                        if (r < 0)
15✔
800
                                return r;
801
                }
802

803
        } else {
804
                const char *e;
8✔
805

806
                e = strchr(spec, ':');
8✔
807
                if (e) {
8✔
808
                        controller = strndup(spec, e-spec);
6✔
809
                        if (!controller)
6✔
810
                                return -ENOMEM;
811
                        if (!cg_controller_is_valid(controller))
6✔
812
                                return -EINVAL;
813

814
                        if (!isempty(e + 1)) {
3✔
815
                                path = strdup(e+1);
2✔
816
                                if (!path)
2✔
817
                                        return -ENOMEM;
818

819
                                if (!path_is_normalized(path) ||
2✔
820
                                    !path_is_absolute(path))
2✔
821
                                        return -EINVAL;
822

823
                                path_simplify(path);
1✔
824
                        }
825

826
                } else {
827
                        if (!cg_controller_is_valid(spec))
2✔
828
                                return -EINVAL;
829

830
                        if (ret_controller) {
1✔
831
                                controller = strdup(spec);
1✔
832
                                if (!controller)
1✔
833
                                        return -ENOMEM;
834
                        }
835
                }
836
        }
837

838
        if (ret_controller)
18✔
839
                *ret_controller = TAKE_PTR(controller);
18✔
840
        if (ret_path)
18✔
841
                *ret_path = TAKE_PTR(path);
18✔
842
        return 0;
843
}
844

845
int cg_mangle_path(const char *path, char **ret) {
435✔
846
        _cleanup_free_ char *c = NULL, *p = NULL;
435✔
847
        int r;
435✔
848

849
        assert(path);
435✔
850
        assert(ret);
435✔
851

852
        /* First, check if it already is a filesystem path */
853
        if (path_startswith(path, "/sys/fs/cgroup"))
435✔
854
                return path_simplify_alloc(path, ret);
431✔
855

856
        /* Otherwise, treat it as cg spec */
857
        r = cg_split_spec(path, &c, &p);
4✔
858
        if (r < 0)
4✔
859
                return r;
860

861
        return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, ret);
8✔
862
}
863

864
int cg_get_root_path(char **ret_path) {
13,063✔
865
        char *p, *e;
13,063✔
866
        int r;
13,063✔
867

868
        assert(ret_path);
13,063✔
869

870
        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
13,063✔
871
        if (r < 0)
13,063✔
872
                return r;
13,063✔
873

874
        e = endswith(p, "/" SPECIAL_INIT_SCOPE);
13,063✔
875
        if (e)
13,063✔
876
                *e = 0;
13,031✔
877

878
        *ret_path = p;
13,063✔
879
        return 0;
13,063✔
880
}
881

882
int cg_shift_path(const char *cgroup, const char *root, const char **ret_shifted) {
11,741✔
883
        int r;
11,741✔
884

885
        assert(cgroup);
11,741✔
886
        assert(ret_shifted);
11,741✔
887

888
        _cleanup_free_ char *rt = NULL;
11,741✔
889
        if (!root) {
11,741✔
890
                /* If the root was specified let's use that, otherwise
891
                 * let's determine it from PID 1 */
892

893
                r = cg_get_root_path(&rt);
1,940✔
894
                if (r < 0)
1,940✔
895
                        return r;
896

897
                root = rt;
1,940✔
898
        }
899

900
        *ret_shifted = path_startswith_full(cgroup, root, PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT) ?: cgroup;
11,741✔
901
        return 0;
11,741✔
902
}
903

904
int cg_pid_get_path_shifted(pid_t pid, const char *root, char **ret_cgroup) {
15,807✔
905
        _cleanup_free_ char *raw = NULL;
15,807✔
906
        const char *c;
15,807✔
907
        int r;
15,807✔
908

909
        assert(pid >= 0);
15,807✔
910
        assert(ret_cgroup);
15,807✔
911

912
        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
15,807✔
913
        if (r < 0)
15,807✔
914
                return r;
915

916
        r = cg_shift_path(raw, root, &c);
11,561✔
917
        if (r < 0)
11,561✔
918
                return r;
919

920
        if (c == raw) {
11,561✔
921
                *ret_cgroup = TAKE_PTR(raw);
11,561✔
922
                return 0;
11,561✔
923
        }
924

925
        return strdup_to(ret_cgroup, c);
×
926
}
927

928
int cg_path_decode_unit(const char *cgroup, char **ret_unit) {
33,465✔
929
        assert(cgroup);
33,465✔
930

931
        size_t n = strcspn(cgroup, "/");
33,465✔
932
        if (n < 3)
33,465✔
933
                return -ENXIO;
934

935
        char *c = strndupa_safe(cgroup, n);
33,439✔
936
        c = cg_unescape(c);
33,439✔
937

938
        if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
33,439✔
939
                return -ENXIO;
940

941
        if (ret_unit)
33,430✔
942
                return strdup_to(ret_unit, c);
33,430✔
943

944
        return 0;
945
}
946

947
static bool valid_slice_name(const char *p, size_t n) {
119,737✔
948
        assert(p || n == 0);
119,737✔
949

950
        if (n < STRLEN("x.slice"))
119,737✔
951
                return false;
952

953
        char *c = strndupa_safe(p, n);
119,668✔
954
        if (!endswith(c, ".slice"))
119,668✔
955
                return false;
956

957
        return unit_name_is_valid(cg_unescape(c), UNIT_NAME_PLAIN);
60,698✔
958
}
959

960
static const char* skip_slices(const char *p) {
42,872✔
961
        assert(p);
42,872✔
962

963
        /* Skips over all slice assignments */
964

965
        for (;;) {
131,188✔
966
                size_t n;
87,030✔
967

968
                p += strspn(p, "/");
87,030✔
969

970
                n = strcspn(p, "/");
87,030✔
971
                if (!valid_slice_name(p, n))
87,030✔
972
                        return p;
42,872✔
973

974
                p += n;
44,158✔
975
        }
976
}
977

978
int cg_path_get_unit_full(const char *path, char **ret_unit, char **ret_subgroup) {
17,552✔
979
        int r;
17,552✔
980

981
        assert(path);
17,552✔
982

983
        const char *e = skip_slices(path);
17,552✔
984

985
        _cleanup_free_ char *unit = NULL;
17,552✔
986
        r = cg_path_decode_unit(e, &unit);
17,552✔
987
        if (r < 0)
17,552✔
988
                return r;
989

990
        /* We skipped over the slices, don't accept any now */
991
        if (endswith(unit, ".slice"))
17,521✔
992
                return -ENXIO;
993

994
        if (ret_subgroup) {
17,521✔
995
                _cleanup_free_ char *subgroup = NULL;
×
996
                e += strcspn(e, "/");
596✔
997
                e += strspn(e, "/");
596✔
998

999
                if (isempty(e))
596✔
1000
                        subgroup = NULL;
1001
                else {
1002
                        subgroup = strdup(e);
232✔
1003
                        if (!subgroup)
232✔
1004
                                return -ENOMEM;
×
1005
                }
1006

1007
                path_simplify(subgroup);
596✔
1008

1009
                *ret_subgroup = TAKE_PTR(subgroup);
596✔
1010
        }
1011

1012
        if (ret_unit)
17,521✔
1013
                *ret_unit = TAKE_PTR(unit);
17,521✔
1014

1015
        return 0;
1016
}
1017

1018
int cg_path_get_unit_path(const char *path, char **ret) {
9,637✔
1019
        _cleanup_free_ char *path_copy = NULL;
9,637✔
1020
        char *unit_name;
9,637✔
1021

1022
        assert(path);
9,637✔
1023
        assert(ret);
9,637✔
1024

1025
        path_copy = strdup(path);
9,637✔
1026
        if (!path_copy)
9,637✔
1027
                return -ENOMEM;
1028

1029
        unit_name = (char*) skip_slices(path_copy);
9,637✔
1030
        unit_name[strcspn(unit_name, "/")] = 0;
9,637✔
1031

1032
        if (!unit_name_is_valid(cg_unescape(unit_name), UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
9,637✔
1033
                return -ENXIO;
1034

1035
        *ret = TAKE_PTR(path_copy);
9,634✔
1036

1037
        return 0;
9,634✔
1038
}
1039

1040
int cg_pid_get_unit_full(pid_t pid, char **ret_unit, char **ret_subgroup) {
667✔
1041
        int r;
667✔
1042

1043
        _cleanup_free_ char *cgroup = NULL;
667✔
1044
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
667✔
1045
        if (r < 0)
667✔
1046
                return r;
1047

1048
        return cg_path_get_unit_full(cgroup, ret_unit, ret_subgroup);
667✔
1049
}
1050

1051
int cg_pidref_get_unit_full(const PidRef *pidref, char **ret_unit, char **ret_subgroup) {
582✔
1052
        int r;
582✔
1053

1054
        if (!pidref_is_set(pidref))
582✔
1055
                return -ESRCH;
582✔
1056
        if (pidref_is_remote(pidref))
1,164✔
1057
                return -EREMOTE;
1058

1059
        _cleanup_free_ char *unit = NULL, *subgroup = NULL;
582✔
1060
        r = cg_pid_get_unit_full(pidref->pid, &unit, &subgroup);
582✔
1061
        if (r < 0)
582✔
1062
                return r;
1063

1064
        r = pidref_verify(pidref);
582✔
1065
        if (r < 0)
582✔
1066
                return r;
1067

1068
        if (ret_unit)
582✔
1069
                *ret_unit = TAKE_PTR(unit);
582✔
1070
        if (ret_subgroup)
582✔
1071
                *ret_subgroup = TAKE_PTR(subgroup);
22✔
1072
        return 0;
1073
}
1074

1075
static const char* skip_session(const char *p) {
15,248✔
1076
        size_t n;
15,248✔
1077

1078
        /* Skip session-*.scope, but require it to be there. */
1079

1080
        if (isempty(p))
15,248✔
1081
                return NULL;
1082

1083
        p += strspn(p, "/");
15,244✔
1084

1085
        n = strcspn(p, "/");
15,244✔
1086
        if (n < STRLEN("session-x.scope"))
15,244✔
1087
                return NULL;
1088

1089
        const char *s = startswith(p, "session-");
15,068✔
1090
        if (!s)
15,068✔
1091
                return NULL;
1092

1093
        /* Note that session scopes never need unescaping, since they cannot conflict with the kernel's
1094
         * own names, hence we don't need to call cg_unescape() here. */
1095
        char *f = strndupa_safe(s, p + n - s),
31✔
1096
             *e = endswith(f, ".scope");
31✔
1097
        if (!e)
31✔
1098
                return NULL;
1099
        *e = '\0';
31✔
1100

1101
        if (!session_id_valid(f))
31✔
1102
                return NULL;
1103

1104
        return skip_leading_slash(p + n);
31✔
1105
}
1106

1107
static const char* skip_user_manager(const char *p) {
15,683✔
1108
        size_t n;
15,683✔
1109

1110
        /* Skip user@*.service or capsule@*.service, but require either of them to be there. */
1111

1112
        if (isempty(p))
15,683✔
1113
                return NULL;
15,683✔
1114

1115
        p += strspn(p, "/");
15,679✔
1116

1117
        n = strcspn(p, "/");
15,679✔
1118
        if (n < CONST_MIN(STRLEN("user@x.service"), STRLEN("capsule@x.service")))
15,679✔
1119
                return NULL;
1120

1121
        /* Any possible errors from functions called below are converted to NULL return, so our callers won't
1122
         * resolve user/capsule name. */
1123
        _cleanup_free_ char *unit_name = strndup(p, n);
15,505✔
1124
        if (!unit_name)
15,505✔
1125
                return NULL;
1126

1127
        _cleanup_free_ char *i = NULL;
15,505✔
1128
        UnitNameFlags type = unit_name_to_instance(unit_name, &i);
15,505✔
1129

1130
        if (type != UNIT_NAME_INSTANCE)
15,505✔
1131
                return NULL;
1132

1133
        /* Note that user manager services never need unescaping, since they cannot conflict with the
1134
         * kernel's own names, hence we don't need to call cg_unescape() here.  Prudently check validity of
1135
         * instance names, they should be always valid as we validate them upon unit start. */
1136
        if (!(startswith(unit_name, "user@") && parse_uid(i, NULL) >= 0) &&
648✔
1137
            !(startswith(unit_name, "capsule@") && capsule_name_is_valid(i) > 0))
114✔
1138
                return NULL;
104✔
1139

1140
        return skip_leading_slash(p + n);
435✔
1141
}
1142

1143
static const char* skip_user_prefix(const char *path) {
15,683✔
1144
        const char *e, *t;
15,683✔
1145

1146
        assert(path);
15,683✔
1147

1148
        /* Skip slices, if there are any */
1149
        e = skip_slices(path);
15,683✔
1150

1151
        /* Skip the user manager, if it's in the path now... */
1152
        t = skip_user_manager(e);
15,683✔
1153
        if (t)
15,683✔
1154
                return t;
1155

1156
        /* Alternatively skip the user session if it is in the path... */
1157
        return skip_session(e);
15,248✔
1158
}
1159

1160
int cg_path_get_user_unit(const char *path, char **ret) {
7,868✔
1161
        const char *t;
7,868✔
1162

1163
        assert(path);
7,868✔
1164

1165
        t = skip_user_prefix(path);
7,868✔
1166
        if (!t)
7,868✔
1167
                return -ENXIO;
1168

1169
        /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1170
         * parser. */
1171
        return cg_path_get_unit(t, ret);
241✔
1172
}
1173

1174
int cg_pid_get_user_unit(pid_t pid, char **ret_unit) {
54✔
1175
        _cleanup_free_ char *cgroup = NULL;
54✔
1176
        int r;
54✔
1177

1178
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
54✔
1179
        if (r < 0)
54✔
1180
                return r;
1181

1182
        return cg_path_get_user_unit(cgroup, ret_unit);
54✔
1183
}
1184

1185
int cg_path_get_machine_name(const char *path, char **ret_machine) {
37✔
1186
        _cleanup_free_ char *u = NULL;
37✔
1187
        const char *sl;
37✔
1188
        int r;
37✔
1189

1190
        r = cg_path_get_unit(path, &u);
37✔
1191
        if (r < 0)
37✔
1192
                return r;
1193

1194
        sl = strjoina("/run/systemd/machines/unit:", u);
185✔
1195
        return readlink_malloc(sl, ret_machine);
37✔
1196
}
1197

1198
int cg_pid_get_machine_name(pid_t pid, char **ret_machine) {
37✔
1199
        _cleanup_free_ char *cgroup = NULL;
37✔
1200
        int r;
37✔
1201

1202
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
37✔
1203
        if (r < 0)
37✔
1204
                return r;
1205

1206
        return cg_path_get_machine_name(cgroup, ret_machine);
37✔
1207
}
1208

1209
int cg_path_get_session(const char *path, char **ret_session) {
8,723✔
1210
        _cleanup_free_ char *unit = NULL;
8,723✔
1211
        char *start, *end;
8,723✔
1212
        int r;
8,723✔
1213

1214
        assert(path);
8,723✔
1215

1216
        r = cg_path_get_unit(path, &unit);
8,723✔
1217
        if (r < 0)
8,723✔
1218
                return r;
1219

1220
        start = startswith(unit, "session-");
8,722✔
1221
        if (!start)
8,722✔
1222
                return -ENXIO;
1223
        end = endswith(start, ".scope");
358✔
1224
        if (!end)
358✔
1225
                return -ENXIO;
1226

1227
        *end = 0;
358✔
1228
        if (!session_id_valid(start))
358✔
1229
                return -ENXIO;
1230

1231
        if (!ret_session)
357✔
1232
                return 0;
1233

1234
        return strdup_to(ret_session, start);
357✔
1235
}
1236

1237
int cg_pid_get_session(pid_t pid, char **ret_session) {
847✔
1238
        _cleanup_free_ char *cgroup = NULL;
847✔
1239
        int r;
847✔
1240

1241
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
847✔
1242
        if (r < 0)
847✔
1243
                return r;
1244

1245
        return cg_path_get_session(cgroup, ret_session);
847✔
1246
}
1247

1248
int cg_pidref_get_session(const PidRef *pidref, char **ret) {
362✔
1249
        int r;
362✔
1250

1251
        if (!pidref_is_set(pidref))
362✔
1252
                return -ESRCH;
362✔
1253
        if (pidref_is_remote(pidref))
724✔
1254
                return -EREMOTE;
1255

1256
        _cleanup_free_ char *session = NULL;
362✔
1257
        r = cg_pid_get_session(pidref->pid, &session);
362✔
1258
        if (r < 0)
362✔
1259
                return r;
1260

1261
        r = pidref_verify(pidref);
311✔
1262
        if (r < 0)
311✔
1263
                return r;
1264

1265
        if (ret)
311✔
1266
                *ret = TAKE_PTR(session);
311✔
1267
        return 0;
1268
}
1269

1270
int cg_path_get_owner_uid(const char *path, uid_t *ret_uid) {
8,076✔
1271
        _cleanup_free_ char *slice = NULL;
8,076✔
1272
        char *start, *end;
8,076✔
1273
        int r;
8,076✔
1274

1275
        assert(path);
8,076✔
1276

1277
        r = cg_path_get_slice(path, &slice);
8,076✔
1278
        if (r < 0)
8,076✔
1279
                return r;
1280

1281
        start = startswith(slice, "user-");
8,076✔
1282
        if (!start)
8,076✔
1283
                return -ENXIO;
1284

1285
        end = endswith(start, ".slice");
337✔
1286
        if (!end)
337✔
1287
                return -ENXIO;
1288

1289
        *end = 0;
337✔
1290
        if (parse_uid(start, ret_uid) < 0)
337✔
1291
                return -ENXIO;
×
1292

1293
        return 0;
1294
}
1295

1296
int cg_pid_get_owner_uid(pid_t pid, uid_t *ret_uid) {
224✔
1297
        _cleanup_free_ char *cgroup = NULL;
224✔
1298
        int r;
224✔
1299

1300
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
224✔
1301
        if (r < 0)
224✔
1302
                return r;
1303

1304
        return cg_path_get_owner_uid(cgroup, ret_uid);
224✔
1305
}
1306

1307
int cg_pidref_get_owner_uid(const PidRef *pidref, uid_t *ret) {
51✔
1308
        int r;
51✔
1309

1310
        if (!pidref_is_set(pidref))
51✔
1311
                return -ESRCH;
51✔
1312
        if (pidref_is_remote(pidref))
51✔
1313
                return -EREMOTE;
1314

1315
        uid_t uid;
51✔
1316
        r = cg_pid_get_owner_uid(pidref->pid, &uid);
51✔
1317
        if (r < 0)
51✔
1318
                return r;
1319

1320
        r = pidref_verify(pidref);
12✔
1321
        if (r < 0)
12✔
1322
                return r;
1323

1324
        if (ret)
12✔
1325
                *ret = uid;
12✔
1326

1327
        return 0;
1328
}
1329

1330
int cg_path_get_slice(const char *p, char **ret_slice) {
16,167✔
1331
        const char *e = NULL;
16,167✔
1332

1333
        assert(p);
16,167✔
1334

1335
        /* Finds the right-most slice unit from the beginning, but stops before we come to
1336
         * the first non-slice unit. */
1337

1338
        for (;;) {
49,247✔
1339
                const char *s;
32,707✔
1340
                int n;
32,707✔
1341

1342
                n = path_find_first_component(&p, /* accept_dot_dot = */ false, &s);
32,707✔
1343
                if (n < 0)
32,707✔
1344
                        return n;
×
1345
                if (!valid_slice_name(s, n))
32,707✔
1346
                        break;
1347

1348
                e = s;
16,540✔
1349
        }
1350

1351
        if (e)
16,167✔
1352
                return cg_path_decode_unit(e, ret_slice);
15,904✔
1353

1354
        if (ret_slice)
263✔
1355
                return strdup_to(ret_slice, SPECIAL_ROOT_SLICE);
263✔
1356

1357
        return 0;
1358
}
1359

1360
int cg_pid_get_slice(pid_t pid, char **ret_slice) {
58✔
1361
        _cleanup_free_ char *cgroup = NULL;
58✔
1362
        int r;
58✔
1363

1364
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
58✔
1365
        if (r < 0)
58✔
1366
                return r;
1367

1368
        return cg_path_get_slice(cgroup, ret_slice);
58✔
1369
}
1370

1371
int cg_path_get_user_slice(const char *p, char **ret_slice) {
7,815✔
1372
        const char *t;
7,815✔
1373
        assert(p);
7,815✔
1374

1375
        t = skip_user_prefix(p);
7,815✔
1376
        if (!t)
7,815✔
1377
                return -ENXIO;
1378

1379
        /* And now it looks pretty much the same as for a system slice, so let's just use the same parser
1380
         * from here on. */
1381
        return cg_path_get_slice(t, ret_slice);
225✔
1382
}
1383

1384
int cg_pid_get_user_slice(pid_t pid, char **ret_slice) {
1✔
1385
        _cleanup_free_ char *cgroup = NULL;
1✔
1386
        int r;
1✔
1387

1388
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1✔
1389
        if (r < 0)
1✔
1390
                return r;
1391

1392
        return cg_path_get_user_slice(cgroup, ret_slice);
1✔
1393
}
1394

1395
bool cg_needs_escape(const char *p) {
21,718✔
1396

1397
        /* Checks if the specified path is a valid cgroup name by our rules, or if it must be escaped. Note
1398
         * that we consider escaped cgroup names invalid here, as they need to be escaped a second time if
1399
         * they shall be used. Also note that various names cannot be made valid by escaping even if we
1400
         * return true here (because too long, or contain the forbidden character "/"). */
1401

1402
        if (!filename_is_valid(p))
21,718✔
1403
                return true;
1404

1405
        if (IN_SET(p[0], '_', '.'))
21,714✔
1406
                return true;
1407

1408
        if (STR_IN_SET(p, "notify_on_release", "release_agent", "tasks"))
21,708✔
1409
                return true;
2✔
1410

1411
        if (startswith(p, "cgroup."))
21,706✔
1412
                return true;
1413

1414
        for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
303,856✔
1415
                const char *q;
282,152✔
1416

1417
                q = startswith(p, cgroup_controller_to_string(c));
282,152✔
1418
                if (!q)
282,152✔
1419
                        continue;
282,152✔
1420

1421
                if (q[0] == '.')
×
1422
                        return true;
1423
        }
1424

1425
        return false;
1426
}
1427

1428
int cg_escape(const char *p, char **ret) {
21,490✔
1429
        _cleanup_free_ char *n = NULL;
21,490✔
1430

1431
        /* This implements very minimal escaping for names to be used as file names in the cgroup tree: any
1432
         * name which might conflict with a kernel name or is prefixed with '_' is prefixed with a '_'. That
1433
         * way, when reading cgroup names it is sufficient to remove a single prefixing underscore if there
1434
         * is one. */
1435

1436
        /* The return value of this function (unlike cg_unescape()) needs free()! */
1437

1438
        if (cg_needs_escape(p)) {
21,490✔
1439
                n = strjoin("_", p);
7✔
1440
                if (!n)
7✔
1441
                        return -ENOMEM;
1442

1443
                if (!filename_is_valid(n)) /* became invalid due to the prefixing? Or contained things like a slash that cannot be fixed by prefixing? */
7✔
1444
                        return -EINVAL;
1445
        } else {
1446
                n = strdup(p);
21,483✔
1447
                if (!n)
21,483✔
1448
                        return -ENOMEM;
1449
        }
1450

1451
        *ret = TAKE_PTR(n);
21,490✔
1452
        return 0;
21,490✔
1453
}
1454

1455
char* cg_unescape(const char *p) {
103,982✔
1456
        assert(p);
103,982✔
1457

1458
        /* The return value of this function (unlike cg_escape())
1459
         * doesn't need free()! */
1460

1461
        if (p[0] == '_')
103,982✔
1462
                return (char*) p+1;
14✔
1463

1464
        return (char*) p;
1465
}
1466

1467
#define CONTROLLER_VALID                        \
1468
        DIGITS LETTERS                          \
1469
        "_"
1470

1471
bool cg_controller_is_valid(const char *p) {
285,078✔
1472
        const char *t, *s;
285,078✔
1473

1474
        if (!p)
285,078✔
1475
                return false;
1476

1477
        if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
285,078✔
1478
                return true;
1479

1480
        s = startswith(p, "name=");
49,495✔
1481
        if (s)
49,495✔
1482
                p = s;
2✔
1483

1484
        if (IN_SET(*p, 0, '_'))
49,495✔
1485
                return false;
1486

1487
        for (t = p; *t; t++)
317,913✔
1488
                if (!strchr(CONTROLLER_VALID, *t))
268,429✔
1489
                        return false;
1490

1491
        if (t - p > NAME_MAX)
49,484✔
1492
                return false;
×
1493

1494
        return true;
1495
}
1496

1497
int cg_slice_to_path(const char *unit, char **ret) {
9,276✔
1498
        _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
9,276✔
1499
        const char *dash;
9,276✔
1500
        int r;
9,276✔
1501

1502
        assert(unit);
9,276✔
1503
        assert(ret);
9,276✔
1504

1505
        if (streq(unit, SPECIAL_ROOT_SLICE))
9,276✔
1506
                return strdup_to(ret, "");
7✔
1507

1508
        if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
9,269✔
1509
                return -EINVAL;
1510

1511
        if (!endswith(unit, ".slice"))
9,258✔
1512
                return -EINVAL;
1513

1514
        r = unit_name_to_prefix(unit, &p);
9,257✔
1515
        if (r < 0)
9,257✔
1516
                return r;
1517

1518
        dash = strchr(p, '-');
9,257✔
1519

1520
        /* Don't allow initial dashes */
1521
        if (dash == p)
9,257✔
1522
                return -EINVAL;
1523

1524
        while (dash) {
9,556✔
1525
                _cleanup_free_ char *escaped = NULL;
304✔
1526
                char n[dash - p + sizeof(".slice")];
304✔
1527

1528
#if HAS_FEATURE_MEMORY_SANITIZER
1529
                /* msan doesn't instrument stpncpy, so it thinks
1530
                 * n is later used uninitialized:
1531
                 * https://github.com/google/sanitizers/issues/926
1532
                 */
1533
                zero(n);
1534
#endif
1535

1536
                /* Don't allow trailing or double dashes */
1537
                if (IN_SET(dash[1], 0, '-'))
304✔
1538
                        return -EINVAL;
1539

1540
                strcpy(stpncpy(n, p, dash - p), ".slice");
302✔
1541
                if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
302✔
1542
                        return -EINVAL;
1543

1544
                r = cg_escape(n, &escaped);
302✔
1545
                if (r < 0)
302✔
1546
                        return r;
1547

1548
                if (!strextend(&s, escaped, "/"))
302✔
1549
                        return -ENOMEM;
1550

1551
                dash = strchr(dash+1, '-');
302✔
1552
        }
1553

1554
        r = cg_escape(unit, &e);
9,252✔
1555
        if (r < 0)
9,252✔
1556
                return r;
1557

1558
        if (!strextend(&s, e))
9,252✔
1559
                return -ENOMEM;
1560

1561
        *ret = TAKE_PTR(s);
9,252✔
1562
        return 0;
9,252✔
1563
}
1564

1565
int cg_is_threaded(const char *path) {
×
1566
        _cleanup_free_ char *fs = NULL, *contents = NULL;
×
1567
        _cleanup_strv_free_ char **v = NULL;
×
1568
        int r;
×
1569

1570
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.type", &fs);
×
1571
        if (r < 0)
×
1572
                return r;
1573

1574
        r = read_full_virtual_file(fs, &contents, NULL);
×
1575
        if (r == -ENOENT)
×
1576
                return false; /* Assume no. */
1577
        if (r < 0)
×
1578
                return r;
1579

1580
        v = strv_split(contents, NULL);
×
1581
        if (!v)
×
1582
                return -ENOMEM;
1583

1584
        /* If the cgroup is in the threaded mode, it contains "threaded".
1585
         * If one of the parents or siblings is in the threaded mode, it may contain "invalid". */
1586
        return strv_contains(v, "threaded") || strv_contains(v, "invalid");
×
1587
}
1588

1589
int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
40,842✔
1590
        _cleanup_free_ char *p = NULL;
40,842✔
1591
        int r;
40,842✔
1592

1593
        assert(attribute);
40,842✔
1594

1595
        r = cg_get_path(controller, path, attribute, &p);
40,842✔
1596
        if (r < 0)
40,842✔
1597
                return r;
1598

1599
        /* https://lore.kernel.org/all/20250419183545.1982187-1-shakeel.butt@linux.dev/ adds O_NONBLOCK
1600
         * semantics to memory.max and memory.high to skip synchronous memory reclaim when O_NONBLOCK is
1601
         * enabled. Let's always open cgroupv2 attribute files in nonblocking mode to immediately take
1602
         * advantage of this and any other asynchronous resource reclaim that's added to the cgroupv2 API in
1603
         * the future. */
1604
        return write_string_file(p, value, WRITE_STRING_FILE_DISABLE_BUFFER|WRITE_STRING_FILE_OPEN_NONBLOCKING);
40,842✔
1605
}
1606

1607
int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
26,458✔
1608
        _cleanup_free_ char *p = NULL;
26,458✔
1609
        int r;
26,458✔
1610

1611
        assert(attribute);
26,458✔
1612

1613
        r = cg_get_path(controller, path, attribute, &p);
26,458✔
1614
        if (r < 0)
26,458✔
1615
                return r;
1616

1617
        return read_one_line_file(p, ret);
26,458✔
1618
}
1619

1620
int cg_get_attribute_as_uint64(const char *controller, const char *path, const char *attribute, uint64_t *ret) {
22,403✔
1621
        _cleanup_free_ char *value = NULL;
22,403✔
1622
        uint64_t v;
22,403✔
1623
        int r;
22,403✔
1624

1625
        assert(ret);
22,403✔
1626

1627
        r = cg_get_attribute(controller, path, attribute, &value);
22,403✔
1628
        if (r == -ENOENT)
22,403✔
1629
                return -ENODATA;
1630
        if (r < 0)
20,434✔
1631
                return r;
1632

1633
        if (streq(value, "max")) {
20,434✔
1634
                *ret = CGROUP_LIMIT_MAX;
4,837✔
1635
                return 0;
4,837✔
1636
        }
1637

1638
        r = safe_atou64(value, &v);
15,597✔
1639
        if (r < 0)
15,597✔
1640
                return r;
1641

1642
        *ret = v;
15,597✔
1643
        return 0;
15,597✔
1644
}
1645

1646
int cg_get_attribute_as_bool(const char *controller, const char *path, const char *attribute) {
61✔
1647
        _cleanup_free_ char *value = NULL;
61✔
1648
        int r;
61✔
1649

1650
        r = cg_get_attribute(controller, path, attribute, &value);
61✔
1651
        if (r == -ENOENT)
61✔
1652
                return -ENODATA;
1653
        if (r < 0)
61✔
1654
                return r;
1655

1656
        return parse_boolean(value);
61✔
1657
}
1658

1659
int cg_get_owner(const char *path, uid_t *ret_uid) {
35✔
1660
        _cleanup_free_ char *f = NULL;
35✔
1661
        struct stat stats;
35✔
1662
        int r;
35✔
1663

1664
        assert(ret_uid);
35✔
1665

1666
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &f);
35✔
1667
        if (r < 0)
35✔
1668
                return r;
1669

1670
        if (stat(f, &stats) < 0)
35✔
1671
                return -errno;
16✔
1672

1673
        r = stat_verify_directory(&stats);
19✔
1674
        if (r < 0)
19✔
1675
                return r;
1676

1677
        *ret_uid = stats.st_uid;
19✔
1678
        return 0;
19✔
1679
}
1680

1681
int cg_get_keyed_attribute(
20,876✔
1682
                const char *controller,
1683
                const char *path,
1684
                const char *attribute,
1685
                char * const *keys,
1686
                char **values) {
1687

1688
        _cleanup_free_ char *filename = NULL, *contents = NULL;
20,876✔
1689
        size_t n;
20,876✔
1690
        int r;
20,876✔
1691

1692
        assert(path);
20,876✔
1693
        assert(attribute);
20,876✔
1694

1695
        /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1696
         * all keys to retrieve. The 'values' parameter should be passed as string size with the same number of
1697
         * entries as 'keys'. On success each entry will be set to the value of the matching key.
1698
         *
1699
         * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
1700

1701
        r = cg_get_path(controller, path, attribute, &filename);
20,876✔
1702
        if (r < 0)
20,876✔
1703
                return r;
1704

1705
        r = read_full_file(filename, &contents, /* ret_size = */ NULL);
20,876✔
1706
        if (r < 0)
20,876✔
1707
                return r;
1708

1709
        n = strv_length(keys);
18,693✔
1710
        if (n == 0) /* No keys to retrieve? That's easy, we are done then */
18,693✔
1711
                return 0;
1712
        assert(strv_is_uniq(keys));
18,693✔
1713

1714
        /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1715
        char **v = newa0(char*, n);
18,693✔
1716
        size_t n_done = 0;
18,693✔
1717

1718
        for (const char *p = contents; *p;) {
62,062✔
1719
                const char *w;
1720
                size_t i;
1721

1722
                for (i = 0; i < n; i++) {
105,439✔
1723
                        w = first_word(p, keys[i]);
68,612✔
1724
                        if (w)
68,612✔
1725
                                break;
1726
                }
1727

1728
                if (w) {
62,060✔
1729
                        if (v[i]) { /* duplicate entry? */
25,233✔
1730
                                r = -EBADMSG;
×
1731
                                goto fail;
×
1732
                        }
1733

1734
                        size_t l = strcspn(w, NEWLINE);
25,233✔
1735

1736
                        v[i] = strndup(w, l);
25,233✔
1737
                        if (!v[i]) {
25,233✔
1738
                                r = -ENOMEM;
×
1739
                                goto fail;
×
1740
                        }
1741

1742
                        n_done++;
25,233✔
1743
                        if (n_done >= n)
25,233✔
1744
                                break;
1745

1746
                        p = w + l;
6,542✔
1747
                } else
1748
                        p += strcspn(p, NEWLINE);
36,827✔
1749

1750
                p += strspn(p, NEWLINE);
43,369✔
1751
        }
1752

1753
        if (n_done < n) {
18,693✔
1754
                r = -ENXIO;
2✔
1755
                goto fail;
2✔
1756
        }
1757

1758
        memcpy(values, v, sizeof(char*) * n);
18,691✔
1759
        return 0;
18,691✔
1760

1761
fail:
2✔
1762
        free_many_charp(v, n);
20,878✔
1763
        return r;
1764
}
1765

1766
int cg_mask_to_string(CGroupMask mask, char **ret) {
8,308✔
1767
        _cleanup_free_ char *s = NULL;
8,308✔
1768
        bool space = false;
8,308✔
1769
        CGroupController c;
8,308✔
1770
        size_t n = 0;
8,308✔
1771

1772
        assert(ret);
8,308✔
1773

1774
        if (mask == 0) {
8,308✔
1775
                *ret = NULL;
4,733✔
1776
                return 0;
4,733✔
1777
        }
1778

1779
        for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
50,050✔
1780
                const char *k;
46,475✔
1781
                size_t l;
46,475✔
1782

1783
                if (!FLAGS_SET(mask, CGROUP_CONTROLLER_TO_MASK(c)))
46,475✔
1784
                        continue;
26,299✔
1785

1786
                k = cgroup_controller_to_string(c);
20,176✔
1787
                l = strlen(k);
20,176✔
1788

1789
                if (!GREEDY_REALLOC(s, n + space + l + 1))
20,176✔
1790
                        return -ENOMEM;
1791

1792
                if (space)
20,176✔
1793
                        s[n] = ' ';
16,601✔
1794
                memcpy(s + n + space, k, l);
20,176✔
1795
                n += space + l;
20,176✔
1796

1797
                space = true;
20,176✔
1798
        }
1799

1800
        assert(s);
3,575✔
1801

1802
        s[n] = 0;
3,575✔
1803
        *ret = TAKE_PTR(s);
3,575✔
1804

1805
        return 0;
3,575✔
1806
}
1807

1808
int cg_mask_from_string(const char *value, CGroupMask *ret) {
3,651✔
1809
        CGroupMask m = 0;
3,651✔
1810

1811
        assert(ret);
3,651✔
1812
        assert(value);
3,651✔
1813

1814
        for (;;) {
24,608✔
1815
                _cleanup_free_ char *n = NULL;
20,957✔
1816
                CGroupController v;
24,608✔
1817
                int r;
24,608✔
1818

1819
                r = extract_first_word(&value, &n, NULL, 0);
24,608✔
1820
                if (r < 0)
24,608✔
1821
                        return r;
×
1822
                if (r == 0)
24,608✔
1823
                        break;
1824

1825
                v = cgroup_controller_from_string(n);
20,957✔
1826
                if (v < 0)
20,957✔
1827
                        continue;
758✔
1828

1829
                m |= CGROUP_CONTROLLER_TO_MASK(v);
20,199✔
1830
        }
1831

1832
        *ret = m;
3,651✔
1833
        return 0;
3,651✔
1834
}
1835

1836
int cg_mask_supported_subtree(const char *root, CGroupMask *ret) {
499✔
1837
        CGroupMask mask;
499✔
1838
        int r;
499✔
1839

1840
        /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
1841
         * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
1842
         * pseudo-controllers. */
1843

1844
        r = cg_all_unified();
499✔
1845
        if (r < 0)
499✔
1846
                return r;
499✔
1847
        if (r > 0) {
499✔
1848
                _cleanup_free_ char *controllers = NULL, *path = NULL;
499✔
1849

1850
                /* In the unified hierarchy we can read the supported and accessible controllers from
1851
                 * the top-level cgroup attribute */
1852

1853
                r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
499✔
1854
                if (r < 0)
499✔
1855
                        return r;
1856

1857
                r = read_one_line_file(path, &controllers);
499✔
1858
                if (r < 0)
499✔
1859
                        return r;
1860

1861
                r = cg_mask_from_string(controllers, &mask);
499✔
1862
                if (r < 0)
499✔
1863
                        return r;
1864

1865
                /* Mask controllers that are not supported in unified hierarchy. */
1866
                mask &= CGROUP_MASK_V2;
499✔
1867

1868
        } else {
1869
                CGroupController c;
×
1870

1871
                /* In the legacy hierarchy, we check which hierarchies are accessible. */
1872

1873
                mask = 0;
×
1874
                for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
×
1875
                        CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
×
1876
                        const char *n;
×
1877

1878
                        if (!FLAGS_SET(CGROUP_MASK_V1, bit))
×
1879
                                continue;
×
1880

1881
                        n = cgroup_controller_to_string(c);
×
1882
                        if (controller_is_v1_accessible(root, n) >= 0)
×
1883
                                mask |= bit;
×
1884
                }
1885
        }
1886

1887
        *ret = mask;
499✔
1888
        return 0;
499✔
1889
}
1890

1891
int cg_mask_supported(CGroupMask *ret) {
247✔
1892
        _cleanup_free_ char *root = NULL;
247✔
1893
        int r;
247✔
1894

1895
        r = cg_get_root_path(&root);
247✔
1896
        if (r < 0)
247✔
1897
                return r;
1898

1899
        return cg_mask_supported_subtree(root, ret);
247✔
1900
}
1901

1902
/* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
1903
 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
1904
 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
1905
 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
1906
 * with other tools.
1907
 *
1908
 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
1909
 * cgroup v2 process management but disable the compat dual layout, we return true on
1910
 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
1911
 */
1912
static thread_local bool unified_systemd_v232;
1913

1914
int cg_unified_cached(bool flush) {
289,778✔
1915
        static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
289,778✔
1916

1917
        struct statfs fs;
289,778✔
1918

1919
        /* Checks if we support the unified hierarchy. Returns an
1920
         * error when the cgroup hierarchies aren't mounted yet or we
1921
         * have any other trouble determining if the unified hierarchy
1922
         * is supported. */
1923

1924
        if (flush)
289,778✔
1925
                unified_cache = CGROUP_UNIFIED_UNKNOWN;
4✔
1926
        else if (unified_cache >= CGROUP_UNIFIED_NONE)
289,774✔
1927
                return unified_cache;
289,778✔
1928

1929
        if (statfs("/sys/fs/cgroup/", &fs) < 0)
13,128✔
1930
                return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
×
1931

1932
        if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
13,128✔
1933
                log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
13,128✔
1934
                unified_cache = CGROUP_UNIFIED_ALL;
13,128✔
1935
        } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
×
1936
                if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
×
1937
                    F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
×
1938
                        log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
×
1939
                        unified_cache = CGROUP_UNIFIED_SYSTEMD;
×
1940
                        unified_systemd_v232 = false;
×
1941
                } else {
1942
                        if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0) {
×
1943
                                if (errno == ENOENT) {
×
1944
                                        /* Some other software may have set up /sys/fs/cgroup in a configuration we do not recognize. */
1945
                                        log_debug_errno(errno, "Unsupported cgroupsv1 setup detected: name=systemd hierarchy not found.");
×
1946
                                        return -ENOMEDIUM;
×
1947
                                }
1948
                                return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
×
1949
                        }
1950

1951
                        if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
×
1952
                                log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
×
1953
                                unified_cache = CGROUP_UNIFIED_SYSTEMD;
×
1954
                                unified_systemd_v232 = true;
×
1955
                        } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
×
1956
                                log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
×
1957
                                unified_cache = CGROUP_UNIFIED_NONE;
×
1958
                        } else {
1959
                                log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
×
1960
                                          (unsigned long long) fs.f_type);
1961
                                unified_cache = CGROUP_UNIFIED_NONE;
×
1962
                        }
1963
                }
1964
        } else if (F_TYPE_EQUAL(fs.f_type, SYSFS_MAGIC)) {
×
1965
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
×
1966
                                       "No filesystem is currently mounted on /sys/fs/cgroup.");
1967
        } else
1968
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
×
1969
                                       "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
1970
                                       (unsigned long long)fs.f_type);
1971

1972
        return unified_cache;
13,128✔
1973
}
1974

1975
int cg_unified_controller(const char *controller) {
40,355✔
1976
        int r;
40,355✔
1977

1978
        r = cg_unified_cached(false);
40,355✔
1979
        if (r < 0)
40,355✔
1980
                return r;
1981

1982
        if (r == CGROUP_UNIFIED_NONE)
40,355✔
1983
                return false;
1984

1985
        if (r >= CGROUP_UNIFIED_ALL)
40,355✔
1986
                return true;
1987

1988
        return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
×
1989
}
1990

1991
int cg_all_unified(void) {
249,417✔
1992
        int r;
249,417✔
1993

1994
        r = cg_unified_cached(false);
249,417✔
1995
        if (r < 0)
249,417✔
1996
                return r;
1997

1998
        return r >= CGROUP_UNIFIED_ALL;
249,417✔
1999
}
2000

2001
int cg_hybrid_unified(void) {
1✔
2002
        int r;
1✔
2003

2004
        r = cg_unified_cached(false);
1✔
2005
        if (r < 0)
1✔
2006
                return r;
2007

2008
        return r == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
1✔
2009
}
2010

2011
int cg_is_delegated(const char *path) {
19✔
2012
        int r;
19✔
2013

2014
        assert(path);
19✔
2015

2016
        r = cg_get_xattr_bool(path, "trusted.delegate");
19✔
2017
        if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
19✔
2018
                return r;
2019

2020
        /* If the trusted xattr isn't set (preferred), then check the untrusted one. Under the assumption
2021
         * that whoever is trusted enough to own the cgroup, is also trusted enough to decide if it is
2022
         * delegated or not this should be safe. */
2023
        r = cg_get_xattr_bool(path, "user.delegate");
6✔
2024
        return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
6✔
2025
}
2026

2027
int cg_is_delegated_fd(int fd) {
199✔
2028
        int r;
199✔
2029

2030
        assert(fd >= 0);
199✔
2031

2032
        r = getxattr_at_bool(fd, /* path= */ NULL, "trusted.delegate", /* at_flags= */ 0);
199✔
2033
        if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
199✔
2034
                return r;
2035

2036
        r = getxattr_at_bool(fd, /* path= */ NULL, "user.delegate", /* at_flags= */ 0);
185✔
2037
        return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
185✔
2038
}
2039

2040
int cg_has_coredump_receive(const char *path) {
2✔
2041
        int r;
2✔
2042

2043
        assert(path);
2✔
2044

2045
        r = cg_get_xattr_bool(path, "user.coredump_receive");
2✔
2046
        if (ERRNO_IS_NEG_XATTR_ABSENT(r))
2✔
2047
                return false;
×
2048

2049
        return r;
2050
}
2051

2052
const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2053
        [CGROUP_IO_RBPS_MAX]  = CGROUP_LIMIT_MAX,
2054
        [CGROUP_IO_WBPS_MAX]  = CGROUP_LIMIT_MAX,
2055
        [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2056
        [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2057
};
2058

2059
static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2060
        [CGROUP_IO_RBPS_MAX]  = "IOReadBandwidthMax",
2061
        [CGROUP_IO_WBPS_MAX]  = "IOWriteBandwidthMax",
2062
        [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2063
        [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2064
};
2065

2066
DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
6,401✔
2067

2068
void cgroup_io_limits_list(void) {
20✔
2069
        DUMP_STRING_TABLE(cgroup_io_limit_type, CGroupIOLimitType, _CGROUP_IO_LIMIT_TYPE_MAX);
100✔
2070
}
20✔
2071

2072
static const char *const cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2073
        [CGROUP_CONTROLLER_CPU]                             = "cpu",
2074
        [CGROUP_CONTROLLER_CPUACCT]                         = "cpuacct",
2075
        [CGROUP_CONTROLLER_CPUSET]                          = "cpuset",
2076
        [CGROUP_CONTROLLER_IO]                              = "io",
2077
        [CGROUP_CONTROLLER_BLKIO]                           = "blkio",
2078
        [CGROUP_CONTROLLER_MEMORY]                          = "memory",
2079
        [CGROUP_CONTROLLER_DEVICES]                         = "devices",
2080
        [CGROUP_CONTROLLER_PIDS]                            = "pids",
2081
        [CGROUP_CONTROLLER_BPF_FIREWALL]                    = "bpf-firewall",
2082
        [CGROUP_CONTROLLER_BPF_DEVICES]                     = "bpf-devices",
2083
        [CGROUP_CONTROLLER_BPF_FOREIGN]                     = "bpf-foreign",
2084
        [CGROUP_CONTROLLER_BPF_SOCKET_BIND]                 = "bpf-socket-bind",
2085
        [CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES] = "bpf-restrict-network-interfaces",
2086
};
2087

2088
DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);
347,903✔
2089

2090
static const char* const managed_oom_mode_table[_MANAGED_OOM_MODE_MAX] = {
2091
        [MANAGED_OOM_AUTO] = "auto",
2092
        [MANAGED_OOM_KILL] = "kill",
2093
};
2094

2095
DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode, ManagedOOMMode);
31,541✔
2096

2097
static const char* const managed_oom_preference_table[_MANAGED_OOM_PREFERENCE_MAX] = {
2098
        [MANAGED_OOM_PREFERENCE_NONE] = "none",
2099
        [MANAGED_OOM_PREFERENCE_AVOID] = "avoid",
2100
        [MANAGED_OOM_PREFERENCE_OMIT] = "omit",
2101
};
2102

2103
DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference, ManagedOOMPreference);
15,509✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc