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