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

systemd / systemd / 21050823169

15 Jan 2026 12:56PM UTC coverage: 72.522% (-0.2%) from 72.704%
21050823169

push

github

keszybz
tree-wide: lock in all memory pages when mlockall() is utilized, and on demand

When employing MCL_FUTURE we don't actually want it to impose
immediate population of malloc()-ed pages. Hence let's set
MCL_ONFAULT everywhere.

Additionally, specify MCL_CURRENT to ensure future memory allocations
on already mapped pages are covered too. (Addresses
https://github.com/systemd/systemd/pull/40319#discussion_r2693726196)

Note that in shutdown the mlockall() is done to avoid keeping swap space
busy, hence a dedicated call w/ MCL_CURRENT and w/o MCL_ONFAULT is made.

2 of 4 new or added lines in 3 files covered. (50.0%)

1162 existing lines in 49 files now uncovered.

309356 of 426567 relevant lines covered (72.52%)

1129967.96 hits per line

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

84.41
/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/mount.h>
8
#include <sys/personality.h>
9
#include <sys/prctl.h>
10
#include <sys/wait.h>
11
#include <syslog.h>
12
#include <threads.h>
13
#include <unistd.h>
14
#if HAVE_VALGRIND_VALGRIND_H
15
#include <valgrind/valgrind.h>
16
#endif
17

18
#include "sd-messages.h"
19

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

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

62
static int get_process_state(pid_t pid) {
12,993✔
63
        _cleanup_free_ char *line = NULL;
12,993✔
64
        const char *p;
12,993✔
65
        char state;
12,993✔
66
        int r;
12,993✔
67

68
        assert(pid >= 0);
12,993✔
69

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

74
        p = procfs_file_alloca(pid, "stat");
12,993✔
75

76
        r = read_one_line_file(p, &line);
12,993✔
77
        if (r == -ENOENT)
12,993✔
78
                return -ESRCH;
79
        if (r < 0)
10,155✔
80
                return r;
81

82
        p = strrchr(line, ')');
10,152✔
83
        if (!p)
10,152✔
84
                return -EIO;
85

86
        p++;
10,152✔
87

88
        if (sscanf(p, " %c", &state) != 1)
10,152✔
89
                return -EIO;
90

91
        return (unsigned char) state;
10,152✔
92
}
93

94
int pid_get_comm(pid_t pid, char **ret) {
42,997✔
95
        _cleanup_free_ char *escaped = NULL, *comm = NULL;
42,997✔
96
        int r;
42,997✔
97

98
        assert(pid >= 0);
42,997✔
99
        assert(ret);
42,997✔
100

101
        if (pid == 0 || pid == getpid_cached()) {
42,997✔
102
                comm = new0(char, TASK_COMM_LEN + 1); /* Must fit in 16 byte according to prctl(2) */
22,717✔
103
                if (!comm)
22,717✔
104
                        return -ENOMEM;
105

106
                if (prctl(PR_GET_NAME, comm) < 0)
22,717✔
107
                        return -errno;
×
108
        } else {
109
                const char *p;
20,280✔
110

111
                p = procfs_file_alloca(pid, "comm");
20,280✔
112

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

121
        escaped = new(char, COMM_MAX_LEN);
38,843✔
122
        if (!escaped)
38,843✔
123
                return -ENOMEM;
124

125
        /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
126
        cellescape(escaped, COMM_MAX_LEN, comm);
38,843✔
127

128
        *ret = TAKE_PTR(escaped);
38,843✔
129
        return 0;
38,843✔
130
}
131

132
int pidref_get_comm(const PidRef *pid, char **ret) {
155✔
133
        _cleanup_free_ char *comm = NULL;
155✔
134
        int r;
155✔
135

136
        if (!pidref_is_set(pid))
155✔
137
                return -ESRCH;
138

139
        if (pidref_is_remote(pid))
310✔
140
                return -EREMOTE;
141

142
        r = pid_get_comm(pid->pid, &comm);
155✔
143
        if (r < 0)
155✔
144
                return r;
145

146
        r = pidref_verify(pid);
155✔
147
        if (r < 0)
155✔
148
                return r;
149

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

155
static int pid_get_cmdline_nulstr(
19,191✔
156
                pid_t pid,
157
                size_t max_size,
158
                ProcessCmdlineFlags flags,
159
                char **ret,
160
                size_t *ret_size) {
161

162
        _cleanup_free_ char *t = NULL;
19,191✔
163
        const char *p;
19,191✔
164
        size_t k;
19,191✔
165
        int r;
19,191✔
166

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

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

186
        if (k == 0) {
14,948✔
187
                if (!(flags & PROCESS_CMDLINE_COMM_FALLBACK))
486✔
188
                        return -ENOENT;
467✔
189

190
                /* Kernel threads have no argv[] */
191
                _cleanup_free_ char *comm = NULL;
19✔
192

193
                r = pid_get_comm(pid, &comm);
19✔
194
                if (r < 0)
19✔
195
                        return r;
196

197
                free(t);
19✔
198
                t = strjoin("[", comm, "]");
19✔
199
                if (!t)
19✔
200
                        return -ENOMEM;
201

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

208
        if (ret)
14,481✔
209
                *ret = TAKE_PTR(t);
14,481✔
210
        if (ret_size)
14,481✔
211
                *ret_size = k;
14,481✔
212

213
        return r;
214
}
215

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

221
        assert(pid >= 0);
14,531✔
222
        assert(ret);
14,531✔
223

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

238
        int full = pid_get_cmdline_nulstr(pid, max_columns, flags, &t, &k);
14,531✔
239
        if (full < 0)
14,531✔
240
                return full;
241

242
        if (flags & (PROCESS_CMDLINE_QUOTE | PROCESS_CMDLINE_QUOTE_POSIX)) {
9,896✔
243
                ShellEscapeFlags shflags = SHELL_ESCAPE_EMPTY |
9,532✔
244
                        FLAGS_SET(flags, PROCESS_CMDLINE_QUOTE_POSIX) * SHELL_ESCAPE_POSIX;
9,532✔
245

246
                assert(!(flags & PROCESS_CMDLINE_USE_LOCALE));
9,532✔
247

248
                _cleanup_strv_free_ char **args = NULL;
9,532✔
249

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

256
                ans = quote_command_line(args, shflags);
9,532✔
257
                if (!ans)
9,532✔
258
                        return -ENOMEM;
259
        } else {
260
                /* Arguments are separated by NULs. Let's replace those with spaces. */
261
                for (size_t i = 0; i < k - 1; i++)
17,884✔
262
                        if (t[i] == '\0')
17,520✔
263
                                t[i] = ' ';
664✔
264

265
                delete_trailing_chars(t, WHITESPACE);
364✔
266

267
                bool eight_bit = (flags & PROCESS_CMDLINE_USE_LOCALE) && !is_locale_utf8();
364✔
268

269
                ans = escape_non_printable_full(t, max_columns,
1,092✔
270
                                                eight_bit * XESCAPE_8_BIT | !full * XESCAPE_FORCE_ELLIPSIS);
674✔
271
                if (!ans)
364✔
272
                        return -ENOMEM;
273

274
                ans = str_realloc(ans);
364✔
275
        }
276

277
        *ret = ans;
9,896✔
278
        return 0;
9,896✔
279
}
280

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

285
        if (!pidref_is_set(pid))
46✔
286
                return -ESRCH;
287

288
        if (pidref_is_remote(pid))
92✔
289
                return -EREMOTE;
290

291
        r = pid_get_cmdline(pid->pid, max_columns, flags, &s);
46✔
292
        if (r < 0)
46✔
293
                return r;
294

295
        r = pidref_verify(pid);
46✔
296
        if (r < 0)
46✔
297
                return r;
298

299
        if (ret)
46✔
300
                *ret = TAKE_PTR(s);
46✔
301
        return 0;
302
}
303

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

310
        assert(pid >= 0);
4,660✔
311
        assert((flags & ~PROCESS_CMDLINE_COMM_FALLBACK) == 0);
4,660✔
312
        assert(ret);
4,660✔
313

314
        r = pid_get_cmdline_nulstr(pid, SIZE_MAX, flags, &t, &k);
4,660✔
315
        if (r < 0)
4,660✔
316
                return r;
317

318
        args = strv_parse_nulstr_full(t, k, /* drop_trailing_nuls= */ true);
4,585✔
319
        if (!args)
4,585✔
320
                return -ENOMEM;
321

322
        *ret = args;
4,585✔
323
        return 0;
4,585✔
324
}
325

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

330
        if (!pidref_is_set(pid))
×
331
                return -ESRCH;
332

333
        if (pidref_is_remote(pid))
×
334
                return -EREMOTE;
335

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

340
        r = pidref_verify(pid);
×
341
        if (r < 0)
×
342
                return r;
343

344
        if (ret)
×
345
                *ret = TAKE_PTR(args);
×
346

347
        return 0;
348
}
349

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

