1 /* SPDX-License-Identifier: LGPL-2.1+ */
14 #include <sys/mount.h>
15 #include <sys/personality.h>
16 #include <sys/prctl.h>
17 #include <sys/types.h>
21 #if HAVE_VALGRIND_VALGRIND_H
22 #include <valgrind/valgrind.h>
25 #include "alloc-util.h"
26 #include "architecture.h"
34 #include "memory-util.h"
36 #include "namespace-util.h"
37 #include "process-util.h"
38 #include "raw-clone.h"
39 #include "rlimit-util.h"
40 #include "signal-util.h"
41 #include "stat-util.h"
42 #include "string-table.h"
43 #include "string-util.h"
44 #include "terminal-util.h"
45 #include "user-util.h"
47 int get_process_state(pid_t pid
) {
51 _cleanup_free_
char *line
= NULL
;
55 p
= procfs_file_alloca(pid
, "stat");
57 r
= read_one_line_file(p
, &line
);
63 p
= strrchr(line
, ')');
69 if (sscanf(p
, " %c", &state
) != 1)
72 return (unsigned char) state
;
75 int get_process_comm(pid_t pid
, char **ret
) {
76 _cleanup_free_
char *escaped
= NULL
, *comm
= NULL
;
83 escaped
= new(char, TASK_COMM_LEN
);
87 p
= procfs_file_alloca(pid
, "comm");
89 r
= read_one_line_file(p
, &comm
);
95 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
96 cellescape(escaped
, TASK_COMM_LEN
, comm
);
98 *ret
= TAKE_PTR(escaped
);
102 int get_process_cmdline(pid_t pid
, size_t max_length
, bool comm_fallback
, char **line
) {
103 _cleanup_fclose_
FILE *f
= NULL
;
106 _cleanup_free_
char *ans
= NULL
;
113 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
114 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
115 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
116 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
117 * command line that resolves to the empty string will return the "comm" name of the process instead.
119 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
120 * comm_fallback is false). Returns 0 and sets *line otherwise. */
122 p
= procfs_file_alloca(pid
, "cmdline");
123 r
= fopen_unlocked(p
, "re", &f
);
129 if (max_length
== 0) {
130 /* This is supposed to be a safety guard against runaway command lines. */
131 long l
= sysconf(_SC_ARG_MAX
);
136 if (max_length
== 1) {
138 /* If there's only room for one byte, return the empty string */
143 *line
= TAKE_PTR(ans
);
147 bool dotdotdot
= false;
150 ans
= new(char, max_length
);
156 while ((c
= getc(f
)) != EOF
) {
183 if (max_length
<= 4) {
187 k
= ans
+ max_length
- 4;
190 /* Eat up final spaces */
191 while (k
> ans
&& isspace(k
[-1])) {
197 strncpy(k
, "...", left
-1);
203 /* Kernel threads have no argv[] */
205 _cleanup_free_
char *t
= NULL
;
213 h
= get_process_comm(pid
, &t
);
217 size_t l
= strlen(t
);
219 if (l
+ 3 <= max_length
) {
220 ans
= strjoin("[", t
, "]");
224 } else if (max_length
<= 6) {
225 ans
= new(char, max_length
);
229 memcpy(ans
, "[...]", max_length
-1);
230 ans
[max_length
-1] = 0;
232 t
[max_length
- 6] = 0;
234 /* Chop off final spaces */
235 delete_trailing_chars(t
, WHITESPACE
);
237 ans
= strjoin("[", t
, "...]");
242 *line
= TAKE_PTR(ans
);
246 k
= realloc(ans
, strlen(ans
) + 1);
256 int rename_process(const char name
[]) {
257 static size_t mm_size
= 0;
258 static char *mm
= NULL
;
259 bool truncated
= false;
262 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
263 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
264 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
265 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
268 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
271 return -EINVAL
; /* let's not confuse users unnecessarily with an empty name */
273 if (!is_main_thread())
274 return -EPERM
; /* Let's not allow setting the process name from other threads than the main one, as we
275 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
276 * process name that isn't correct on any other threads */
280 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
281 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
282 if (prctl(PR_SET_NAME
, name
) < 0)
283 log_debug_errno(errno
, "PR_SET_NAME failed: %m");
284 if (l
>= TASK_COMM_LEN
) /* Linux process names can be 15 chars at max */
287 /* Second step, change glibc's ID of the process name. */
288 if (program_invocation_name
) {
291 k
= strlen(program_invocation_name
);
292 strncpy(program_invocation_name
, name
, k
);
297 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
298 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
299 * the end. This is the best option for changing /proc/self/cmdline. */
301 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
302 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
303 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
304 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
307 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
308 else if (mm_size
< l
+1) {
312 nn_size
= PAGE_ALIGN(l
+1);
313 nn
= mmap(NULL
, nn_size
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
314 if (nn
== MAP_FAILED
) {
315 log_debug_errno(errno
, "mmap() failed: %m");
319 strncpy(nn
, name
, nn_size
);
321 /* Now, let's tell the kernel about this new memory */
322 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
323 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
324 * below the desired start address, in which case the kernel may have kicked this back due
325 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
326 * action). The proper solution would be to have a prctl() API that could set both start+end
327 * simultaneously, or at least let us query the existing address to anticipate this condition
328 * and respond accordingly. For now, we can only guess at the cause of this failure and try
329 * a workaround--which will briefly expand the arg space to something potentially huge before
330 * resizing it to what we want. */
331 log_debug_errno(errno
, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
333 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0) {
334 log_debug_errno(errno
, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
335 (void) munmap(nn
, nn_size
);
339 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
340 log_debug_errno(errno
, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
344 /* And update the end pointer to the new end, too. If this fails, we don't really know what
345 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
347 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0)
348 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
352 (void) munmap(mm
, mm_size
);
357 strncpy(mm
, name
, mm_size
);
359 /* Update the end pointer, continuing regardless of any failure. */
360 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) mm
+ l
+ 1, 0, 0) < 0)
361 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
365 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
366 * it still looks here */
368 if (saved_argc
> 0) {
374 k
= strlen(saved_argv
[0]);
375 strncpy(saved_argv
[0], name
, k
);
380 for (i
= 1; i
< saved_argc
; i
++) {
384 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
391 int is_kernel_thread(pid_t pid
) {
392 _cleanup_free_
char *line
= NULL
;
393 unsigned long long flags
;
399 if (IN_SET(pid
, 0, 1) || pid
== getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
401 if (!pid_is_valid(pid
))
404 p
= procfs_file_alloca(pid
, "stat");
405 r
= read_one_line_file(p
, &line
);
411 /* Skip past the comm field */
412 q
= strrchr(line
, ')');
417 /* Skip 6 fields to reach the flags field */
418 for (i
= 0; i
< 6; i
++) {
419 l
= strspn(q
, WHITESPACE
);
424 l
= strcspn(q
, WHITESPACE
);
430 /* Skip preceding whitespace */
431 l
= strspn(q
, WHITESPACE
);
436 /* Truncate the rest */
437 l
= strcspn(q
, WHITESPACE
);
442 r
= safe_atollu(q
, &flags
);
446 return !!(flags
& PF_KTHREAD
);
449 int get_process_capeff(pid_t pid
, char **capeff
) {
456 p
= procfs_file_alloca(pid
, "status");
458 r
= get_proc_field(p
, "CapEff", WHITESPACE
, capeff
);
465 static int get_process_link_contents(const char *proc_file
, char **name
) {
471 r
= readlink_malloc(proc_file
, name
);
480 int get_process_exe(pid_t pid
, char **name
) {
487 p
= procfs_file_alloca(pid
, "exe");
488 r
= get_process_link_contents(p
, name
);
492 d
= endswith(*name
, " (deleted)");
499 static int get_process_id(pid_t pid
, const char *field
, uid_t
*uid
) {
500 _cleanup_fclose_
FILE *f
= NULL
;
510 p
= procfs_file_alloca(pid
, "status");
511 r
= fopen_unlocked(p
, "re", &f
);
518 _cleanup_free_
char *line
= NULL
;
521 r
= read_line(f
, LONG_LINE_MAX
, &line
);
529 if (startswith(l
, field
)) {
531 l
+= strspn(l
, WHITESPACE
);
533 l
[strcspn(l
, WHITESPACE
)] = 0;
535 return parse_uid(l
, uid
);
542 int get_process_uid(pid_t pid
, uid_t
*uid
) {
544 if (pid
== 0 || pid
== getpid_cached()) {
549 return get_process_id(pid
, "Uid:", uid
);
552 int get_process_gid(pid_t pid
, gid_t
*gid
) {
554 if (pid
== 0 || pid
== getpid_cached()) {
559 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
560 return get_process_id(pid
, "Gid:", gid
);
563 int get_process_cwd(pid_t pid
, char **cwd
) {
568 p
= procfs_file_alloca(pid
, "cwd");
570 return get_process_link_contents(p
, cwd
);
573 int get_process_root(pid_t pid
, char **root
) {
578 p
= procfs_file_alloca(pid
, "root");
580 return get_process_link_contents(p
, root
);
583 #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
585 int get_process_environ(pid_t pid
, char **env
) {
586 _cleanup_fclose_
FILE *f
= NULL
;
587 _cleanup_free_
char *outcome
= NULL
;
588 size_t allocated
= 0, sz
= 0;
595 p
= procfs_file_alloca(pid
, "environ");
597 r
= fopen_unlocked(p
, "re", &f
);
606 if (sz
>= ENVIRONMENT_BLOCK_MAX
)
609 if (!GREEDY_REALLOC(outcome
, allocated
, sz
+ 5))
612 r
= safe_fgetc(f
, &c
);
619 outcome
[sz
++] = '\n';
621 sz
+= cescape_char(c
, outcome
+ sz
);
625 *env
= TAKE_PTR(outcome
);
630 int get_process_ppid(pid_t pid
, pid_t
*_ppid
) {
632 _cleanup_free_
char *line
= NULL
;
639 if (pid
== 0 || pid
== getpid_cached()) {
644 p
= procfs_file_alloca(pid
, "stat");
645 r
= read_one_line_file(p
, &line
);
651 /* Let's skip the pid and comm fields. The latter is enclosed
652 * in () but does not escape any () in its value, so let's
653 * skip over it manually */
655 p
= strrchr(line
, ')');
667 if ((long unsigned) (pid_t
) ppid
!= ppid
)
670 *_ppid
= (pid_t
) ppid
;
675 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
686 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
691 return negative_errno();
700 * < 0 : wait_for_terminate() failed to get the state of the
701 * process, the process was terminated by a signal, or
702 * failed for an unknown reason.
703 * >=0 : The process terminated normally, and its exit code is
706 * That is, success is indicated by a return value of zero, and an
707 * error is indicated by a non-zero value.
709 * A warning is emitted if the process terminates abnormally,
710 * and also if it returns non-zero unless check_exit_code is true.
712 int wait_for_terminate_and_check(const char *name
, pid_t pid
, WaitFlags flags
) {
713 _cleanup_free_
char *buffer
= NULL
;
720 r
= get_process_comm(pid
, &buffer
);
722 log_debug_errno(r
, "Failed to acquire process name of " PID_FMT
", ignoring: %m", pid
);
727 prio
= flags
& WAIT_LOG_ABNORMAL
? LOG_ERR
: LOG_DEBUG
;
729 r
= wait_for_terminate(pid
, &status
);
731 return log_full_errno(prio
, r
, "Failed to wait for %s: %m", strna(name
));
733 if (status
.si_code
== CLD_EXITED
) {
734 if (status
.si_status
!= EXIT_SUCCESS
)
735 log_full(flags
& WAIT_LOG_NON_ZERO_EXIT_STATUS
? LOG_ERR
: LOG_DEBUG
,
736 "%s failed with exit status %i.", strna(name
), status
.si_status
);
738 log_debug("%s succeeded.", name
);
740 return status
.si_status
;
742 } else if (IN_SET(status
.si_code
, CLD_KILLED
, CLD_DUMPED
)) {
744 log_full(prio
, "%s terminated by signal %s.", strna(name
), signal_to_string(status
.si_status
));
748 log_full(prio
, "%s failed due to unknown reason.", strna(name
));
755 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
756 * was terminated by a signal, or failed for an unknown reason.
758 * >=0 : The process terminated normally with no failures.
760 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
761 * states are indicated by error is indicated by a non-zero value.
763 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
764 * to remain entirely race-free.
766 int wait_for_terminate_with_timeout(pid_t pid
, usec_t timeout
) {
771 assert_se(sigemptyset(&mask
) == 0);
772 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
774 /* Drop into a sigtimewait-based timeout. Waiting for the
776 until
= now(CLOCK_MONOTONIC
) + timeout
;
779 siginfo_t status
= {};
782 n
= now(CLOCK_MONOTONIC
);
786 r
= sigtimedwait(&mask
, NULL
, timespec_store(&ts
, until
- n
)) < 0 ? -errno
: 0;
787 /* Assuming we woke due to the child exiting. */
788 if (waitid(P_PID
, pid
, &status
, WEXITED
|WNOHANG
) == 0) {
789 if (status
.si_pid
== pid
) {
790 /* This is the correct child.*/
791 if (status
.si_code
== CLD_EXITED
)
792 return (status
.si_status
== 0) ? 0 : -EPROTO
;
797 /* Not the child, check for errors and proceed appropriately */
801 /* Timed out, child is likely hung. */
804 /* Received a different signal and should retry */
807 /* Return any unexpected errors */
816 void sigkill_wait(pid_t pid
) {
819 if (kill(pid
, SIGKILL
) >= 0)
820 (void) wait_for_terminate(pid
, NULL
);
823 void sigkill_waitp(pid_t
*pid
) {
834 void sigterm_wait(pid_t pid
) {
837 if (kill_and_sigcont(pid
, SIGTERM
) >= 0)
838 (void) wait_for_terminate(pid
, NULL
);
841 int kill_and_sigcont(pid_t pid
, int sig
) {
844 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
846 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
847 * affected by a process being suspended anyway. */
848 if (r
>= 0 && !IN_SET(sig
, SIGCONT
, SIGKILL
))
849 (void) kill(pid
, SIGCONT
);
854 int getenv_for_pid(pid_t pid
, const char *field
, char **ret
) {
855 _cleanup_fclose_
FILE *f
= NULL
;
865 if (pid
== 0 || pid
== getpid_cached()) {
882 if (!pid_is_valid(pid
))
885 path
= procfs_file_alloca(pid
, "environ");
887 r
= fopen_unlocked(path
, "re", &f
);
895 _cleanup_free_
char *line
= NULL
;
897 if (sum
> ENVIRONMENT_BLOCK_MAX
) /* Give up searching eventually */
900 r
= read_nul_string(f
, LONG_LINE_MAX
, &line
);
903 if (r
== 0) /* EOF */
908 if (strneq(line
, field
, l
) && line
[l
] == '=') {
909 value
= strdup(line
+ l
+ 1);
922 int pid_is_my_child(pid_t pid
) {
929 r
= get_process_ppid(pid
, &ppid
);
933 return ppid
== getpid_cached();
936 bool pid_is_unwaited(pid_t pid
) {
937 /* Checks whether a PID is still valid at all, including a zombie */
942 if (pid
<= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
945 if (pid
== getpid_cached())
948 if (kill(pid
, 0) >= 0)
951 return errno
!= ESRCH
;
954 bool pid_is_alive(pid_t pid
) {
957 /* Checks whether a PID is still valid and not a zombie */
962 if (pid
<= 1) /* If we or PID 1 would be a zombie, this code would not be running */
965 if (pid
== getpid_cached())
968 r
= get_process_state(pid
);
969 if (IN_SET(r
, -ESRCH
, 'Z'))
975 int pid_from_same_root_fs(pid_t pid
) {
981 if (pid
== 0 || pid
== getpid_cached())
984 root
= procfs_file_alloca(pid
, "root");
986 return files_same(root
, "/proc/1/root", 0);
989 bool is_main_thread(void) {
990 static thread_local
int cached
= 0;
992 if (_unlikely_(cached
== 0))
993 cached
= getpid_cached() == gettid() ? 1 : -1;
998 _noreturn_
void freeze(void) {
1002 /* Make sure nobody waits for us on a socket anymore */
1003 (void) close_all_fds(NULL
, 0);
1007 /* Let's not freeze right away, but keep reaping zombies. */
1012 r
= waitid(P_ALL
, 0, &si
, WEXITED
);
1013 if (r
< 0 && errno
!= EINTR
)
1017 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
1022 bool oom_score_adjust_is_valid(int oa
) {
1023 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
1026 unsigned long personality_from_string(const char *p
) {
1030 return PERSONALITY_INVALID
;
1032 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1033 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1034 * the same register size. */
1036 architecture
= architecture_from_string(p
);
1037 if (architecture
< 0)
1038 return PERSONALITY_INVALID
;
1040 if (architecture
== native_architecture())
1042 #ifdef SECONDARY_ARCHITECTURE
1043 if (architecture
== SECONDARY_ARCHITECTURE
)
1047 return PERSONALITY_INVALID
;
1050 const char* personality_to_string(unsigned long p
) {
1051 int architecture
= _ARCHITECTURE_INVALID
;
1054 architecture
= native_architecture();
1055 #ifdef SECONDARY_ARCHITECTURE
1056 else if (p
== PER_LINUX32
)
1057 architecture
= SECONDARY_ARCHITECTURE
;
1060 if (architecture
< 0)
1063 return architecture_to_string(architecture
);
1066 int safe_personality(unsigned long p
) {
1069 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1070 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1071 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1072 * the return value indicating the same issue, so that we are definitely on the safe side.
1074 * See https://github.com/systemd/systemd/issues/6737 */
1077 ret
= personality(p
);
1088 int opinionated_personality(unsigned long *ret
) {
1091 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1092 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1093 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1095 current
= safe_personality(PERSONALITY_INVALID
);
1099 if (((unsigned long) current
& 0xffff) == PER_LINUX32
)
1107 void valgrind_summary_hack(void) {
1108 #if HAVE_VALGRIND_VALGRIND_H
1109 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
1111 pid
= raw_clone(SIGCHLD
);
1113 log_emergency_errno(errno
, "Failed to fork off valgrind helper: %m");
1117 log_info("Spawned valgrind helper as PID "PID_FMT
".", pid
);
1118 (void) wait_for_terminate(pid
, NULL
);
1124 int pid_compare_func(const pid_t
*a
, const pid_t
*b
) {
1125 /* Suitable for usage in qsort() */
1129 int ioprio_parse_priority(const char *s
, int *ret
) {
1135 r
= safe_atoi(s
, &i
);
1139 if (!ioprio_priority_is_valid(i
))
1146 /* The cached PID, possible values:
1148 * == UNSET [0] → cache not initialized yet
1149 * == BUSY [-1] → some thread is initializing it at the moment
1150 * any other → the cached PID
1153 #define CACHED_PID_UNSET ((pid_t) 0)
1154 #define CACHED_PID_BUSY ((pid_t) -1)
1156 static pid_t cached_pid
= CACHED_PID_UNSET
;
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
;
1163 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1164 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1165 * libpthread, as it is part of glibc anyway. */
1166 extern int __register_atfork(void (*prepare
) (void), void (*parent
) (void), void (*child
) (void), void *dso_handle
);
1167 extern void* __dso_handle _weak_
;
1169 pid_t
getpid_cached(void) {
1170 static bool installed
= false;
1171 pid_t current_value
;
1173 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1174 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1175 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1176 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1178 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1179 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1182 current_value
= __sync_val_compare_and_swap(&cached_pid
, CACHED_PID_UNSET
, CACHED_PID_BUSY
);
1184 switch (current_value
) {
1186 case CACHED_PID_UNSET
: { /* Not initialized yet, then do so now */
1189 new_pid
= raw_getpid();
1192 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1193 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1194 * we'll check for errors only in the most generic fashion possible. */
1196 if (__register_atfork(NULL
, NULL
, reset_cached_pid
, __dso_handle
) != 0) {
1197 /* OOM? Let's try again later */
1198 cached_pid
= CACHED_PID_UNSET
;
1205 cached_pid
= new_pid
;
1209 case CACHED_PID_BUSY
: /* Somebody else is currently initializing */
1210 return raw_getpid();
1212 default: /* Properly initialized */
1213 return current_value
;
1217 int must_be_root(void) {
1222 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Need to be root.");
1227 const int except_fds
[],
1228 size_t n_except_fds
,
1232 pid_t original_pid
, pid
;
1233 sigset_t saved_ss
, ss
;
1234 bool block_signals
= false;
1237 /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1238 * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1240 prio
= flags
& FORK_LOG
? LOG_ERR
: LOG_DEBUG
;
1242 original_pid
= getpid_cached();
1244 if (flags
& (FORK_RESET_SIGNALS
|FORK_DEATHSIG
)) {
1245 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1246 * be sure that SIGTERMs are not lost we might send to the child. */
1248 assert_se(sigfillset(&ss
) >= 0);
1249 block_signals
= true;
1251 } else if (flags
& FORK_WAIT
) {
1252 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1254 assert_se(sigemptyset(&ss
) >= 0);
1255 assert_se(sigaddset(&ss
, SIGCHLD
) >= 0);
1256 block_signals
= true;
1260 if (sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) < 0)
1261 return log_full_errno(prio
, errno
, "Failed to set signal mask: %m");
1263 if (flags
& FORK_NEW_MOUNTNS
)
1264 pid
= raw_clone(SIGCHLD
|CLONE_NEWNS
);
1270 if (block_signals
) /* undo what we did above */
1271 (void) sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
);
1273 return log_full_errno(prio
, r
, "Failed to fork: %m");
1276 /* We are in the parent process */
1278 log_debug("Successfully forked off '%s' as PID " PID_FMT
".", strna(name
), pid
);
1280 if (flags
& FORK_WAIT
) {
1281 r
= wait_for_terminate_and_check(name
, pid
, (flags
& FORK_LOG
? WAIT_LOG
: 0));
1284 if (r
!= EXIT_SUCCESS
) /* exit status > 0 should be treated as failure, too */
1288 if (block_signals
) /* undo what we did above */
1289 (void) sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
);
1297 /* We are in the child process */
1299 if (flags
& FORK_REOPEN_LOG
) {
1300 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1302 log_set_open_when_needed(true);
1306 r
= rename_process(name
);
1308 log_full_errno(flags
& FORK_LOG
? LOG_WARNING
: LOG_DEBUG
,
1309 r
, "Failed to rename process, ignoring: %m");
1312 if (flags
& FORK_DEATHSIG
)
1313 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0) {
1314 log_full_errno(prio
, errno
, "Failed to set death signal: %m");
1315 _exit(EXIT_FAILURE
);
1318 if (flags
& FORK_RESET_SIGNALS
) {
1319 r
= reset_all_signal_handlers();
1321 log_full_errno(prio
, r
, "Failed to reset signal handlers: %m");
1322 _exit(EXIT_FAILURE
);
1325 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1326 r
= reset_signal_mask();
1328 log_full_errno(prio
, r
, "Failed to reset signal mask: %m");
1329 _exit(EXIT_FAILURE
);
1331 } else if (block_signals
) { /* undo what we did above */
1332 if (sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) < 0) {
1333 log_full_errno(prio
, errno
, "Failed to restore signal mask: %m");
1334 _exit(EXIT_FAILURE
);
1338 if (flags
& FORK_DEATHSIG
) {
1340 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1341 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1345 /* Parent is in a differn't PID namespace. */;
1346 else if (ppid
!= original_pid
) {
1347 log_debug("Parent died early, raising SIGTERM.");
1348 (void) raise(SIGTERM
);
1349 _exit(EXIT_FAILURE
);
1353 if (FLAGS_SET(flags
, FORK_NEW_MOUNTNS
| FORK_MOUNTNS_SLAVE
)) {
1355 /* Optionally, make sure we never propagate mounts to the host. */
1357 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
) < 0) {
1358 log_full_errno(prio
, errno
, "Failed to remount root directory as MS_SLAVE: %m");
1359 _exit(EXIT_FAILURE
);
1363 if (flags
& FORK_CLOSE_ALL_FDS
) {
1364 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1367 r
= close_all_fds(except_fds
, n_except_fds
);
1369 log_full_errno(prio
, r
, "Failed to close all file descriptors: %m");
1370 _exit(EXIT_FAILURE
);
1374 /* When we were asked to reopen the logs, do so again now */
1375 if (flags
& FORK_REOPEN_LOG
) {
1377 log_set_open_when_needed(false);
1380 if (flags
& FORK_NULL_STDIO
) {
1381 r
= make_null_stdio();
1383 log_full_errno(prio
, r
, "Failed to connect stdin/stdout to /dev/null: %m");
1384 _exit(EXIT_FAILURE
);
1388 if (flags
& FORK_RLIMIT_NOFILE_SAFE
) {
1389 r
= rlimit_nofile_safe();
1391 log_full_errno(prio
, r
, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1392 _exit(EXIT_FAILURE
);
1397 *ret_pid
= getpid_cached();
1403 const char *outer_name
,
1404 const char *inner_name
,
1405 const int except_fds
[],
1406 size_t n_except_fds
,
1417 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1418 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1419 * /proc/self/fd works correctly. */
1421 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
);
1429 r
= namespace_enter(pidns_fd
, mntns_fd
, netns_fd
, userns_fd
, root_fd
);
1431 log_full_errno(FLAGS_SET(flags
, FORK_LOG
) ? LOG_ERR
: LOG_DEBUG
, r
, "Failed to join namespace: %m");
1432 _exit(EXIT_FAILURE
);
1435 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1436 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
);
1438 _exit(EXIT_FAILURE
);
1446 r
= wait_for_terminate_and_check(inner_name
, pid
, FLAGS_SET(flags
, FORK_LOG
) ? WAIT_LOG
: 0);
1448 _exit(EXIT_FAILURE
);
1456 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
1457 bool stdout_is_tty
, stderr_is_tty
;
1465 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1467 r
= safe_fork_full(name
, except
, n_except
, FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_CLOSE_ALL_FDS
, ret_pid
);
1475 stdout_is_tty
= isatty(STDOUT_FILENO
);
1476 stderr_is_tty
= isatty(STDERR_FILENO
);
1478 if (!stdout_is_tty
|| !stderr_is_tty
) {
1481 /* Detach from stdout/stderr. and reopen
1482 * /dev/tty for them. This is important to
1483 * ensure that when systemctl is started via
1484 * popen() or a similar call that expects to
1485 * read EOF we actually do generate EOF and
1486 * not delay this indefinitely by because we
1487 * keep an unused copy of stdin around. */
1488 fd
= open("/dev/tty", O_WRONLY
);
1490 log_error_errno(errno
, "Failed to open /dev/tty: %m");
1491 _exit(EXIT_FAILURE
);
1494 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
1495 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
1496 _exit(EXIT_FAILURE
);
1499 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
1500 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
1501 _exit(EXIT_FAILURE
);
1504 safe_close_above_stdio(fd
);
1507 (void) rlimit_nofile_safe();
1509 /* Count arguments */
1511 for (n
= 0; va_arg(ap
, char*); n
++)
1516 l
= newa(char*, n
+ 1);
1518 /* Fill in arguments */
1520 for (i
= 0; i
<= n
; i
++)
1521 l
[i
] = va_arg(ap
, char*);
1525 _exit(EXIT_FAILURE
);
1528 int set_oom_score_adjust(int value
) {
1529 char t
[DECIMAL_STR_MAX(int)];
1531 sprintf(t
, "%i", value
);
1533 return write_string_file("/proc/self/oom_score_adj", t
,
1534 WRITE_STRING_FILE_VERIFY_ON_FAILURE
|WRITE_STRING_FILE_DISABLE_BUFFER
);
1537 int cpus_in_affinity_mask(void) {
1548 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), c
) >= 0) {
1551 k
= CPU_COUNT_S(CPU_ALLOC_SIZE(n
), c
);
1571 static const char *const ioprio_class_table
[] = {
1572 [IOPRIO_CLASS_NONE
] = "none",
1573 [IOPRIO_CLASS_RT
] = "realtime",
1574 [IOPRIO_CLASS_BE
] = "best-effort",
1575 [IOPRIO_CLASS_IDLE
] = "idle"
1578 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, IOPRIO_N_CLASSES
);
1580 static const char *const sigchld_code_table
[] = {
1581 [CLD_EXITED
] = "exited",
1582 [CLD_KILLED
] = "killed",
1583 [CLD_DUMPED
] = "dumped",
1584 [CLD_TRAPPED
] = "trapped",
1585 [CLD_STOPPED
] = "stopped",
1586 [CLD_CONTINUED
] = "continued",
1589 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1591 static const char* const sched_policy_table
[] = {
1592 [SCHED_OTHER
] = "other",
1593 [SCHED_BATCH
] = "batch",
1594 [SCHED_IDLE
] = "idle",
1595 [SCHED_FIFO
] = "fifo",
1599 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);