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

systemd / systemd / 22081376732

16 Feb 2026 09:47PM UTC coverage: 72.633% (+0.2%) from 72.384%
22081376732

push

github

web-flow
report: enforce metric prefix (#40647)

Addressing
> we should enforce that metrics ids begin with the varlink service name

from #40633

48 of 59 new or added lines in 1 file covered. (81.36%)

3079 existing lines in 84 files now uncovered.

312905 of 430802 relevant lines covered (72.63%)

1136024.03 hits per line

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

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

3
#include <linux/oom.h>
4
#include <pthread.h>
5
#include <spawn.h>
6
#include <stdio.h>
7
#include <sys/mman.h>
8
#include <sys/mount.h>
9
#include <sys/personality.h>
10
#include <sys/prctl.h>
11
#include <sys/wait.h>
12
#include <syslog.h>
13
#include <threads.h>
14
#include <unistd.h>
15
#if HAVE_VALGRIND_VALGRIND_H
16
#include <valgrind/valgrind.h>
17
#endif
18

19
#include "sd-messages.h"
20

21
#include "alloc-util.h"
22
#include "architecture.h"
23
#include "argv-util.h"
24
#include "capability-util.h"
25
#include "cgroup-util.h"
26
#include "dirent-util.h"
27
#include "dlfcn-util.h"
28
#include "env-file.h"
29
#include "errno-util.h"
30
#include "escape.h"
31
#include "fd-util.h"
32
#include "fileio.h"
33
#include "fs-util.h"
34
#include "hostname-util.h"
35
#include "io-util.h"
36
#include "iovec-util.h"
37
#include "locale-util.h"
38
#include "log.h"
39
#include "memory-util.h"
40
#include "mountpoint-util.h"
41
#include "namespace-util.h"
42
#include "nulstr-util.h"
43
#include "parse-util.h"
44
#include "path-util.h"
45
#include "pidfd-util.h"
46
#include "pidref.h"
47
#include "process-util.h"
48
#include "raw-clone.h"
49
#include "rlimit-util.h"
50
#include "signal-util.h"
51
#include "socket-util.h"
52
#include "stat-util.h"
53
#include "stdio-util.h"
54
#include "string-table.h"
55
#include "string-util.h"
56
#include "time-util.h"
57
#include "user-util.h"
58

59
/* The kernel limits userspace processes to TASK_COMM_LEN (16 bytes), but allows higher values for its own
60
 * workers, e.g. "kworker/u9:3-kcryptd/253:0". Let's pick a fixed smallish limit that will work for the kernel.
61
 */
62
#define COMM_MAX_LEN 128
63

64
static int get_process_state(pid_t pid) {
13,239✔
65
        _cleanup_free_ char *line = NULL;
13,239✔
66
        const char *p;
13,239✔
67
        char state;
13,239✔
68
        int r;
13,239✔
69

70
        assert(pid >= 0);
13,239✔
71

72
        /* Shortcut: if we are enquired about our own state, we are obviously running */
73
        if (pid == 0 || pid == getpid_cached())
13,239✔
74
                return (unsigned char) 'R';
×
75

76
        p = procfs_file_alloca(pid, "stat");
13,239✔
77

78
        r = read_one_line_file(p, &line);
13,239✔
79
        if (r == -ENOENT)
13,239✔
80
                return -ESRCH;
81
        if (r < 0)
10,386✔
82
                return r;
83

84
        p = strrchr(line, ')');
10,385✔
85
        if (!p)
10,385✔
86
                return -EIO;
87

88
        p++;
10,385✔
89

90
        if (sscanf(p, " %c", &state) != 1)
10,385✔
91
                return -EIO;
92

93
        return (unsigned char) state;
10,385✔
94
}
95

96
int pid_get_comm(pid_t pid, char **ret) {
45,416✔
97
        _cleanup_free_ char *escaped = NULL, *comm = NULL;
45,416✔
98
        int r;
45,416✔
99

100
        assert(pid >= 0);
45,416✔
101
        assert(ret);
45,416✔
102

103
        if (pid == 0 || pid == getpid_cached()) {
45,416✔
104
                comm = new0(char, TASK_COMM_LEN + 1); /* Must fit in 16 byte according to prctl(2) */
25,348✔
105
                if (!comm)
25,348✔
106
                        return -ENOMEM;
107

108
                if (prctl(PR_GET_NAME, comm) < 0)
25,348✔
109
                        return -errno;
×
110
        } else {
111
                const char *p;
20,068✔
112

113
                p = procfs_file_alloca(pid, "comm");
20,068✔
114

115
                /* Note that process names of kernel threads can be much longer than TASK_COMM_LEN */
116
                r = read_one_line_file(p, &comm);
20,068✔
117
                if (r == -ENOENT)
20,068✔
118
                        return -ESRCH;
119
                if (r < 0)
16,098✔
120
                        return r;
121
        }
122

123
        escaped = new(char, COMM_MAX_LEN);
41,445✔
124
        if (!escaped)
41,445✔
125
                return -ENOMEM;
126

127
        /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
128
        cellescape(escaped, COMM_MAX_LEN, comm);
41,445✔
129

130
        *ret = TAKE_PTR(escaped);
41,445✔
131
        return 0;
41,445✔
132
}
133

134
int pidref_get_comm(const PidRef *pid, char **ret) {
188✔
135
        _cleanup_free_ char *comm = NULL;
188✔
136
        int r;
188✔
137

138
        if (!pidref_is_set(pid))
188✔
139
                return -ESRCH;
140

141
        if (pidref_is_remote(pid))
376✔
142
                return -EREMOTE;
143

144
        r = pid_get_comm(pid->pid, &comm);
188✔
145
        if (r < 0)
188✔
146
                return r;
147

148
        r = pidref_verify(pid);
188✔
149
        if (r < 0)
188✔
150
                return r;
151

152
        if (ret)
188✔
153
                *ret = TAKE_PTR(comm);
188✔
154
        return 0;
155
}
156

157
static int pid_get_cmdline_nulstr(
18,747✔
158
                pid_t pid,
159
                size_t max_size,
160
                ProcessCmdlineFlags flags,
161
                char **ret,
162
                size_t *ret_size) {
163

164
        _cleanup_free_ char *t = NULL;
18,747✔
165
        const char *p;
18,747✔
166
        size_t k;
18,747✔
167
        int r;
18,747✔
168

169
        /* Retrieves a process' command line as a "sized nulstr", i.e. possibly without the last NUL, but
170
         * with a specified size.
171
         *
172
         * If PROCESS_CMDLINE_COMM_FALLBACK is specified in flags and the process has no command line set
173
         * (the case for kernel threads), or has a command line that resolves to the empty string, will
174
         * return the "comm" name of the process instead. This will use at most _SC_ARG_MAX bytes of input
175
         * data.
176
         *
177
         * Returns an error, 0 if output was read but is truncated, 1 otherwise.
178
         */
179

180
        p = procfs_file_alloca(pid, "cmdline");
18,963✔
181
        r = read_virtual_file(p, max_size, &t, &k); /* Let's assume that each input byte results in >= 1
18,747✔
182
                                                     * columns of output. We ignore zero-width codepoints. */
183
        if (r == -ENOENT)
18,747✔
184
                return -ESRCH;
185
        if (r < 0)
14,687✔
186
                return r;
187

188
        if (k == 0) {
14,685✔
189
                if (!(flags & PROCESS_CMDLINE_COMM_FALLBACK))
378✔
190
                        return -ENOENT;
355✔
191

192
                /* Kernel threads have no argv[] */
193
                _cleanup_free_ char *comm = NULL;
23✔
194

195
                r = pid_get_comm(pid, &comm);
23✔
196
                if (r < 0)
23✔
197
                        return r;
198

199
                free(t);
23✔
200
                t = strjoin("[", comm, "]");
23✔
201
                if (!t)
23✔
202
                        return -ENOMEM;
203

204
                k = strlen(t);
23✔
205
                r = k <= max_size;
23✔
206
                if (r == 0) /* truncation */
23✔
207
                        t[max_size] = '\0';
12✔
208
        }
209

210
        if (ret)
14,330✔
211
                *ret = TAKE_PTR(t);
14,330✔
212
        if (ret_size)
14,330✔
213
                *ret_size = k;
14,330✔
214

215
        return r;
216
}
217

218
int pid_get_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) {
14,060✔
219
        _cleanup_free_ char *t = NULL;
14,060✔
220
        size_t k;
14,060✔
221
        char *ans;
14,060✔
222

223
        assert(pid >= 0);
14,060✔
224
        assert(ret);
14,060✔
225

226
        /* Retrieve and format a command line. See above for discussion of retrieval options.
227
         *
228
         * There are two main formatting modes:
229
         *
230
         * - when PROCESS_CMDLINE_QUOTE is specified, output is quoted in C/Python style. If no shell special
231
         *   characters are present, this output can be copy-pasted into the terminal to execute. UTF-8
232
         *   output is assumed.
233
         *
234
         * - otherwise, a compact non-roundtrippable form is returned. Non-UTF8 bytes are replaced by �. The
235
         *   returned string is of the specified console width at most, abbreviated with an ellipsis.
236
         *
237
         * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
238
         * PROCESS_CMDLINE_COMM_FALLBACK is not specified). Returns 0 and sets *line otherwise. */
239

240
        int full = pid_get_cmdline_nulstr(pid, max_columns, flags, &t, &k);
14,060✔
241
        if (full < 0)
14,060✔
242
                return full;
243

244
        if (flags & (PROCESS_CMDLINE_QUOTE | PROCESS_CMDLINE_QUOTE_POSIX)) {
9,718✔
245
                ShellEscapeFlags shflags = SHELL_ESCAPE_EMPTY |
9,384✔
246
                        FLAGS_SET(flags, PROCESS_CMDLINE_QUOTE_POSIX) * SHELL_ESCAPE_POSIX;
9,384✔
247

248
                assert(!(flags & PROCESS_CMDLINE_USE_LOCALE));
9,384✔
249

250
                _cleanup_strv_free_ char **args = NULL;
9,384✔
251

252
                /* Drop trailing NULs, otherwise strv_parse_nulstr() adds additional empty strings at the end.
253
                 * See also issue #21186. */
254
                args = strv_parse_nulstr_full(t, k, /* drop_trailing_nuls= */ true);
9,384✔
255
                if (!args)
9,384✔
256
                        return -ENOMEM;
257

258
                ans = quote_command_line(args, shflags);
9,384✔
259
                if (!ans)
9,384✔
260
                        return -ENOMEM;
261
        } else {
262
                /* Arguments are separated by NULs. Let's replace those with spaces. */
263
                for (size_t i = 0; i < k - 1; i++)
16,618✔
264
                        if (t[i] == '\0')
16,284✔
265
                                t[i] = ' ';
574✔
266

267
                delete_trailing_chars(t, WHITESPACE);
334✔
268

269
                bool eight_bit = (flags & PROCESS_CMDLINE_USE_LOCALE) && !is_locale_utf8();
334✔
270

271
                ans = escape_non_printable_full(t, max_columns,
1,002✔
272
                                                eight_bit * XESCAPE_8_BIT | !full * XESCAPE_FORCE_ELLIPSIS);
619✔
273
                if (!ans)
334✔
274
                        return -ENOMEM;
275

276
                ans = str_realloc(ans);
334✔
277
        }
278

279
        *ret = ans;
9,718✔
280
        return 0;
9,718✔
281
}
282

283
int pidref_get_cmdline(const PidRef *pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) {
47✔
284
        _cleanup_free_ char *s = NULL;
47✔
285
        int r;
47✔
286

287
        if (!pidref_is_set(pid))
47✔
288
                return -ESRCH;
289

290
        if (pidref_is_remote(pid))
94✔
291
                return -EREMOTE;
292

293
        r = pid_get_cmdline(pid->pid, max_columns, flags, &s);
47✔
294
        if (r < 0)
47✔
295
                return r;
296

297
        r = pidref_verify(pid);
47✔
298
        if (r < 0)
47✔
299
                return r;
300

301
        if (ret)
47✔
302
                *ret = TAKE_PTR(s);
47✔
303
        return 0;
304
}
305