356
        assert(machine);
35✔
357
        assert(pid);
35✔
358

359
        if (streq(machine, ".host")) {
35✔
360
                *pid = 1;
1✔
361
                return 0;
1✔
362
        }
363

364
        if (!hostname_is_valid(machine, 0))
34✔
365
                return -EINVAL;
366

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

378
        if (!streq_ptr(class, "container"))
34✔
379
                return -EIO;
380

381
        r = parse_pid(s, &leader);
34✔
382
        if (r < 0)
34✔
383
                return r;
384
        if (leader <= 1)
34✔
385
                return -EIO;
386

387
        *pid = leader;
34✔
388
        return 0;
34✔
389
}
390

391
int pid_is_kernel_thread(pid_t pid) {
3,884✔
392
        int r;
3,884✔
393

394
        if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
3,884✔
395
                return 0;
3,884✔
396
        if (!pid_is_valid(pid))
3,859✔
397
                return -EINVAL;
398

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

407
        /* Skip past the comm field */
408
        char *q = strrchr(line, ')');
3,859✔
409
        if (!q)
3,859✔
410
                return -EINVAL;
411
        q++;
3,859✔
412

413
        /* Skip 6 fields to reach the flags field */
414
        for (size_t i = 0; i < 6; i++) {
27,013✔
415
                size_t l = strspn(q, WHITESPACE);
23,154✔
416
                if (l < 1)
23,154✔
417
                        return -EINVAL;
418
                q += l;
23,154✔
419

420
                l = strcspn(q, WHITESPACE);
23,154✔
421
                if (l < 1)
23,154✔
422
                        return -EINVAL;
423
                q += l;
23,154✔
424
        }
425

426
        /* Skip preceding whitespace */
427
        size_t l = strspn(q, WHITESPACE);
3,859✔
428
        if (l < 1)
3,859✔
429
                return -EINVAL;
430
        q += l;
3,859✔
431

432
        /* Truncate the rest */
433
        l = strcspn(q, WHITESPACE);
3,859✔
434
        if (l < 1)
3,859✔
435
                return -EINVAL;
436
        q[l] = 0;
3,859✔
437

438
        unsigned long long flags;
3,859✔
439
        r = safe_atollu(q, &flags);
3,859✔
440
        if (r < 0)
3,859✔
441
                return r;
442

443
        return !!(flags & PF_KTHREAD);
3,859✔
444
}
445

446
int pidref_is_kernel_thread(const PidRef *pid) {
1,625✔
447
        int result, r;
1,625✔
448

449
        if (!pidref_is_set(pid))
1,625✔
450
                return -ESRCH;
451

452
        if (pidref_is_remote(pid))
1,625✔
453
                return -EREMOTE;
454

455
        result = pid_is_kernel_thread(pid->pid);
1,625✔
456
        if (result < 0)
1,625✔
457
                return result;
458

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

463
        return result;
464
}
465

466
static int get_process_link_contents(pid_t pid, const char *proc_file, char **ret) {
14,004✔
467
        const char *p;
14,004✔
468
        int r;
14,004✔
469

470
        assert(proc_file);
14,004✔
471

472
        p = procfs_file_alloca(pid, proc_file);
14,008✔
473

474
        r = readlink_malloc(p, ret);
14,004✔
475
        return (r == -ENOENT && proc_mounted() > 0) ? -ESRCH : r;
14,004✔
476
}
477

478
int get_process_exe(pid_t pid, char **ret) {
13,978✔
479
        char *d;
13,978✔
480
        int r;
13,978✔
481

482
        assert(pid >= 0);
13,978✔
483

484
        r = get_process_link_contents(pid, "exe", ret);
13,978✔
485
        if (r < 0)
13,978✔
486
                return r;
487

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

494
        return 0;
495
}
496

