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