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