497
int pid_get_uid(pid_t pid, uid_t *ret) {
3,895✔
498
        int r;
3,895✔
499

500
        assert(pid >= 0);
3,895✔
501
        assert(ret);
3,895✔
502

503
        if (pid == 0 || pid == getpid_cached()) {
3,895✔
504
                *ret = getuid();
2✔
505
                return 0;
3,895✔
506
        }
507

508
        _cleanup_free_ char *v = NULL;
3,893✔
509
        r = procfs_file_get_field(pid, "status", "Uid", &v);
3,893✔
510
        if (r == -ENOENT)
3,893✔
511
                return -ESRCH;
512
        if (r < 0)
172✔
513
                return r;
514

515
        return parse_uid(v, ret);
172✔
516
}
517

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

521
        if (!pidref_is_set(pid))
69✔
522
                return -ESRCH;
69✔
523

524
        if (pidref_is_remote(pid))
69✔
525
                return -EREMOTE;
526

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

533
        uid_t uid;
3✔
534
        r = pid_get_uid(pid->pid, &uid);
3✔
535
        if (r < 0)
3✔
536
                return r;
537

538
        r = pidref_verify(pid);
3✔
539
        if (r < 0)
3✔
540
                return r;
541

542
        if (ret)
3✔
543
                *ret = uid;
3✔
544
        return 0;
545
}
546

547
int get_process_gid(pid_t pid, gid_t *ret) {
3,892✔
548
        int r;
3,892✔
549

550
        assert(pid >= 0);
3,892✔
551
        assert(ret);
3,892✔
552

553
        if (pid == 0 || pid == getpid_cached()) {
3,892✔
554
                *ret = getgid();
1✔
555
                return 0;
3,892✔
556
        }
557

558
        _cleanup_free_ char *v = NULL;
3,891✔
559
        r = procfs_file_get_field(pid, "status", "Gid", &v);
3,891✔
560
        if (r == -ENOENT)
3,891✔
561
                return -ESRCH;
562
        if (r < 0)
170✔
563
                return r;
564

565
        return parse_gid(v, ret);
3,891✔
566
}
567

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

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

574
        return get_process_link_contents(pid, "cwd", ret);
13✔
575
}
576

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

582
#define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
583

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

591
        assert(pid >= 0);
15✔
592
        assert(ret);
15✔
593

594
        p = procfs_file_alloca(pid, "environ");
15✔
595

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

602
        for (;;) {
6,418✔
603
                char c;
6,433✔
604

605
                if (sz >= ENVIRONMENT_BLOCK_MAX)
6,433✔
606
                        return -ENOBUFS;
×
607

608
                if (!GREEDY_REALLOC(outcome, sz + 5))
6,433✔
609
                        return -ENOMEM;
610

611
                r = safe_fgetc(f, &c);
6,433✔
612
                if (r < 0)
6,433✔
613
                        return r;
614
                if (r == 0)
6,433✔
615
                        break;
616

617
                if (c == '\0')
6,418✔
618
                        outcome[sz++] = '\n';
228✔
619
                else
620
                        sz += cescape_char(c, outcome + sz);
6,190✔
621
        }
622

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

626
        return 0;
15✔
627
}
628

629
int pid_get_ppid(pid_t pid, pid_t *ret) {
1,527✔
630
        _cleanup_free_ char *line = NULL;
1,527✔
631
        unsigned long ppid;
1,527✔
632
        const char *p;
1,527✔
633
        int r;
1,527✔
634

635
        assert(pid >= 0);
1,527✔
636

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

642
        if (pid == getpid_cached()) {
1,523✔
643
                if (ret)
6✔
644
                        *ret = getppid();
6✔
645
                return 0;
6✔
646
        }
647

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

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

658
        p = strrchr(line, ')');
1,516✔
659
        if (!p)
1,516✔
660
                return -EIO;
661
        p++;
1,516✔
662

663
        if (sscanf(p, " "
1,516✔
664
                   "%*c "  /* state */
665
                   "%lu ", /* ppid */
666
                   &ppid) != 1)
667
                return -EIO;
668

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

675
        if ((pid_t) ppid < 0 || (unsigned long) (pid_t) ppid != ppid)
1,516✔
676
                return -ERANGE;
677

678
        if (ret)
1,516✔
679
                *ret = (pid_t) ppid;
1,516✔
680

681
        return 0;
682
}
683

684
int pidref_get_ppid(const PidRef *pidref, pid_t *ret) {
2,465✔
685
        int r;
2,465✔
686

687
        if (!pidref_is_set(pidref))
2,465✔
688
                return -ESRCH;
2,465✔
689

690
        if (pidref_is_remote(pidref))
2,465✔
691
                return -EREMOTE;
692

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

699
        pid_t ppid;
1,521✔
700
        r = pid_get_ppid(pidref->pid, ret ? &ppid : NULL);
1,521✔
701
        if (r < 0)
1,521✔
702
                return r;
703

704
        r = pidref_verify(pidref);
1,520✔
705
        if (r < 0)
1,520✔
706
                return r;
707

708
        if (ret)
1,520✔
709
                *ret = ppid;
1,520✔
710
        return 0;
711
}
712

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

717
        assert(ret);
11✔
718

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

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

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

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

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

743
                *ret = TAKE_PIDREF(parent);
10✔
744
                return 0;
10✔
745
        }
746

747
        /* Give up after 16 tries */
748
        return -ENOTRECOVERABLE;
749
}
750

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

756
        assert(pid >= 0);
580✔
757

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

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

768
        p = strrchr(line, ')');
580✔
769
        if (!p)
580✔
770
                return -EIO;
771
        p++;
580✔
772

773
        unsigned long llu;
580✔
774

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

799
        if (ret)
580✔
800
                *ret = jiffies_to_usec(llu); /* CLOCK_BOOTTIME */
580✔
801

802
        return 0;
803
}
804

805
int pidref_get_start_time(const PidRef *pid, usec_t *ret) {
580✔
806
        usec_t t;
580✔
807
        int r;
580✔
808

809
        if (!pidref_is_set(pid))
580✔
810
                return -ESRCH;
580✔
811

812
        if (pidref_is_remote(pid))
580✔
813
                return -EREMOTE;
814

815
        r = pid_get_start_time(pid->pid, ret ? &t : NULL);
580✔
816
        if (r < 0)
580✔
817
                return r;
818

819
        r = pidref_verify(pid);
580✔
820
        if (r < 0)
580✔
821
                return r;
822

823
        if (ret)
580✔
824
                *ret = t;
580✔
825

826
        return 0;
827
}
828