306
int pid_get_cmdline_strv(pid_t pid, ProcessCmdlineFlags flags, char ***ret) {
4,687✔
307
        _cleanup_free_ char *t = NULL;
4,687✔
308
        char **args;
4,687✔
309
        size_t k;
4,687✔
310
        int r;
4,687✔
311

312
        assert(pid >= 0);
4,687✔
313
        assert((flags & ~PROCESS_CMDLINE_COMM_FALLBACK) == 0);
4,687✔
314
        assert(ret);
4,687✔
315

316
        r = pid_get_cmdline_nulstr(pid, SIZE_MAX, flags, &t, &k);
4,687✔
317
        if (r < 0)
4,687✔
318
                return r;
319

320
        args = strv_parse_nulstr_full(t, k, /* drop_trailing_nuls= */ true);
4,612✔
321
        if (!args)
4,612✔
322
                return -ENOMEM;
323

324
        *ret = args;
4,612✔
325
        return 0;
4,612✔
326
}
327

328
int pidref_get_cmdline_strv(const PidRef *pid, ProcessCmdlineFlags flags, char ***ret) {
×
329
        _cleanup_strv_free_ char **args = NULL;
×
330
        int r;
×
331

332
        if (!pidref_is_set(pid))
×
333
                return -ESRCH;
334

335
        if (pidref_is_remote(pid))
×
336
                return -EREMOTE;
337

338
        r = pid_get_cmdline_strv(pid->pid, flags, &args);
×
339
        if (r < 0)
×
340
                return r;
341

342
        r = pidref_verify(pid);
×
343
        if (r < 0)
×
344
                return r;
345

346
        if (ret)
×
347
                *ret = TAKE_PTR(args);
×
348

349
        return 0;
350
}
351

352
int container_get_leader(const char *machine, pid_t *pid) {
36✔
353
        _cleanup_free_ char *s = NULL, *class = NULL;
36✔
354
        const char *p;
36✔
355
        pid_t leader;
36✔
356
        int r;
36✔
357

358
        assert(machine);
36✔
359
        assert(pid);
36✔
360

361
        if (streq(machine, ".host")) {
36✔
362
                *pid = 1;
1✔
363
                return 0;
1✔
364
        }
365

366
        if (!hostname_is_valid(machine, 0))
35✔
367
                return -EINVAL;
368

369
        p = strjoina("/run/systemd/machines/", machine);
175✔
370
        r = parse_env_file(NULL, p,
35✔
371
                           "LEADER", &s,
372
                           "CLASS", &class);
373
        if (r == -ENOENT)
35✔
374
                return -EHOSTDOWN;
375
        if (r < 0)
35✔
376
                return r;
377
        if (!s)
35✔
378
                return -EIO;
379

380
        if (!streq_ptr(class, "container"))
35✔
381
                return -EIO;
382

383
        r = parse_pid(s, &leader);
35✔
384
        if (r < 0)
35✔
385
                return r;
386
        if (leader <= 1)
35✔
387
                return -EIO;
388

389
        *pid = leader;
35✔
390
        return 0;
35✔
391
}
392

393
int pid_is_kernel_thread(pid_t pid) {
4,123✔
394
        int r;
4,123✔
395

396
        if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
4,123✔
397
                return 0;
4,123✔
398
        if (!pid_is_valid(pid))
4,098✔
399
                return -EINVAL;
400

401
        const char *p = procfs_file_alloca(pid, "stat");
4,098✔
402
        _cleanup_free_ char *line = NULL;
4,098✔
403
        r = read_one_line_file(p, &line);
4,098✔
404
        if (r == -ENOENT)
4,098✔
405
                return -ESRCH;
406
        if (r < 0)
4,098✔
407
                return r;
408

409
        /* Skip past the comm field */
410
        char *q = strrchr(line, ')');
4,098✔
411
        if (!q)
4,098✔
412
                return -EINVAL;
413
        q++;
4,098✔
414

415
        /* Skip 6 fields to reach the flags field */
416
        for (size_t i = 0; i < 6; i++) {
28,686✔
417
                size_t l = strspn(q, WHITESPACE);
24,588✔
418
                if (l < 1)
24,588✔
419
                        return -EINVAL;
420
                q += l;
24,588✔
421

422
                l = strcspn(q, WHITESPACE);
24,588✔
423
                if (l < 1)
24,588✔
424
                        return -EINVAL;
425
                q += l;
24,588✔
426
        }
427

428
        /* Skip preceding whitespace */
429
        size_t l = strspn(q, WHITESPACE);
4,098✔
430
        if (l < 1)
4,098✔
431
                return -EINVAL;
432
        q += l;
4,098✔
433

434
        /* Truncate the rest */
435
        l = strcspn(q, WHITESPACE);
4,098✔
436
        if (l < 1)
4,098✔
437
                return -EINVAL;
438
        q[l] = 0;
4,098✔
439

440
        unsigned long long flags;
4,098✔
441
        r = safe_atollu(q, &flags);
4,098✔
442
        if (r < 0)
4,098✔
443
                return r;
444

445
        return !!(flags & PF_KTHREAD);
4,098✔
446
}
447

448
int pidref_is_kernel_thread(const PidRef *pid) {
1,753✔
449
        int result, r;
1,753✔
450

451
        if (!pidref_is_set(pid))
1,753✔
452
                return -ESRCH;
453

454
        if (pidref_is_remote(pid))
1,753✔
455
                return -EREMOTE;
456

457
        result = pid_is_kernel_thread(pid->pid);
1,753✔
458
        if (result < 0)
1,753✔
459
                return result;
460

461
        r = pidref_verify(pid); /* Verify that the PID wasn't reused since */
1,753✔
462
        if (r < 0)
1,753✔
463
                return r;
×
464

465
        return result;
466
}
467

468
static int get_process_link_contents(pid_t pid, const char *proc_file, char **ret) {
13,562✔
469
        const char *p;
13,562✔
470
        int r;
13,562✔
471

472
        assert(proc_file);
13,562✔
473

474
        p = procfs_file_alloca(pid, proc_file);
13,566✔
475

476
        r = readlink_malloc(p, ret);
13,562✔
477
        return (r == -ENOENT && proc_mounted() > 0) ? -ESRCH : r;
13,562✔
478
}
479

480
int get_process_exe(pid_t pid, char **ret) {
13,536✔
481
        char *d;
13,536✔
482
        int r;
13,536✔
483

484
        assert(pid >= 0);
13,536✔
485

486
        r = get_process_link_contents(pid, "exe", ret);
13,536✔
487
        if (r < 0)
13,536✔
488
                return r;
489

490
        if (ret) {
9,355✔
491
                d = endswith(*ret, " (deleted)");
9,355✔
492
                if (d)
9,355✔
493
                        *d = '\0';
×
494
        }
495

496
        return 0;
497
}
498

499
int pid_get_uid(pid_t pid, uid_t *ret) {
3,311✔
500
        int r;
3,311✔
501

502
        assert(pid >= 0);
3,311✔
503
        assert(ret);
3,311✔
504

505
        if (pid == 0 || pid == getpid_cached()) {
3,311✔
506
                *ret = getuid();
1✔
507
                return 0;
3,311✔
508
        }
509

510
        _cleanup_free_ char *v = NULL;
3,310✔
511
        r = procfs_file_get_field(pid, "status", "Uid", &v);
3,310✔
512
        if (r == -ENOENT)
3,310✔
513
                return -ESRCH;
514
        if (r < 0)
159✔
515
                return r;
516

517
        return parse_uid(v, ret);
159✔
518
}
519

520
int pidref_get_uid(const PidRef *pid, uid_t *ret) {
69✔
521
        int r;
69✔
522

523
        if (!pidref_is_set(pid))
69✔
524
                return -ESRCH;
69✔
525

526
        if (pidref_is_remote(pid))
69✔
527
                return -EREMOTE;
528

529
        if (pid->fd >= 0) {
69✔
530
                r = pidfd_get_uid(pid->fd, ret);
69✔
531
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
69✔
532
                        return r;
533
        }
534

535
        uid_t uid;
×
536
        r = pid_get_uid(pid->pid, &uid);
×
537
        if (r < 0)
×
538
                return r;
539

540
        r = pidref_verify(pid);
×
541
        if (r < 0)
×
542
                return r;
543

544
        if (ret)
×
545
                *ret = uid;
×
546
        return 0;
547
}
548

549
int get_process_gid(pid_t pid, gid_t *ret) {
3,311✔
550
        int r;
3,311✔
551

552
        assert(pid >= 0);
3,311✔
553
        assert(ret);
3,311✔
554

555
        if (pid == 0 || pid == getpid_cached()) {
3,311✔
556
                *ret = getgid();
1✔
557
                return 0;
3,311✔
558
        }
559

560
        _cleanup_free_ char *v = NULL;
3,310✔
561
        r = procfs_file_get_field(pid, "status", "Gid", &v);
3,310✔
562
        if (r == -ENOENT)
3,310✔
563
                return -ESRCH;
564
        if (r < 0)
159✔
565
                return r;
566

567
        return parse_gid(v, ret);
3,310✔
568
}
569

570
int get_process_cwd(pid_t pid, char **ret) {
13✔
571
        assert(pid >= 0);
13✔
572

573
        if (pid == 0 || pid == getpid_cached())
13✔
574
                return safe_getcwd(ret);
×
575

576
        return get_process_link_contents(pid, "cwd", ret);
13✔
577
}
578

579
int get_process_root(pid_t pid, char **ret) {
13✔
580
        assert(pid >= 0);
13✔
581
        return get_process_link_contents(pid, "root", ret);
13✔
582
}
583

584
#define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
585

586
int get_process_environ(pid_t pid, char **ret) {
15✔
587
        _cleanup_fclose_ FILE *f = NULL;
15✔
588
        _cleanup_free_ char *outcome = NULL;
15✔
589
        size_t sz = 0;
15✔
590
        const char *p;
15✔
591
        int r;
15✔
592

593
        assert(pid >= 0);
15✔
594
        assert(ret);
15✔
595

596
        p = procfs_file_alloca(pid, "environ");
15✔
597

598
        r = fopen_unlocked(p, "re", &f);
15✔
599
        if (r == -ENOENT)
15✔
600
                return -ESRCH;
601
        if (r < 0)
15✔
602
                return r;
603

604
        for (;;) {
6,608✔
605
                char c;
6,623✔
606

607
                if (sz >= ENVIRONMENT_BLOCK_MAX)
6,623✔
608
                        return -ENOBUFS;
×
609

610
                if (!GREEDY_REALLOC(outcome, sz + 5))
6,623✔
611
                        return -ENOMEM;
612

613
                r = safe_fgetc(f, &c);
6,623✔
614
                if (r < 0)
6,623✔
615
                        return r;
616
                if (r == 0)
6,623✔
617
                        break;
618

619
                if (c == '\0')
6,608✔
620
                        outcome[sz++] = '\n';
235✔
621
                else
622
                        sz += cescape_char(c, outcome + sz);
6,373✔
623
        }
624

625
        outcome[sz] = '\0';
15✔
626
        *ret = TAKE_PTR(outcome);
15✔
627

628
        return 0;
15✔
629
}
630

