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