829
int get_process_umask(pid_t pid, mode_t *ret) {
21,976✔
830
        _cleanup_free_ char *m = NULL;
21,976✔
831
        int r;
21,976✔
832

833
        assert(pid >= 0);
21,976✔
834
        assert(ret);
21,976✔
835

836
        r = procfs_file_get_field(pid, "status", "Umask", &m);
21,976✔
837
        if (r == -ENOENT)
21,976✔
838
                return -ESRCH;
839
        if (r < 0)
21,976✔
840
                return r;
841

842
        return parse_mode(m, ret);
21,976✔
843
}
844

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

862
        if (!pidref_is_set(pidref))
6,858✔
863
                return -ESRCH;
6,858✔
864
        if (pidref_is_remote(pidref))
13,716✔
865
                return -EREMOTE;
866
        if (pidref->pid == 1 || pidref_is_self(pidref))
6,858✔
867
                return -ECHILD;
×
868

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

878
        int prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
6,858✔
879

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

885
        if (status.si_code == CLD_EXITED) {
6,858✔
886
                if (status.si_status != EXIT_SUCCESS)
6,858✔
887
                        log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
64✔
888
                                 "'%s' failed with exit status %i.", strna(name), status.si_status);
889
                else
890
                        log_debug("'%s' succeeded.", name);
6,794✔
891

892
                return status.si_status;
6,858✔
893

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

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

902
int kill_and_sigcont(pid_t pid, int sig) {
×
903
        int r;
×
904

905
        r = RET_NERRNO(kill(pid, sig));
×
906

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

912
        return r;
×
913
}
914

915
int getenv_for_pid(pid_t pid, const char *field, char **ret) {
4,770✔
916
        _cleanup_fclose_ FILE *f = NULL;
4,770✔
917
        const char *path;
4,770✔
918
        size_t sum = 0;
4,770✔
919
        int r;
4,770✔
920

921
        assert(pid >= 0);
4,770✔
922
        assert(field);
4,770✔
923
        assert(ret);
4,770✔
924

925
        if (pid == 0 || pid == getpid_cached())
4,770✔
926
                return strdup_to_full(ret, getenv(field));
14✔
927

928
        if (!pid_is_valid(pid))
4,756✔
929
                return -EINVAL;
930

931
        path = procfs_file_alloca(pid, "environ");
4,756✔
932

933
        r = fopen_unlocked(path, "re", &f);
4,756✔
934
        if (r == -ENOENT)
4,756✔
935
                return -ESRCH;
936
        if (r < 0)
4,349✔
937
                return r;
938

939
        for (;;) {
50,955✔
940
                _cleanup_free_ char *line = NULL;
23,981✔
941
                const char *match;
26,992✔
942

943
                if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
26,992✔
944
                        return -ENOBUFS;
945

946
                r = read_nul_string(f, LONG_LINE_MAX, &line);
26,992✔
947
                if (r < 0)
26,992✔
948
                        return r;
949
                if (r == 0)  /* EOF */
26,992✔
950
                        break;
951

952
                sum += r;
23,981✔
953

954
                match = startswith(line, field);
23,981✔
955
                if (match && *match == '=')
23,981✔
956
                        return strdup_to_full(ret, match + 1);
18✔
957
        }
958

959
        *ret = NULL;
3,011✔
960
        return 0;
3,011✔
961
}
962

963
int pidref_is_my_child(PidRef *pid) {
2,443✔
964
        int r;
2,443✔
965

966
        if (!pidref_is_set(pid))
2,443✔
967
                return -ESRCH;
2,443✔
968

969
        if (pidref_is_remote(pid))
2,443✔
970
                return -EREMOTE;
971

972
        if (pid->pid == 1 || pidref_is_self(pid))
2,443✔
973
                return false;
×
974

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

982
        return ppid == getpid_cached();
2,443✔
983
}
984

985
int pid_is_my_child(pid_t pid) {
×
986

987
        if (pid == 0)
×
988
                return false;
×
989

990
        return pidref_is_my_child(&PIDREF_MAKE_FROM_PID(pid));
×
991
}
992

993
int pidref_is_unwaited(PidRef *pid) {
8,821✔
994
        int r;
8,821✔
995

996
        /* Checks whether a PID is still valid at all, including a zombie */
997

998
        if (!pidref_is_set(pid))
8,821✔
999
                return -ESRCH;
1000

1001
        if (pidref_is_remote(pid))
8,820✔
1002
                return -EREMOTE;
1003

1004
        if (pid->pid == 1 || pidref_is_self(pid))
8,820✔
1005
                return true;
1✔
1006

1007
        r = pidref_kill(pid, 0);
8,819✔
1008
        if (r == -ESRCH)
8,819✔
1009
                return false;
1010
        if (r < 0)
2,135✔
1011
                return r;
182✔
1012

1013
        return true;
1014
}
1015

1016
int pid_is_unwaited(pid_t pid) {
8,244✔
1017

1018
        if (pid == 0)
8,244✔
1019
                return true;
8,244✔
1020

1021
        return pidref_is_unwaited(&PIDREF_MAKE_FROM_PID(pid));
8,244✔
1022
}
1023

1024
int pid_is_alive(pid_t pid) {
12,995✔
1025
        int r;
12,995✔
1026

1027
        /* Checks whether a PID is still valid and not a zombie */
1028

1029
        if (pid < 0)
12,995✔
1030
                return -ESRCH;
1031

1032
        if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
12,994✔
1033
                return true;
1034

1035
        if (pid == getpid_cached())
12,994✔
1036
                return true;
1037

1038
        r = get_process_state(pid);
12,993✔
1039
        if (r == -ESRCH)
12,993✔
1040
                return false;
1041
        if (r < 0)
10,152✔
1042
                return r;
1043

1044
        return r != 'Z';
10,152✔
1045
}
1046

1047
int pidref_is_alive(const PidRef *pidref) {
12,992✔
1048
        int r, result;
12,992✔
1049

1050
        if (!pidref_is_set(pidref))
12,992✔
1051
                return -ESRCH;
1052

1053
        if (pidref_is_remote(pidref))
12,990✔
1054
                return -EREMOTE;
1055

1056
        result = pid_is_alive(pidref->pid);
12,990✔
1057
        if (result < 0) {
12,990✔
1058
                assert(result != -ESRCH);
×
1059
                return result;
1060
        }
1061

1062
        r = pidref_verify(pidref);
12,990✔
1063
        if (r == -ESRCH)
12,990✔
1064
                return false;
1065
        if (r < 0)
10,146✔
1066
                return r;
×
1067

1068
        return result;
1069
}
1070

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

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

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

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

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