631
int pid_get_ppid(pid_t pid, pid_t *ret) {
6✔
632
        _cleanup_free_ char *line = NULL;
6✔
633
        unsigned long ppid;
6✔
634
        const char *p;
6✔
635
        int r;
6✔
636

637
        assert(pid >= 0);
6✔
638

639
        if (pid == 0)
6✔
640
                pid = getpid_cached();
1✔
641
        if (pid == 1) /* PID 1 has no parent, shortcut this case */
6✔
642
                return -EADDRNOTAVAIL;
643

644
        if (pid == getpid_cached()) {
3✔
645
                if (ret)
2✔
646
                        *ret = getppid();
2✔
647
                return 0;
2✔
648
        }
649

650
        p = procfs_file_alloca(pid, "stat");
1✔
651
        r = read_one_line_file(p, &line);
1✔
652
        if (r == -ENOENT)
1✔
653
                return -ESRCH;
654
        if (r < 0)
×
655
                return r;
656

657
        /* Let's skip the pid and comm fields. The latter is enclosed in () but does not escape any () in its
658
         * value, so let's skip over it manually */
659

660
        p = strrchr(line, ')');
×
661
        if (!p)
×
662
                return -EIO;
663
        p++;
×
664

665
        if (sscanf(p, " "
×
666
                   "%*c "  /* state */
667
                   "%lu ", /* ppid */
668
                   &ppid) != 1)
669
                return -EIO;
670

671
        /* If ppid is zero the process has no parent. Which might be the case for PID 1 (caught above)
672
         * but also for processes originating in other namespaces that are inserted into a pidns.
673
         * Return a recognizable error in this case. */
674
        if (ppid == 0)
×
675
                return -EADDRNOTAVAIL;
676

677
        if ((pid_t) ppid < 0 || (unsigned long) (pid_t) ppid != ppid)
×
678
                return -ERANGE;
679

680
        if (ret)
×
681
                *ret = (pid_t) ppid;
×
682

683
        return 0;
684
}
685

686
int pidref_get_ppid(const PidRef *pidref, pid_t *ret) {
2,631✔
687
        int r;
2,631✔
688

689
        if (!pidref_is_set(pidref))
2,631✔
690
                return -ESRCH;
2,631✔
691

692
        if (pidref_is_remote(pidref))
2,631✔
693
                return -EREMOTE;
694

695
        if (pidref->fd >= 0) {
2,631✔
696
                r = pidfd_get_ppid(pidref->fd, ret);
2,631✔
697
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
2,631✔
698
                        return r;
699
        }
700

701
        pid_t ppid;
×
702
        r = pid_get_ppid(pidref->pid, ret ? &ppid : NULL);
×
703
        if (r < 0)
×
704
                return r;
705

706
        r = pidref_verify(pidref);
×
707
        if (r < 0)
×
708
                return r;
709

710
        if (ret)
×
711
                *ret = ppid;
×
712
        return 0;
713
}
714

715
int pidref_get_ppid_as_pidref(const PidRef *pidref, PidRef *ret) {
11✔
716
        pid_t ppid;
11✔
717
        int r;
11✔
718

719
        assert(ret);
11✔
720

721
        r = pidref_get_ppid(pidref, &ppid);
11✔
722
        if (r < 0)
11✔
723
                return r;
11✔
724

725
        for (unsigned attempt = 0; attempt < 16; attempt++) {
10✔
726
                _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
10✔
727

728
                r = pidref_set_pid(&parent, ppid);
10✔
729
                if (r < 0)
10✔
730
                        return r;
731

732
                /* If we have a pidfd of the original PID, let's verify that the process we acquired really
733
                 * is the parent still */
734
                if (pidref->fd >= 0) {
10✔
735
                        r = pidref_get_ppid(pidref, &ppid);
10✔
736
                        if (r < 0)
10✔
737
                                return r;
738

739
                        /* Did the PPID change since we queried it? if so we might have pinned the wrong
740
                         * process, if its PID got reused by now. Let's try again */
741
                        if (parent.pid != ppid)
10✔
742
                                continue;
×
743
                }
744

745
                *ret = TAKE_PIDREF(parent);
10✔
746
                return 0;
10✔
747
        }
748

749
        /* Give up after 16 tries */
750
        return -ENOTRECOVERABLE;
751
}
752

753
int pid_get_start_time(pid_t pid, usec_t *ret) {
674✔
754
        _cleanup_free_ char *line = NULL;
674✔
755
        const char *p;
674✔
756
        int r;
674✔
757

758
        assert(pid >= 0);
674✔
759

760
        p = procfs_file_alloca(pid, "stat");
674✔
761
        r = read_one_line_file(p, &line);
674✔
762
        if (r == -ENOENT)
674✔
763
                return -ESRCH;
764
        if (r < 0)
674✔
765
                return r;
766

767
        /* Let's skip the pid and comm fields. The latter is enclosed in () but does not escape any () in its
768
         * value, so let's skip over it manually */
769

770
        p = strrchr(line, ')');
674✔
771
        if (!p)
674✔
772
                return -EIO;
773
        p++;
674✔
774

775
        unsigned long llu;
674✔
776

777
        if (sscanf(p, " "
674✔
778
                   "%*c " /* state */
779
                   "%*u " /* ppid */
780
                   "%*u " /* pgrp */
781
                   "%*u " /* session */
782
                   "%*u " /* tty_nr */
783
                   "%*u " /* tpgid */
784
                   "%*u " /* flags */
785
                   "%*u " /* minflt */
786
                   "%*u " /* cminflt */
787
                   "%*u " /* majflt */
788
                   "%*u " /* cmajflt */
789
                   "%*u " /* utime */
790
                   "%*u " /* stime */
791
                   "%*u " /* cutime */
792
                   "%*u " /* cstime */
793
                   "%*i " /* priority */
794
                   "%*i " /* nice */
795
                   "%*u " /* num_threads */
796
                   "%*u " /* itrealvalue */
797
                   "%lu ", /* starttime */
798
                   &llu) != 1)
799
                return -EIO;
800

801
        if (ret)
674✔
802
                *ret = jiffies_to_usec(llu); /* CLOCK_BOOTTIME */
674✔
803

804
        return 0;
805
}
806

807
int pidref_get_start_time(const PidRef *pid, usec_t *ret) {
674✔
808
        usec_t t;
674✔
809
        int r;
674✔
810

811
        if (!pidref_is_set(pid))
674✔
812
                return -ESRCH;
674✔
813

814
        if (pidref_is_remote(pid))
674✔
815
                return -EREMOTE;
816

817
        r = pid_get_start_time(pid->pid, ret ? &t : NULL);
674✔
818
        if (r < 0)
674✔
819
                return r;
820

821
        r = pidref_verify(pid);
674✔
822
        if (r < 0)
674✔
823
                return r;
824

825
        if (ret)
674✔
826
                *ret = t;
674✔
827

828
        return 0;
829
}
830

831
int get_process_umask(pid_t pid, mode_t *ret) {
24,514✔
832
        _cleanup_free_ char *m = NULL;
24,514✔
833
        int r;
24,514✔
834

835
        assert(pid >= 0);
24,514✔
836
        assert(ret);
24,514✔
837

838
        r = procfs_file_get_field(pid, "status", "Umask", &m);
24,514✔
839
        if (r == -ENOENT)
24,514✔
840
                return -ESRCH;
841
        if (r < 0)
24,514✔
842
                return r;
843

844
        return parse_mode(m, ret);
24,514✔
845
}
846

847
/*
848
 * Return values:
849
 * < 0 : pidref_wait_for_terminate() failed to get the state of the
850
 *       process, the process was terminated by a signal, or
851
 *       failed for an unknown reason.
852
 * >=0 : The process terminated normally, and its exit code is
853
 *       returned.
854
 *
855
 * That is, success is indicated by a return value of zero, and an
856
 * error is indicated by a non-zero value.
857
 *
858
 * A warning is emitted if the process terminates abnormally,
859
 * and also if it returns non-zero unless check_exit_code is true.
860
 */
861
int pidref_wait_for_terminate_and_check(const char *name, PidRef *pidref, WaitFlags flags) {
7,504✔
862
        int r;
7,504✔
863

864
        if (!pidref_is_set(pidref))
7,504✔
865
                return -ESRCH;
7,504✔
866
        if (pidref_is_remote(pidref))
15,008✔
867
                return -EREMOTE;
868
        if (pidref->pid == 1 || pidref_is_self(pidref))
7,504✔
869
                return -ECHILD;
×
870

871
        _cleanup_free_ char *buffer = NULL;
7,504✔
872
        if (!name) {
7,504✔
873
                r = pidref_get_comm(pidref, &buffer);
2✔
874
                if (r < 0)
2✔
875
                        log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pidref->pid);
×
876
                else
877
                        name = buffer;
2✔
878
        }
879

880
        int prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
7,504✔
881

882
        siginfo_t status;
7,504✔
883
        r = pidref_wait_for_terminate(pidref, &status);
7,504✔
884
        if (r < 0)
7,504✔
885
                return log_full_errno(prio, r, "Failed to wait for '%s': %m", strna(name));
×
886

887
        if (status.si_code == CLD_EXITED) {
7,504✔
888
                if (status.si_status != EXIT_SUCCESS)
7,504✔
889
                        log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
73✔
890
                                 "'%s' failed with exit status %i.", strna(name), status.si_status);
891
                else
892
                        log_debug("'%s' succeeded.", name);
7,431✔
893

894
                return status.si_status;
7,504✔
895

896
        } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED))
×
897
                return log_full_errno(prio, SYNTHETIC_ERRNO(EPROTO),
×
898
                                      "'%s' terminated by signal %s.", strna(name), signal_to_string(status.si_status));
899

900
        return log_full_errno(prio, SYNTHETIC_ERRNO(EPROTO),
×
901
                              "'%s' failed due to unknown reason.", strna(name));
902
}
903

904
int kill_and_sigcont(pid_t pid, int sig) {
×
905
        int r;
×
906

907
        r = RET_NERRNO(kill(pid, sig));
×
908

909
        /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
910
         * affected by a process being suspended anyway. */
911
        if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
×
912
                (void) kill(pid, SIGCONT);
×
913

914
        return r;
×
915
}
916

917
int getenv_for_pid(pid_t pid, const char *field, char **ret) {
5,232✔
918
        _cleanup_fclose_ FILE *f = NULL;
5,232✔
919
        const char *path;
5,232✔
920
        size_t sum = 0;
5,232✔
921
        int r;
5,232✔
922

923
        assert(pid >= 0);
5,232✔
924
        assert(field);
5,232✔
925
        assert(ret);
5,232✔
926

927
        if (pid == 0 || pid == getpid_cached())
5,232✔
928
                return strdup_to_full(ret, getenv(field));
14✔
929

930
        if (!pid_is_valid(pid))
5,218✔
931
                return -EINVAL;
932

933
        path = procfs_file_alloca(pid, "environ");
5,218✔
934

935
        r = fopen_unlocked(path, "re", &f);
5,218✔
936
        if (r == -ENOENT)
5,218✔
937
                return -ESRCH;
938
        if (r < 0)
4,811✔
939
                return r;
940

941
        for (;;) {
57,171✔
942
                _cleanup_free_ char *line = NULL;
26,893✔
943
                const char *match;
30,296✔
944

945
                if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
30,296✔
946
                        return -ENOBUFS;
947

948
                r = read_nul_string(f, LONG_LINE_MAX, &line);
30,296✔
949
                if (r < 0)
30,296✔
950
                        return r;
951
                if (r == 0)  /* EOF */
30,296✔
952
                        break;
953

954
                sum += r;
26,893✔
955

956
                match = startswith(line, field);
26,893✔
957
                if (match && *match == '=')
26,893✔
958
                        return strdup_to_full(ret, match + 1);
18✔
959
        }
960

961
        *ret = NULL;
3,403✔
962
        return 0;
3,403✔
963
}
964

