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