1098
        if (pidref_equal(a, b))
20✔
1099
                return true;
1100

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

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

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

1117
        return result;
1118
}
1119

1120
bool is_main_thread(void) {
7,097,313✔
1121
        static thread_local int cached = -1;
7,097,313✔
1122

1123
        if (cached < 0)
7,097,313✔
1124
                cached = getpid_cached() == gettid();
55,875✔
1125

1126
        return cached;
7,097,313✔
1127
}
1128

1129
bool oom_score_adjust_is_valid(int oa) {
6,640✔
1130
        return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
6,640✔
1131
}
1132

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

1136
        if (!s)
9✔
1137
                return PERSONALITY_INVALID;
1138

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

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

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

1154
        return PERSONALITY_INVALID;
1155
}
1156

1157
const char* personality_to_string(unsigned long p) {
2,783✔
1158
        Architecture architecture = _ARCHITECTURE_INVALID;
2,783✔
1159

1160
        if (p == PER_LINUX)
2,783✔
1161
                architecture = native_architecture();
1162
#ifdef ARCHITECTURE_SECONDARY
1163
        else if (p == PER_LINUX32)
2,778✔
1164
                architecture = ARCHITECTURE_SECONDARY;
1165
#endif
1166

1167
        if (architecture < 0)
1168
                return NULL;
1169

1170
        return architecture_to_string(architecture);
7✔
1171
}
1172

1173
int safe_personality(unsigned long p) {
1,483✔
1174
        int ret;
1,483✔
1175

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

1183
        errno = 0;
1,483✔
1184
        ret = personality(p);
1,483✔
1185
        if (ret < 0) {
1,483✔
1186
                if (errno != 0)
12✔
1187
                        return -errno;
12✔
1188

1189
                errno = -ret;
×
1190
        }
1191

1192
        return ret;
1193
}
1194

1195
int opinionated_personality(unsigned long *ret) {
1,468✔
1196
        int current;
1,468✔
1197

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

1202
        current = safe_personality(PERSONALITY_INVALID);
1,468✔
1203
        if (current < 0)
1,468✔
1204
                return current;
1205

1206
        if (((unsigned long) current & OPINIONATED_PERSONALITY_MASK) == PER_LINUX32)
1,468✔
1207
                *ret = PER_LINUX32;
×
1208
        else
1209
                *ret = PER_LINUX;
1,468✔
1210

1211
        return 0;
1212
}
1213

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

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

1241
bool nice_is_valid(int n) {
870✔
1242
        return n >= PRIO_MIN && n < PRIO_MAX;
870✔
1243
}
1244

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

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

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

1257
        r = sched_get_priority_min(policy);
4✔
1258
        if (r >= 0)
4✔
1259
                return r;
3✔
1260

1261
        /* Fallback priority */
1262
        return 0;
1263
}
1264

1265
int sched_get_priority_max_safe(int policy) {
4✔
1266
        int r;
4✔
1267

1268
        r = sched_get_priority_max(policy);
4✔
1269
        if (r >= 0)
4✔
1270
                return r;
3✔
1271

1272
        return 0;
1273
}
1274

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

1282
#define CACHED_PID_UNSET ((pid_t) 0)
1283
#define CACHED_PID_BUSY ((pid_t) -1)
1284

1285
static pid_t cached_pid = CACHED_PID_UNSET;
1286

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

1292
pid_t getpid_cached(void) {
149,857,961✔
1293
        static bool installed = false;
149,857,961✔
1294
        pid_t current_value = CACHED_PID_UNSET;
149,857,961✔
1295

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

1305
        (void) __atomic_compare_exchange_n(
149,857,961✔
1306
                        &cached_pid,
1307
                        &current_value,
1308
                        CACHED_PID_BUSY,
1309
                        false,
1310
                        __ATOMIC_SEQ_CST,
1311
                        __ATOMIC_SEQ_CST);
1312

1313
        switch (current_value) {
149,857,961✔
1314

1315
        case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
101,811✔
1316
                pid_t new_pid;
101,811✔
1317

1318
                new_pid = getpid();
101,811✔
1319

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

1325
                        if (pthread_atfork(NULL, NULL, reset_cached_pid) != 0) {
71,622✔
1326
                                /* OOM? Let's try again later */
1327
                                cached_pid = CACHED_PID_UNSET;
×
1328
                                return new_pid;
×
1329
                        }
1330

1331
                        installed = true;
71,622✔
1332
                }
1333

1334
                cached_pid = new_pid;
101,811✔
1335
                return new_pid;
101,811✔
1336
        }
1337

1338
        case CACHED_PID_BUSY: /* Somebody else is currently initializing */
×
1339
                return getpid();
×
1340

1341
        default: /* Properly initialized */
1342
                return current_value;
1343
        }
1344
}
1345

1346
int must_be_root(void) {
56✔
1347

1348
        if (geteuid() == 0)
56✔
1349
                return 0;
1350

1351
        return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be root.");
×
1352
}
1353

1354
pid_t clone_with_nested_stack(int (*fn)(void *), int flags, void *userdata) {
3,513✔
1355
        size_t ps;
3,513✔
1356
        pid_t pid;
3,513✔
1357
        void *mystack;
3,513✔
1358

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

1367
        assert((flags & (CLONE_VM|CLONE_PARENT_SETTID|CLONE_CHILD_SETTID|
3,513✔
1368
                         CLONE_CHILD_CLEARTID|CLONE_SETTLS)) == 0);
1369

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

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

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

1390
        return pid;
1391
}
1392

1393
static int fork_flags_to_signal(ForkFlags flags) {
28,375✔
1394
        return (flags & FORK_DEATHSIG_SIGTERM) ? SIGTERM :
28,375✔
1395
                (flags & FORK_DEATHSIG_SIGINT) ? SIGINT :
736✔
1396
                                                 SIGKILL;
1397
}
1398