965
int pidref_is_my_child(PidRef *pid) {
2,609✔
966
        int r;
2,609✔
967

968
        if (!pidref_is_set(pid))
2,609✔
969
                return -ESRCH;
2,609✔
970

971
        if (pidref_is_remote(pid))
2,609✔
972
                return -EREMOTE;
973

974
        if (pid->pid == 1 || pidref_is_self(pid))
2,609✔
975
                return false;
×
976

977
        pid_t ppid;
2,609✔
978
        r = pidref_get_ppid(pid, &ppid);
2,609✔
979
        if (r == -EADDRNOTAVAIL) /* if this process is outside of our pidns, it is definitely not our child */
2,609✔
980
                return false;
981
        if (r < 0)
2,609✔
982
                return r;
983

984
        return ppid == getpid_cached();
2,609✔
985
}
986

987
int pid_is_my_child(pid_t pid) {
×
988

989
        if (pid == 0)
×
990
                return false;
×
991

992
        return pidref_is_my_child(&PIDREF_MAKE_FROM_PID(pid));
×
993
}
994

995
int pidref_is_unwaited(PidRef *pid) {
8,450✔
996
        int r;
8,450✔
997

998
        /* Checks whether a PID is still valid at all, including a zombie */
999

1000
        if (!pidref_is_set(pid))
8,450✔
1001
                return -ESRCH;
1002

1003
        if (pidref_is_remote(pid))
8,449✔
1004
                return -EREMOTE;
1005

1006
        if (pid->pid == 1 || pidref_is_self(pid))
8,449✔
1007
                return true;
5✔
1008

1009
        r = pidref_kill(pid, 0);
8,444✔
1010
        if (r == -ESRCH)
8,444✔
1011
                return false;
1012
        if (r < 0)
2,033✔
1013
                return r;
170✔
1014

1015
        return true;
1016
}
1017

1018
int pid_is_unwaited(pid_t pid) {
7,776✔
1019

1020
        if (pid == 0)
7,776✔
1021
                return true;
7,776✔
1022

1023
        return pidref_is_unwaited(&PIDREF_MAKE_FROM_PID(pid));
7,776✔
1024
}
1025

1026
int pid_is_alive(pid_t pid) {
13,241✔
1027
        int r;
13,241✔
1028

1029
        /* Checks whether a PID is still valid and not a zombie */
1030

1031
        if (pid < 0)
13,241✔
1032
                return -ESRCH;
1033

1034
        if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
13,240✔
1035
                return true;
1036

1037
        if (pid == getpid_cached())
13,240✔
1038
                return true;
1039

1040
        r = get_process_state(pid);
13,239✔
1041
        if (r == -ESRCH)
13,239✔
1042
                return false;
1043
        if (r < 0)
10,385✔
1044
                return r;
1045

1046
        return r != 'Z';
10,385✔
1047
}
1048

1049
int pidref_is_alive(const PidRef *pidref) {
13,236✔
1050
        int r, result;
13,236✔
1051

1052
        if (!pidref_is_set(pidref))
13,236✔
1053
                return -ESRCH;
1054

1055
        if (pidref_is_remote(pidref))
13,236✔
1056
                return -EREMOTE;
1057

1058
        result = pid_is_alive(pidref->pid);
13,236✔
1059
        if (result < 0) {
13,236✔
1060
                assert(result != -ESRCH);
×
1061
                return result;
1062
        }
1063

1064
        r = pidref_verify(pidref);
13,236✔
1065
        if (r == -ESRCH)
13,236✔
1066
                return false;
1067
        if (r < 0)
10,381✔
1068
                return r;
×
1069

1070
        return result;
1071
}
1072

1073
int pidref_from_same_root_fs(PidRef *a, PidRef *b) {
20✔
1074
        _cleanup_(pidref_done) PidRef self = PIDREF_NULL;
×
1075
        int r;
20✔
1076

1077
        /* Checks if the two specified processes have the same root fs. Either can be specified as NULL in
1078
         * which case we'll check against ourselves. */
1079

1080
        if (!a || !b) {
20✔
1081
                r = pidref_set_self(&self);
×
1082
                if (r < 0)
×
1083
                        return r;
1084
                if (!a)
×
1085
                        a = &self;
×
1086
                if (!b)
×
1087
                        b = &self;
×
1088
        }
1089

1090
        if (!pidref_is_set(a) || !pidref_is_set(b))
20✔
1091
                return -ESRCH;
×
1092

1093
        /* If one of the two processes have the same root they cannot have the same root fs, but if both of
1094
         * them do we don't know */
1095
        if (pidref_is_remote(a) && pidref_is_remote(b))
20✔
1096
                return -EREMOTE;
1097
        if (pidref_is_remote(a) || pidref_is_remote(b))
60✔
1098
                return false;
1099

1100
        if (pidref_equal(a, b))
20✔
1101
                return true;
1102

1103
        const char *roota = procfs_file_alloca(a->pid, "root");
18✔
1104
        const char *rootb = procfs_file_alloca(b->pid, "root");
18✔
1105

1106
        int result = inode_same(roota, rootb, 0);
18✔
1107
        if (result == -ENOENT)
18✔
1108
                return proc_mounted() == 0 ? -ENOSYS : -ESRCH;
×
1109
        if (result < 0)
18✔
1110
                return result;
1111

1112
        r = pidref_verify(a);
18✔
1113
        if (r < 0)
18✔
1114
                return r;
1115
        r = pidref_verify(b);
18✔
1116
        if (r < 0)
18✔
1117
                return r;
×
1118

1119
        return result;
1120
}
1121

1122
bool is_main_thread(void) {
7,635,782✔
1123
        static thread_local int cached = -1;
7,635,782✔
1124

1125
        if (cached < 0)
7,635,782✔
1126
                cached = getpid_cached() == gettid();
57,636✔
1127

1128
        return cached;
7,635,782✔
1129
}
1130

1131
unsigned long personality_from_string(const char *s) {
9✔
1132
        Architecture architecture;
9✔
1133

1134
        if (!s)
9✔
1135
                return PERSONALITY_INVALID;
1136

1137
        /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1138
         * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1139
         * the same register size. */
1140

1141
        architecture = architecture_from_string(s);
8✔
1142
        if (architecture < 0)
8✔
1143
                return PERSONALITY_INVALID;
1144

1145
        if (architecture == native_architecture())
6✔
1146
                return PER_LINUX;
1147
#ifdef ARCHITECTURE_SECONDARY
1148
        if (architecture == ARCHITECTURE_SECONDARY)
3✔
1149
                return PER_LINUX32;
2✔
1150
#endif
1151

1152
        return PERSONALITY_INVALID;
1153
}
1154

1155
const char* personality_to_string(unsigned long p) {
3,036✔
1156
        Architecture architecture = _ARCHITECTURE_INVALID;
3,036✔
1157

1158
        if (p == PER_LINUX)
3,036✔
1159
                architecture = native_architecture();
1160
#ifdef ARCHITECTURE_SECONDARY
1161
        else if (p == PER_LINUX32)
3,031✔
1162
                architecture = ARCHITECTURE_SECONDARY;
1163
#endif
1164

1165
        if (architecture < 0)
1166
                return NULL;
1167

1168
        return architecture_to_string(architecture);
7✔
1169
}
1170

1171
int safe_personality(unsigned long p) {
1,495✔
1172
        int ret;
1,495✔
1173

1174
        /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1175
         * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1176
         * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1177
         * the return value indicating the same issue, so that we are definitely on the safe side.
1178
         *
1179
         * See https://github.com/systemd/systemd/issues/6737 */
1180

1181
        errno = 0;
1,495✔
1182
        ret = personality(p);
1,495✔
1183
        if (ret < 0) {
1,495✔
1184
                if (errno != 0)
12✔
1185
                        return -errno;
12✔
1186

UNCOV
1187
                errno = -ret;
×
1188
        }
1189

1190
        return ret;
1191
}
1192

1193
int opinionated_personality(unsigned long *ret) {
1,480✔
1194
        int current;
1,480✔
1195

1196
        /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1197
         * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1198
         * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1199

1200
        current = safe_personality(PERSONALITY_INVALID);
1,480✔
1201
        if (current < 0)
1,480✔
1202
                return current;
1203

1204
        if (((unsigned long) current & OPINIONATED_PERSONALITY_MASK) == PER_LINUX32)
1,480✔
UNCOV
1205
                *ret = PER_LINUX32;
×
1206
        else
1207
                *ret = PER_LINUX;
1,480✔
1208

1209
        return 0;
1210
}
1211

1212
void valgrind_summary_hack(void) {
39✔
1213
#if HAVE_VALGRIND_VALGRIND_H
1214
        if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
1215
                pid_t pid;
1216
                pid = raw_clone(SIGCHLD);
1217
                if (pid < 0)
1218
                        log_struct_errno(
1219
                                LOG_EMERG, errno,
1220
                                LOG_MESSAGE_ID(SD_MESSAGE_VALGRIND_HELPER_FORK_STR),
1221
                                LOG_MESSAGE("Failed to fork off valgrind helper: %m"));
1222
                else if (pid == 0)
1223
                        exit(EXIT_SUCCESS);
1224
                else {
1225
                        log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
1226
                        _cleanup_(pidref_done) PidRef pidref = PIDREF_MAKE_FROM_PID(pid);
1227
                        (void) pidref_set_pid(&pidref, pid);
1228
                        (void) pidref_wait_for_terminate(&pidref, NULL);
1229
                }
1230
        }
1231
#endif
1232
}
39✔
1233

1234
int pid_compare_func(const pid_t *a, const pid_t *b) {
1,412✔
1235
        /* Suitable for usage in qsort() */
1236
        return CMP(*a, *b);
1,412✔
1237
}
1238

1239
bool nice_is_valid(int n) {
892✔
1240
        return n >= PRIO_MIN && n < PRIO_MAX;
892✔
1241
}
1242

UNCOV
1243
bool sched_policy_is_valid(int policy) {
×
UNCOV
1244
        return IN_SET(policy, SCHED_OTHER, SCHED_BATCH, SCHED_IDLE, SCHED_FIFO, SCHED_RR, SCHED_EXT);
×
1245
}
1246

1247
bool sched_policy_supported(int policy) {
4✔
1248
        return sched_get_priority_min(policy) >= 0;
4✔
1249
}
1250

1251
/* Wrappers around sched_get_priority_{min,max}() that gracefully handles missing SCHED_EXT support in the kernel */
1252
int sched_get_priority_min_safe(int policy) {
4✔
1253
        int r;
4✔
1254

1255
        r = sched_get_priority_min(policy);
4✔
1256
        if (r >= 0)
4✔
1257
                return r;
4✔
1258

1259
        /* Fallback priority */
1260
        return 0;
1261
}
1262

1263
int sched_get_priority_max_safe(int policy) {
4✔
1264
        int r;
4✔
1265

1266
        r = sched_get_priority_max(policy);
4✔
1267
        if (r >= 0)
4✔
1268
                return r;
4✔
1269

1270
        return 0;
1271
}
1272

1273
/* The cached PID, possible values:
1274
 *
1275
 *     == UNSET [0]  → cache not initialized yet
1276
 *     == BUSY [-1]  → some thread is initializing it at the moment
1277
 *     any other     → the cached PID
1278
 */
1279

1280
#define CACHED_PID_UNSET ((pid_t) 0)
1281
#define CACHED_PID_BUSY ((pid_t) -1)
1282

1283
static pid_t cached_pid = CACHED_PID_UNSET;
1284

1285
void reset_cached_pid(void) {
1,691✔
1286
        /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1287
        cached_pid = CACHED_PID_UNSET;
1,691✔
1288
}
1,691✔
1289

