LCOV - code coverage report
Current view: top level - basic - process-util.c (source / functions) Hit Total Coverage
Test: main_coverage.info Lines: 357 686 52.0 %
Date: 2019-08-22 15:41:25 Functions: 30 50 60.0 %

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

Generated by: LCOV version 1.14