1399
int pidref_safe_fork_full(
27,451✔
1400
                const char *name,
1401
                const int stdio_fds[3],
1402
                int except_fds[],
1403
                size_t n_except_fds,
1404
                ForkFlags flags,
1405
                PidRef *ret) {
1406

1407
        pid_t original_pid, pid;
27,451✔
1408
        sigset_t saved_ss, ss;
27,451✔
1409
        _unused_ _cleanup_(block_signals_reset) sigset_t *saved_ssp = NULL;
×
1410
        bool block_signals = false, block_all = false, intermediary = false;
27,451✔
1411
        _cleanup_close_pair_ int pidref_transport_fds[2] = EBADF_PAIR;
56,926✔
1412
        int prio, r;
27,451✔
1413

1414
        assert(!FLAGS_SET(flags, FORK_WAIT|FORK_FREEZE));
27,451✔
1415
        assert(!FLAGS_SET(flags, FORK_DETACH) ||
27,451✔
1416
               (flags & (FORK_WAIT|FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT|FORK_DEATHSIG_SIGKILL)) == 0);
1417

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

1422
        prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG;
27,451✔
1423

1424
        original_pid = getpid_cached();
27,451✔
1425

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

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

1436
                assert_se(sigfillset(&ss) >= 0);
23,402✔
1437
                block_signals = block_all = true;
1438

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

1442
                assert_se(sigemptyset(&ss) >= 0);
157✔
1443
                assert_se(sigaddset(&ss, SIGCHLD) >= 0);
157✔
1444
                block_signals = true;
1445
        }
1446

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

1453
        if (FLAGS_SET(flags, FORK_DETACH)) {
27,451✔
1454
                /* Fork off intermediary child if needed */
1455

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

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

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

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

1472
                                pidref_transport_fds[1] = safe_close(pidref_transport_fds[1]);
11✔
1473

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

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

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

1500
                                return 1; /* return in the parent */
11✔
1501
                        }
1502

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

1508
        if ((flags & (FORK_NEW_MOUNTNS|FORK_NEW_USERNS|FORK_NEW_NETNS|FORK_NEW_PIDNS)) != 0)
27,457✔
1509
                pid = raw_clone(SIGCHLD|
5,593✔
1510
                                (FLAGS_SET(flags, FORK_NEW_MOUNTNS) ? CLONE_NEWNS : 0) |
5,593✔
1511
                                (FLAGS_SET(flags, FORK_NEW_USERNS) ? CLONE_NEWUSER : 0) |
5,593✔
1512
                                (FLAGS_SET(flags, FORK_NEW_NETNS) ? CLONE_NEWNET : 0) |
5,593✔
1513
                                (FLAGS_SET(flags, FORK_NEW_PIDNS) ? CLONE_NEWPID : 0));
5,593✔
1514
        else
1515
                pid = fork();
21,864✔
1516
        if (pid < 0)
56,926✔
1517
                return log_full_errno(prio, errno, "Failed to fork off '%s': %m", strna(name));
×
1518
        if (pid > 0) {
56,926✔
1519

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

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

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

1543
                        _exit(EXIT_SUCCESS);
11✔
1544
                }
1545

1546
                /* We are in the parent process */
1547
                log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid);
27,104✔
1548

1549
                if (flags & FORK_WAIT) {
27,104✔
1550
                        if (block_all) {
841✔
1551
                                /* undo everything except SIGCHLD */
1552
                                ss = saved_ss;
684✔
1553
                                assert_se(sigaddset(&ss, SIGCHLD) >= 0);
684✔
1554
                                (void) sigprocmask(SIG_SETMASK, &ss, NULL);
684✔
1555
                        }
1556

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

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

1570
                        return 1;
841✔
1571
                }
1572

1573
                if (ret) {
26,263✔
1574
                        r = pidref_set_pid(ret, pid);
25,020✔
1575
                        if (r < 0) /* Let's not fail for this, no matter what, the process exists after all, and that's key */
25,020✔
1576
                                *ret = PIDREF_MAKE_FROM_PID(pid);
×
1577
                }
1578

1579
                return 1;
26,263✔
1580
        }
1581

1582
        /* We are in the child process */
1583

1584
        pidref_transport_fds[1] = safe_close(pidref_transport_fds[1]);
29,811✔
1585

1586
        /* Restore signal mask manually */
1587
        saved_ssp = NULL;
29,811✔
1588

1589
        if (flags & FORK_REOPEN_LOG) {
29,811✔
1590
                /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1591
                log_close();
6,810✔
1592
                log_set_open_when_needed(true);
6,810✔
1593
                log_settle_target();
6,810✔
1594
        }
1595

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

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

1613
        if (flags & (FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT|FORK_DEATHSIG_SIGKILL))
29,811✔
1614
                if (prctl(PR_SET_PDEATHSIG, fork_flags_to_signal(flags)) < 0) {
28,375✔
1615
                        log_full_errno(prio, errno, "Failed to set death signal: %m");
×
1616
                        _exit(EXIT_FAILURE);
×
1617
                }
1618