1290
pid_t getpid_cached(void) {
149,160,330✔
1291
        static bool installed = false;
149,160,330✔
1292
        pid_t current_value = CACHED_PID_UNSET;
149,160,330✔
1293

1294
        /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1295
         * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1296
         * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1297
         * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1298
         *
1299
         * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1300
         * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1301
         */
1302

1303
        (void) __atomic_compare_exchange_n(
149,160,330✔
1304
                        &cached_pid,
1305
                        &current_value,
1306
                        CACHED_PID_BUSY,
1307
                        false,
1308
                        __ATOMIC_SEQ_CST,
1309
                        __ATOMIC_SEQ_CST);
1310

1311
        switch (current_value) {
149,160,330✔
1312

1313
        case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
105,674✔
1314
                pid_t new_pid;
105,674✔
1315

1316
                new_pid = getpid();
105,674✔
1317

1318
                if (!installed) {
105,674✔
1319
                        /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1320
                         * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1321
                         * we'll check for errors only in the most generic fashion possible. */
1322

1323
                        if (pthread_atfork(NULL, NULL, reset_cached_pid) != 0) {
73,616✔
1324
                                /* OOM? Let's try again later */
UNCOV
1325
                                cached_pid = CACHED_PID_UNSET;
×
UNCOV
1326
                                return new_pid;
×
1327
                        }
1328

1329
                        installed = true;
73,616✔
1330
                }
1331

1332
                cached_pid = new_pid;
105,674✔
1333
                return new_pid;
105,674✔
1334
        }
1335

UNCOV
1336
        case CACHED_PID_BUSY: /* Somebody else is currently initializing */
×
UNCOV
1337
                return getpid();
×
1338

1339
        default: /* Properly initialized */
1340
                return current_value;
1341
        }
1342
}
1343

1344
int must_be_root(void) {
66✔
1345

1346
        if (geteuid() == 0)
66✔
1347
                return 0;
1348

UNCOV
1349
        return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be root.");
×
1350
}
1351

1352
pid_t clone_with_nested_stack(int (*fn)(void *), int flags, void *userdata) {
3,602✔
1353
        size_t ps;
3,602✔
1354
        pid_t pid;
3,602✔
1355
        void *mystack;
3,602✔
1356

1357
        /* A wrapper around glibc's clone() call that automatically sets up a "nested" stack. Only supports
1358
         * invocations without CLONE_VM, so that we can continue to use the parent's stack mapping.
1359
         *
1360
         * Note: glibc's clone() wrapper does not synchronize malloc() locks. This means that if the parent
1361
         * is threaded these locks will be in an undefined state in the child, and hence memory allocations
1362
         * are likely going to run into deadlocks. Hence: if you use this function make sure your parent is
1363
         * strictly single-threaded or your child never calls malloc(). */
1364

1365
        assert((flags & (CLONE_VM|CLONE_PARENT_SETTID|CLONE_CHILD_SETTID|
3,602✔
1366
                         CLONE_CHILD_CLEARTID|CLONE_SETTLS)) == 0);
1367

1368
        /* We allocate some space on the stack to use as the stack for the child (hence "nested"). Note that
1369
         * the net effect is that the child will have the start of its stack inside the stack of the parent,
1370
         * but since they are a CoW copy of each other that's fine. We allocate one page-aligned page. But
1371
         * since we don't want to deal with differences between systems where the stack grows backwards or
1372
         * forwards we'll allocate one more and place the stack address in the middle. Except that we also
1373
         * want it page aligned, hence we'll allocate one page more. Makes 3. */
1374

1375
        ps = page_size();
3,602✔
1376
        mystack = alloca(ps*3);
3,602✔
1377
        mystack = (uint8_t*) mystack + ps; /* move pointer one page ahead since stacks usually grow backwards */
3,602✔
1378
        mystack = (void*) ALIGN_TO((uintptr_t) mystack, ps); /* align to page size (moving things further ahead) */
3,602✔
1379

1380
#if HAVE_CLONE
1381
        pid = clone(fn, mystack, flags, userdata);
3,602✔
1382
#else
1383
        pid = __clone2(fn, mystack, ps, flags, userdata);
1384
#endif
1385
        if (pid < 0)
3,602✔
UNCOV
1386
                return -errno;
×
1387

1388
        return pid;
1389
}
1390

1391
static int fork_flags_to_signal(ForkFlags flags) {
30,219✔
1392
        return (flags & FORK_DEATHSIG_SIGTERM) ? SIGTERM :
30,219✔
1393
                (flags & FORK_DEATHSIG_SIGINT) ? SIGINT :
927✔
1394
                                                 SIGKILL;
1395
}
1396

1397
int pidref_safe_fork_full(
29,100✔
1398
                const char *name,
1399
                const int stdio_fds[3],
1400
                int except_fds[],
1401
                size_t n_except_fds,
1402
                ForkFlags flags,
1403
                PidRef *ret) {
1404

1405
        pid_t original_pid, pid;
29,100✔
1406
        sigset_t saved_ss, ss;
29,100✔
UNCOV
1407
        _unused_ _cleanup_(block_signals_reset) sigset_t *saved_ssp = NULL;
×
1408
        bool block_signals = false, block_all = false, intermediary = false;
29,100✔
1409
        _cleanup_close_pair_ int pidref_transport_fds[2] = EBADF_PAIR;
60,373✔
1410
        int prio, r;
29,100✔
1411

1412
        assert(!FLAGS_SET(flags, FORK_WAIT|FORK_FREEZE));
29,100✔
1413
        assert(!FLAGS_SET(flags, FORK_DETACH) ||
29,100✔
1414
               (flags & (FORK_WAIT|FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT|FORK_DEATHSIG_SIGKILL)) == 0);
1415

1416
        /* A wrapper around fork(), that does a couple of important initializations in addition to mere
1417
         * forking. If provided, ret is initialized in both the parent and the child process, both times
1418
         * referencing the child process. Returns == 0 in the child and > 0 in the parent. */
1419

1420
        prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG;
29,100✔
1421

1422
        original_pid = getpid_cached();
29,100✔
1423

1424
        if (flags & FORK_FLUSH_STDIO) {
29,100✔
1425
                fflush(stdout);
5✔
1426
                fflush(stderr); /* This one shouldn't be necessary, stderr should be unbuffered anyway, but let's better be safe than sorry */
5✔
1427
        }
1428

1429
        if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT)) {
29,100✔
1430
                /* We temporarily block all signals, so that the new child has them blocked initially. This
1431
                 * way, we can be sure that SIGTERMs are not lost we might send to the child. (Note that for
1432
                 * FORK_DEATHSIG_SIGKILL we don't bother, since it cannot be blocked anyway.) */
1433

1434
                assert_se(sigfillset(&ss) >= 0);
24,757✔
1435
                block_signals = block_all = true;
1436

1437
        } else if (flags & FORK_WAIT) {
4,343✔
1438
                /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1439

1440
                assert_se(sigemptyset(&ss) >= 0);
164✔
1441
                assert_se(sigaddset(&ss, SIGCHLD) >= 0);
164✔
1442
                block_signals = true;
1443
        }
1444

1445
        if (block_signals) {
1446
                if (sigprocmask(SIG_BLOCK, &ss, &saved_ss) < 0)
24,921✔
UNCOV
1447
                        return log_full_errno(prio, errno, "Failed to block signal mask: %m");
×
1448
                saved_ssp = &saved_ss;
24,921✔
1449
        }
1450

1451
        if (FLAGS_SET(flags, FORK_DETACH)) {
29,100✔
1452
                /* Fork off intermediary child if needed */
1453

1454
                r = is_reaper_process();
108✔
1455
                if (r < 0)
108✔
UNCOV
1456
                        return log_full_errno(prio, r, "Failed to determine if we are a reaper process: %m");
×
1457

1458
                if (!r) {
108✔
1459
                        /* Not a reaper process, hence do a double fork() so we are reparented to one */
1460

1461
                        if (ret && socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pidref_transport_fds) < 0)
11✔
UNCOV
1462
                                return log_full_errno(prio, errno, "Failed to allocate pidref socket: %m");
×
1463

1464
                        pid = fork();
11✔
1465
                        if (pid < 0)
28✔
1466
                                return log_full_errno(prio, errno, "Failed to fork off '%s': %m", strna(name));
×
1467
                        if (pid > 0) {
28✔
1468
                                log_debug("Successfully forked off intermediary '%s' as PID " PID_FMT ".", strna(name), pid);
11✔
1469

1470
                                pidref_transport_fds[1] = safe_close(pidref_transport_fds[1]);
11✔
1471

1472
                                if (pidref_transport_fds[0] >= 0) {
11✔
1473
                                        /* Wait for the intermediary child to exit so the caller can be
1474
                                         * certain the actual child process has been reparented by the time
1475
                                         * this function returns. */
1476
                                        r = pidref_wait_for_terminate_and_check(
10✔
1477
                                                        name,
1478
                                                        &PIDREF_MAKE_FROM_PID(pid),
10✔
1479
                                                        FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1480
                                        if (r < 0)
10✔
UNCOV
1481
                                                return log_full_errno(prio, r, "Failed to wait for intermediary process: %m");
×
1482
                                        if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */
10✔
1483
                                                return -EPROTO;
1484

1485
                                        int pidfd;
10✔
1486
                                        ssize_t n = receive_one_fd_iov(
20✔
1487
                                                        pidref_transport_fds[0],
1488
                                                        &IOVEC_MAKE(&pid, sizeof(pid)),
10✔
1489
                                                        /* iovlen= */ 1,
1490
                                                        /* flags= */ 0,
1491
                                                        &pidfd);
1492
                                        if (n < 0)
10✔
UNCOV
1493
                                                return log_full_errno(prio, n, "Failed to receive child pidref: %m");
×
1494

1495
                                        *ret = (PidRef) { .pid = pid, .fd = pidfd };
10✔
1496
                                }
1497

1498
                                return 1; /* return in the parent */
11✔
1499
                        }
1500

1501
                        pidref_transport_fds[0] = safe_close(pidref_transport_fds[0]);
17✔
1502
                        intermediary = true;
17✔
1503
                }
1504
        }
1505

1506
        if ((flags & (FORK_NEW_MOUNTNS|FORK_NEW_USERNS|FORK_NEW_NETNS|FORK_NEW_PIDNS)) != 0)
29,106✔
1507
                pid = raw_clone(SIGCHLD|
6,041✔
1508
                                (FLAGS_SET(flags, FORK_NEW_MOUNTNS) ? CLONE_NEWNS : 0) |
6,041✔
1509
                                (FLAGS_SET(flags, FORK_NEW_USERNS) ? CLONE_NEWUSER : 0) |
6,041✔
1510
                                (FLAGS_SET(flags, FORK_NEW_NETNS) ? CLONE_NEWNET : 0) |
6,041✔
1511
                                (FLAGS_SET(flags, FORK_NEW_PIDNS) ? CLONE_NEWPID : 0));
6,041✔
1512
        else
1513
                pid = fork();
23,065✔
1514
        if (pid < 0)
60,373✔
1515
                return log_full_errno(prio, errno, "Failed to fork off '%s': %m", strna(name));
2✔
1516
        if (pid > 0) {
60,372✔
1517

1518
                /* If we are in the intermediary process, exit now */
1519
                if (intermediary) {
28,687✔
1520
                        if (pidref_transport_fds[1] >= 0) {
11✔
1521
                                _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
10✔
1522

1523
                                r = pidref_set_pid(&pidref, pid);
10✔
1524
                                if (r < 0) {
10✔
UNCOV
1525
                                        log_full_errno(prio, r, "Failed to open reference to PID "PID_FMT": %m", pid);
×
UNCOV
1526
                                        _exit(EXIT_FAILURE);
×
1527
                                }
1528

1529
                                r = send_one_fd_iov(
10✔
1530
                                                pidref_transport_fds[1],
1531
                                                pidref.fd,
1532
                                                &IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
1533
                                                /* iovlen= */ 1,
1534
                                                /* flags= */ 0);
1535
                                if (r < 0) {
10✔
UNCOV
1536
                                        log_full_errno(prio, r, "Failed to send child pidref: %m");
×
UNCOV
1537
                                        _exit(EXIT_FAILURE);
×
1538
                                }
1539
                        }
1540

1541
                        _exit(EXIT_SUCCESS);
11✔
1542
                }
1543

1544
                /* We are in the parent process */
1545
                log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid);
