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