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