28,676✔
1546

1547
                if (flags & FORK_WAIT) {
28,676✔
1548
                        if (block_all) {
889✔
1549
                                /* undo everything except SIGCHLD */
1550
                                ss = saved_ss;
725✔
1551
                                assert_se(sigaddset(&ss, SIGCHLD) >= 0);
725✔
1552
                                (void) sigprocmask(SIG_SETMASK, &ss, NULL);
725✔
1553
                        }
1554

1555
                        r = pidref_wait_for_terminate_and_check(
889✔
1556
                                        name,
1557
                                        &PIDREF_MAKE_FROM_PID(pid),
889✔
1558
                                        FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1559
                        if (r < 0)
889✔
1560
                                return r;
889✔
1561
                        if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */
889✔
1562
                                return -EPROTO;
1563

1564
                        /* If we are in the parent and successfully waited, then the process doesn't exist anymore. */
1565
                        if (ret)
889✔
1566
                                *ret = PIDREF_NULL;
2✔
1567

1568
                        return 1;
889✔
1569
                }
1570

1571
                if (ret) {
27,787✔
1572
                        r = pidref_set_pid(ret, pid);
26,531✔
1573
                        if (r < 0) /* Let's not fail for this, no matter what, the process exists after all, and that's key */
26,531✔
UNCOV
1574
                                *ret = PIDREF_MAKE_FROM_PID(pid);
×
1575
                }
1576

1577
                return 1;
27,787✔
1578
        }
1579

1580
        /* We are in the child process */
1581

1582
        pidref_transport_fds[1] = safe_close(pidref_transport_fds[1]);
31,685✔
1583

1584
        /* Restore signal mask manually */
1585
        saved_ssp = NULL;
31,685✔
1586

1587
        if (flags & FORK_REOPEN_LOG) {
31,685✔
1588
                /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1589
                log_close();
7,764✔
1590
                log_set_open_when_needed(true);
7,764✔
1591
                log_settle_target();
7,764✔
1592
        }
1593

1594
        if (name) {
31,685✔
1595
                r = rename_process(name);
31,685✔
1596
                if (r < 0)
31,685✔
UNCOV
1597
                        log_full_errno(flags & FORK_LOG ? LOG_WARNING : LOG_DEBUG,
×
1598
                                       r, "Failed to rename process, ignoring: %m");
1599
        }
1600

1601
        /* let's disable dlopen() in the child, as a paranoia safety precaution: children should not live for
1602
         * long and only do minimal work before exiting or exec()ing. Doing dlopen() is not either. If people
1603
         * want dlopen() they should do it before forking. This is a safety precaution in particular for
1604
         * cases where the child does namespace shenanigans: we should never end up loading a module from a
1605
         * foreign environment. Note that this has no effect on NSS! (i.e. it only has effect on uses of our
1606
         * dlopen_safe(), which we use comprehensively in our codebase, but glibc NSS doesn't bother, of
1607
         * course.) */
1608
        if (!FLAGS_SET(flags, FORK_ALLOW_DLOPEN))
31,685✔
1609
                block_dlopen();
31,646✔
1610

1611
        if (flags & (FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT|FORK_DEATHSIG_SIGKILL))
31,685✔
1612
                if (prctl(PR_SET_PDEATHSIG, fork_flags_to_signal(flags)) < 0) {
30,219✔
UNCOV
1613
                        log_full_errno(prio, errno, "Failed to set death signal: %m");
×
UNCOV
1614
                        _exit(EXIT_FAILURE);
×
1615
                }
1616

1617
        if (flags & FORK_RESET_SIGNALS) {
31,685✔
1618
                r = reset_all_signal_handlers();
26,350✔
1619
                if (r < 0) {
26,350✔
UNCOV
1620
                        log_full_errno(prio, r, "Failed to reset signal handlers: %m");
×
UNCOV
1621
                        _exit(EXIT_FAILURE);
×
1622
                }
1623

1624
                /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1625
                r = reset_signal_mask();
26,350✔
1626
                if (r < 0) {
26,350✔
UNCOV
1627
                        log_full_errno(prio, r, "Failed to reset signal mask: %m");
×
UNCOV
1628
                        _exit(EXIT_FAILURE);
×
1629
                }
1630
        } else if (block_signals) { /* undo what we did above */
5,335✔
1631
                if (sigprocmask(SIG_SETMASK, &saved_ss, NULL) < 0) {
4,885✔
1632
                        log_full_errno(prio, errno, "Failed to restore signal mask: %m");
×
UNCOV
1633
                        _exit(EXIT_FAILURE);
×
1634
                }
1635
        }
1636

1637
        if (flags & (FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGKILL|FORK_DEATHSIG_SIGINT)) {
31,685✔
1638
                pid_t ppid;
30,219✔
1639
                /* Let's see if the parent PID is still the one we started from? If not, then the parent
1640
                 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1641

1642
                ppid = getppid();
30,219✔
1643
                if (ppid == 0)
30,219✔
1644
                        /* Parent is in a different PID namespace. */;
1645
                else if (ppid != original_pid) {
30,180✔
UNCOV
1646
                        int sig = fork_flags_to_signal(flags);
×
UNCOV
1647
                        log_debug("Parent died early, raising %s.", signal_to_string(sig));
×
UNCOV
1648
                        (void) raise(sig);
×
UNCOV
1649
                        _exit(EXIT_FAILURE);
×
1650
                }
1651
        }
1652

1653
        if (FLAGS_SET(flags, FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE)) {
31,685✔
1654
                /* Optionally, make sure we never propagate mounts to the host. */
1655
                if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
156✔
UNCOV
1656
                        log_full_errno(prio, errno, "Failed to remount root directory as MS_SLAVE: %m");
×
UNCOV
1657
                        _exit(EXIT_FAILURE);
×
1658
                }
1659
        }
1660

1661
        if (FLAGS_SET(flags, FORK_PRIVATE_TMP)) {
31,685✔
UNCOV
1662
                assert(FLAGS_SET(flags, FORK_NEW_MOUNTNS));
×
1663

1664
                /* Optionally, overmount new tmpfs instance on /tmp/. */
UNCOV
1665
                r = mount_nofollow("tmpfs", "/tmp", "tmpfs",
×
1666
                                   MS_NOSUID|MS_NODEV,
1667
                                   "mode=01777" TMPFS_LIMITS_RUN);
UNCOV
1668
                if (r < 0) {
×
1669
                        log_full_errno(prio, r, "Failed to overmount /tmp/: %m");
×
UNCOV
1670
                        _exit(EXIT_FAILURE);
×
1671
                }
1672
        }
1673

1674
        if (flags & FORK_REARRANGE_STDIO) {
31,685✔
1675
                if (stdio_fds) {
15,911✔
1676
                        r = rearrange_stdio(stdio_fds[0], stdio_fds[1], stdio_fds[2]);
15,895✔
1677
                        if (r < 0) {
15,895✔
UNCOV
1678
                                log_full_errno(prio, r, "Failed to rearrange stdio fds: %m");
×
UNCOV
1679
                                _exit(EXIT_FAILURE);
×
1680
                        }
1681

1682
                        /* Turn off O_NONBLOCK on the fdio fds, in case it was left on */
1683
                        stdio_disable_nonblock();
15,895✔
1684
                } else {
1685
                        r = make_null_stdio();
16✔
1686
                        if (r < 0) {
16✔
UNCOV
1687
                                log_full_errno(prio, r, "Failed to connect stdin/stdout to /dev/null: %m");
×
UNCOV
1688
                                _exit(EXIT_FAILURE);
×
1689
                        }
1690
                }
1691
        } else if (flags & FORK_STDOUT_TO_STDERR) {
15,774✔
1692
                if (dup2(STDERR_FILENO, STDOUT_FILENO) < 0) {
2✔
UNCOV
1693
                        log_full_errno(prio, errno, "Failed to connect stdout to stderr: %m");
×
UNCOV
1694
                        _exit(EXIT_FAILURE);
×
1695
                }
1696
        }
1697

1698
        if (flags & FORK_CLOSE_ALL_FDS) {
31,685✔
1699
                /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1700
                log_close();
25,167✔
1701

1702
                r = close_all_fds(except_fds, n_except_fds);
25,167✔
1703
                if (r < 0) {
25,167✔
UNCOV
1704
                        log_full_errno(prio, r, "Failed to close all file descriptors: %m");
×
UNCOV
1705
                        _exit(EXIT_FAILURE);
×
1706
                }
1707
        }
1708

1709
        if (flags & FORK_PACK_FDS) {
31,685✔
1710
                /* FORK_CLOSE_ALL_FDS ensures that except_fds are the only FDs >= 3 that are
1711
                 * open, this is including the log. This is required by pack_fds, which will
1712
                 * get stuck in an infinite loop of any FDs other than except_fds are open. */
1713
                assert(FLAGS_SET(flags, FORK_CLOSE_ALL_FDS));
118✔
1714

1715
                r = pack_fds(except_fds, n_except_fds);
118✔
1716
                if (r < 0) {
118✔
UNCOV
1717
                        log_full_errno(prio, r, "Failed to pack file descriptors: %m");
×
UNCOV
1718
                        _exit(EXIT_FAILURE);
×
1719
                }
1720
        }
1721

1722
        if (flags & FORK_CLOEXEC_OFF) {
31,685✔
1723
                r = fd_cloexec_many(except_fds, n_except_fds, false);
133✔
1724
                if (r < 0) {
133✔
UNCOV
1725
                        log_full_errno(prio, r, "Failed to turn off O_CLOEXEC on file descriptors: %m");
×
UNCOV
1726
                        _exit(EXIT_FAILURE);
×
1727
                }
1728
        }
1729

1730
        /* When we were asked to reopen the logs, do so again now */
1731
        if (flags & FORK_REOPEN_LOG) {
31,685✔
1732
                log_open();
7,764✔
1733
                log_set_open_when_needed(false);
7,764✔
1734
        }
1735

1736
        if (flags & FORK_RLIMIT_NOFILE_SAFE) {
31,685✔
1737
                r = rlimit_nofile_safe();
16,921✔
1738
                if (r < 0) {
16,921✔
UNCOV
1739
                        log_full_errno(prio, r, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
×
UNCOV
1740
                        _exit(EXIT_FAILURE);
×
1741
                }
1742
        }
1743

1744
        if (!FLAGS_SET(flags, FORK_KEEP_NOTIFY_SOCKET)) {
31,685✔
1745
                r = RET_NERRNO(unsetenv("NOTIFY_SOCKET"));
31,685✔
UNCOV
1746
                if (r < 0) {
×
UNCOV
1747
                        log_full_errno(prio, r, "Failed to unset $NOTIFY_SOCKET: %m");
×
UNCOV
1748
                        _exit(EXIT_FAILURE);
×
1749
                }
1750
        }
1751

1752
        if (FLAGS_SET(flags, FORK_FREEZE))
31,685✔
UNCOV
1753
                freeze();
×
1754

1755
        if (ret) {
31,685✔
1756
                r = pidref_set_self(ret);
29,406✔
1757
                if (r < 0) {
29,406✔
UNCOV
1758
                        log_full_errno(prio, r, "Failed to acquire PID reference on ourselves: %m");
×
UNCOV
1759
                        _exit(EXIT_FAILURE);
×
1760
                }
1761
        }
1762

1763
        return 0;
1764
}
1765

