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 /* 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.
52 #define COMM_MAX_LEN 128
54 static int get_process_state(pid_t pid
) {
58 _cleanup_free_
char *line
= NULL
;
62 p
= procfs_file_alloca(pid
, "stat");
64 r
= read_one_line_file(p
, &line
);
70 p
= strrchr(line
, ')');
76 if (sscanf(p
, " %c", &state
) != 1)
79 return (unsigned char) state
;
82 int get_process_comm(pid_t pid
, char **ret
) {
83 _cleanup_free_
char *escaped
= NULL
, *comm
= NULL
;
90 escaped
= new(char, COMM_MAX_LEN
);
94 p
= procfs_file_alloca(pid
, "comm");
96 r
= read_one_line_file(p
, &comm
);
102 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
103 cellescape(escaped
, COMM_MAX_LEN
, comm
);
105 *ret
= TAKE_PTR(escaped
);
109 int get_process_cmdline(pid_t pid
, size_t max_columns
, ProcessCmdlineFlags flags
, char **line
) {
110 _cleanup_fclose_
FILE *f
= NULL
;
111 _cleanup_free_
char *t
= NULL
, *ans
= NULL
;
116 /* This is supposed to be a safety guard against runaway command lines. */
117 size_t max_length
= sc_arg_max();
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
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. */
132 p
= procfs_file_alloca(pid
, "cmdline");
133 r
= fopen_unlocked(p
, "re", &f
);
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 if ((size_t) 4 * max_columns
+ 1 < max_columns
)
142 max_length
= MIN(max_length
, (size_t) 4 * max_columns
+ 1);
144 t
= new(char, max_length
);
148 k
= fread(t
, 1, max_length
, f
);
150 /* Arguments are separated by NULs. Let's replace those with spaces. */
151 for (size_t i
= 0; i
< k
- 1; i
++)
155 t
[k
] = '\0'; /* Normally, t[k] is already NUL, so this is just a guard in case of short read */
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. */
163 if (!(flags
& PROCESS_CMDLINE_COMM_FALLBACK
))
166 /* Kernel threads have no argv[] */
167 _cleanup_free_
char *t2
= NULL
;
169 r
= get_process_comm(pid
, &t2
);
174 t
= strjoin("[", t2
, "]");
179 delete_trailing_chars(t
, WHITESPACE
);
181 ans
= utf8_escape_non_printable_full(t
, max_columns
);
185 (void) str_realloc(&ans
);
186 *line
= TAKE_PTR(ans
);
190 int rename_process(const char name
[]) {
191 static size_t mm_size
= 0;
192 static char *mm
= NULL
;
193 bool truncated
= false;
196 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
197 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
198 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
199 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
202 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
205 return -EINVAL
; /* let's not confuse users unnecessarily with an empty name */
207 if (!is_main_thread())
208 return -EPERM
; /* Let's not allow setting the process name from other threads than the main one, as we
209 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
210 * process name that isn't correct on any other threads */
214 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
215 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
216 if (prctl(PR_SET_NAME
, name
) < 0)
217 log_debug_errno(errno
, "PR_SET_NAME failed: %m");
218 if (l
>= TASK_COMM_LEN
) /* Linux userspace process names can be 15 chars at max */
221 /* Second step, change glibc's ID of the process name. */
222 if (program_invocation_name
) {
225 k
= strlen(program_invocation_name
);
226 strncpy(program_invocation_name
, name
, k
);
231 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
232 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
233 * the end. This is the best option for changing /proc/self/cmdline. */
235 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
236 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
237 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
238 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
241 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
242 else if (mm_size
< l
+1) {
246 nn_size
= PAGE_ALIGN(l
+1);
247 nn
= mmap(NULL
, nn_size
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
248 if (nn
== MAP_FAILED
) {
249 log_debug_errno(errno
, "mmap() failed: %m");
253 strncpy(nn
, name
, nn_size
);
255 /* Now, let's tell the kernel about this new memory */
256 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
257 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
258 * below the desired start address, in which case the kernel may have kicked this back due
259 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
260 * action). The proper solution would be to have a prctl() API that could set both start+end
261 * simultaneously, or at least let us query the existing address to anticipate this condition
262 * and respond accordingly. For now, we can only guess at the cause of this failure and try
263 * a workaround--which will briefly expand the arg space to something potentially huge before
264 * resizing it to what we want. */
265 log_debug_errno(errno
, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
267 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0) {
268 log_debug_errno(errno
, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
269 (void) munmap(nn
, nn_size
);
273 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
274 log_debug_errno(errno
, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
278 /* And update the end pointer to the new end, too. If this fails, we don't really know what
279 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
281 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0)
282 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
286 (void) munmap(mm
, mm_size
);
291 strncpy(mm
, name
, mm_size
);
293 /* Update the end pointer, continuing regardless of any failure. */
294 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) mm
+ l
+ 1, 0, 0) < 0)
295 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
299 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
300 * it still looks here */
302 if (saved_argc
> 0) {
308 k
= strlen(saved_argv
[0]);
309 strncpy(saved_argv
[0], name
, k
);
314 for (i
= 1; i
< saved_argc
; i
++) {
318 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
325 int is_kernel_thread(pid_t pid
) {
326 _cleanup_free_
char *line
= NULL
;
327 unsigned long long flags
;
333 if (IN_SET(pid
, 0, 1) || pid
== getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
335 if (!pid_is_valid(pid
))
338 p
= procfs_file_alloca(pid
, "stat");
339 r
= read_one_line_file(p
, &line
);
345 /* Skip past the comm field */
346 q
= strrchr(line
, ')');
351 /* Skip 6 fields to reach the flags field */
352 for (i
= 0; i
< 6; i
++) {
353 l
= strspn(q
, WHITESPACE
);
358 l
= strcspn(q
, WHITESPACE
);
364 /* Skip preceding whitespace */
365 l
= strspn(q
, WHITESPACE
);
370 /* Truncate the rest */
371 l
= strcspn(q
, WHITESPACE
);
376 r
= safe_atollu(q
, &flags
);
380 return !!(flags
& PF_KTHREAD
);
383 int get_process_capeff(pid_t pid
, char **capeff
) {
390 p
= procfs_file_alloca(pid
, "status");
392 r
= get_proc_field(p
, "CapEff", WHITESPACE
, capeff
);
399 static int get_process_link_contents(const char *proc_file
, char **name
) {
405 r
= readlink_malloc(proc_file
, name
);
414 int get_process_exe(pid_t pid
, char **name
) {
421 p
= procfs_file_alloca(pid
, "exe");
422 r
= get_process_link_contents(p
, name
);
426 d
= endswith(*name
, " (deleted)");
433 static int get_process_id(pid_t pid
, const char *field
, uid_t
*uid
) {
434 _cleanup_fclose_
FILE *f
= NULL
;
444 p
= procfs_file_alloca(pid
, "status");
445 r
= fopen_unlocked(p
, "re", &f
);
452 _cleanup_free_
char *line
= NULL
;
455 r
= read_line(f
, LONG_LINE_MAX
, &line
);
463 if (startswith(l
, field
)) {
465 l
+= strspn(l
, WHITESPACE
);
467 l
[strcspn(l
, WHITESPACE
)] = 0;
469 return parse_uid(l
, uid
);
476 int get_process_uid(pid_t pid
, uid_t
*uid
) {
478 if (pid
== 0 || pid
== getpid_cached()) {
483 return get_process_id(pid
, "Uid:", uid
);
486 int get_process_gid(pid_t pid
, gid_t
*gid
) {
488 if (pid
== 0 || pid
== getpid_cached()) {
493 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
494 return get_process_id(pid
, "Gid:", gid
);
497 int get_process_cwd(pid_t pid
, char **cwd
) {
502 p
= procfs_file_alloca(pid
, "cwd");
504 return get_process_link_contents(p
, cwd
);
507 int get_process_root(pid_t pid
, char **root
) {
512 p
= procfs_file_alloca(pid
, "root");
514 return get_process_link_contents(p
, root
);
517 #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
519 int get_process_environ(pid_t pid
, char **env
) {
520 _cleanup_fclose_
FILE *f
= NULL
;
521 _cleanup_free_
char *outcome
= NULL
;
522 size_t allocated
= 0, sz
= 0;
529 p
= procfs_file_alloca(pid
, "environ");
531 r
= fopen_unlocked(p
, "re", &f
);
540 if (sz
>= ENVIRONMENT_BLOCK_MAX
)
543 if (!GREEDY_REALLOC(outcome
, allocated
, sz
+ 5))
546 r
= safe_fgetc(f
, &c
);
553 outcome
[sz
++] = '\n';
555 sz
+= cescape_char(c
, outcome
+ sz
);
559 *env
= TAKE_PTR(outcome
);
564 int get_process_ppid(pid_t pid
, pid_t
*_ppid
) {
566 _cleanup_free_
char *line
= NULL
;
573 if (pid
== 0 || pid
== getpid_cached()) {
578 p
= procfs_file_alloca(pid
, "stat");
579 r
= read_one_line_file(p
, &line
);
585 /* Let's skip the pid and comm fields. The latter is enclosed
586 * in () but does not escape any () in its value, so let's
587 * skip over it manually */
589 p
= strrchr(line
, ')');
601 if ((long unsigned) (pid_t
) ppid
!= ppid
)
604 *_ppid
= (pid_t
) ppid
;
609 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
620 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
625 return negative_errno();
634 * < 0 : wait_for_terminate() failed to get the state of the
635 * process, the process was terminated by a signal, or
636 * failed for an unknown reason.
637 * >=0 : The process terminated normally, and its exit code is
640 * That is, success is indicated by a return value of zero, and an
641 * error is indicated by a non-zero value.
643 * A warning is emitted if the process terminates abnormally,
644 * and also if it returns non-zero unless check_exit_code is true.
646 int wait_for_terminate_and_check(const char *name
, pid_t pid
, WaitFlags flags
) {
647 _cleanup_free_
char *buffer
= NULL
;
654 r
= get_process_comm(pid
, &buffer
);
656 log_debug_errno(r
, "Failed to acquire process name of " PID_FMT
", ignoring: %m", pid
);
661 prio
= flags
& WAIT_LOG_ABNORMAL
? LOG_ERR
: LOG_DEBUG
;
663 r
= wait_for_terminate(pid
, &status
);
665 return log_full_errno(prio
, r
, "Failed to wait for %s: %m", strna(name
));
667 if (status
.si_code
== CLD_EXITED
) {
668 if (status
.si_status
!= EXIT_SUCCESS
)
669 log_full(flags
& WAIT_LOG_NON_ZERO_EXIT_STATUS
? LOG_ERR
: LOG_DEBUG
,
670 "%s failed with exit status %i.", strna(name
), status
.si_status
);
672 log_debug("%s succeeded.", name
);
674 return status
.si_status
;
676 } else if (IN_SET(status
.si_code
, CLD_KILLED
, CLD_DUMPED
)) {
678 log_full(prio
, "%s terminated by signal %s.", strna(name
), signal_to_string(status
.si_status
));
682 log_full(prio
, "%s failed due to unknown reason.", strna(name
));
689 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
690 * was terminated by a signal, or failed for an unknown reason.
692 * >=0 : The process terminated normally with no failures.
694 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
695 * states are indicated by error is indicated by a non-zero value.
697 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
698 * to remain entirely race-free.
700 int wait_for_terminate_with_timeout(pid_t pid
, usec_t timeout
) {
705 assert_se(sigemptyset(&mask
) == 0);
706 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
708 /* Drop into a sigtimewait-based timeout. Waiting for the
710 until
= now(CLOCK_MONOTONIC
) + timeout
;
713 siginfo_t status
= {};
716 n
= now(CLOCK_MONOTONIC
);
720 r
= sigtimedwait(&mask
, NULL
, timespec_store(&ts
, until
- n
)) < 0 ? -errno
: 0;
721 /* Assuming we woke due to the child exiting. */
722 if (waitid(P_PID
, pid
, &status
, WEXITED
|WNOHANG
) == 0) {
723 if (status
.si_pid
== pid
) {
724 /* This is the correct child.*/
725 if (status
.si_code
== CLD_EXITED
)
726 return (status
.si_status
== 0) ? 0 : -EPROTO
;
731 /* Not the child, check for errors and proceed appropriately */
735 /* Timed out, child is likely hung. */
738 /* Received a different signal and should retry */
741 /* Return any unexpected errors */
750 void sigkill_wait(pid_t pid
) {
753 if (kill(pid
, SIGKILL
) >= 0)
754 (void) wait_for_terminate(pid
, NULL
);
757 void sigkill_waitp(pid_t
*pid
) {
768 void sigterm_wait(pid_t pid
) {
771 if (kill_and_sigcont(pid
, SIGTERM
) >= 0)
772 (void) wait_for_terminate(pid
, NULL
);
775 int kill_and_sigcont(pid_t pid
, int sig
) {
778 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
780 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
781 * affected by a process being suspended anyway. */
782 if (r
>= 0 && !IN_SET(sig
, SIGCONT
, SIGKILL
))
783 (void) kill(pid
, SIGCONT
);
788 int getenv_for_pid(pid_t pid
, const char *field
, char **ret
) {
789 _cleanup_fclose_
FILE *f
= NULL
;
799 if (pid
== 0 || pid
== getpid_cached()) {
816 if (!pid_is_valid(pid
))
819 path
= procfs_file_alloca(pid
, "environ");
821 r
= fopen_unlocked(path
, "re", &f
);
829 _cleanup_free_
char *line
= NULL
;
831 if (sum
> ENVIRONMENT_BLOCK_MAX
) /* Give up searching eventually */
834 r
= read_nul_string(f
, LONG_LINE_MAX
, &line
);
837 if (r
== 0) /* EOF */
842 if (strneq(line
, field
, l
) && line
[l
] == '=') {
843 value
= strdup(line
+ l
+ 1);
856 int pid_is_my_child(pid_t pid
) {
863 r
= get_process_ppid(pid
, &ppid
);
867 return ppid
== getpid_cached();
870 bool pid_is_unwaited(pid_t pid
) {
871 /* Checks whether a PID is still valid at all, including a zombie */
876 if (pid
<= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
879 if (pid
== getpid_cached())
882 if (kill(pid
, 0) >= 0)
885 return errno
!= ESRCH
;
888 bool pid_is_alive(pid_t pid
) {
891 /* Checks whether a PID is still valid and not a zombie */
896 if (pid
<= 1) /* If we or PID 1 would be a zombie, this code would not be running */
899 if (pid
== getpid_cached())
902 r
= get_process_state(pid
);
903 if (IN_SET(r
, -ESRCH
, 'Z'))
909 int pid_from_same_root_fs(pid_t pid
) {
915 if (pid
== 0 || pid
== getpid_cached())
918 root
= procfs_file_alloca(pid
, "root");
920 return files_same(root
, "/proc/1/root", 0);
923 bool is_main_thread(void) {
924 static thread_local
int cached
= 0;
926 if (_unlikely_(cached
== 0))
927 cached
= getpid_cached() == gettid() ? 1 : -1;
932 _noreturn_
void freeze(void) {
936 /* Make sure nobody waits for us on a socket anymore */
937 (void) close_all_fds(NULL
, 0);
941 /* Let's not freeze right away, but keep reaping zombies. */
946 r
= waitid(P_ALL
, 0, &si
, WEXITED
);
947 if (r
< 0 && errno
!= EINTR
)
951 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
956 bool oom_score_adjust_is_valid(int oa
) {
957 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
960 unsigned long personality_from_string(const char *p
) {
964 return PERSONALITY_INVALID
;
966 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
967 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
968 * the same register size. */
970 architecture
= architecture_from_string(p
);
971 if (architecture
< 0)
972 return PERSONALITY_INVALID
;
974 if (architecture
== native_architecture())
976 #ifdef SECONDARY_ARCHITECTURE
977 if (architecture
== SECONDARY_ARCHITECTURE
)
981 return PERSONALITY_INVALID
;
984 const char* personality_to_string(unsigned long p
) {
985 int architecture
= _ARCHITECTURE_INVALID
;
988 architecture
= native_architecture();
989 #ifdef SECONDARY_ARCHITECTURE
990 else if (p
== PER_LINUX32
)
991 architecture
= SECONDARY_ARCHITECTURE
;
994 if (architecture
< 0)
997 return architecture_to_string(architecture
);
1000 int safe_personality(unsigned long p
) {
1003 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1004 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1005 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1006 * the return value indicating the same issue, so that we are definitely on the safe side.
1008 * See https://github.com/systemd/systemd/issues/6737 */
1011 ret
= personality(p
);
1022 int opinionated_personality(unsigned long *ret
) {
1025 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1026 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1027 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1029 current
= safe_personality(PERSONALITY_INVALID
);
1033 if (((unsigned long) current
& 0xffff) == PER_LINUX32
)
1041 void valgrind_summary_hack(void) {
1042 #if HAVE_VALGRIND_VALGRIND_H
1043 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
1045 pid
= raw_clone(SIGCHLD
);
1047 log_emergency_errno(errno
, "Failed to fork off valgrind helper: %m");
1051 log_info("Spawned valgrind helper as PID "PID_FMT
".", pid
);
1052 (void) wait_for_terminate(pid
, NULL
);
1058 int pid_compare_func(const pid_t
*a
, const pid_t
*b
) {
1059 /* Suitable for usage in qsort() */
1063 int ioprio_parse_priority(const char *s
, int *ret
) {
1069 r
= safe_atoi(s
, &i
);
1073 if (!ioprio_priority_is_valid(i
))
1080 /* The cached PID, possible values:
1082 * == UNSET [0] → cache not initialized yet
1083 * == BUSY [-1] → some thread is initializing it at the moment
1084 * any other → the cached PID
1087 #define CACHED_PID_UNSET ((pid_t) 0)
1088 #define CACHED_PID_BUSY ((pid_t) -1)
1090 static pid_t cached_pid
= CACHED_PID_UNSET
;
1092 void reset_cached_pid(void) {
1093 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1094 cached_pid
= CACHED_PID_UNSET
;
1097 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1098 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1099 * libpthread, as it is part of glibc anyway. */
1100 extern int __register_atfork(void (*prepare
) (void), void (*parent
) (void), void (*child
) (void), void *dso_handle
);
1101 extern void* __dso_handle _weak_
;
1103 pid_t
getpid_cached(void) {
1104 static bool installed
= false;
1105 pid_t current_value
;
1107 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1108 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1109 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1110 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1112 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1113 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1116 current_value
= __sync_val_compare_and_swap(&cached_pid
, CACHED_PID_UNSET
, CACHED_PID_BUSY
);
1118 switch (current_value
) {
1120 case CACHED_PID_UNSET
: { /* Not initialized yet, then do so now */
1123 new_pid
= raw_getpid();
1126 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1127 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1128 * we'll check for errors only in the most generic fashion possible. */
1130 if (__register_atfork(NULL
, NULL
, reset_cached_pid
, __dso_handle
) != 0) {
1131 /* OOM? Let's try again later */
1132 cached_pid
= CACHED_PID_UNSET
;
1139 cached_pid
= new_pid
;
1143 case CACHED_PID_BUSY
: /* Somebody else is currently initializing */
1144 return raw_getpid();
1146 default: /* Properly initialized */
1147 return current_value
;
1151 int must_be_root(void) {
1156 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Need to be root.");
1161 const int except_fds
[],
1162 size_t n_except_fds
,
1166 pid_t original_pid
, pid
;
1167 sigset_t saved_ss
, ss
;
1168 bool block_signals
= false;
1171 /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1172 * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1174 prio
= flags
& FORK_LOG
? LOG_ERR
: LOG_DEBUG
;
1176 original_pid
= getpid_cached();
1178 if (flags
& (FORK_RESET_SIGNALS
|FORK_DEATHSIG
)) {
1179 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1180 * be sure that SIGTERMs are not lost we might send to the child. */
1182 assert_se(sigfillset(&ss
) >= 0);
1183 block_signals
= true;
1185 } else if (flags
& FORK_WAIT
) {
1186 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1188 assert_se(sigemptyset(&ss
) >= 0);
1189 assert_se(sigaddset(&ss
, SIGCHLD
) >= 0);
1190 block_signals
= true;
1194 if (sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) < 0)
1195 return log_full_errno(prio
, errno
, "Failed to set signal mask: %m");
1197 if (flags
& FORK_NEW_MOUNTNS
)
1198 pid
= raw_clone(SIGCHLD
|CLONE_NEWNS
);
1204 if (block_signals
) /* undo what we did above */
1205 (void) sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
);
1207 return log_full_errno(prio
, r
, "Failed to fork: %m");
1210 /* We are in the parent process */
1212 log_debug("Successfully forked off '%s' as PID " PID_FMT
".", strna(name
), pid
);
1214 if (flags
& FORK_WAIT
) {
1215 r
= wait_for_terminate_and_check(name
, pid
, (flags
& FORK_LOG
? WAIT_LOG
: 0));
1218 if (r
!= EXIT_SUCCESS
) /* exit status > 0 should be treated as failure, too */
1222 if (block_signals
) /* undo what we did above */
1223 (void) sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
);
1231 /* We are in the child process */
1233 if (flags
& FORK_REOPEN_LOG
) {
1234 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1236 log_set_open_when_needed(true);
1240 r
= rename_process(name
);
1242 log_full_errno(flags
& FORK_LOG
? LOG_WARNING
: LOG_DEBUG
,
1243 r
, "Failed to rename process, ignoring: %m");
1246 if (flags
& FORK_DEATHSIG
)
1247 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0) {
1248 log_full_errno(prio
, errno
, "Failed to set death signal: %m");
1249 _exit(EXIT_FAILURE
);
1252 if (flags
& FORK_RESET_SIGNALS
) {
1253 r
= reset_all_signal_handlers();
1255 log_full_errno(prio
, r
, "Failed to reset signal handlers: %m");
1256 _exit(EXIT_FAILURE
);
1259 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1260 r
= reset_signal_mask();
1262 log_full_errno(prio
, r
, "Failed to reset signal mask: %m");
1263 _exit(EXIT_FAILURE
);
1265 } else if (block_signals
) { /* undo what we did above */
1266 if (sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) < 0) {
1267 log_full_errno(prio
, errno
, "Failed to restore signal mask: %m");
1268 _exit(EXIT_FAILURE
);
1272 if (flags
& FORK_DEATHSIG
) {
1274 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1275 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1279 /* Parent is in a differn't PID namespace. */;
1280 else if (ppid
!= original_pid
) {
1281 log_debug("Parent died early, raising SIGTERM.");
1282 (void) raise(SIGTERM
);
1283 _exit(EXIT_FAILURE
);
1287 if (FLAGS_SET(flags
, FORK_NEW_MOUNTNS
| FORK_MOUNTNS_SLAVE
)) {
1289 /* Optionally, make sure we never propagate mounts to the host. */
1291 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
) < 0) {
1292 log_full_errno(prio
, errno
, "Failed to remount root directory as MS_SLAVE: %m");
1293 _exit(EXIT_FAILURE
);
1297 if (flags
& FORK_CLOSE_ALL_FDS
) {
1298 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1301 r
= close_all_fds(except_fds
, n_except_fds
);
1303 log_full_errno(prio
, r
, "Failed to close all file descriptors: %m");
1304 _exit(EXIT_FAILURE
);
1308 /* When we were asked to reopen the logs, do so again now */
1309 if (flags
& FORK_REOPEN_LOG
) {
1311 log_set_open_when_needed(false);
1314 if (flags
& FORK_NULL_STDIO
) {
1315 r
= make_null_stdio();
1317 log_full_errno(prio
, r
, "Failed to connect stdin/stdout to /dev/null: %m");
1318 _exit(EXIT_FAILURE
);
1322 if (flags
& FORK_RLIMIT_NOFILE_SAFE
) {
1323 r
= rlimit_nofile_safe();
1325 log_full_errno(prio
, r
, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1326 _exit(EXIT_FAILURE
);
1331 *ret_pid
= getpid_cached();
1337 const char *outer_name
,
1338 const char *inner_name
,
1339 const int except_fds
[],
1340 size_t n_except_fds
,
1351 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1352 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1353 * /proc/self/fd works correctly. */
1355 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
);
1363 r
= namespace_enter(pidns_fd
, mntns_fd
, netns_fd
, userns_fd
, root_fd
);
1365 log_full_errno(FLAGS_SET(flags
, FORK_LOG
) ? LOG_ERR
: LOG_DEBUG
, r
, "Failed to join namespace: %m");
1366 _exit(EXIT_FAILURE
);
1369 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1370 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
);
1372 _exit(EXIT_FAILURE
);
1380 r
= wait_for_terminate_and_check(inner_name
, pid
, FLAGS_SET(flags
, FORK_LOG
) ? WAIT_LOG
: 0);
1382 _exit(EXIT_FAILURE
);
1390 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
1391 bool stdout_is_tty
, stderr_is_tty
;
1399 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1401 r
= safe_fork_full(name
, except
, n_except
, FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_CLOSE_ALL_FDS
, ret_pid
);
1409 stdout_is_tty
= isatty(STDOUT_FILENO
);
1410 stderr_is_tty
= isatty(STDERR_FILENO
);
1412 if (!stdout_is_tty
|| !stderr_is_tty
) {
1415 /* Detach from stdout/stderr. and reopen
1416 * /dev/tty for them. This is important to
1417 * ensure that when systemctl is started via
1418 * popen() or a similar call that expects to
1419 * read EOF we actually do generate EOF and
1420 * not delay this indefinitely by because we
1421 * keep an unused copy of stdin around. */
1422 fd
= open("/dev/tty", O_WRONLY
);
1424 log_error_errno(errno
, "Failed to open /dev/tty: %m");
1425 _exit(EXIT_FAILURE
);
1428 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
1429 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
1430 _exit(EXIT_FAILURE
);
1433 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
1434 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
1435 _exit(EXIT_FAILURE
);
1438 safe_close_above_stdio(fd
);
1441 (void) rlimit_nofile_safe();
1443 /* Count arguments */
1445 for (n
= 0; va_arg(ap
, char*); n
++)
1450 l
= newa(char*, n
+ 1);
1452 /* Fill in arguments */
1454 for (i
= 0; i
<= n
; i
++)
1455 l
[i
] = va_arg(ap
, char*);
1459 _exit(EXIT_FAILURE
);
1462 int set_oom_score_adjust(int value
) {
1463 char t
[DECIMAL_STR_MAX(int)];
1465 sprintf(t
, "%i", value
);
1467 return write_string_file("/proc/self/oom_score_adj", t
,
1468 WRITE_STRING_FILE_VERIFY_ON_FAILURE
|WRITE_STRING_FILE_DISABLE_BUFFER
);
1471 int cpus_in_affinity_mask(void) {
1482 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), c
) >= 0) {
1485 k
= CPU_COUNT_S(CPU_ALLOC_SIZE(n
), c
);
1505 static const char *const ioprio_class_table
[] = {
1506 [IOPRIO_CLASS_NONE
] = "none",
1507 [IOPRIO_CLASS_RT
] = "realtime",
1508 [IOPRIO_CLASS_BE
] = "best-effort",
1509 [IOPRIO_CLASS_IDLE
] = "idle"
1512 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, IOPRIO_N_CLASSES
);
1514 static const char *const sigchld_code_table
[] = {
1515 [CLD_EXITED
] = "exited",
1516 [CLD_KILLED
] = "killed",
1517 [CLD_DUMPED
] = "dumped",
1518 [CLD_TRAPPED
] = "trapped",
1519 [CLD_STOPPED
] = "stopped",
1520 [CLD_CONTINUED
] = "continued",
1523 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1525 static const char* const sched_policy_table
[] = {
1526 [SCHED_OTHER
] = "other",
1527 [SCHED_BATCH
] = "batch",
1528 [SCHED_IDLE
] = "idle",
1529 [SCHED_FIFO
] = "fifo",
1533 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);