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"
35 #include "memory-util.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"
49 static int get_process_state(pid_t pid
) {
53 _cleanup_free_
char *line
= NULL
;
57 p
= procfs_file_alloca(pid
, "stat");
59 r
= read_one_line_file(p
, &line
);
65 p
= strrchr(line
, ')');
71 if (sscanf(p
, " %c", &state
) != 1)
74 return (unsigned char) state
;
77 int get_process_comm(pid_t pid
, char **ret
) {
78 _cleanup_free_
char *escaped
= NULL
, *comm
= NULL
;
85 escaped
= new(char, TASK_COMM_LEN
);
89 p
= procfs_file_alloca(pid
, "comm");
91 r
= read_one_line_file(p
, &comm
);
97 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
98 cellescape(escaped
, TASK_COMM_LEN
, comm
);
100 *ret
= TAKE_PTR(escaped
);
104 int get_process_cmdline(pid_t pid
, size_t max_columns
, bool comm_fallback
, char **line
) {
105 _cleanup_fclose_
FILE *f
= NULL
;
106 _cleanup_free_
char *t
= NULL
, *ans
= NULL
;
111 /* This is supposed to be a safety guard against runaway command lines. */
112 size_t max_length
= sc_arg_max();
117 /* Retrieves a process' command line. Replaces non-utf8 bytes by replacement character (�). If
118 * max_columns is != -1 will return a string of the specified console width at most, abbreviated with
119 * an ellipsis. If comm_fallback is true and the process has no command line set (the case for kernel
120 * threads), or has a command line that resolves to the empty string will return the "comm" name of
121 * the process instead. This will use at most _SC_ARG_MAX bytes of input data.
123 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
124 * comm_fallback is false). Returns 0 and sets *line otherwise. */
126 p
= procfs_file_alloca(pid
, "cmdline");
127 r
= fopen_unlocked(p
, "re", &f
);
133 /* We assume that each four-byte character uses one or two columns. If we ever check for combining
134 * characters, this assumption will need to be adjusted. */
135 if ((size_t) 4 * max_columns
+ 1 < max_columns
)
136 max_length
= MIN(max_length
, (size_t) 4 * max_columns
+ 1);
138 t
= new(char, max_length
);
142 k
= fread(t
, 1, max_length
, f
);
144 /* Arguments are separated by NULs. Let's replace those with spaces. */
145 for (size_t i
= 0; i
< k
- 1; i
++)
149 t
[k
] = '\0'; /* Normally, t[k] is already NUL, so this is just a guard in case of short read */
151 /* We only treat getting nothing as an error. We *could* also get an error after reading some
152 * data, but we ignore that case, as such an error is rather unlikely and we prefer to get
153 * some data rather than none. */
160 /* Kernel threads have no argv[] */
161 _cleanup_free_
char *t2
= NULL
;
163 r
= get_process_comm(pid
, &t2
);
168 t
= strjoin("[", t2
, "]");
173 delete_trailing_chars(t
, WHITESPACE
);
175 ans
= utf8_escape_non_printable_full(t
, max_columns
);
179 (void) str_realloc(&ans
);
180 *line
= TAKE_PTR(ans
);
184 int rename_process(const char name
[]) {
185 static size_t mm_size
= 0;
186 static char *mm
= NULL
;
187 bool truncated
= false;
190 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
191 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
192 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
193 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
196 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
199 return -EINVAL
; /* let's not confuse users unnecessarily with an empty name */
201 if (!is_main_thread())
202 return -EPERM
; /* Let's not allow setting the process name from other threads than the main one, as we
203 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
204 * process name that isn't correct on any other threads */
208 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
209 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
210 if (prctl(PR_SET_NAME
, name
) < 0)
211 log_debug_errno(errno
, "PR_SET_NAME failed: %m");
212 if (l
>= TASK_COMM_LEN
) /* Linux process names can be 15 chars at max */
215 /* Second step, change glibc's ID of the process name. */
216 if (program_invocation_name
) {
219 k
= strlen(program_invocation_name
);
220 strncpy(program_invocation_name
, name
, k
);
225 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
226 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
227 * the end. This is the best option for changing /proc/self/cmdline. */
229 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
230 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
231 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
232 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
235 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
236 else if (mm_size
< l
+1) {
240 nn_size
= PAGE_ALIGN(l
+1);
241 nn
= mmap(NULL
, nn_size
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
242 if (nn
== MAP_FAILED
) {
243 log_debug_errno(errno
, "mmap() failed: %m");
247 strncpy(nn
, name
, nn_size
);
249 /* Now, let's tell the kernel about this new memory */
250 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
251 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
252 * below the desired start address, in which case the kernel may have kicked this back due
253 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
254 * action). The proper solution would be to have a prctl() API that could set both start+end
255 * simultaneously, or at least let us query the existing address to anticipate this condition
256 * and respond accordingly. For now, we can only guess at the cause of this failure and try
257 * a workaround--which will briefly expand the arg space to something potentially huge before
258 * resizing it to what we want. */
259 log_debug_errno(errno
, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
261 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0) {
262 log_debug_errno(errno
, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
263 (void) munmap(nn
, nn_size
);
267 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
268 log_debug_errno(errno
, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
272 /* And update the end pointer to the new end, too. If this fails, we don't really know what
273 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
275 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0)
276 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
280 (void) munmap(mm
, mm_size
);
285 strncpy(mm
, name
, mm_size
);
287 /* Update the end pointer, continuing regardless of any failure. */
288 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) mm
+ l
+ 1, 0, 0) < 0)
289 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
293 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
294 * it still looks here */
296 if (saved_argc
> 0) {
302 k
= strlen(saved_argv
[0]);
303 strncpy(saved_argv
[0], name
, k
);
308 for (i
= 1; i
< saved_argc
; i
++) {
312 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
319 int is_kernel_thread(pid_t pid
) {
320 _cleanup_free_
char *line
= NULL
;
321 unsigned long long flags
;
327 if (IN_SET(pid
, 0, 1) || pid
== getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
329 if (!pid_is_valid(pid
))
332 p
= procfs_file_alloca(pid
, "stat");
333 r
= read_one_line_file(p
, &line
);
339 /* Skip past the comm field */
340 q
= strrchr(line
, ')');
345 /* Skip 6 fields to reach the flags field */
346 for (i
= 0; i
< 6; i
++) {
347 l
= strspn(q
, WHITESPACE
);
352 l
= strcspn(q
, WHITESPACE
);
358 /* Skip preceding whitespace */
359 l
= strspn(q
, WHITESPACE
);
364 /* Truncate the rest */
365 l
= strcspn(q
, WHITESPACE
);
370 r
= safe_atollu(q
, &flags
);
374 return !!(flags
& PF_KTHREAD
);
377 int get_process_capeff(pid_t pid
, char **capeff
) {
384 p
= procfs_file_alloca(pid
, "status");
386 r
= get_proc_field(p
, "CapEff", WHITESPACE
, capeff
);
393 static int get_process_link_contents(const char *proc_file
, char **name
) {
399 r
= readlink_malloc(proc_file
, name
);
408 int get_process_exe(pid_t pid
, char **name
) {
415 p
= procfs_file_alloca(pid
, "exe");
416 r
= get_process_link_contents(p
, name
);
420 d
= endswith(*name
, " (deleted)");
427 static int get_process_id(pid_t pid
, const char *field
, uid_t
*uid
) {
428 _cleanup_fclose_
FILE *f
= NULL
;
438 p
= procfs_file_alloca(pid
, "status");
439 r
= fopen_unlocked(p
, "re", &f
);
446 _cleanup_free_
char *line
= NULL
;
449 r
= read_line(f
, LONG_LINE_MAX
, &line
);
457 if (startswith(l
, field
)) {
459 l
+= strspn(l
, WHITESPACE
);
461 l
[strcspn(l
, WHITESPACE
)] = 0;
463 return parse_uid(l
, uid
);
470 int get_process_uid(pid_t pid
, uid_t
*uid
) {
472 if (pid
== 0 || pid
== getpid_cached()) {
477 return get_process_id(pid
, "Uid:", uid
);
480 int get_process_gid(pid_t pid
, gid_t
*gid
) {
482 if (pid
== 0 || pid
== getpid_cached()) {
487 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
488 return get_process_id(pid
, "Gid:", gid
);
491 int get_process_cwd(pid_t pid
, char **cwd
) {
496 p
= procfs_file_alloca(pid
, "cwd");
498 return get_process_link_contents(p
, cwd
);
501 int get_process_root(pid_t pid
, char **root
) {
506 p
= procfs_file_alloca(pid
, "root");
508 return get_process_link_contents(p
, root
);
511 #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
513 int get_process_environ(pid_t pid
, char **env
) {
514 _cleanup_fclose_
FILE *f
= NULL
;
515 _cleanup_free_
char *outcome
= NULL
;
516 size_t allocated
= 0, sz
= 0;
523 p
= procfs_file_alloca(pid
, "environ");
525 r
= fopen_unlocked(p
, "re", &f
);
534 if (sz
>= ENVIRONMENT_BLOCK_MAX
)
537 if (!GREEDY_REALLOC(outcome
, allocated
, sz
+ 5))
540 r
= safe_fgetc(f
, &c
);
547 outcome
[sz
++] = '\n';
549 sz
+= cescape_char(c
, outcome
+ sz
);
553 *env
= TAKE_PTR(outcome
);
558 int get_process_ppid(pid_t pid
, pid_t
*_ppid
) {
560 _cleanup_free_
char *line
= NULL
;
567 if (pid
== 0 || pid
== getpid_cached()) {
572 p
= procfs_file_alloca(pid
, "stat");
573 r
= read_one_line_file(p
, &line
);
579 /* Let's skip the pid and comm fields. The latter is enclosed
580 * in () but does not escape any () in its value, so let's
581 * skip over it manually */
583 p
= strrchr(line
, ')');
595 if ((long unsigned) (pid_t
) ppid
!= ppid
)
598 *_ppid
= (pid_t
) ppid
;
603 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
614 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
619 return negative_errno();
628 * < 0 : wait_for_terminate() failed to get the state of the
629 * process, the process was terminated by a signal, or
630 * failed for an unknown reason.
631 * >=0 : The process terminated normally, and its exit code is
634 * That is, success is indicated by a return value of zero, and an
635 * error is indicated by a non-zero value.
637 * A warning is emitted if the process terminates abnormally,
638 * and also if it returns non-zero unless check_exit_code is true.
640 int wait_for_terminate_and_check(const char *name
, pid_t pid
, WaitFlags flags
) {
641 _cleanup_free_
char *buffer
= NULL
;
648 r
= get_process_comm(pid
, &buffer
);
650 log_debug_errno(r
, "Failed to acquire process name of " PID_FMT
", ignoring: %m", pid
);
655 prio
= flags
& WAIT_LOG_ABNORMAL
? LOG_ERR
: LOG_DEBUG
;
657 r
= wait_for_terminate(pid
, &status
);
659 return log_full_errno(prio
, r
, "Failed to wait for %s: %m", strna(name
));
661 if (status
.si_code
== CLD_EXITED
) {
662 if (status
.si_status
!= EXIT_SUCCESS
)
663 log_full(flags
& WAIT_LOG_NON_ZERO_EXIT_STATUS
? LOG_ERR
: LOG_DEBUG
,
664 "%s failed with exit status %i.", strna(name
), status
.si_status
);
666 log_debug("%s succeeded.", name
);
668 return status
.si_status
;
670 } else if (IN_SET(status
.si_code
, CLD_KILLED
, CLD_DUMPED
)) {
672 log_full(prio
, "%s terminated by signal %s.", strna(name
), signal_to_string(status
.si_status
));
676 log_full(prio
, "%s failed due to unknown reason.", strna(name
));
683 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
684 * was terminated by a signal, or failed for an unknown reason.
686 * >=0 : The process terminated normally with no failures.
688 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
689 * states are indicated by error is indicated by a non-zero value.
691 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
692 * to remain entirely race-free.
694 int wait_for_terminate_with_timeout(pid_t pid
, usec_t timeout
) {
699 assert_se(sigemptyset(&mask
) == 0);
700 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
702 /* Drop into a sigtimewait-based timeout. Waiting for the
704 until
= now(CLOCK_MONOTONIC
) + timeout
;
707 siginfo_t status
= {};
710 n
= now(CLOCK_MONOTONIC
);
714 r
= sigtimedwait(&mask
, NULL
, timespec_store(&ts
, until
- n
)) < 0 ? -errno
: 0;
715 /* Assuming we woke due to the child exiting. */
716 if (waitid(P_PID
, pid
, &status
, WEXITED
|WNOHANG
) == 0) {
717 if (status
.si_pid
== pid
) {
718 /* This is the correct child.*/
719 if (status
.si_code
== CLD_EXITED
)
720 return (status
.si_status
== 0) ? 0 : -EPROTO
;
725 /* Not the child, check for errors and proceed appropriately */
729 /* Timed out, child is likely hung. */
732 /* Received a different signal and should retry */
735 /* Return any unexpected errors */
744 void sigkill_wait(pid_t pid
) {
747 if (kill(pid
, SIGKILL
) >= 0)
748 (void) wait_for_terminate(pid
, NULL
);
751 void sigkill_waitp(pid_t
*pid
) {
762 void sigterm_wait(pid_t pid
) {
765 if (kill_and_sigcont(pid
, SIGTERM
) >= 0)
766 (void) wait_for_terminate(pid
, NULL
);
769 int kill_and_sigcont(pid_t pid
, int sig
) {
772 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
774 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
775 * affected by a process being suspended anyway. */
776 if (r
>= 0 && !IN_SET(sig
, SIGCONT
, SIGKILL
))
777 (void) kill(pid
, SIGCONT
);
782 int getenv_for_pid(pid_t pid
, const char *field
, char **ret
) {
783 _cleanup_fclose_
FILE *f
= NULL
;
793 if (pid
== 0 || pid
== getpid_cached()) {
810 if (!pid_is_valid(pid
))
813 path
= procfs_file_alloca(pid
, "environ");
815 r
= fopen_unlocked(path
, "re", &f
);
823 _cleanup_free_
char *line
= NULL
;
825 if (sum
> ENVIRONMENT_BLOCK_MAX
) /* Give up searching eventually */
828 r
= read_nul_string(f
, LONG_LINE_MAX
, &line
);
831 if (r
== 0) /* EOF */
836 if (strneq(line
, field
, l
) && line
[l
] == '=') {
837 value
= strdup(line
+ l
+ 1);
850 int pid_is_my_child(pid_t pid
) {
857 r
= get_process_ppid(pid
, &ppid
);
861 return ppid
== getpid_cached();
864 bool pid_is_unwaited(pid_t pid
) {
865 /* Checks whether a PID is still valid at all, including a zombie */
870 if (pid
<= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
873 if (pid
== getpid_cached())
876 if (kill(pid
, 0) >= 0)
879 return errno
!= ESRCH
;
882 bool pid_is_alive(pid_t pid
) {
885 /* Checks whether a PID is still valid and not a zombie */
890 if (pid
<= 1) /* If we or PID 1 would be a zombie, this code would not be running */
893 if (pid
== getpid_cached())
896 r
= get_process_state(pid
);
897 if (IN_SET(r
, -ESRCH
, 'Z'))
903 int pid_from_same_root_fs(pid_t pid
) {
909 if (pid
== 0 || pid
== getpid_cached())
912 root
= procfs_file_alloca(pid
, "root");
914 return files_same(root
, "/proc/1/root", 0);
917 bool is_main_thread(void) {
918 static thread_local
int cached
= 0;
920 if (_unlikely_(cached
== 0))
921 cached
= getpid_cached() == gettid() ? 1 : -1;
926 _noreturn_
void freeze(void) {
930 /* Make sure nobody waits for us on a socket anymore */
931 (void) close_all_fds(NULL
, 0);
935 /* Let's not freeze right away, but keep reaping zombies. */
940 r
= waitid(P_ALL
, 0, &si
, WEXITED
);
941 if (r
< 0 && errno
!= EINTR
)
945 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
950 bool oom_score_adjust_is_valid(int oa
) {
951 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
954 unsigned long personality_from_string(const char *p
) {
958 return PERSONALITY_INVALID
;
960 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
961 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
962 * the same register size. */
964 architecture
= architecture_from_string(p
);
965 if (architecture
< 0)
966 return PERSONALITY_INVALID
;
968 if (architecture
== native_architecture())
970 #ifdef SECONDARY_ARCHITECTURE
971 if (architecture
== SECONDARY_ARCHITECTURE
)
975 return PERSONALITY_INVALID
;
978 const char* personality_to_string(unsigned long p
) {
979 int architecture
= _ARCHITECTURE_INVALID
;
982 architecture
= native_architecture();
983 #ifdef SECONDARY_ARCHITECTURE
984 else if (p
== PER_LINUX32
)
985 architecture
= SECONDARY_ARCHITECTURE
;
988 if (architecture
< 0)
991 return architecture_to_string(architecture
);
994 int safe_personality(unsigned long p
) {
997 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
998 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
999 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1000 * the return value indicating the same issue, so that we are definitely on the safe side.
1002 * See https://github.com/systemd/systemd/issues/6737 */
1005 ret
= personality(p
);
1016 int opinionated_personality(unsigned long *ret
) {
1019 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1020 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1021 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1023 current
= safe_personality(PERSONALITY_INVALID
);
1027 if (((unsigned long) current
& 0xffff) == PER_LINUX32
)
1035 void valgrind_summary_hack(void) {
1036 #if HAVE_VALGRIND_VALGRIND_H
1037 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
1039 pid
= raw_clone(SIGCHLD
);
1041 log_emergency_errno(errno
, "Failed to fork off valgrind helper: %m");
1045 log_info("Spawned valgrind helper as PID "PID_FMT
".", pid
);
1046 (void) wait_for_terminate(pid
, NULL
);
1052 int pid_compare_func(const pid_t
*a
, const pid_t
*b
) {
1053 /* Suitable for usage in qsort() */
1057 int ioprio_parse_priority(const char *s
, int *ret
) {
1063 r
= safe_atoi(s
, &i
);
1067 if (!ioprio_priority_is_valid(i
))
1074 /* The cached PID, possible values:
1076 * == UNSET [0] → cache not initialized yet
1077 * == BUSY [-1] → some thread is initializing it at the moment
1078 * any other → the cached PID
1081 #define CACHED_PID_UNSET ((pid_t) 0)
1082 #define CACHED_PID_BUSY ((pid_t) -1)
1084 static pid_t cached_pid
= CACHED_PID_UNSET
;
1086 void reset_cached_pid(void) {
1087 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1088 cached_pid
= CACHED_PID_UNSET
;
1091 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1092 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1093 * libpthread, as it is part of glibc anyway. */
1094 extern int __register_atfork(void (*prepare
) (void), void (*parent
) (void), void (*child
) (void), void *dso_handle
);
1095 extern void* __dso_handle _weak_
;
1097 pid_t
getpid_cached(void) {
1098 static bool installed
= false;
1099 pid_t current_value
;
1101 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1102 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1103 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1104 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1106 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1107 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1110 current_value
= __sync_val_compare_and_swap(&cached_pid
, CACHED_PID_UNSET
, CACHED_PID_BUSY
);
1112 switch (current_value
) {
1114 case CACHED_PID_UNSET
: { /* Not initialized yet, then do so now */
1117 new_pid
= raw_getpid();
1120 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1121 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1122 * we'll check for errors only in the most generic fashion possible. */
1124 if (__register_atfork(NULL
, NULL
, reset_cached_pid
, __dso_handle
) != 0) {
1125 /* OOM? Let's try again later */
1126 cached_pid
= CACHED_PID_UNSET
;
1133 cached_pid
= new_pid
;
1137 case CACHED_PID_BUSY
: /* Somebody else is currently initializing */
1138 return raw_getpid();
1140 default: /* Properly initialized */
1141 return current_value
;
1145 int must_be_root(void) {
1150 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Need to be root.");
1155 const int except_fds
[],
1156 size_t n_except_fds
,
1160 pid_t original_pid
, pid
;
1161 sigset_t saved_ss
, ss
;
1162 bool block_signals
= false;
1165 /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1166 * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1168 prio
= flags
& FORK_LOG
? LOG_ERR
: LOG_DEBUG
;
1170 original_pid
= getpid_cached();
1172 if (flags
& (FORK_RESET_SIGNALS
|FORK_DEATHSIG
)) {
1173 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1174 * be sure that SIGTERMs are not lost we might send to the child. */
1176 assert_se(sigfillset(&ss
) >= 0);
1177 block_signals
= true;
1179 } else if (flags
& FORK_WAIT
) {
1180 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1182 assert_se(sigemptyset(&ss
) >= 0);
1183 assert_se(sigaddset(&ss
, SIGCHLD
) >= 0);
1184 block_signals
= true;
1188 if (sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) < 0)
1189 return log_full_errno(prio
, errno
, "Failed to set signal mask: %m");
1191 if (flags
& FORK_NEW_MOUNTNS
)
1192 pid
= raw_clone(SIGCHLD
|CLONE_NEWNS
);
1198 if (block_signals
) /* undo what we did above */
1199 (void) sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
);
1201 return log_full_errno(prio
, r
, "Failed to fork: %m");
1204 /* We are in the parent process */
1206 log_debug("Successfully forked off '%s' as PID " PID_FMT
".", strna(name
), pid
);
1208 if (flags
& FORK_WAIT
) {
1209 r
= wait_for_terminate_and_check(name
, pid
, (flags
& FORK_LOG
? WAIT_LOG
: 0));
1212 if (r
!= EXIT_SUCCESS
) /* exit status > 0 should be treated as failure, too */
1216 if (block_signals
) /* undo what we did above */
1217 (void) sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
);
1225 /* We are in the child process */
1227 if (flags
& FORK_REOPEN_LOG
) {
1228 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1230 log_set_open_when_needed(true);
1234 r
= rename_process(name
);
1236 log_full_errno(flags
& FORK_LOG
? LOG_WARNING
: LOG_DEBUG
,
1237 r
, "Failed to rename process, ignoring: %m");
1240 if (flags
& FORK_DEATHSIG
)
1241 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0) {
1242 log_full_errno(prio
, errno
, "Failed to set death signal: %m");
1243 _exit(EXIT_FAILURE
);
1246 if (flags
& FORK_RESET_SIGNALS
) {
1247 r
= reset_all_signal_handlers();
1249 log_full_errno(prio
, r
, "Failed to reset signal handlers: %m");
1250 _exit(EXIT_FAILURE
);
1253 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1254 r
= reset_signal_mask();
1256 log_full_errno(prio
, r
, "Failed to reset signal mask: %m");
1257 _exit(EXIT_FAILURE
);
1259 } else if (block_signals
) { /* undo what we did above */
1260 if (sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) < 0) {
1261 log_full_errno(prio
, errno
, "Failed to restore signal mask: %m");
1262 _exit(EXIT_FAILURE
);
1266 if (flags
& FORK_DEATHSIG
) {
1268 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1269 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1273 /* Parent is in a differn't PID namespace. */;
1274 else if (ppid
!= original_pid
) {
1275 log_debug("Parent died early, raising SIGTERM.");
1276 (void) raise(SIGTERM
);
1277 _exit(EXIT_FAILURE
);
1281 if (FLAGS_SET(flags
, FORK_NEW_MOUNTNS
| FORK_MOUNTNS_SLAVE
)) {
1283 /* Optionally, make sure we never propagate mounts to the host. */
1285 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
) < 0) {
1286 log_full_errno(prio
, errno
, "Failed to remount root directory as MS_SLAVE: %m");
1287 _exit(EXIT_FAILURE
);
1291 if (flags
& FORK_CLOSE_ALL_FDS
) {
1292 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1295 r
= close_all_fds(except_fds
, n_except_fds
);
1297 log_full_errno(prio
, r
, "Failed to close all file descriptors: %m");
1298 _exit(EXIT_FAILURE
);
1302 /* When we were asked to reopen the logs, do so again now */
1303 if (flags
& FORK_REOPEN_LOG
) {
1305 log_set_open_when_needed(false);
1308 if (flags
& FORK_NULL_STDIO
) {
1309 r
= make_null_stdio();
1311 log_full_errno(prio
, r
, "Failed to connect stdin/stdout to /dev/null: %m");
1312 _exit(EXIT_FAILURE
);
1316 if (flags
& FORK_RLIMIT_NOFILE_SAFE
) {
1317 r
= rlimit_nofile_safe();
1319 log_full_errno(prio
, r
, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1320 _exit(EXIT_FAILURE
);
1325 *ret_pid
= getpid_cached();
1331 const char *outer_name
,
1332 const char *inner_name
,
1333 const int except_fds
[],
1334 size_t n_except_fds
,
1345 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1346 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1347 * /proc/self/fd works correctly. */
1349 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
);
1357 r
= namespace_enter(pidns_fd
, mntns_fd
, netns_fd
, userns_fd
, root_fd
);
1359 log_full_errno(FLAGS_SET(flags
, FORK_LOG
) ? LOG_ERR
: LOG_DEBUG
, r
, "Failed to join namespace: %m");
1360 _exit(EXIT_FAILURE
);
1363 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1364 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
);
1366 _exit(EXIT_FAILURE
);
1374 r
= wait_for_terminate_and_check(inner_name
, pid
, FLAGS_SET(flags
, FORK_LOG
) ? WAIT_LOG
: 0);
1376 _exit(EXIT_FAILURE
);
1384 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
1385 bool stdout_is_tty
, stderr_is_tty
;
1393 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1395 r
= safe_fork_full(name
, except
, n_except
, FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_CLOSE_ALL_FDS
, ret_pid
);
1403 stdout_is_tty
= isatty(STDOUT_FILENO
);
1404 stderr_is_tty
= isatty(STDERR_FILENO
);
1406 if (!stdout_is_tty
|| !stderr_is_tty
) {
1409 /* Detach from stdout/stderr. and reopen
1410 * /dev/tty for them. This is important to
1411 * ensure that when systemctl is started via
1412 * popen() or a similar call that expects to
1413 * read EOF we actually do generate EOF and
1414 * not delay this indefinitely by because we
1415 * keep an unused copy of stdin around. */
1416 fd
= open("/dev/tty", O_WRONLY
);
1418 log_error_errno(errno
, "Failed to open /dev/tty: %m");
1419 _exit(EXIT_FAILURE
);
1422 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
1423 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
1424 _exit(EXIT_FAILURE
);
1427 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
1428 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
1429 _exit(EXIT_FAILURE
);
1432 safe_close_above_stdio(fd
);
1435 (void) rlimit_nofile_safe();
1437 /* Count arguments */
1439 for (n
= 0; va_arg(ap
, char*); n
++)
1444 l
= newa(char*, n
+ 1);
1446 /* Fill in arguments */
1448 for (i
= 0; i
<= n
; i
++)
1449 l
[i
] = va_arg(ap
, char*);
1453 _exit(EXIT_FAILURE
);
1456 int set_oom_score_adjust(int value
) {
1457 char t
[DECIMAL_STR_MAX(int)];
1459 sprintf(t
, "%i", value
);
1461 return write_string_file("/proc/self/oom_score_adj", t
,
1462 WRITE_STRING_FILE_VERIFY_ON_FAILURE
|WRITE_STRING_FILE_DISABLE_BUFFER
);
1465 int cpus_in_affinity_mask(void) {
1476 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), c
) >= 0) {
1479 k
= CPU_COUNT_S(CPU_ALLOC_SIZE(n
), c
);
1499 static const char *const ioprio_class_table
[] = {
1500 [IOPRIO_CLASS_NONE
] = "none",
1501 [IOPRIO_CLASS_RT
] = "realtime",
1502 [IOPRIO_CLASS_BE
] = "best-effort",
1503 [IOPRIO_CLASS_IDLE
] = "idle"
1506 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, IOPRIO_N_CLASSES
);
1508 static const char *const sigchld_code_table
[] = {
1509 [CLD_EXITED
] = "exited",
1510 [CLD_KILLED
] = "killed",
1511 [CLD_DUMPED
] = "dumped",
1512 [CLD_TRAPPED
] = "trapped",
1513 [CLD_STOPPED
] = "stopped",
1514 [CLD_CONTINUED
] = "continued",
1517 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1519 static const char* const sched_policy_table
[] = {
1520 [SCHED_OTHER
] = "other",
1521 [SCHED_BATCH
] = "batch",
1522 [SCHED_IDLE
] = "idle",
1523 [SCHED_FIFO
] = "fifo",
1527 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);