1766
int namespace_fork_full(
136✔
1767
                const char *outer_name,
1768
                const char *inner_name,
1769
                int except_fds[],
1770
                size_t n_except_fds,
1771
                ForkFlags flags,
1772
                int pidns_fd,
1773
                int mntns_fd,
1774
                int netns_fd,
1775
                int userns_fd,
1776
                int root_fd,
1777
                PidRef *ret) {
1778

UNCOV
1779
        _cleanup_(pidref_done_sigkill_wait) PidRef pidref_outer = PIDREF_NULL;
×
1780
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
228✔
1781
        int r, prio = FLAGS_SET(flags, FORK_LOG) ? LOG_ERR : LOG_DEBUG;
136✔
1782

1783
        /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1784
         * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1785
         * /proc/self/fd works correctly.
1786
         *
1787
         * TODO: once we can rely on PIDFD_INFO_EXIT, do not keep the middle process around and instead
1788
         * return the pidfd of the inner process for direct tracking. */
1789

1790
        /* Insist on PDEATHSIG being enabled, as the pid returned is the one of the middle man, and otherwise
1791
         * killing of it won't be propagated to the inner child. */
1792
        assert((flags & (FORK_DEATHSIG_SIGKILL|FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT)) != 0);
136✔
1793
        assert((flags & (FORK_DETACH|FORK_FREEZE)) == 0);
136✔
1794
        assert(!FLAGS_SET(flags, FORK_ALLOW_DLOPEN)); /* never allow loading shared library from another ns */
136✔
1795

1796
        /* We want read() to block as a synchronization point */
1797
        assert_cc(sizeof(int) <= PIPE_BUF);
136✔
1798
        if (pipe2(errno_pipe_fd, O_CLOEXEC) < 0)
136✔
UNCOV
1799
                return log_full_errno(prio, errno, "Failed to create pipe: %m");
×
1800

1801
        r = pidref_safe_fork_full(
363✔
1802
                        outer_name,
1803
                        /* stdio_fds= */ NULL, /* except_fds= */ NULL, /* n_except_fds= */ 0,
1804
                        (flags|FORK_DEATHSIG_SIGKILL) & ~(FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT|FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_USERNS|FORK_NEW_NETNS|FORK_NEW_PIDNS|FORK_CLOSE_ALL_FDS|FORK_PACK_FDS|FORK_CLOEXEC_OFF|FORK_RLIMIT_NOFILE_SAFE),
136✔
1805
                        &pidref_outer);
1806
        if (r == -EPROTO && FLAGS_SET(flags, FORK_WAIT)) {
227✔
UNCOV
1807
                errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
×
1808

UNCOV
1809
                int k = read_errno(errno_pipe_fd[0]);
×
UNCOV
1810
                if (k < 0 && k != -EIO)
×
1811
                        return k;
1812
        }
1813
        if (r < 0)
227✔
1814
                return r;
1815
        if (r == 0) {
227✔
UNCOV
1816
                _cleanup_(pidref_done) PidRef pidref_inner = PIDREF_NULL;
×
1817

1818
                /* Child */
1819

1820
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
91✔
1821

1822
                r = namespace_enter(pidns_fd, mntns_fd, netns_fd, userns_fd, root_fd);
91✔
1823
                if (r < 0) {
91✔
UNCOV
1824
                        log_full_errno(prio, r, "Failed to join namespace: %m");
×
UNCOV
1825
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1826
                }
1827

1828
                /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1829
                r = pidref_safe_fork_full(
274✔
1830
                                inner_name,
1831
                                NULL,
1832
                                except_fds, n_except_fds,
1833
                                flags & ~(FORK_WAIT|FORK_RESET_SIGNALS|FORK_REARRANGE_STDIO|FORK_FLUSH_STDIO|FORK_STDOUT_TO_STDERR),
91✔
1834
                                &pidref_inner);
1835
                if (r < 0)
183✔
UNCOV
1836
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1837
                if (r == 0) {
183✔
1838
                        /* Child */
1839

1840
                        if (!FLAGS_SET(flags, FORK_CLOSE_ALL_FDS)) {
92✔
1841
                                errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
89✔
1842
                                pidref_done(&pidref_outer);
89✔
1843
                        } else {
1844
                                errno_pipe_fd[1] = -EBADF;
3✔
1845
                                pidref_outer = PIDREF_NULL;
3✔
1846
                        }
1847

1848
                        if (ret)
92✔
1849
                                *ret = TAKE_PIDREF(pidref_inner);
92✔
1850
                        return 0;
92✔
1851
                }
1852

1853
                log_close();
91✔
1854
                log_set_open_when_needed(true);
91✔
1855

1856
                (void) close_all_fds(&pidref_inner.fd, 1);
91✔
1857

1858
                r = pidref_wait_for_terminate_and_check(
182✔
1859
                                inner_name,
1860
                                &pidref_inner,
1861
                                FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1862
                if (r < 0)
91✔
UNCOV
1863
                        _exit(EXIT_FAILURE);
×
1864

1865
                _exit(r);
91✔
1866
        }
1867

1868
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
136✔
1869

1870
        r = read_errno(errno_pipe_fd[0]);
136✔
1871
        if (r < 0)
136✔
1872
                return r; /* the child logs about failures on its own, no need to duplicate here */
1873

1874
        if (ret)
136✔
1875
                *ret = TAKE_PIDREF(pidref_outer);
136✔
1876
        else
UNCOV
1877
                pidref_done(&pidref_outer); /* disarm sigkill_wait */
×
1878

1879
        return 1;
1880
}
1881

1882
bool oom_score_adjust_is_valid(int oa) {
7,006✔
1883
        return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
7,006✔
1884
}
1885

1886
int set_oom_score_adjust(int value) {
3,774✔
1887
        char t[DECIMAL_STR_MAX(int)];
3,774✔
1888

1889
        if (!oom_score_adjust_is_valid(value))
3,774✔
1890
                return -EINVAL;
3,774✔
1891

1892
        xsprintf(t, "%i", value);
3,774✔
1893

1894
        return write_string_file("/proc/self/oom_score_adj", t,
3,774✔
1895
                                 WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
1896
}
1897

1898
int get_oom_score_adjust(int *ret) {
2,523✔
1899
        _cleanup_free_ char *t = NULL;
2,523✔
1900
        int r, a;
2,523✔
1901

1902
        r = read_virtual_file("/proc/self/oom_score_adj", SIZE_MAX, &t, NULL);
2,523✔
1903
        if (r < 0)
2,523✔
1904
                return r;
1905

1906
        delete_trailing_chars(t, WHITESPACE);
2,523✔
1907

1908
        r = safe_atoi(t, &a);
2,523✔
1909
        if (r < 0)
2,523✔
1910
                return r;
1911

1912
        if (!oom_score_adjust_is_valid(a))
2,523✔
1913
                return -ENODATA;
1914

1915
        if (ret)
2,523✔
1916
                *ret = a;
2,523✔
1917

1918
        return 0;
1919
}
1920

1921
static int rlimit_to_nice(rlim_t limit) {
2✔
1922
        if (limit <= 1)
2✔
1923
                return PRIO_MAX-1; /* i.e. 19 */
1924

1925
        if (limit >= -PRIO_MIN + PRIO_MAX)
2✔
1926
                return PRIO_MIN; /* i.e. -20 */
1927

1928
        return PRIO_MAX - (int) limit;
2✔
1929
}
1930

1931
int setpriority_closest(int priority) {
25✔
1932
        struct rlimit highest;
25✔
1933
        int r, current, limit;
25✔
1934

1935
        /* Try to set requested nice level */
1936
        r = RET_NERRNO(setpriority(PRIO_PROCESS, 0, priority));
25✔
1937
        if (r >= 0)
2✔
1938
                return 1;
23✔
1939
        if (!ERRNO_IS_NEG_PRIVILEGE(r))
2✔
1940
                return r;
1941

1942
        errno = 0;
2✔
1943
        current = getpriority(PRIO_PROCESS, 0);
2✔
1944
        if (errno != 0)
2✔
UNCOV
1945
                return -errno;
×
1946

1947
        if (priority == current)
2✔
1948
                return 1;
1949

1950
       /* Hmm, we'd expect that raising the nice level from our status quo would always work. If it doesn't,
1951
        * then the whole setpriority() system call is blocked to us, hence let's propagate the error
1952
        * right-away */
1953
        if (priority > current)
2✔
1954
                return r;
1955

1956
        if (getrlimit(RLIMIT_NICE, &highest) < 0)
2✔
UNCOV
1957
                return -errno;
×
1958

1959
        limit = rlimit_to_nice(highest.rlim_cur);
2✔
1960

1961
        /* Push to the allowed limit if we're higher than that. Note that we could also be less nice than
1962
         * limit allows us, but still higher than what's requested. In that case our current value is
1963
         * the best choice. */
1964
        if (current > limit)
2✔
1965
                if (setpriority(PRIO_PROCESS, 0, limit) < 0)
2✔
UNCOV
1966
                        return -errno;
×
1967

1968
        log_debug("Cannot set requested nice level (%i), using next best (%i).", priority, MIN(current, limit));
2✔
1969
        return 0;
1970
}
1971

UNCOV
1972
_noreturn_ void freeze(void) {
×
UNCOV
1973
        log_close();
×
1974

1975
        /* Make sure nobody waits for us (i.e. on one of our sockets) anymore. Note that we use
1976
         * close_all_fds_without_malloc() instead of plain close_all_fds() here, since we want this function
1977
         * to be compatible with being called from signal handlers. */
UNCOV
1978
        (void) close_all_fds_without_malloc(NULL, 0);
×
1979

1980
        /* Let's not freeze right away, but keep reaping zombies. */
UNCOV
1981
        for (;;) {
×
1982
                siginfo_t si = {};
×
1983

UNCOV
1984
                if (waitid(P_ALL, 0, &si, WEXITED) < 0 && errno != EINTR)
×
1985
                        break;
1986
        }
1987

1988
        /* waitid() failed with an ECHLD error (because there are no left-over child processes) or any other
1989
         * (unexpected) error. Freeze for good now! */
UNCOV
1990
        for (;;)
×
UNCOV
1991
                pause();
×
1992
}
1993

1994
int get_process_threads(pid_t pid) {
7✔
1995
        _cleanup_free_ char *t = NULL;
7✔
1996
        int n, r;
7✔
1997

1998
        if (pid < 0)
7✔
1999
                return -EINVAL;
2000

2001
        r = procfs_file_get_field(pid, "status", "Threads", &t);
7✔
2002
        if (r == -ENOENT)
7✔
2003
                return -ESRCH;
2004
        if (r < 0)
7✔
2005
                return r;
2006

2007
        r = safe_atoi(t, &n);
7✔
2008
        if (r < 0)
7✔
2009
                return r;
2010
        if (n < 0)
7✔
UNCOV
2011
                return -EINVAL;
×
2012

2013
        return n;
2014
}
2015

2016
int is_reaper_process(void) {
3,714✔
2017
        int b = 0;
3,714✔
2018

2019
        /* Checks if we are running in a reaper process, i.e. if we are expected to deal with processes
2020
         * reparented to us. This simply checks if we are PID 1 or if PR_SET_CHILD_SUBREAPER was called. */
2021

2022
        if (getpid_cached() == 1)
3,714✔
2023
                return true;
3,714✔
2024

2025
        if (prctl(PR_GET_CHILD_SUBREAPER, (unsigned long) &b, 0UL, 0UL, 0UL) < 0)
366✔
UNCOV
2026
                return -errno;
×
2027

2028
        return b != 0;
366✔
2029
}
2030

2031
int make_reaper_process(bool b) {
667✔
2032

2033
        if (getpid_cached() == 1) {
667✔
2034

2035
                if (!b)
53✔
2036
                        return -EINVAL;
2037

2038
                return 0;
53✔
2039
        }
2040

2041
        /* Some prctl()s insist that all 5 arguments are specified, others do not. Let's always specify all,
2042
         * to avoid any ambiguities */
2043
        if (prctl(PR_SET_CHILD_SUBREAPER, (unsigned long) b, 0UL, 0UL, 0UL) < 0)
614✔
UNCOV
2044
                return -errno;
×
2045

2046
        return 0;
2047
}
2048

UNCOV
2049
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(posix_spawnattr_t*, posix_spawnattr_destroy, NULL);
×
2050

2051
int posix_spawn_wrapper(
2,525✔
2052
                const char *path,
2053
                char * const *argv,
2054
                char * const *envp,
2055
                const char *cgroup,
2056
                PidRef *ret_pidref) {
2057

2058
        short flags = POSIX_SPAWN_SETSIGMASK;
2,525✔
2059
        posix_spawnattr_t attr;
2,525✔
2060
        sigset_t mask;
2,525✔
2061
        int r;
2,525✔
2062

2063
        /* Forks and invokes 'path' with 'argv' and 'envp' using CLONE_VM and CLONE_VFORK, which means the
2064
         * caller will be blocked until the child either exits or exec's. The memory of the child will be
2065
         * fully shared with the memory of the parent, so that there are no copy-on-write or memory.max
2066
         * issues.
2067
         *
2068
         * Also, move the newly-created process into 'cgroup' through POSIX_SPAWN_SETCGROUP (clone3())
2069
         * if available.
2070
         * returns 1: We're already in the right cgroup
2071
         *         0: 'cgroup' not specified or POSIX_SPAWN_SETCGROUP is not supported. The caller
2072
         *            needs to call 'cg_attach' on their own */
2073

2074
        assert(path);
2,525✔
2075
        assert(argv);
2,525✔
2076
        assert(ret_pidref);
2,525✔
2077

2078
        assert_se(sigfillset(&mask) >= 0);
2,525✔
2079

2080
        r = posix_spawnattr_init(&attr);
2,525✔
2081
        if (r != 0)
2,525✔
2082
                return -r; /* These functions return a positive errno on failure */
2,525✔
2083

2084
        /* Initialization needs to succeed before we can set up a destructor. */
2085
        _unused_ _cleanup_(posix_spawnattr_destroyp) posix_spawnattr_t *attr_destructor = &attr;
5,050✔
2086

2087
#if HAVE_PIDFD_SPAWN
2088
        static bool have_clone_into_cgroup = true; /* kernel 5.7+ */
2,525✔
2089
        _cleanup_close_ int cgroup_fd = -EBADF;
2,525✔
2090

2091
        if (cgroup && have_clone_into_cgroup) {
2,525✔
2092
                _cleanup_free_ char *resolved_cgroup = NULL;
2,525✔
2093

2094
                r = cg_get_path(cgroup, /* suffix= */ NULL, &resolved_cgroup);
2,525✔
2095
                if (r < 0)
2,525✔
2096
                        return r;
2097

2098
                cgroup_fd = open(resolved_cgroup, O_PATH|O_DIRECTORY|O_CLOEXEC);
2,525✔
2099
                if (cgroup_fd < 0)
2,525✔
UNCOV
2100
                        return -errno;
×
2101

2102
                r = posix_spawnattr_setcgroup_np(&attr, cgroup_fd);
2,525✔
2103
                if (r != 0)
2,525✔
2104
                        return -r;
×
2105

2106
                flags |= POSIX_SPAWN_SETCGROUP;
2,525✔
2107
        }
2108
#endif
2109

2110
        r = posix_spawnattr_setflags(&attr, flags);
2,525✔
2111
        if (r != 0)
2,525✔
UNCOV
2112
                return -r;
×
2113
        r = posix_spawnattr_setsigmask(&attr, &mask);
2,525✔
2114
        if (r != 0)
2,525✔
UNCOV
2115
                return -r;
×
2116

2117
#if HAVE_PIDFD_SPAWN
2118
        _cleanup_close_ int pidfd = -EBADF;
2,525✔
2119

2120
        r = pidfd_spawn(&pidfd, path, NULL, &attr, argv, envp);
2,525✔
2121
        if (ERRNO_IS_NOT_SUPPORTED(r) && FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP) && cg_is_threaded(cgroup) > 0)
2,525✔
2122
                return -EUCLEAN; /* clone3() could also return EOPNOTSUPP if the target cgroup is in threaded mode,
2123
                                    turn that into something recognizable */
2124
        if ((ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r)) &&
2,525✔
2125
            FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP)) {
2126
                /* Compiled on a newer host, or seccomp&friends blocking clone3()? Fallback, but
2127
                 * need to disable POSIX_SPAWN_SETCGROUP, which is what redirects to clone3().
2128
                 * CLONE_INTO_CGROUP definitely won't work, hence remember the fact so that we don't
2129
                 * retry every time.
2130
                 * Note, CLONE_INTO_CGROUP is supported since kernel v5.7, but some architectures still
2131
                 * do not support clone3(). Hence, we need to keep the fallback logic for a while. */
UNCOV
2132
                have_clone_into_cgroup = false;
×
2133

UNCOV
2134
                flags &= ~POSIX_SPAWN_SETCGROUP;
×
UNCOV
2135
                r = posix_spawnattr_setflags(&attr, flags);
×
2136
                if (r != 0)
×
UNCOV
2137
                        return -r;
×
2138

2139
                r = pidfd_spawn(&pidfd, path, NULL, &attr, argv, envp);
×
2140
        }
