]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/process-util.c
Move cpus_in_affinity_mask() to cpu-set-util.[ch]
[thirdparty/systemd.git] / src / basic / process-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
0b452006 2
4f5dd394 3#include <ctype.h>
0b452006 4#include <errno.h>
11c3a366
TA
5#include <limits.h>
6#include <linux/oom.h>
0b452006 7#include <signal.h>
4f5dd394
LP
8#include <stdbool.h>
9#include <stdio.h>
11c3a366 10#include <stdlib.h>
4f5dd394 11#include <string.h>
9bfaffd5 12#include <sys/mman.h>
e2047ba9 13#include <sys/mount.h>
7b3e062c 14#include <sys/personality.h>
405f8907 15#include <sys/prctl.h>
4f5dd394
LP
16#include <sys/types.h>
17#include <sys/wait.h>
11c3a366 18#include <syslog.h>
4f5dd394 19#include <unistd.h>
349cc4a5 20#if HAVE_VALGRIND_VALGRIND_H
dcadc967
EV
21#include <valgrind/valgrind.h>
22#endif
0b452006 23
b5efdb8a 24#include "alloc-util.h"
6e5f1b57 25#include "architecture.h"
4f5dd394 26#include "escape.h"
3ffd4af2 27#include "fd-util.h"
0b452006 28#include "fileio.h"
f4f15635 29#include "fs-util.h"
7b3e062c 30#include "ioprio.h"
0b452006 31#include "log.h"
11c3a366 32#include "macro.h"
0a970718 33#include "memory-util.h"
11c3a366 34#include "missing.h"
0cb8e3d1 35#include "namespace-util.h"
93cc7779 36#include "process-util.h"
8869a0b4 37#include "raw-clone.h"
909106eb 38#include "rlimit-util.h"
93cc7779 39#include "signal-util.h"
1359fffa 40#include "stat-util.h"
7b3e062c 41#include "string-table.h"
07630cea 42#include "string-util.h"
4c253ed1 43#include "terminal-util.h"
b1d4f8e1 44#include "user-util.h"
0b452006
RC
45
46int get_process_state(pid_t pid) {
47 const char *p;
48 char state;
49 int r;
50 _cleanup_free_ char *line = NULL;
51
52 assert(pid >= 0);
53
54 p = procfs_file_alloca(pid, "stat");
a644184a 55
0b452006 56 r = read_one_line_file(p, &line);
a644184a
LP
57 if (r == -ENOENT)
58 return -ESRCH;
0b452006
RC
59 if (r < 0)
60 return r;
61
62 p = strrchr(line, ')');
63 if (!p)
64 return -EIO;
65
66 p++;
67
68 if (sscanf(p, " %c", &state) != 1)
69 return -EIO;
70
71 return (unsigned char) state;
72}
73
ce268825
LP
74int get_process_comm(pid_t pid, char **ret) {
75 _cleanup_free_ char *escaped = NULL, *comm = NULL;
0b452006
RC
76 const char *p;
77 int r;
78
ce268825 79 assert(ret);
0b452006
RC
80 assert(pid >= 0);
81
ce268825
LP
82 escaped = new(char, TASK_COMM_LEN);
83 if (!escaped)
84 return -ENOMEM;
85
0b452006
RC
86 p = procfs_file_alloca(pid, "comm");
87
ce268825 88 r = read_one_line_file(p, &comm);
0b452006
RC
89 if (r == -ENOENT)
90 return -ESRCH;
ce268825
LP
91 if (r < 0)
92 return r;
93
94 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
95 cellescape(escaped, TASK_COMM_LEN, comm);
0b452006 96
ce268825
LP
97 *ret = TAKE_PTR(escaped);
98 return 0;
0b452006
RC
99}
100
101int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
102 _cleanup_fclose_ FILE *f = NULL;
ba4cd7e2 103 bool space = false;
eb1ec489
MS
104 char *k;
105 _cleanup_free_ char *ans = NULL;
0b452006 106 const char *p;
fdeea3f4 107 int c, r;
0b452006
RC
108
109 assert(line);
110 assert(pid >= 0);
111
69281c49
LP
112 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
113 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
114 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
115 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
116 * command line that resolves to the empty string will return the "comm" name of the process instead.
117 *
118 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
c0534780 119 * comm_fallback is false). Returns 0 and sets *line otherwise. */
69281c49 120
0b452006 121 p = procfs_file_alloca(pid, "cmdline");
fdeea3f4
ZJS
122 r = fopen_unlocked(p, "re", &f);
123 if (r == -ENOENT)
124 return -ESRCH;
125 if (r < 0)
126 return r;
35bbbf85 127
2d5d2e0c
ZJS
128 if (max_length == 0) {
129 /* This is supposed to be a safety guard against runaway command lines. */
130 long l = sysconf(_SC_ARG_MAX);
131 assert(l > 0);
132 max_length = l;
133 }
134
69281c49
LP
135 if (max_length == 1) {
136
137 /* If there's only room for one byte, return the empty string */
c0534780
ZJS
138 ans = new0(char, 1);
139 if (!ans)
69281c49
LP
140 return -ENOMEM;
141
eb1ec489 142 *line = TAKE_PTR(ans);
69281c49
LP
143 return 0;
144
0b452006 145 } else {
69281c49 146 bool dotdotdot = false;
0b452006
RC
147 size_t left;
148
c0534780
ZJS
149 ans = new(char, max_length);
150 if (!ans)
0b452006
RC
151 return -ENOMEM;
152
c0534780 153 k = ans;
0b452006
RC
154 left = max_length;
155 while ((c = getc(f)) != EOF) {
156
157 if (isprint(c)) {
69281c49 158
0b452006 159 if (space) {
69281c49
LP
160 if (left <= 2) {
161 dotdotdot = true;
0b452006 162 break;
69281c49 163 }
0b452006
RC
164
165 *(k++) = ' ';
166 left--;
167 space = false;
168 }
169
69281c49
LP
170 if (left <= 1) {
171 dotdotdot = true;
0b452006 172 break;
69281c49 173 }
0b452006
RC
174
175 *(k++) = (char) c;
176 left--;
c0534780 177 } else if (k > ans)
0b452006
RC
178 space = true;
179 }
180
69281c49
LP
181 if (dotdotdot) {
182 if (max_length <= 4) {
c0534780 183 k = ans;
69281c49
LP
184 left = max_length;
185 } else {
c0534780 186 k = ans + max_length - 4;
69281c49
LP
187 left = 4;
188
189 /* Eat up final spaces */
c0534780 190 while (k > ans && isspace(k[-1])) {
69281c49
LP
191 k--;
192 left++;
193 }
194 }
195
196 strncpy(k, "...", left-1);
b09df4e2 197 k[left-1] = 0;
0b452006
RC
198 } else
199 *k = 0;
200 }
201
202 /* Kernel threads have no argv[] */
c0534780 203 if (isempty(ans)) {
0b452006
RC
204 _cleanup_free_ char *t = NULL;
205 int h;
206
eb1ec489 207 ans = mfree(ans);
0b452006
RC
208
209 if (!comm_fallback)
210 return -ENOENT;
211
212 h = get_process_comm(pid, &t);
213 if (h < 0)
214 return h;
215
2d5d2e0c 216 size_t l = strlen(t);
69281c49 217
2d5d2e0c
ZJS
218 if (l + 3 <= max_length) {
219 ans = strjoin("[", t, "]");
220 if (!ans)
221 return -ENOMEM;
69281c49 222
2d5d2e0c
ZJS
223 } else if (max_length <= 6) {
224 ans = new(char, max_length);
225 if (!ans)
226 return -ENOMEM;
69281c49 227
2d5d2e0c
ZJS
228 memcpy(ans, "[...]", max_length-1);
229 ans[max_length-1] = 0;
230 } else {
231 t[max_length - 6] = 0;
69281c49 232
2d5d2e0c
ZJS
233 /* Chop off final spaces */
234 delete_trailing_chars(t, WHITESPACE);
69281c49 235
2d5d2e0c
ZJS
236 ans = strjoin("[", t, "...]");
237 if (!ans)
238 return -ENOMEM;
69281c49 239 }
eb1ec489
MS
240
241 *line = TAKE_PTR(ans);
242 return 0;
0b452006
RC
243 }
244
eb1ec489
MS
245 k = realloc(ans, strlen(ans) + 1);
246 if (!k)
247 return -ENOMEM;
248
249 ans = NULL;
250 *line = k;
251
0b452006
RC
252 return 0;
253}
254
9bfaffd5
LP
255int rename_process(const char name[]) {
256 static size_t mm_size = 0;
257 static char *mm = NULL;
258 bool truncated = false;
259 size_t l;
260
261 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
262 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
263 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
264 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
265 * truncated.
266 *
267 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
268
269 if (isempty(name))
270 return -EINVAL; /* let's not confuse users unnecessarily with an empty name */
405f8907 271
1096bb8a
LP
272 if (!is_main_thread())
273 return -EPERM; /* Let's not allow setting the process name from other threads than the main one, as we
274 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
275 * process name that isn't correct on any other threads */
276
9bfaffd5 277 l = strlen(name);
405f8907 278
5a8af747
LP
279 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
280 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
281 if (prctl(PR_SET_NAME, name) < 0)
282 log_debug_errno(errno, "PR_SET_NAME failed: %m");
92f14395 283 if (l >= TASK_COMM_LEN) /* Linux process names can be 15 chars at max */
9bfaffd5
LP
284 truncated = true;
285
286 /* Second step, change glibc's ID of the process name. */
287 if (program_invocation_name) {
288 size_t k;
289
290 k = strlen(program_invocation_name);
291 strncpy(program_invocation_name, name, k);
292 if (l > k)
293 truncated = true;
294 }
295
296 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
297 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
13e785f7 298 * the end. This is the best option for changing /proc/self/cmdline. */
01f989c6
JW
299
300 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
301 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
302 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
303 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
304 * mmap() is not. */
305 if (geteuid() != 0)
306 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
307 else if (mm_size < l+1) {
9bfaffd5
LP
308 size_t nn_size;
309 char *nn;
310
9bfaffd5
LP
311 nn_size = PAGE_ALIGN(l+1);
312 nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
313 if (nn == MAP_FAILED) {
314 log_debug_errno(errno, "mmap() failed: %m");
315 goto use_saved_argv;
316 }
405f8907 317
9bfaffd5
LP
318 strncpy(nn, name, nn_size);
319
320 /* Now, let's tell the kernel about this new memory */
321 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
14ee72b7
FS
322 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
323 * below the desired start address, in which case the kernel may have kicked this back due
324 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
325 * action). The proper solution would be to have a prctl() API that could set both start+end
326 * simultaneously, or at least let us query the existing address to anticipate this condition
327 * and respond accordingly. For now, we can only guess at the cause of this failure and try
328 * a workaround--which will briefly expand the arg space to something potentially huge before
329 * resizing it to what we want. */
330 log_debug_errno(errno, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
331
332 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) {
333 log_debug_errno(errno, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
334 (void) munmap(nn, nn_size);
335 goto use_saved_argv;
336 }
9bfaffd5 337
14ee72b7
FS
338 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
339 log_debug_errno(errno, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
340 goto use_saved_argv;
341 }
342 } else {
343 /* And update the end pointer to the new end, too. If this fails, we don't really know what
344 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
345 * and continue. */
346 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0)
347 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
348 }
9bfaffd5
LP
349
350 if (mm)
351 (void) munmap(mm, mm_size);
352
353 mm = nn;
354 mm_size = nn_size;
01f989c6 355 } else {
9bfaffd5
LP
356 strncpy(mm, name, mm_size);
357
01f989c6
JW
358 /* Update the end pointer, continuing regardless of any failure. */
359 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0)
360 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
361 }
362
9bfaffd5
LP
363use_saved_argv:
364 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
365 * it still looks here */
405f8907
LP
366
367 if (saved_argc > 0) {
368 int i;
369
9bfaffd5
LP
370 if (saved_argv[0]) {
371 size_t k;
372
373 k = strlen(saved_argv[0]);
374 strncpy(saved_argv[0], name, k);
375 if (l > k)
376 truncated = true;
377 }
405f8907
LP
378
379 for (i = 1; i < saved_argc; i++) {
380 if (!saved_argv[i])
381 break;
382
383 memzero(saved_argv[i], strlen(saved_argv[i]));
384 }
385 }
9bfaffd5
LP
386
387 return !truncated;
405f8907
LP
388}
389
0b452006 390int is_kernel_thread(pid_t pid) {
36b5119a
LP
391 _cleanup_free_ char *line = NULL;
392 unsigned long long flags;
393 size_t l, i;
0b452006 394 const char *p;
36b5119a
LP
395 char *q;
396 int r;
0b452006 397
4c701096 398 if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
0b452006 399 return 0;
36b5119a
LP
400 if (!pid_is_valid(pid))
401 return -EINVAL;
0b452006 402
36b5119a
LP
403 p = procfs_file_alloca(pid, "stat");
404 r = read_one_line_file(p, &line);
405 if (r == -ENOENT)
406 return -ESRCH;
407 if (r < 0)
408 return r;
0b452006 409
36b5119a
LP
410 /* Skip past the comm field */
411 q = strrchr(line, ')');
412 if (!q)
413 return -EINVAL;
414 q++;
415
416 /* Skip 6 fields to reach the flags field */
417 for (i = 0; i < 6; i++) {
418 l = strspn(q, WHITESPACE);
419 if (l < 1)
420 return -EINVAL;
421 q += l;
422
423 l = strcspn(q, WHITESPACE);
424 if (l < 1)
425 return -EINVAL;
426 q += l;
a644184a 427 }
0b452006 428
f21f31b2 429 /* Skip preceding whitespace */
36b5119a
LP
430 l = strspn(q, WHITESPACE);
431 if (l < 1)
432 return -EINVAL;
433 q += l;
35bbbf85 434
36b5119a
LP
435 /* Truncate the rest */
436 l = strcspn(q, WHITESPACE);
437 if (l < 1)
438 return -EINVAL;
439 q[l] = 0;
0b452006 440
36b5119a
LP
441 r = safe_atollu(q, &flags);
442 if (r < 0)
443 return r;
0b452006 444
36b5119a 445 return !!(flags & PF_KTHREAD);
0b452006
RC
446}
447
448int get_process_capeff(pid_t pid, char **capeff) {
449 const char *p;
a644184a 450 int r;
0b452006
RC
451
452 assert(capeff);
453 assert(pid >= 0);
454
455 p = procfs_file_alloca(pid, "status");
456
c4cd1d4d 457 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
a644184a
LP
458 if (r == -ENOENT)
459 return -ESRCH;
460
461 return r;
0b452006
RC
462}
463
464static int get_process_link_contents(const char *proc_file, char **name) {
465 int r;
466
467 assert(proc_file);
468 assert(name);
469
470 r = readlink_malloc(proc_file, name);
a644184a
LP
471 if (r == -ENOENT)
472 return -ESRCH;
0b452006 473 if (r < 0)
a644184a 474 return r;
0b452006
RC
475
476 return 0;
477}
478
479int get_process_exe(pid_t pid, char **name) {
480 const char *p;
481 char *d;
482 int r;
483
484 assert(pid >= 0);
485
486 p = procfs_file_alloca(pid, "exe");
487 r = get_process_link_contents(p, name);
488 if (r < 0)
489 return r;
490
491 d = endswith(*name, " (deleted)");
492 if (d)
493 *d = '\0';
494
495 return 0;
496}
497
498static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
499 _cleanup_fclose_ FILE *f = NULL;
0b452006 500 const char *p;
7e7a16a0 501 int r;
0b452006
RC
502
503 assert(field);
504 assert(uid);
505
07b38ba5 506 if (pid < 0)
6f8cbcdb
LP
507 return -EINVAL;
508
0b452006 509 p = procfs_file_alloca(pid, "status");
fdeea3f4
ZJS
510 r = fopen_unlocked(p, "re", &f);
511 if (r == -ENOENT)
512 return -ESRCH;
513 if (r < 0)
514 return r;
35bbbf85 515
7e7a16a0
LP
516 for (;;) {
517 _cleanup_free_ char *line = NULL;
0b452006
RC
518 char *l;
519
7e7a16a0
LP
520 r = read_line(f, LONG_LINE_MAX, &line);
521 if (r < 0)
522 return r;
523 if (r == 0)
524 break;
525
0b452006
RC
526 l = strstrip(line);
527
528 if (startswith(l, field)) {
529 l += strlen(field);
530 l += strspn(l, WHITESPACE);
531
532 l[strcspn(l, WHITESPACE)] = 0;
533
534 return parse_uid(l, uid);
535 }
536 }
537
538 return -EIO;
539}
540
541int get_process_uid(pid_t pid, uid_t *uid) {
6f8cbcdb
LP
542
543 if (pid == 0 || pid == getpid_cached()) {
544 *uid = getuid();
545 return 0;
546 }
547
0b452006
RC
548 return get_process_id(pid, "Uid:", uid);
549}
550
551int get_process_gid(pid_t pid, gid_t *gid) {
6f8cbcdb
LP
552
553 if (pid == 0 || pid == getpid_cached()) {
554 *gid = getgid();
555 return 0;
556 }
557
0b452006
RC
558 assert_cc(sizeof(uid_t) == sizeof(gid_t));
559 return get_process_id(pid, "Gid:", gid);
560}
561
562int get_process_cwd(pid_t pid, char **cwd) {
563 const char *p;
564
565 assert(pid >= 0);
566
567 p = procfs_file_alloca(pid, "cwd");
568
569 return get_process_link_contents(p, cwd);
570}
571
572int get_process_root(pid_t pid, char **root) {
573 const char *p;
574
575 assert(pid >= 0);
576
577 p = procfs_file_alloca(pid, "root");
578
579 return get_process_link_contents(p, root);
580}
581
2a7797e9
LP
582#define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
583
0b452006
RC
584int get_process_environ(pid_t pid, char **env) {
585 _cleanup_fclose_ FILE *f = NULL;
586 _cleanup_free_ char *outcome = NULL;
0b452006 587 size_t allocated = 0, sz = 0;
2a7797e9
LP
588 const char *p;
589 int r;
0b452006
RC
590
591 assert(pid >= 0);
592 assert(env);
593
594 p = procfs_file_alloca(pid, "environ");
595
fdeea3f4
ZJS
596 r = fopen_unlocked(p, "re", &f);
597 if (r == -ENOENT)
598 return -ESRCH;
599 if (r < 0)
600 return r;
35bbbf85 601
2a7797e9
LP
602 for (;;) {
603 char c;
604
605 if (sz >= ENVIRONMENT_BLOCK_MAX)
606 return -ENOBUFS;
607
0b452006
RC
608 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
609 return -ENOMEM;
610
2a7797e9
LP
611 r = safe_fgetc(f, &c);
612 if (r < 0)
613 return r;
614 if (r == 0)
615 break;
616
0b452006
RC
617 if (c == '\0')
618 outcome[sz++] = '\n';
619 else
620 sz += cescape_char(c, outcome + sz);
621 }
622
2a7797e9 623 outcome[sz] = '\0';
ae2a15bc 624 *env = TAKE_PTR(outcome);
0b452006
RC
625
626 return 0;
627}
628
6bc73acb 629int get_process_ppid(pid_t pid, pid_t *_ppid) {
0b452006
RC
630 int r;
631 _cleanup_free_ char *line = NULL;
632 long unsigned ppid;
633 const char *p;
634
635 assert(pid >= 0);
636 assert(_ppid);
637
6f8cbcdb 638 if (pid == 0 || pid == getpid_cached()) {
0b452006
RC
639 *_ppid = getppid();
640 return 0;
641 }
642
643 p = procfs_file_alloca(pid, "stat");
644 r = read_one_line_file(p, &line);
a644184a
LP
645 if (r == -ENOENT)
646 return -ESRCH;
0b452006
RC
647 if (r < 0)
648 return r;
649
650 /* Let's skip the pid and comm fields. The latter is enclosed
651 * in () but does not escape any () in its value, so let's
652 * skip over it manually */
653
654 p = strrchr(line, ')');
655 if (!p)
656 return -EIO;
657
658 p++;
659
660 if (sscanf(p, " "
661 "%*c " /* state */
662 "%lu ", /* ppid */
663 &ppid) != 1)
664 return -EIO;
665
666 if ((long unsigned) (pid_t) ppid != ppid)
667 return -ERANGE;
668
669 *_ppid = (pid_t) ppid;
670
671 return 0;
672}
673
674int wait_for_terminate(pid_t pid, siginfo_t *status) {
675 siginfo_t dummy;
676
677 assert(pid >= 1);
678
679 if (!status)
680 status = &dummy;
681
682 for (;;) {
683 zero(*status);
684
685 if (waitid(P_PID, pid, status, WEXITED) < 0) {
686
687 if (errno == EINTR)
688 continue;
689
3f0083a2 690 return negative_errno();
0b452006
RC
691 }
692
693 return 0;
694 }
695}
696
697/*
698 * Return values:
699 * < 0 : wait_for_terminate() failed to get the state of the
700 * process, the process was terminated by a signal, or
701 * failed for an unknown reason.
702 * >=0 : The process terminated normally, and its exit code is
703 * returned.
704 *
705 * That is, success is indicated by a return value of zero, and an
706 * error is indicated by a non-zero value.
707 *
708 * A warning is emitted if the process terminates abnormally,
709 * and also if it returns non-zero unless check_exit_code is true.
710 */
7d4904fe
LP
711int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) {
712 _cleanup_free_ char *buffer = NULL;
0b452006 713 siginfo_t status;
7d4904fe 714 int r, prio;
0b452006 715
0b452006
RC
716 assert(pid > 1);
717
7d4904fe
LP
718 if (!name) {
719 r = get_process_comm(pid, &buffer);
720 if (r < 0)
721 log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid);
722 else
723 name = buffer;
724 }
725
726 prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
727
0b452006
RC
728 r = wait_for_terminate(pid, &status);
729 if (r < 0)
7d4904fe 730 return log_full_errno(prio, r, "Failed to wait for %s: %m", strna(name));
0b452006
RC
731
732 if (status.si_code == CLD_EXITED) {
7d4904fe
LP
733 if (status.si_status != EXIT_SUCCESS)
734 log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
735 "%s failed with exit status %i.", strna(name), status.si_status);
0b452006
RC
736 else
737 log_debug("%s succeeded.", name);
738
739 return status.si_status;
7d4904fe 740
3742095b 741 } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
0b452006 742
7d4904fe 743 log_full(prio, "%s terminated by signal %s.", strna(name), signal_to_string(status.si_status));
0b452006
RC
744 return -EPROTO;
745 }
746
7d4904fe 747 log_full(prio, "%s failed due to unknown reason.", strna(name));
0b452006
RC
748 return -EPROTO;
749}
750
d5641e0d
KW
751/*
752 * Return values:
e225e5c3
LP
753 *
754 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
755 * was terminated by a signal, or failed for an unknown reason.
756 *
d5641e0d
KW
757 * >=0 : The process terminated normally with no failures.
758 *
e225e5c3
LP
759 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
760 * states are indicated by error is indicated by a non-zero value.
761 *
762 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
763 * to remain entirely race-free.
d5641e0d
KW
764 */
765int wait_for_terminate_with_timeout(pid_t pid, usec_t timeout) {
766 sigset_t mask;
767 int r;
768 usec_t until;
769
770 assert_se(sigemptyset(&mask) == 0);
771 assert_se(sigaddset(&mask, SIGCHLD) == 0);
772
773 /* Drop into a sigtimewait-based timeout. Waiting for the
774 * pid to exit. */
775 until = now(CLOCK_MONOTONIC) + timeout;
776 for (;;) {
777 usec_t n;
778 siginfo_t status = {};
779 struct timespec ts;
780
781 n = now(CLOCK_MONOTONIC);
782 if (n >= until)
783 break;
784
785 r = sigtimedwait(&mask, NULL, timespec_store(&ts, until - n)) < 0 ? -errno : 0;
786 /* Assuming we woke due to the child exiting. */
787 if (waitid(P_PID, pid, &status, WEXITED|WNOHANG) == 0) {
788 if (status.si_pid == pid) {
789 /* This is the correct child.*/
790 if (status.si_code == CLD_EXITED)
791 return (status.si_status == 0) ? 0 : -EPROTO;
792 else
793 return -EPROTO;
794 }
795 }
796 /* Not the child, check for errors and proceed appropriately */
797 if (r < 0) {
798 switch (r) {
799 case -EAGAIN:
800 /* Timed out, child is likely hung. */
801 return -ETIMEDOUT;
802 case -EINTR:
803 /* Received a different signal and should retry */
804 continue;
805 default:
806 /* Return any unexpected errors */
807 return r;
808 }
809 }
810 }
811
812 return -EPROTO;
813}
814
89c9030d
LP
815void sigkill_wait(pid_t pid) {
816 assert(pid > 1);
817
53640e6f 818 if (kill(pid, SIGKILL) >= 0)
89c9030d
LP
819 (void) wait_for_terminate(pid, NULL);
820}
821
822void sigkill_waitp(pid_t *pid) {
dfd14786
LP
823 PROTECT_ERRNO;
824
4d0d3d41
LP
825 if (!pid)
826 return;
827 if (*pid <= 1)
828 return;
829
89c9030d 830 sigkill_wait(*pid);
4d0d3d41
LP
831}
832
392cf1d0
SL
833void sigterm_wait(pid_t pid) {
834 assert(pid > 1);
835
53640e6f 836 if (kill_and_sigcont(pid, SIGTERM) >= 0)
392cf1d0
SL
837 (void) wait_for_terminate(pid, NULL);
838}
839
0b452006
RC
840int kill_and_sigcont(pid_t pid, int sig) {
841 int r;
842
843 r = kill(pid, sig) < 0 ? -errno : 0;
844
26f417d3
LP
845 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
846 * affected by a process being suspended anyway. */
a3d8d68c 847 if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
26f417d3 848 (void) kill(pid, SIGCONT);
0b452006
RC
849
850 return r;
851}
852
e70f4453 853int getenv_for_pid(pid_t pid, const char *field, char **ret) {
0b452006
RC
854 _cleanup_fclose_ FILE *f = NULL;
855 char *value = NULL;
0b452006 856 const char *path;
0d90bd92
LP
857 size_t l, sum = 0;
858 int r;
0b452006
RC
859
860 assert(pid >= 0);
861 assert(field);
e70f4453
LP
862 assert(ret);
863
864 if (pid == 0 || pid == getpid_cached()) {
865 const char *e;
866
867 e = getenv(field);
868 if (!e) {
869 *ret = NULL;
870 return 0;
871 }
872
873 value = strdup(e);
874 if (!value)
875 return -ENOMEM;
876
877 *ret = value;
878 return 1;
879 }
0b452006 880
0d90bd92
LP
881 if (!pid_is_valid(pid))
882 return -EINVAL;
883
0b452006
RC
884 path = procfs_file_alloca(pid, "environ");
885
fdeea3f4
ZJS
886 r = fopen_unlocked(path, "re", &f);
887 if (r == -ENOENT)
888 return -ESRCH;
889 if (r < 0)
890 return r;
35bbbf85 891
0b452006 892 l = strlen(field);
0d90bd92
LP
893 for (;;) {
894 _cleanup_free_ char *line = NULL;
0b452006 895
0d90bd92
LP
896 if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
897 return -ENOBUFS;
0b452006 898
0d90bd92
LP
899 r = read_nul_string(f, LONG_LINE_MAX, &line);
900 if (r < 0)
901 return r;
902 if (r == 0) /* EOF */
903 break;
0b452006 904
0d90bd92 905 sum += r;
0b452006 906
041b5ae1 907 if (strneq(line, field, l) && line[l] == '=') {
0b452006
RC
908 value = strdup(line + l + 1);
909 if (!value)
910 return -ENOMEM;
911
e70f4453
LP
912 *ret = value;
913 return 1;
0b452006 914 }
0d90bd92 915 }
0b452006 916
e70f4453
LP
917 *ret = NULL;
918 return 0;
0b452006
RC
919}
920
4d051546
FB
921int pid_is_my_child(pid_t pid) {
922 pid_t ppid;
923 int r;
924
925 if (pid <= 1)
926 return false;
927
928 r = get_process_ppid(pid, &ppid);
929 if (r < 0)
930 return r;
931
932 return ppid == getpid_cached();
933}
934
0b452006
RC
935bool pid_is_unwaited(pid_t pid) {
936 /* Checks whether a PID is still valid at all, including a zombie */
937
07b38ba5 938 if (pid < 0)
0b452006
RC
939 return false;
940
5fd9b2c5
LP
941 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
942 return true;
943
6f8cbcdb
LP
944 if (pid == getpid_cached())
945 return true;
946
0b452006
RC
947 if (kill(pid, 0) >= 0)
948 return true;
949
950 return errno != ESRCH;
951}
952
953bool pid_is_alive(pid_t pid) {
954 int r;
955
956 /* Checks whether a PID is still valid and not a zombie */
957
07b38ba5 958 if (pid < 0)
0b452006
RC
959 return false;
960
5fd9b2c5
LP
961 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
962 return true;
963
6f8cbcdb
LP
964 if (pid == getpid_cached())
965 return true;
966
0b452006 967 r = get_process_state(pid);
4c701096 968 if (IN_SET(r, -ESRCH, 'Z'))
0b452006
RC
969 return false;
970
971 return true;
972}
d4510856 973
1359fffa
MS
974int pid_from_same_root_fs(pid_t pid) {
975 const char *root;
976
07b38ba5 977 if (pid < 0)
6f8cbcdb
LP
978 return false;
979
980 if (pid == 0 || pid == getpid_cached())
981 return true;
1359fffa
MS
982
983 root = procfs_file_alloca(pid, "root");
984
e3f791a2 985 return files_same(root, "/proc/1/root", 0);
1359fffa
MS
986}
987
d4510856
LP
988bool is_main_thread(void) {
989 static thread_local int cached = 0;
990
991 if (_unlikely_(cached == 0))
df0ff127 992 cached = getpid_cached() == gettid() ? 1 : -1;
d4510856
LP
993
994 return cached > 0;
995}
7b3e062c 996
848e863a 997_noreturn_ void freeze(void) {
7b3e062c 998
3da48d7a
EV
999 log_close();
1000
7b3e062c 1001 /* Make sure nobody waits for us on a socket anymore */
7acf581a 1002 (void) close_all_fds(NULL, 0);
7b3e062c
LP
1003
1004 sync();
1005
8647283e
MS
1006 /* Let's not freeze right away, but keep reaping zombies. */
1007 for (;;) {
1008 int r;
1009 siginfo_t si = {};
1010
1011 r = waitid(P_ALL, 0, &si, WEXITED);
1012 if (r < 0 && errno != EINTR)
1013 break;
1014 }
1015
1016 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
7b3e062c
LP
1017 for (;;)
1018 pause();
1019}
1020
1021bool oom_score_adjust_is_valid(int oa) {
1022 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
1023}
1024
1025unsigned long personality_from_string(const char *p) {
6e5f1b57 1026 int architecture;
7b3e062c 1027
0c0fea07
LP
1028 if (!p)
1029 return PERSONALITY_INVALID;
1030
6e5f1b57
LP
1031 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1032 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1033 * the same register size. */
1034
1035 architecture = architecture_from_string(p);
1036 if (architecture < 0)
1037 return PERSONALITY_INVALID;
7b3e062c 1038
0c0fea07 1039 if (architecture == native_architecture())
7b3e062c 1040 return PER_LINUX;
0c0fea07
LP
1041#ifdef SECONDARY_ARCHITECTURE
1042 if (architecture == SECONDARY_ARCHITECTURE)
f2d1736c 1043 return PER_LINUX32;
7b3e062c
LP
1044#endif
1045
1046 return PERSONALITY_INVALID;
1047}
1048
1049const char* personality_to_string(unsigned long p) {
6e5f1b57 1050 int architecture = _ARCHITECTURE_INVALID;
7b3e062c 1051
7b3e062c 1052 if (p == PER_LINUX)
0c0fea07
LP
1053 architecture = native_architecture();
1054#ifdef SECONDARY_ARCHITECTURE
6e5f1b57 1055 else if (p == PER_LINUX32)
0c0fea07 1056 architecture = SECONDARY_ARCHITECTURE;
7b3e062c
LP
1057#endif
1058
6e5f1b57
LP
1059 if (architecture < 0)
1060 return NULL;
1061
1062 return architecture_to_string(architecture);
7b3e062c
LP
1063}
1064
21022b9d
LP
1065int safe_personality(unsigned long p) {
1066 int ret;
1067
1068 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1069 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1070 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1071 * the return value indicating the same issue, so that we are definitely on the safe side.
1072 *
1073 * See https://github.com/systemd/systemd/issues/6737 */
1074
1075 errno = 0;
1076 ret = personality(p);
1077 if (ret < 0) {
1078 if (errno != 0)
1079 return -errno;
1080
1081 errno = -ret;
1082 }
1083
1084 return ret;
1085}
1086
e8132d63
LP
1087int opinionated_personality(unsigned long *ret) {
1088 int current;
1089
1090 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1091 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1092 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1093
21022b9d 1094 current = safe_personality(PERSONALITY_INVALID);
e8132d63 1095 if (current < 0)
21022b9d 1096 return current;
e8132d63
LP
1097
1098 if (((unsigned long) current & 0xffff) == PER_LINUX32)
1099 *ret = PER_LINUX32;
1100 else
1101 *ret = PER_LINUX;
1102
1103 return 0;
1104}
1105
dcadc967 1106void valgrind_summary_hack(void) {
349cc4a5 1107#if HAVE_VALGRIND_VALGRIND_H
df0ff127 1108 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
dcadc967 1109 pid_t pid;
8869a0b4 1110 pid = raw_clone(SIGCHLD);
dcadc967
EV
1111 if (pid < 0)
1112 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
1113 else if (pid == 0)
1114 exit(EXIT_SUCCESS);
1115 else {
1116 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
1117 (void) wait_for_terminate(pid, NULL);
1118 }
1119 }
1120#endif
1121}
1122
93bab288 1123int pid_compare_func(const pid_t *a, const pid_t *b) {
291d565a 1124 /* Suitable for usage in qsort() */
93bab288 1125 return CMP(*a, *b);
291d565a
LP
1126}
1127
7f452159
LP
1128int ioprio_parse_priority(const char *s, int *ret) {
1129 int i, r;
1130
1131 assert(s);
1132 assert(ret);
1133
1134 r = safe_atoi(s, &i);
1135 if (r < 0)
1136 return r;
1137
1138 if (!ioprio_priority_is_valid(i))
1139 return -EINVAL;
1140
1141 *ret = i;
1142 return 0;
1143}
1144
5c30a6d2
LP
1145/* The cached PID, possible values:
1146 *
1147 * == UNSET [0] → cache not initialized yet
1148 * == BUSY [-1] → some thread is initializing it at the moment
1149 * any other → the cached PID
1150 */
1151
1152#define CACHED_PID_UNSET ((pid_t) 0)
1153#define CACHED_PID_BUSY ((pid_t) -1)
1154
1155static pid_t cached_pid = CACHED_PID_UNSET;
1156
799a960d 1157void reset_cached_pid(void) {
5c30a6d2
LP
1158 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1159 cached_pid = CACHED_PID_UNSET;
1160}
1161
1162/* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1163 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1164 * libpthread, as it is part of glibc anyway. */
2bb8d8d9 1165extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void *dso_handle);
d34dae18 1166extern void* __dso_handle _weak_;
5c30a6d2
LP
1167
1168pid_t getpid_cached(void) {
5d71bac3 1169 static bool installed = false;
5c30a6d2
LP
1170 pid_t current_value;
1171
1172 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1173 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1174 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1175 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1176 *
1177 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
a4041e4f 1178 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
5c30a6d2
LP
1179 */
1180
1181 current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1182
1183 switch (current_value) {
1184
1185 case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1186 pid_t new_pid;
1187
996def17 1188 new_pid = raw_getpid();
5c30a6d2 1189
5d71bac3
LP
1190 if (!installed) {
1191 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1192 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1193 * we'll check for errors only in the most generic fashion possible. */
1194
1195 if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) {
1196 /* OOM? Let's try again later */
1197 cached_pid = CACHED_PID_UNSET;
1198 return new_pid;
1199 }
1200
1201 installed = true;
5c30a6d2
LP
1202 }
1203
1204 cached_pid = new_pid;
1205 return new_pid;
1206 }
1207
1208 case CACHED_PID_BUSY: /* Somebody else is currently initializing */
996def17 1209 return raw_getpid();
5c30a6d2
LP
1210
1211 default: /* Properly initialized */
1212 return current_value;
1213 }
1214}
1215
fba868fa
LP
1216int must_be_root(void) {
1217
1218 if (geteuid() == 0)
1219 return 0;
1220
baaa35ad 1221 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be root.");
fba868fa
LP
1222}
1223
4c253ed1
LP
1224int safe_fork_full(
1225 const char *name,
1226 const int except_fds[],
1227 size_t n_except_fds,
1228 ForkFlags flags,
1229 pid_t *ret_pid) {
1230
1231 pid_t original_pid, pid;
1f5d1e02 1232 sigset_t saved_ss, ss;
a41f6217 1233 bool block_signals = false;
b6e1fff1 1234 int prio, r;
4c253ed1
LP
1235
1236 /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1237 * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1238
b6e1fff1
LP
1239 prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG;
1240
4c253ed1
LP
1241 original_pid = getpid_cached();
1242
1f5d1e02 1243 if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG)) {
1f5d1e02
LP
1244 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1245 * be sure that SIGTERMs are not lost we might send to the child. */
4c253ed1 1246
cd2a429e 1247 assert_se(sigfillset(&ss) >= 0);
1f5d1e02
LP
1248 block_signals = true;
1249
1250 } else if (flags & FORK_WAIT) {
1f5d1e02
LP
1251 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1252
cd2a429e
ZJS
1253 assert_se(sigemptyset(&ss) >= 0);
1254 assert_se(sigaddset(&ss, SIGCHLD) >= 0);
1f5d1e02 1255 block_signals = true;
4c253ed1
LP
1256 }
1257
1f5d1e02
LP
1258 if (block_signals)
1259 if (sigprocmask(SIG_SETMASK, &ss, &saved_ss) < 0)
1260 return log_full_errno(prio, errno, "Failed to set signal mask: %m");
1261
be39f6ee
LP
1262 if (flags & FORK_NEW_MOUNTNS)
1263 pid = raw_clone(SIGCHLD|CLONE_NEWNS);
1264 else
1265 pid = fork();
4c253ed1
LP
1266 if (pid < 0) {
1267 r = -errno;
1268
1269 if (block_signals) /* undo what we did above */
1270 (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL);
1271
b6e1fff1 1272 return log_full_errno(prio, r, "Failed to fork: %m");
4c253ed1
LP
1273 }
1274 if (pid > 0) {
1275 /* We are in the parent process */
1276
1f5d1e02
LP
1277 log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid);
1278
1279 if (flags & FORK_WAIT) {
1280 r = wait_for_terminate_and_check(name, pid, (flags & FORK_LOG ? WAIT_LOG : 0));
1281 if (r < 0)
1282 return r;
1283 if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */
1284 return -EPROTO;
1285 }
1286
4c253ed1
LP
1287 if (block_signals) /* undo what we did above */
1288 (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL);
1289
4c253ed1
LP
1290 if (ret_pid)
1291 *ret_pid = pid;
1292
1293 return 1;
1294 }
1295
1296 /* We are in the child process */
1297
1298 if (flags & FORK_REOPEN_LOG) {
1299 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1300 log_close();
1301 log_set_open_when_needed(true);
1302 }
1303
1304 if (name) {
1305 r = rename_process(name);
1306 if (r < 0)
b6e1fff1
LP
1307 log_full_errno(flags & FORK_LOG ? LOG_WARNING : LOG_DEBUG,
1308 r, "Failed to rename process, ignoring: %m");
4c253ed1
LP
1309 }
1310
1311 if (flags & FORK_DEATHSIG)
1312 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) {
b6e1fff1 1313 log_full_errno(prio, errno, "Failed to set death signal: %m");
4c253ed1
LP
1314 _exit(EXIT_FAILURE);
1315 }
1316
1317 if (flags & FORK_RESET_SIGNALS) {
1318 r = reset_all_signal_handlers();
1319 if (r < 0) {
b6e1fff1 1320 log_full_errno(prio, r, "Failed to reset signal handlers: %m");
4c253ed1
LP
1321 _exit(EXIT_FAILURE);
1322 }
1323
1324 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1325 r = reset_signal_mask();
1326 if (r < 0) {
b6e1fff1 1327 log_full_errno(prio, r, "Failed to reset signal mask: %m");
4c253ed1
LP
1328 _exit(EXIT_FAILURE);
1329 }
1330 } else if (block_signals) { /* undo what we did above */
1331 if (sigprocmask(SIG_SETMASK, &saved_ss, NULL) < 0) {
b6e1fff1 1332 log_full_errno(prio, errno, "Failed to restore signal mask: %m");
4c253ed1
LP
1333 _exit(EXIT_FAILURE);
1334 }
1335 }
1336
1337 if (flags & FORK_DEATHSIG) {
7ddc2dc5 1338 pid_t ppid;
4c253ed1
LP
1339 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1340 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1341
7ddc2dc5
SL
1342 ppid = getppid();
1343 if (ppid == 0)
1344 /* Parent is in a differn't PID namespace. */;
1345 else if (ppid != original_pid) {
4c253ed1
LP
1346 log_debug("Parent died early, raising SIGTERM.");
1347 (void) raise(SIGTERM);
1348 _exit(EXIT_FAILURE);
1349 }
1350 }
1351
d94a24ca 1352 if (FLAGS_SET(flags, FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE)) {
e2047ba9
LP
1353
1354 /* Optionally, make sure we never propagate mounts to the host. */
1355
1356 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
1357 log_full_errno(prio, errno, "Failed to remount root directory as MS_SLAVE: %m");
1358 _exit(EXIT_FAILURE);
1359 }
1360 }
1361
4c253ed1
LP
1362 if (flags & FORK_CLOSE_ALL_FDS) {
1363 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1364 log_close();
1365
1366 r = close_all_fds(except_fds, n_except_fds);
1367 if (r < 0) {
b6e1fff1 1368 log_full_errno(prio, r, "Failed to close all file descriptors: %m");
4c253ed1
LP
1369 _exit(EXIT_FAILURE);
1370 }
1371 }
1372
1373 /* When we were asked to reopen the logs, do so again now */
1374 if (flags & FORK_REOPEN_LOG) {
1375 log_open();
1376 log_set_open_when_needed(false);
1377 }
1378
1379 if (flags & FORK_NULL_STDIO) {
1380 r = make_null_stdio();
1381 if (r < 0) {
b6e1fff1 1382 log_full_errno(prio, r, "Failed to connect stdin/stdout to /dev/null: %m");
4c253ed1
LP
1383 _exit(EXIT_FAILURE);
1384 }
1385 }
1386
909106eb
LP
1387 if (flags & FORK_RLIMIT_NOFILE_SAFE) {
1388 r = rlimit_nofile_safe();
1389 if (r < 0) {
1390 log_full_errno(prio, r, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1391 _exit(EXIT_FAILURE);
1392 }
1393 }
1394
4c253ed1
LP
1395 if (ret_pid)
1396 *ret_pid = getpid_cached();
1397
1398 return 0;
1399}
1400
27096982
LP
1401int namespace_fork(
1402 const char *outer_name,
1403 const char *inner_name,
1404 const int except_fds[],
1405 size_t n_except_fds,
1406 ForkFlags flags,
1407 int pidns_fd,
1408 int mntns_fd,
1409 int netns_fd,
1410 int userns_fd,
1411 int root_fd,
1412 pid_t *ret_pid) {
1413
1414 int r;
1415
1416 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1417 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1418 * /proc/self/fd works correctly. */
1419
1420 r = safe_fork_full(outer_name, except_fds, n_except_fds, (flags|FORK_DEATHSIG) & ~(FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE), ret_pid);
1421 if (r < 0)
1422 return r;
1423 if (r == 0) {
1424 pid_t pid;
1425
1426 /* Child */
1427
1428 r = namespace_enter(pidns_fd, mntns_fd, netns_fd, userns_fd, root_fd);
1429 if (r < 0) {
1430 log_full_errno(FLAGS_SET(flags, FORK_LOG) ? LOG_ERR : LOG_DEBUG, r, "Failed to join namespace: %m");
1431 _exit(EXIT_FAILURE);
1432 }
1433
1434 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1435 r = safe_fork_full(inner_name, except_fds, n_except_fds, flags & ~(FORK_WAIT|FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_NULL_STDIO), &pid);
1436 if (r < 0)
1437 _exit(EXIT_FAILURE);
1438 if (r == 0) {
1439 /* Child */
1440 if (ret_pid)
1441 *ret_pid = pid;
1442 return 0;
1443 }
1444
1445 r = wait_for_terminate_and_check(inner_name, pid, FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1446 if (r < 0)
1447 _exit(EXIT_FAILURE);
1448
1449 _exit(r);
1450 }
1451
1452 return 1;
1453}
1454
da6053d0 1455int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) {
78752f2e 1456 bool stdout_is_tty, stderr_is_tty;
da6053d0 1457 size_t n, i;
78752f2e
LP
1458 va_list ap;
1459 char **l;
1460 int r;
1461
1462 assert(path);
1463
1464 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1465
1466 r = safe_fork_full(name, except, n_except, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS, ret_pid);
1467 if (r < 0)
1468 return r;
1469 if (r > 0)
1470 return 0;
1471
1472 /* In the child: */
1473
1474 stdout_is_tty = isatty(STDOUT_FILENO);
1475 stderr_is_tty = isatty(STDERR_FILENO);
1476
1477 if (!stdout_is_tty || !stderr_is_tty) {
1478 int fd;
1479
1480 /* Detach from stdout/stderr. and reopen
1481 * /dev/tty for them. This is important to
1482 * ensure that when systemctl is started via
1483 * popen() or a similar call that expects to
1484 * read EOF we actually do generate EOF and
1485 * not delay this indefinitely by because we
1486 * keep an unused copy of stdin around. */
1487 fd = open("/dev/tty", O_WRONLY);
1488 if (fd < 0) {
1489 log_error_errno(errno, "Failed to open /dev/tty: %m");
1490 _exit(EXIT_FAILURE);
1491 }
1492
1493 if (!stdout_is_tty && dup2(fd, STDOUT_FILENO) < 0) {
1494 log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1495 _exit(EXIT_FAILURE);
1496 }
1497
1498 if (!stderr_is_tty && dup2(fd, STDERR_FILENO) < 0) {
1499 log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1500 _exit(EXIT_FAILURE);
1501 }
1502
e7685a77 1503 safe_close_above_stdio(fd);
78752f2e
LP
1504 }
1505
595225af
LP
1506 (void) rlimit_nofile_safe();
1507
78752f2e
LP
1508 /* Count arguments */
1509 va_start(ap, path);
1510 for (n = 0; va_arg(ap, char*); n++)
1511 ;
1512 va_end(ap);
1513
1514 /* Allocate strv */
cf409d15 1515 l = newa(char*, n + 1);
78752f2e
LP
1516
1517 /* Fill in arguments */
1518 va_start(ap, path);
1519 for (i = 0; i <= n; i++)
1520 l[i] = va_arg(ap, char*);
1521 va_end(ap);
1522
1523 execv(path, l);
1524 _exit(EXIT_FAILURE);
1525}
1526
9f8168eb
LP
1527int set_oom_score_adjust(int value) {
1528 char t[DECIMAL_STR_MAX(int)];
1529
1530 sprintf(t, "%i", value);
1531
1532 return write_string_file("/proc/self/oom_score_adj", t,
1533 WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
1534}
1535
7b3e062c
LP
1536static const char *const ioprio_class_table[] = {
1537 [IOPRIO_CLASS_NONE] = "none",
1538 [IOPRIO_CLASS_RT] = "realtime",
1539 [IOPRIO_CLASS_BE] = "best-effort",
f44b3035 1540 [IOPRIO_CLASS_IDLE] = "idle",
7b3e062c
LP
1541};
1542
10062bbc 1543DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, IOPRIO_N_CLASSES);
7b3e062c
LP
1544
1545static const char *const sigchld_code_table[] = {
1546 [CLD_EXITED] = "exited",
1547 [CLD_KILLED] = "killed",
1548 [CLD_DUMPED] = "dumped",
1549 [CLD_TRAPPED] = "trapped",
1550 [CLD_STOPPED] = "stopped",
1551 [CLD_CONTINUED] = "continued",
1552};
1553
1554DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1555
1556static const char* const sched_policy_table[] = {
1557 [SCHED_OTHER] = "other",
1558 [SCHED_BATCH] = "batch",
1559 [SCHED_IDLE] = "idle",
1560 [SCHED_FIFO] = "fifo",
f44b3035 1561 [SCHED_RR] = "rr",
7b3e062c
LP
1562};
1563
1564DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);