1619
        if (flags & FORK_RESET_SIGNALS) {
29,811✔
1620
                r = reset_all_signal_handlers();
24,842✔
1621
                if (r < 0) {
24,842✔
1622
                        log_full_errno(prio, r, "Failed to reset signal handlers: %m");
×
1623
                        _exit(EXIT_FAILURE);
×
1624
                }
1625

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

1639
        if (flags & (FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGKILL|FORK_DEATHSIG_SIGINT)) {
29,811✔
1640
                pid_t ppid;
28,375✔
1641
                /* Let's see if the parent PID is still the one we started from? If not, then the parent
1642
                 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1643

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

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

1663
        if (FLAGS_SET(flags, FORK_PRIVATE_TMP)) {
29,811✔
1664
                assert(FLAGS_SET(flags, FORK_NEW_MOUNTNS));
×
1665

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

1676
        if (flags & FORK_REARRANGE_STDIO) {
29,811✔
1677
                if (stdio_fds) {
15,582✔
1678
                        r = rearrange_stdio(stdio_fds[0], stdio_fds[1], stdio_fds[2]);
15,566✔
1679
                        if (r < 0) {
15,566✔
1680
                                log_full_errno(prio, r, "Failed to rearrange stdio fds: %m");
×
1681
                                _exit(EXIT_FAILURE);
×
1682
                        }
1683

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

1700
        if (flags & FORK_CLOSE_ALL_FDS) {
29,811✔
1701
                /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1702
                log_close();
23,952✔
1703

1704
                r = close_all_fds(except_fds, n_except_fds);
23,952✔
1705
                if (r < 0) {
23,952✔
1706
                        log_full_errno(prio, r, "Failed to close all file descriptors: %m");
×
1707
                        _exit(EXIT_FAILURE);
×
1708
                }
1709
        }
1710

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

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

1724
        if (flags & FORK_CLOEXEC_OFF) {
29,811✔
1725
                r = fd_cloexec_many(except_fds, n_except_fds, false);
107✔
1726
                if (r < 0) {
107✔
1727
                        log_full_errno(prio, r, "Failed to turn off O_CLOEXEC on file descriptors: %m");
×
1728
                        _exit(EXIT_FAILURE);
×
1729
                }
1730
        }
1731

1732
        /* When we were asked to reopen the logs, do so again now */
1733
        if (flags & FORK_REOPEN_LOG) {
29,811✔
1734
                log_open();
6,810✔
1735
                log_set_open_when_needed(false);
6,810✔
1736
        }
1737

1738
        if (flags & FORK_RLIMIT_NOFILE_SAFE) {
29,811✔
1739
                r = rlimit_nofile_safe();
16,706✔
1740
                if (r < 0) {
16,706✔
1741
                        log_full_errno(prio, r, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
×
1742
                        _exit(EXIT_FAILURE);
×
1743
                }
1744
        }
1745

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

1754
        if (FLAGS_SET(flags, FORK_FREEZE))
29,811✔
1755
                freeze();
×
1756

1757
        if (ret) {
29,811✔
1758
                r = pidref_set_self(ret);
27,597✔
1759
                if (r < 0) {
27,597✔
1760
                        log_full_errno(prio, r, "Failed to acquire PID reference on ourselves: %m");
×
1761
                        _exit(EXIT_FAILURE);
×
1762
                }
1763
        }
1764

1765
        return 0;
1766
}
1767

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

1781
        _cleanup_(pidref_done_sigkill_wait) PidRef pidref_outer = PIDREF_NULL;
×
1782
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
220✔
1783
        int r, prio = FLAGS_SET(flags, FORK_LOG) ? LOG_ERR : LOG_DEBUG;
131✔
1784

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

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

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

1803
        r = pidref_safe_fork_full(
350✔
1804
                        outer_name,
1805
                        /* stdio_fds = */ NULL, /* except_fds = */ NULL, /* n_except_fds = */ 0,
1806
                        (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),
131✔
1807
                        &pidref_outer);
1808
        if (r == -EPROTO && FLAGS_SET(flags, FORK_WAIT)) {
219✔
1809
                errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
×
1810

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

1820
                /* Child */
1821

1822
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
88✔
1823

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

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

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

1850
                        if (ret)
89✔
1851
                                *ret = TAKE_PIDREF(pidref_inner);
89✔
1852
                        return 0;
89✔
1853
                }
1854

1855
                log_close();
88✔
1856
                log_set_open_when_needed(true);
88✔
1857

1858
                (void) close_all_fds(&pidref_inner.fd, 1);
88✔
1859

1860
                r = pidref_wait_for_terminate_and_check(
176✔
1861
                                inner_name,
1862
                                &pidref_inner,
1863
                                FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1864
                if (r < 0)
88✔
1865
                        _exit(EXIT_FAILURE);
×
1866

1867
                _exit(r);
88✔
1868
        }
1869

1870
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
131✔
1871

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

1876
        if (ret)
131✔
1877
                *ret = TAKE_PIDREF(pidref_outer);
131✔
1878
        else
1879
                pidref_done(&pidref_outer); /* disarm sigkill_wait */
×
1880

1881
        return 1;
1882
}
1883

1884
int set_oom_score_adjust(int value) {
3,572✔
1885
        char t[DECIMAL_STR_MAX(int)];
3,572✔
1886

1887
        if (!oom_score_adjust_is_valid(value))
3,572✔
1888
                return -EINVAL;
3,572✔
1889

1890
        xsprintf(t, "%i", value);
3,572✔
1891

1892
        return write_string_file("/proc/self/oom_score_adj", t,
3,572✔
1893
                                 WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
1894
}
1895

1896
int get_oom_score_adjust(int *ret) {
2,377✔
1897
        _cleanup_free_ char *t = NULL;
2,377✔
1898
        int r, a;
2,377✔
1899

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

1904
        delete_trailing_chars(t, WHITESPACE);
2,377✔
1905

1906
        r = safe_atoi(t, &a);
2,377✔
1907
        if (r < 0)
2,377✔
1908
                return r;
1909

1910
        if (!oom_score_adjust_is_valid(a))
2,377✔
1911
                return -ENODATA;
1912

1913
        if (ret)
2,377✔
1914
                *ret = a;
2,377✔
1915

1916
        return 0;
1917
}
1918

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

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

1926
        return PRIO_MAX - (int) limit;
2✔
1927
}
1928

1929
int setpriority_closest(int priority) {
27✔
1930
        struct rlimit highest;
27✔
1931
        int r, current, limit;
27✔
1932

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

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

1945
        if (priority == current)
2✔
1946
                return 1;
1947

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

1954
        if (getrlimit(RLIMIT_NICE, &highest) < 0)
2✔
1955
                return -errno;
×
1956

1957
        limit = rlimit_to_nice(highest.rlim_cur);
2✔
1958

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

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

1970
_noreturn_ void freeze(void) {
×
1971
        log_close();
×
1972

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

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

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

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

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

1996
        if (pid < 0)
7✔
1997
                return -EINVAL;
1998

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

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

2011
        return n;
2012
}
2013

2014
int is_reaper_process(void) {
3,622✔
2015
        int b = 0;
3,622✔
2016

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

2020
        if (getpid_cached() == 1)
3,622✔
2021
                return true;
3,622✔
2022

2023
        if (prctl(PR_GET_CHILD_SUBREAPER, (unsigned long) &b, 0UL, 0UL, 0UL) < 0)
351✔
2024
                return -errno;
×
2025

2026
        return b != 0;
351✔
2027
}
2028

2029
int make_reaper_process(bool b) {
664✔
2030

2031
        if (getpid_cached() == 1) {
664✔
2032

2033
                if (!b)
52✔
2034
                        return -EINVAL;
2035

2036
                return 0;
52✔
2037
        }
2038

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

2044
        return 0;
2045
}
2046

2047
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(posix_spawnattr_t*, posix_spawnattr_destroy, NULL);
×
2048

2049
int posix_spawn_wrapper(
2,421✔
2050
                const char *path,
2051
                char * const *argv,
2052
                char * const *envp,
2053
                const char *cgroup,
2054
                PidRef *ret_pidref) {
2055

2056
        short flags = POSIX_SPAWN_SETSIGMASK;
2,421✔
2057
        posix_spawnattr_t attr;
2,421✔
2058
        sigset_t mask;
2,421✔
2059
        int r;
2,421✔
2060

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

2072
        assert(path);
2,421✔
2073
        assert(argv);
2,421✔
2074
        assert(ret_pidref);
2,421✔
2075

2076
        assert_se(sigfillset(&mask) >= 0);
2,421✔
2077

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

2082
        /* Initialization needs to succeed before we can set up a destructor. */
2083
        _unused_ _cleanup_(posix_spawnattr_destroyp) posix_spawnattr_t *attr_destructor = &attr;
4,842✔
2084

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

2089
        if (cgroup && have_clone_into_cgroup) {
2,421✔
2090
                _cleanup_free_ char *resolved_cgroup = NULL;
2,421✔
2091

2092
                r = cg_get_path(cgroup, /* suffix= */ NULL, &resolved_cgroup);
2,421✔
2093
                if (r < 0)
2,421✔
2094
                        return r;
2095

2096
                cgroup_fd = open(resolved_cgroup, O_PATH|O_DIRECTORY|O_CLOEXEC);
2,421✔
2097
                if (cgroup_fd < 0)
2,421✔
2098
                        return -errno;
×
2099

2100
                r = posix_spawnattr_setcgroup_np(&attr, cgroup_fd);
2,421✔
2101
                if (r != 0)
2,421✔
2102
                        return -r;
×
2103

2104
                flags |= POSIX_SPAWN_SETCGROUP;
2,421✔
2105
        }
2106
#endif
2107

2108
        r = posix_spawnattr_setflags(&attr, flags);
2,421✔
2109
        if (r != 0)
2,421✔
2110
                return -r;
×
2111
        r = posix_spawnattr_setsigmask(&attr, &mask);
2,421✔
2112
        if (r != 0)
2,421✔
2113
                return -r;
×
2114

2115
#if HAVE_PIDFD_SPAWN
2116
        _cleanup_close_ int pidfd = -EBADF;
2,421✔
2117

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

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

2137
                r = pidfd_spawn(&pidfd, path, NULL, &attr, argv, envp);
×
2138
        }
2139
        if (r != 0)
2,421✔
2140
                return -r;
×
2141

2142
        r = pidref_set_pidfd_consume(ret_pidref, TAKE_FD(pidfd));
2,421✔
2143
        if (r < 0)
2,421✔
2144
                return r;
2145

2146
        return FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP);
2,421✔
2147
#else
2148
        pid_t pid;
2149

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

2154
        r = pidref_set_pid(ret_pidref, pid);
2155
        if (r < 0)
2156
                return r;
2157

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

2162
int proc_dir_open(DIR **ret) {
13✔
2163
        DIR *d;
13✔
2164

2165
        assert(ret);
13✔
2166

2167
        d = opendir("/proc");
13✔
2168
        if (!d)
13✔
2169
                return -errno;
×
2170

2171
        *ret = d;
13✔
2172
        return 0;
13✔
2173
}
2174

2175
int proc_dir_read(DIR *d, pid_t *ret) {
1,168✔
2176
        assert(d);
1,168✔
2177

2178
        for (;;) {
1,952✔
2179
                struct dirent *de;
1,952✔
2180

2181
                errno = 0;
1,952✔
2182
                de = readdir_no_dot(d);
1,952✔
2183
                if (!de) {
1,952✔
2184
                        if (errno != 0)
13✔
2185
                                return -errno;
×
2186

2187
                        break;
13✔
2188
                }
2189

2190
                if (!IN_SET(de->d_type, DT_DIR, DT_UNKNOWN))
1,939✔
2191
                        continue;
641✔
2192

2193
                if (parse_pid(de->d_name, ret) >= 0)
1,298✔
2194
                        return 1;
2195
        }
2196

2197
        if (ret)
13✔
2198
                *ret = 0;
13✔
2199
        return 0;
2200
}
2201

2202
int proc_dir_read_pidref(DIR *d, PidRef *ret) {
1,127✔
2203
        int r;
1,127✔
2204

2205
        assert(d);
1,127✔
2206

2207
        for (;;) {
1,127✔
2208
                pid_t pid;
1,127✔
2209

2210
                r = proc_dir_read(d, &pid);
1,127✔
2211
                if (r < 0)
1,127✔
2212
                        return r;
1,115✔
2213
                if (r == 0)
1,127✔
2214
                        break;
2215

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

2222
                return 1;
2223
        }
2224

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

2230
static const char *const sigchld_code_table[] = {
2231
        [CLD_EXITED] = "exited",
2232
        [CLD_KILLED] = "killed",
2233
        [CLD_DUMPED] = "dumped",
2234
        [CLD_TRAPPED] = "trapped",
2235
        [CLD_STOPPED] = "stopped",
2236
        [CLD_CONTINUED] = "continued",
2237
};
2238

2239
DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
8,808✔
2240

2241
static const char* const sched_policy_table[] = {
2242
        [SCHED_OTHER] = "other",
2243
        [SCHED_BATCH] = "batch",
2244
        [SCHED_IDLE]  = "idle",
2245
        [SCHED_FIFO]  = "fifo",
2246
        [SCHED_EXT]   = "ext",
2247
        [SCHED_RR]    = "rr",
2248
};
2249

2250
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
53✔
2251

2252
_noreturn_ void report_errno_and_exit(int errno_fd, int error) {
64✔
2253
        int r;
64✔
2254

2255
        if (error >= 0)
64✔
2256
                _exit(EXIT_SUCCESS);
63✔
2257

2258
        assert(errno_fd >= 0);
1✔
2259

2260
        r = loop_write(errno_fd, &error, sizeof(error));
1✔
2261
        if (r < 0)
1✔
2262
                log_debug_errno(r, "Failed to write errno to errno_fd=%d: %m", errno_fd);
×
2263

2264
        _exit(EXIT_FAILURE);
1✔
2265
}
2266

2267
int read_errno(int errno_fd) {
134✔
2268
        int r;
134✔
2269

2270
        assert(errno_fd >= 0);
134✔
2271

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

2275
        ssize_t n = loop_read(errno_fd, &r, sizeof(r), /* do_poll= */ false);
134✔
2276
        if (n < 0) {
134✔
2277
                log_debug_errno(n, "Failed to read errno: %m");
×
2278
                return -EIO;
×
2279
        }
2280
        if (n == 0) /* the process exited without reporting an error, assuming success */
134✔
2281
                return 0;
2282
        if (n != sizeof(r))
×
2283
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Received unexpected amount of bytes (%zi) while reading errno.", n);
×
2284

2285
        if (r == 0)
×
2286
                return 0;
2287
        if (r < 0) /* child process reported an error, return it */
×
2288
                return log_debug_errno(r, "Child process failed with errno: %m");
×
2289

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