2141
        if (r != 0)
2,525✔
UNCOV
2142
                return -r;
×
2143

2144
        r = pidref_set_pidfd_consume(ret_pidref, TAKE_FD(pidfd));
2,525✔
2145
        if (r < 0)
2,525✔
2146
                return r;
2147

2148
        return FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP);
2,525✔
2149
#else
2150
        pid_t pid;
2151

2152
        r = posix_spawn(&pid, path, NULL, &attr, argv, envp);
2153
        if (r != 0)
2154
                return -r;
2155

2156
        r = pidref_set_pid(ret_pidref, pid);
2157
        if (r < 0)
2158
                return r;
2159

2160
        return 0; /* We did not use CLONE_INTO_CGROUP so return 0, the caller will have to move the child */
2161
#endif
2162
}
2163

2164
int proc_dir_open(DIR **ret) {
13✔
2165
        DIR *d;
13✔
2166

2167
        assert(ret);
13✔
2168

2169
        d = opendir("/proc");
13✔
2170
        if (!d)
13✔
UNCOV
2171
                return -errno;
×
2172

2173
        *ret = d;
13✔
2174
        return 0;
13✔
2175
}
2176

2177
int proc_dir_read(DIR *d, pid_t *ret) {
1,172✔
2178
        assert(d);
1,172✔
2179

2180
        for (;;) {
1,956✔
2181
                struct dirent *de;
1,956✔
2182

2183
                errno = 0;
1,956✔
2184
                de = readdir_no_dot(d);
1,956✔
2185
                if (!de) {
1,956✔
2186
                        if (errno != 0)
13✔
UNCOV
2187
                                return -errno;
×
2188

2189
                        break;
13✔
2190
                }
2191

2192
                if (!IN_SET(de->d_type, DT_DIR, DT_UNKNOWN))
1,943✔
2193
                        continue;
641✔
2194

2195
                if (parse_pid(de->d_name, ret) >= 0)
1,302✔
2196
                        return 1;
2197
        }
2198

2199
        if (ret)
13✔
2200
                *ret = 0;
13✔
2201
        return 0;
2202
}
2203

2204
int proc_dir_read_pidref(DIR *d, PidRef *ret) {
1,131✔
2205
        int r;
1,131✔
2206

2207
        assert(d);
1,131✔
2208

2209
        for (;;) {
1,131✔
2210
                pid_t pid;
1,131✔
2211

2212
                r = proc_dir_read(d, &pid);
1,131✔
2213
                if (r < 0)
1,131✔
2214
                        return r;
1,119✔
2215
                if (r == 0)
1,131✔
2216
                        break;
2217

2218
                r = pidref_set_pid(ret, pid);
1,119✔
2219
                if (r == -ESRCH) /* gone by now? skip it */
1,119✔
UNCOV
2220
                        continue;
×
2221
                if (r < 0)
1,119✔
UNCOV
2222
                        return r;
×
2223

2224
                return 1;
2225
        }
2226

2227
        if (ret)
12✔
2228
                *ret = PIDREF_NULL;
12✔
2229
        return 0;
2230
}
2231

2232
int safe_mlockall(int flags) {
162✔
2233
        int r;
162✔
2234

2235
        /* When dealing with sensitive data, let's lock ourselves into memory. We do this only when
2236
         * privileged however, as otherwise the amount of lockable memory that RLIMIT_MEMLOCK grants us is
2237
         * frequently too low to make this work. The resource limit has no effect on CAP_IPC_LOCK processes,
2238
         * hence that's the capability we check for. */
2239
        r = have_effective_cap(CAP_IPC_LOCK);
162✔
2240
        if (r < 0)
162✔
UNCOV
2241
                return log_debug_errno(r, "Failed to determine if we have CAP_IPC_LOCK: %m");
×
2242
        if (r == 0)
162✔
UNCOV
2243
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Lacking CAP_IPC_LOCK, skipping mlockall().");
×
2244

2245
        if (mlockall(flags) < 0)
162✔
UNCOV
2246
                return log_debug_errno(errno, "Failed to call mlockall(): %m");
×
2247

2248
        log_debug("Successfully called mlockall().");
162✔
2249
        return 0;
2250
}
2251

2252
static const char *const sigchld_code_table[] = {
2253
        [CLD_EXITED] = "exited",
2254
        [CLD_KILLED] = "killed",
2255
        [CLD_DUMPED] = "dumped",
2256
        [CLD_TRAPPED] = "trapped",
2257
        [CLD_STOPPED] = "stopped",
2258
        [CLD_CONTINUED] = "continued",
2259
};
2260

2261
DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
9,109✔
2262

2263
static const char* const sched_policy_table[] = {
2264
        [SCHED_OTHER] = "other",
2265
        [SCHED_BATCH] = "batch",
2266
        [SCHED_IDLE]  = "idle",
2267
        [SCHED_FIFO]  = "fifo",
2268
        [SCHED_EXT]   = "ext",
2269
        [SCHED_RR]    = "rr",
2270
};
2271

2272
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
53✔
2273

2274
_noreturn_ void report_errno_and_exit(int errno_fd, int error) {
185✔
2275
        int r;
185✔
2276

2277
        if (error >= 0)
185✔
2278
                _exit(EXIT_SUCCESS);
184✔
2279

2280
        assert(errno_fd >= 0);
1✔
2281

2282
        r = loop_write(errno_fd, &error, sizeof(error));
1✔
2283
        if (r < 0)
1✔
UNCOV
2284
                log_debug_errno(r, "Failed to write errno to errno_fd=%d: %m", errno_fd);
×
2285

2286
        _exit(EXIT_FAILURE);
1✔
2287
}
2288

2289
int read_errno(int errno_fd) {
139✔
2290
        int r;
139✔
2291

2292
        assert(errno_fd >= 0);
139✔
2293

2294
        /* The issue here is that it's impossible to distinguish between an error code returned by child and
2295
         * IO error arose when reading it. So, the function logs errors and return EIO for the later case. */
2296

2297
        ssize_t n = loop_read(errno_fd, &r, sizeof(r), /* do_poll= */ false);
139✔
2298
        if (n < 0) {
139✔
UNCOV
2299
                log_debug_errno(n, "Failed to read errno: %m");
×
UNCOV
2300
                return -EIO;
×
2301
        }
2302
        if (n == 0) /* the process exited without reporting an error, assuming success */
139✔
2303
                return 0;
2304
        if (n != sizeof(r))
×
UNCOV
2305
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Received unexpected amount of bytes (%zi) while reading errno.", n);
×
2306

UNCOV
2307
        if (r == 0)
×
2308
                return 0;
2309
        if (r < 0) /* child process reported an error, return it */
×
UNCOV
2310
                return log_debug_errno(r, "Child process failed with errno: %m");
×
2311

UNCOV
2312
        return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Received positive errno from child, refusing: %d", r);
×
2313
}
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