1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
12 #include <sys/mount.h>
13 #include <sys/personality.h>
14 #include <sys/prctl.h>
15 #include <sys/types.h>
19 #if HAVE_VALGRIND_VALGRIND_H
20 #include <valgrind/valgrind.h>
23 #include "alloc-util.h"
24 #include "architecture.h"
26 #include "errno-util.h"
31 #include "locale-util.h"
34 #include "memory-util.h"
35 #include "missing_sched.h"
36 #include "missing_syscall.h"
37 #include "namespace-util.h"
38 #include "path-util.h"
39 #include "process-util.h"
40 #include "raw-clone.h"
41 #include "rlimit-util.h"
42 #include "signal-util.h"
43 #include "stat-util.h"
44 #include "stdio-util.h"
45 #include "string-table.h"
46 #include "string-util.h"
47 #include "terminal-util.h"
48 #include "user-util.h"
51 /* The kernel limits userspace processes to TASK_COMM_LEN (16 bytes), but allows higher values for its own
52 * workers, e.g. "kworker/u9:3-kcryptd/253:0". Let's pick a fixed smallish limit that will work for the kernel.
54 #define COMM_MAX_LEN 128
56 static int get_process_state(pid_t pid
) {
57 _cleanup_free_
char *line
= NULL
;
64 /* Shortcut: if we are enquired about our own state, we are obviously running */
65 if (pid
== 0 || pid
== getpid_cached())
66 return (unsigned char) 'R';
68 p
= procfs_file_alloca(pid
, "stat");
70 r
= read_one_line_file(p
, &line
);
76 p
= strrchr(line
, ')');
82 if (sscanf(p
, " %c", &state
) != 1)
85 return (unsigned char) state
;
88 int get_process_comm(pid_t pid
, char **ret
) {
89 _cleanup_free_
char *escaped
= NULL
, *comm
= NULL
;
95 if (pid
== 0 || pid
== getpid_cached()) {
96 comm
= new0(char, TASK_COMM_LEN
+ 1); /* Must fit in 16 byte according to prctl(2) */
100 if (prctl(PR_GET_NAME
, comm
) < 0)
105 p
= procfs_file_alloca(pid
, "comm");
107 /* Note that process names of kernel threads can be much longer than TASK_COMM_LEN */
108 r
= read_one_line_file(p
, &comm
);
115 escaped
= new(char, COMM_MAX_LEN
);
119 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
120 cellescape(escaped
, COMM_MAX_LEN
, comm
);
122 *ret
= TAKE_PTR(escaped
);
126 static int get_process_cmdline_nulstr(
129 ProcessCmdlineFlags flags
,
138 /* Retrieves a process' command line as a "sized nulstr", i.e. possibly without the last NUL, but
139 * with a specified size.
141 * If PROCESS_CMDLINE_COMM_FALLBACK is specified in flags and the process has no command line set
142 * (the case for kernel threads), or has a command line that resolves to the empty string, will
143 * return the "comm" name of the process instead. This will use at most _SC_ARG_MAX bytes of input
146 * Returns an error, 0 if output was read but is truncated, 1 otherwise.
149 p
= procfs_file_alloca(pid
, "cmdline");
150 r
= read_virtual_file(p
, max_size
, &t
, &k
); /* Let's assume that each input byte results in >= 1
151 * columns of output. We ignore zero-width codepoints. */
160 if (!(flags
& PROCESS_CMDLINE_COMM_FALLBACK
))
163 /* Kernel threads have no argv[] */
164 _cleanup_free_
char *comm
= NULL
;
166 r
= get_process_comm(pid
, &comm
);
170 t
= strjoin("[", comm
, "]");
176 if (r
== 0) /* truncation */
185 int get_process_cmdline(pid_t pid
, size_t max_columns
, ProcessCmdlineFlags flags
, char **ret
) {
186 _cleanup_free_
char *t
= NULL
;
193 /* Retrieve and format a commandline. See above for discussion of retrieval options.
195 * There are two main formatting modes:
197 * - when PROCESS_CMDLINE_QUOTE is specified, output is quoted in C/Python style. If no shell special
198 * characters are present, this output can be copy-pasted into the terminal to execute. UTF-8
201 * - otherwise, a compact non-roundtrippable form is returned. Non-UTF8 bytes are replaced by �. The
202 * returned string is of the specified console width at most, abbreviated with an ellipsis.
204 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
205 * PROCESS_CMDLINE_COMM_FALLBACK is not specified). Returns 0 and sets *line otherwise. */
207 int full
= get_process_cmdline_nulstr(pid
, max_columns
, flags
, &t
, &k
);
211 if (flags
& (PROCESS_CMDLINE_QUOTE
| PROCESS_CMDLINE_QUOTE_POSIX
)) {
212 ShellEscapeFlags shflags
= SHELL_ESCAPE_EMPTY
|
213 FLAGS_SET(flags
, PROCESS_CMDLINE_QUOTE_POSIX
) * SHELL_ESCAPE_POSIX
;
215 assert(!(flags
& PROCESS_CMDLINE_USE_LOCALE
));
217 _cleanup_strv_free_
char **args
= NULL
;
219 args
= strv_parse_nulstr(t
, k
);
223 /* Drop trailing empty strings. See issue #21186. */
224 STRV_FOREACH_BACKWARDS(p
, args
) {
231 ans
= quote_command_line(args
, shflags
);
235 /* Arguments are separated by NULs. Let's replace those with spaces. */
236 for (size_t i
= 0; i
< k
- 1; i
++)
240 delete_trailing_chars(t
, WHITESPACE
);
242 bool eight_bit
= (flags
& PROCESS_CMDLINE_USE_LOCALE
) && !is_locale_utf8();
244 ans
= escape_non_printable_full(t
, max_columns
,
245 eight_bit
* XESCAPE_8_BIT
| !full
* XESCAPE_FORCE_ELLIPSIS
);
249 ans
= str_realloc(ans
);
256 static int update_argv(const char name
[], size_t l
) {
257 static int can_do
= -1;
261 can_do
= false; /* We'll set it to true only if the whole process works */
263 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
264 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
265 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
266 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
269 return log_debug_errno(SYNTHETIC_ERRNO(EPERM
),
270 "Skipping PR_SET_MM, as we don't have privileges.");
272 static size_t mm_size
= 0;
273 static char *mm
= NULL
;
280 nn_size
= PAGE_ALIGN(l
+1);
281 nn
= mmap(NULL
, nn_size
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
282 if (nn
== MAP_FAILED
)
283 return log_debug_errno(errno
, "mmap() failed: %m");
285 strncpy(nn
, name
, nn_size
);
287 /* Now, let's tell the kernel about this new memory */
288 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
289 if (ERRNO_IS_PRIVILEGE(errno
))
290 return log_debug_errno(errno
, "PR_SET_MM_ARG_START failed: %m");
292 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
293 * below the desired start address, in which case the kernel may have kicked this back due
294 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
295 * action). The proper solution would be to have a prctl() API that could set both start+end
296 * simultaneously, or at least let us query the existing address to anticipate this condition
297 * and respond accordingly. For now, we can only guess at the cause of this failure and try
298 * a workaround--which will briefly expand the arg space to something potentially huge before
299 * resizing it to what we want. */
300 log_debug_errno(errno
, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
302 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0) {
303 r
= log_debug_errno(errno
, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
304 (void) munmap(nn
, nn_size
);
308 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0)
309 return log_debug_errno(errno
, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
311 /* And update the end pointer to the new end, too. If this fails, we don't really know what
312 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
314 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0)
315 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
319 (void) munmap(mm
, mm_size
);
324 strncpy(mm
, name
, mm_size
);
326 /* Update the end pointer, continuing regardless of any failure. */
327 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) mm
+ l
+ 1, 0, 0) < 0)
328 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
335 int rename_process(const char name
[]) {
336 bool truncated
= false;
338 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
339 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
340 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
341 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
344 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
347 return -EINVAL
; /* let's not confuse users unnecessarily with an empty name */
349 if (!is_main_thread())
350 return -EPERM
; /* Let's not allow setting the process name from other threads than the main one, as we
351 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
352 * process name that isn't correct on any other threads */
354 size_t l
= strlen(name
);
356 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
357 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
358 if (prctl(PR_SET_NAME
, name
) < 0)
359 log_debug_errno(errno
, "PR_SET_NAME failed: %m");
360 if (l
>= TASK_COMM_LEN
) /* Linux userspace process names can be 15 chars at max */
363 /* Second step, change glibc's ID of the process name. */
364 if (program_invocation_name
) {
367 k
= strlen(program_invocation_name
);
368 strncpy(program_invocation_name
, name
, k
);
373 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
374 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
375 * the end. This is the best option for changing /proc/self/cmdline. */
376 (void) update_argv(name
, l
);
378 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
379 * it still looks here */
380 if (saved_argc
> 0) {
384 k
= strlen(saved_argv
[0]);
385 strncpy(saved_argv
[0], name
, k
);
390 for (int i
= 1; i
< saved_argc
; i
++) {
394 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
401 int is_kernel_thread(pid_t pid
) {
402 _cleanup_free_
char *line
= NULL
;
403 unsigned long long flags
;
409 if (IN_SET(pid
, 0, 1) || pid
== getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
411 if (!pid_is_valid(pid
))
414 p
= procfs_file_alloca(pid
, "stat");
415 r
= read_one_line_file(p
, &line
);
421 /* Skip past the comm field */
422 q
= strrchr(line
, ')');
427 /* Skip 6 fields to reach the flags field */
428 for (i
= 0; i
< 6; i
++) {
429 l
= strspn(q
, WHITESPACE
);
434 l
= strcspn(q
, WHITESPACE
);
440 /* Skip preceding whitespace */
441 l
= strspn(q
, WHITESPACE
);
446 /* Truncate the rest */
447 l
= strcspn(q
, WHITESPACE
);
452 r
= safe_atollu(q
, &flags
);
456 return !!(flags
& PF_KTHREAD
);
459 int get_process_capeff(pid_t pid
, char **ret
) {
466 p
= procfs_file_alloca(pid
, "status");
468 r
= get_proc_field(p
, "CapEff", WHITESPACE
, ret
);
475 static int get_process_link_contents(const char *proc_file
, char **ret
) {
481 r
= readlink_malloc(proc_file
, ret
);
490 int get_process_exe(pid_t pid
, char **ret
) {
498 p
= procfs_file_alloca(pid
, "exe");
499 r
= get_process_link_contents(p
, ret
);
503 d
= endswith(*ret
, " (deleted)");
510 static int get_process_id(pid_t pid
, const char *field
, uid_t
*ret
) {
511 _cleanup_fclose_
FILE *f
= NULL
;
521 p
= procfs_file_alloca(pid
, "status");
522 r
= fopen_unlocked(p
, "re", &f
);
529 _cleanup_free_
char *line
= NULL
;
532 r
= read_line(f
, LONG_LINE_MAX
, &line
);
540 if (startswith(l
, field
)) {
542 l
+= strspn(l
, WHITESPACE
);
544 l
[strcspn(l
, WHITESPACE
)] = 0;
546 return parse_uid(l
, ret
);
553 int get_process_uid(pid_t pid
, uid_t
*ret
) {
555 if (pid
== 0 || pid
== getpid_cached()) {
560 return get_process_id(pid
, "Uid:", ret
);
563 int get_process_gid(pid_t pid
, gid_t
*ret
) {
565 if (pid
== 0 || pid
== getpid_cached()) {
570 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
571 return get_process_id(pid
, "Gid:", ret
);
574 int get_process_cwd(pid_t pid
, char **ret
) {
580 if (pid
== 0 || pid
== getpid_cached())
581 return safe_getcwd(ret
);
583 p
= procfs_file_alloca(pid
, "cwd");
585 return get_process_link_contents(p
, ret
);
588 int get_process_root(pid_t pid
, char **ret
) {
594 p
= procfs_file_alloca(pid
, "root");
596 return get_process_link_contents(p
, ret
);
599 #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
601 int get_process_environ(pid_t pid
, char **ret
) {
602 _cleanup_fclose_
FILE *f
= NULL
;
603 _cleanup_free_
char *outcome
= NULL
;
611 p
= procfs_file_alloca(pid
, "environ");
613 r
= fopen_unlocked(p
, "re", &f
);
622 if (sz
>= ENVIRONMENT_BLOCK_MAX
)
625 if (!GREEDY_REALLOC(outcome
, sz
+ 5))
628 r
= safe_fgetc(f
, &c
);
635 outcome
[sz
++] = '\n';
637 sz
+= cescape_char(c
, outcome
+ sz
);
641 *ret
= TAKE_PTR(outcome
);
646 int get_process_ppid(pid_t pid
, pid_t
*ret
) {
647 _cleanup_free_
char *line
= NULL
;
654 if (pid
== 0 || pid
== getpid_cached()) {
660 if (pid
== 1) /* PID 1 has no parent, shortcut this case */
661 return -EADDRNOTAVAIL
;
663 p
= procfs_file_alloca(pid
, "stat");
664 r
= read_one_line_file(p
, &line
);
670 /* Let's skip the pid and comm fields. The latter is enclosed in () but does not escape any () in its
671 * value, so let's skip over it manually */
673 p
= strrchr(line
, ')');
685 /* If ppid is zero the process has no parent. Which might be the case for PID 1 but also for
686 * processes originating in other namespaces that are inserted into a pidns. Return a recognizable
687 * error in this case. */
689 return -EADDRNOTAVAIL
;
691 if ((pid_t
) ppid
< 0 || (unsigned long) (pid_t
) ppid
!= ppid
)
700 int get_process_umask(pid_t pid
, mode_t
*ret
) {
701 _cleanup_free_
char *m
= NULL
;
708 p
= procfs_file_alloca(pid
, "status");
710 r
= get_proc_field(p
, "Umask", WHITESPACE
, &m
);
714 return parse_mode(m
, ret
);
717 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
728 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
733 return negative_errno();
742 * < 0 : wait_for_terminate() failed to get the state of the
743 * process, the process was terminated by a signal, or
744 * failed for an unknown reason.
745 * >=0 : The process terminated normally, and its exit code is
748 * That is, success is indicated by a return value of zero, and an
749 * error is indicated by a non-zero value.
751 * A warning is emitted if the process terminates abnormally,
752 * and also if it returns non-zero unless check_exit_code is true.
754 int wait_for_terminate_and_check(const char *name
, pid_t pid
, WaitFlags flags
) {
755 _cleanup_free_
char *buffer
= NULL
;
762 r
= get_process_comm(pid
, &buffer
);
764 log_debug_errno(r
, "Failed to acquire process name of " PID_FMT
", ignoring: %m", pid
);
769 prio
= flags
& WAIT_LOG_ABNORMAL
? LOG_ERR
: LOG_DEBUG
;
771 r
= wait_for_terminate(pid
, &status
);
773 return log_full_errno(prio
, r
, "Failed to wait for %s: %m", strna(name
));
775 if (status
.si_code
== CLD_EXITED
) {
776 if (status
.si_status
!= EXIT_SUCCESS
)
777 log_full(flags
& WAIT_LOG_NON_ZERO_EXIT_STATUS
? LOG_ERR
: LOG_DEBUG
,
778 "%s failed with exit status %i.", strna(name
), status
.si_status
);
780 log_debug("%s succeeded.", name
);
782 return status
.si_status
;
784 } else if (IN_SET(status
.si_code
, CLD_KILLED
, CLD_DUMPED
)) {
786 log_full(prio
, "%s terminated by signal %s.", strna(name
), signal_to_string(status
.si_status
));
790 log_full(prio
, "%s failed due to unknown reason.", strna(name
));
797 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
798 * was terminated by a signal, or failed for an unknown reason.
800 * >=0 : The process terminated normally with no failures.
802 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
803 * states are indicated by error is indicated by a non-zero value.
805 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
806 * to remain entirely race-free.
808 int wait_for_terminate_with_timeout(pid_t pid
, usec_t timeout
) {
813 assert_se(sigemptyset(&mask
) == 0);
814 assert_se(sigaddset(&mask
, SIGCHLD
) == 0);
816 /* Drop into a sigtimewait-based timeout. Waiting for the
818 until
= usec_add(now(CLOCK_MONOTONIC
), timeout
);
821 siginfo_t status
= {};
823 n
= now(CLOCK_MONOTONIC
);
827 r
= RET_NERRNO(sigtimedwait(&mask
, NULL
, TIMESPEC_STORE(until
- n
)));
828 /* Assuming we woke due to the child exiting. */
829 if (waitid(P_PID
, pid
, &status
, WEXITED
|WNOHANG
) == 0) {
830 if (status
.si_pid
== pid
) {
831 /* This is the correct child. */
832 if (status
.si_code
== CLD_EXITED
)
833 return (status
.si_status
== 0) ? 0 : -EPROTO
;
838 /* Not the child, check for errors and proceed appropriately */
842 /* Timed out, child is likely hung. */
845 /* Received a different signal and should retry */
848 /* Return any unexpected errors */
857 void sigkill_wait(pid_t pid
) {
860 (void) kill(pid
, SIGKILL
);
861 (void) wait_for_terminate(pid
, NULL
);
864 void sigkill_waitp(pid_t
*pid
) {
875 void sigterm_wait(pid_t pid
) {
878 (void) kill_and_sigcont(pid
, SIGTERM
);
879 (void) wait_for_terminate(pid
, NULL
);
882 int kill_and_sigcont(pid_t pid
, int sig
) {
885 r
= RET_NERRNO(kill(pid
, sig
));
887 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
888 * affected by a process being suspended anyway. */
889 if (r
>= 0 && !IN_SET(sig
, SIGCONT
, SIGKILL
))
890 (void) kill(pid
, SIGCONT
);
895 int getenv_for_pid(pid_t pid
, const char *field
, char **ret
) {
896 _cleanup_fclose_
FILE *f
= NULL
;
906 if (pid
== 0 || pid
== getpid_cached()) {
923 if (!pid_is_valid(pid
))
926 path
= procfs_file_alloca(pid
, "environ");
928 r
= fopen_unlocked(path
, "re", &f
);
936 _cleanup_free_
char *line
= NULL
;
938 if (sum
> ENVIRONMENT_BLOCK_MAX
) /* Give up searching eventually */
941 r
= read_nul_string(f
, LONG_LINE_MAX
, &line
);
944 if (r
== 0) /* EOF */
949 if (strneq(line
, field
, l
) && line
[l
] == '=') {
950 value
= strdup(line
+ l
+ 1);
963 int pid_is_my_child(pid_t pid
) {
970 r
= get_process_ppid(pid
, &ppid
);
974 return ppid
== getpid_cached();
977 bool pid_is_unwaited(pid_t pid
) {
978 /* Checks whether a PID is still valid at all, including a zombie */
983 if (pid
<= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
986 if (pid
== getpid_cached())
989 if (kill(pid
, 0) >= 0)
992 return errno
!= ESRCH
;
995 bool pid_is_alive(pid_t pid
) {
998 /* Checks whether a PID is still valid and not a zombie */
1003 if (pid
<= 1) /* If we or PID 1 would be a zombie, this code would not be running */
1006 if (pid
== getpid_cached())
1009 r
= get_process_state(pid
);
1010 if (IN_SET(r
, -ESRCH
, 'Z'))
1016 int pid_from_same_root_fs(pid_t pid
) {
1022 if (pid
== 0 || pid
== getpid_cached())
1025 root
= procfs_file_alloca(pid
, "root");
1027 return files_same(root
, "/proc/1/root", 0);
1030 bool is_main_thread(void) {
1031 static thread_local
int cached
= 0;
1033 if (_unlikely_(cached
== 0))
1034 cached
= getpid_cached() == gettid() ? 1 : -1;
1039 bool oom_score_adjust_is_valid(int oa
) {
1040 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
1043 unsigned long personality_from_string(const char *p
) {
1047 return PERSONALITY_INVALID
;
1049 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1050 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1051 * the same register size. */
1053 architecture
= architecture_from_string(p
);
1054 if (architecture
< 0)
1055 return PERSONALITY_INVALID
;
1057 if (architecture
== native_architecture())
1059 #ifdef ARCHITECTURE_SECONDARY
1060 if (architecture
== ARCHITECTURE_SECONDARY
)
1064 return PERSONALITY_INVALID
;
1067 const char* personality_to_string(unsigned long p
) {
1068 int architecture
= _ARCHITECTURE_INVALID
;
1071 architecture
= native_architecture();
1072 #ifdef ARCHITECTURE_SECONDARY
1073 else if (p
== PER_LINUX32
)
1074 architecture
= ARCHITECTURE_SECONDARY
;
1077 if (architecture
< 0)
1080 return architecture_to_string(architecture
);
1083 int safe_personality(unsigned long p
) {
1086 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1087 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1088 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1089 * the return value indicating the same issue, so that we are definitely on the safe side.
1091 * See https://github.com/systemd/systemd/issues/6737 */
1094 ret
= personality(p
);
1105 int opinionated_personality(unsigned long *ret
) {
1108 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1109 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1110 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1112 current
= safe_personality(PERSONALITY_INVALID
);
1116 if (((unsigned long) current
& 0xffff) == PER_LINUX32
)
1124 void valgrind_summary_hack(void) {
1125 #if HAVE_VALGRIND_VALGRIND_H
1126 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
1128 pid
= raw_clone(SIGCHLD
);
1130 log_emergency_errno(errno
, "Failed to fork off valgrind helper: %m");
1134 log_info("Spawned valgrind helper as PID "PID_FMT
".", pid
);
1135 (void) wait_for_terminate(pid
, NULL
);
1141 int pid_compare_func(const pid_t
*a
, const pid_t
*b
) {
1142 /* Suitable for usage in qsort() */
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 pid_t
getpid_cached(void) {
1164 static bool installed
= false;
1165 pid_t current_value
;
1167 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1168 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1169 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1170 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1172 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1173 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1176 current_value
= __sync_val_compare_and_swap(&cached_pid
, CACHED_PID_UNSET
, CACHED_PID_BUSY
);
1178 switch (current_value
) {
1180 case CACHED_PID_UNSET
: { /* Not initialized yet, then do so now */
1183 new_pid
= raw_getpid();
1186 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1187 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1188 * we'll check for errors only in the most generic fashion possible. */
1190 if (pthread_atfork(NULL
, NULL
, reset_cached_pid
) != 0) {
1191 /* OOM? Let's try again later */
1192 cached_pid
= CACHED_PID_UNSET
;
1199 cached_pid
= new_pid
;
1203 case CACHED_PID_BUSY
: /* Somebody else is currently initializing */
1204 return raw_getpid();
1206 default: /* Properly initialized */
1207 return current_value
;
1211 int must_be_root(void) {
1216 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Need to be root.");
1219 static void restore_sigsetp(sigset_t
**ssp
) {
1221 (void) sigprocmask(SIG_SETMASK
, *ssp
, NULL
);
1226 const int except_fds
[],
1227 size_t n_except_fds
,
1231 pid_t original_pid
, pid
;
1232 sigset_t saved_ss
, ss
;
1233 _unused_
_cleanup_(restore_sigsetp
) sigset_t
*saved_ssp
= NULL
;
1234 bool block_signals
= false, block_all
= 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_FLUSH_STDIO
) {
1246 fflush(stderr
); /* This one shouldn't be necessary, stderr should be unbuffered anyway, but let's better be safe than sorry */
1249 if (flags
& (FORK_RESET_SIGNALS
|FORK_DEATHSIG
)) {
1250 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1251 * be sure that SIGTERMs are not lost we might send to the child. */
1253 assert_se(sigfillset(&ss
) >= 0);
1254 block_signals
= block_all
= true;
1256 } else if (flags
& FORK_WAIT
) {
1257 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1259 assert_se(sigemptyset(&ss
) >= 0);
1260 assert_se(sigaddset(&ss
, SIGCHLD
) >= 0);
1261 block_signals
= true;
1264 if (block_signals
) {
1265 if (sigprocmask(SIG_SETMASK
, &ss
, &saved_ss
) < 0)
1266 return log_full_errno(prio
, errno
, "Failed to set signal mask: %m");
1267 saved_ssp
= &saved_ss
;
1270 if ((flags
& (FORK_NEW_MOUNTNS
|FORK_NEW_USERNS
)) != 0)
1271 pid
= raw_clone(SIGCHLD
|
1272 (FLAGS_SET(flags
, FORK_NEW_MOUNTNS
) ? CLONE_NEWNS
: 0) |
1273 (FLAGS_SET(flags
, FORK_NEW_USERNS
) ? CLONE_NEWUSER
: 0));
1277 return log_full_errno(prio
, errno
, "Failed to fork: %m");
1279 /* We are in the parent process */
1281 log_debug("Successfully forked off '%s' as PID " PID_FMT
".", strna(name
), pid
);
1283 if (flags
& FORK_WAIT
) {
1285 /* undo everything except SIGCHLD */
1287 assert_se(sigaddset(&ss
, SIGCHLD
) >= 0);
1288 (void) sigprocmask(SIG_SETMASK
, &ss
, NULL
);
1291 r
= wait_for_terminate_and_check(name
, pid
, (flags
& FORK_LOG
? WAIT_LOG
: 0));
1294 if (r
!= EXIT_SUCCESS
) /* exit status > 0 should be treated as failure, too */
1304 /* We are in the child process */
1306 /* Restore signal mask manually */
1309 if (flags
& FORK_REOPEN_LOG
) {
1310 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1312 log_set_open_when_needed(true);
1316 r
= rename_process(name
);
1318 log_full_errno(flags
& FORK_LOG
? LOG_WARNING
: LOG_DEBUG
,
1319 r
, "Failed to rename process, ignoring: %m");
1322 if (flags
& (FORK_DEATHSIG
|FORK_DEATHSIG_SIGINT
))
1323 if (prctl(PR_SET_PDEATHSIG
, (flags
& FORK_DEATHSIG_SIGINT
) ? SIGINT
: SIGTERM
) < 0) {
1324 log_full_errno(prio
, errno
, "Failed to set death signal: %m");
1325 _exit(EXIT_FAILURE
);
1328 if (flags
& FORK_RESET_SIGNALS
) {
1329 r
= reset_all_signal_handlers();
1331 log_full_errno(prio
, r
, "Failed to reset signal handlers: %m");
1332 _exit(EXIT_FAILURE
);
1335 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1336 r
= reset_signal_mask();
1338 log_full_errno(prio
, r
, "Failed to reset signal mask: %m");
1339 _exit(EXIT_FAILURE
);
1341 } else if (block_signals
) { /* undo what we did above */
1342 if (sigprocmask(SIG_SETMASK
, &saved_ss
, NULL
) < 0) {
1343 log_full_errno(prio
, errno
, "Failed to restore signal mask: %m");
1344 _exit(EXIT_FAILURE
);
1348 if (flags
& FORK_DEATHSIG
) {
1350 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1351 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1355 /* Parent is in a different PID namespace. */;
1356 else if (ppid
!= original_pid
) {
1357 log_debug("Parent died early, raising SIGTERM.");
1358 (void) raise(SIGTERM
);
1359 _exit(EXIT_FAILURE
);
1363 if (FLAGS_SET(flags
, FORK_NEW_MOUNTNS
| FORK_MOUNTNS_SLAVE
)) {
1365 /* Optionally, make sure we never propagate mounts to the host. */
1367 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
) < 0) {
1368 log_full_errno(prio
, errno
, "Failed to remount root directory as MS_SLAVE: %m");
1369 _exit(EXIT_FAILURE
);
1373 if (flags
& FORK_CLOSE_ALL_FDS
) {
1374 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1377 r
= close_all_fds(except_fds
, n_except_fds
);
1379 log_full_errno(prio
, r
, "Failed to close all file descriptors: %m");
1380 _exit(EXIT_FAILURE
);
1384 /* When we were asked to reopen the logs, do so again now */
1385 if (flags
& FORK_REOPEN_LOG
) {
1387 log_set_open_when_needed(false);
1390 if (flags
& FORK_NULL_STDIO
) {
1391 r
= make_null_stdio();
1393 log_full_errno(prio
, r
, "Failed to connect stdin/stdout to /dev/null: %m");
1394 _exit(EXIT_FAILURE
);
1397 } else if (flags
& FORK_STDOUT_TO_STDERR
) {
1398 if (dup2(STDERR_FILENO
, STDOUT_FILENO
) < 0) {
1399 log_full_errno(prio
, errno
, "Failed to connect stdout to stderr: %m");
1400 _exit(EXIT_FAILURE
);
1404 if (flags
& FORK_RLIMIT_NOFILE_SAFE
) {
1405 r
= rlimit_nofile_safe();
1407 log_full_errno(prio
, r
, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1408 _exit(EXIT_FAILURE
);
1413 *ret_pid
= getpid_cached();
1419 const char *outer_name
,
1420 const char *inner_name
,
1421 const int except_fds
[],
1422 size_t n_except_fds
,
1433 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1434 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1435 * /proc/self/fd works correctly. */
1437 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
);
1445 r
= namespace_enter(pidns_fd
, mntns_fd
, netns_fd
, userns_fd
, root_fd
);
1447 log_full_errno(FLAGS_SET(flags
, FORK_LOG
) ? LOG_ERR
: LOG_DEBUG
, r
, "Failed to join namespace: %m");
1448 _exit(EXIT_FAILURE
);
1451 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1452 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
);
1454 _exit(EXIT_FAILURE
);
1462 r
= wait_for_terminate_and_check(inner_name
, pid
, FLAGS_SET(flags
, FORK_LOG
) ? WAIT_LOG
: 0);
1464 _exit(EXIT_FAILURE
);
1472 int set_oom_score_adjust(int value
) {
1473 char t
[DECIMAL_STR_MAX(int)];
1475 xsprintf(t
, "%i", value
);
1477 return write_string_file("/proc/self/oom_score_adj", t
,
1478 WRITE_STRING_FILE_VERIFY_ON_FAILURE
|WRITE_STRING_FILE_DISABLE_BUFFER
);
1481 int get_oom_score_adjust(int *ret
) {
1482 _cleanup_free_
char *t
= NULL
;
1485 r
= read_virtual_file("/proc/self/oom_score_adj", SIZE_MAX
, &t
, NULL
);
1489 delete_trailing_chars(t
, WHITESPACE
);
1491 assert_se(safe_atoi(t
, &a
) >= 0);
1492 assert_se(oom_score_adjust_is_valid(a
));
1499 int pidfd_get_pid(int fd
, pid_t
*ret
) {
1500 char path
[STRLEN("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
1501 _cleanup_free_
char *fdinfo
= NULL
;
1508 xsprintf(path
, "/proc/self/fdinfo/%i", fd
);
1510 r
= read_full_virtual_file(path
, &fdinfo
, NULL
);
1511 if (r
== -ENOENT
) /* if fdinfo doesn't exist we assume the process does not exist */
1516 p
= startswith(fdinfo
, "Pid:");
1518 p
= strstr(fdinfo
, "\nPid:");
1520 return -ENOTTY
; /* not a pidfd? */
1525 p
+= strspn(p
, WHITESPACE
);
1526 p
[strcspn(p
, WHITESPACE
)] = 0;
1528 return parse_pid(p
, ret
);
1531 static int rlimit_to_nice(rlim_t limit
) {
1533 return PRIO_MAX
-1; /* i.e. 19 */
1535 if (limit
>= -PRIO_MIN
+ PRIO_MAX
)
1536 return PRIO_MIN
; /* i.e. -20 */
1538 return PRIO_MAX
- (int) limit
;
1541 int setpriority_closest(int priority
) {
1542 int current
, limit
, saved_errno
;
1543 struct rlimit highest
;
1545 /* Try to set requested nice level */
1546 if (setpriority(PRIO_PROCESS
, 0, priority
) >= 0)
1549 /* Permission failed */
1550 saved_errno
= -errno
;
1551 if (!ERRNO_IS_PRIVILEGE(saved_errno
))
1555 current
= getpriority(PRIO_PROCESS
, 0);
1559 if (priority
== current
)
1562 /* Hmm, we'd expect that raising the nice level from our status quo would always work. If it doesn't,
1563 * then the whole setpriority() system call is blocked to us, hence let's propagate the error
1565 if (priority
> current
)
1568 if (getrlimit(RLIMIT_NICE
, &highest
) < 0)
1571 limit
= rlimit_to_nice(highest
.rlim_cur
);
1573 /* We are already less nice than limit allows us */
1574 if (current
< limit
) {
1575 log_debug("Cannot raise nice level, permissions and the resource limit do not allow it.");
1579 /* Push to the allowed limit */
1580 if (setpriority(PRIO_PROCESS
, 0, limit
) < 0)
1583 log_debug("Cannot set requested nice level (%i), used next best (%i).", priority
, limit
);
1587 bool invoked_as(char *argv
[], const char *token
) {
1588 if (!argv
|| isempty(argv
[0]))
1594 return strstr(last_path_component(argv
[0]), token
);
1597 _noreturn_
void freeze(void) {
1600 /* Make sure nobody waits for us (i.e. on one of our sockets) anymore. Note that we use
1601 * close_all_fds_without_malloc() instead of plain close_all_fds() here, since we want this function
1602 * to be compatible with being called from signal handlers. */
1603 (void) close_all_fds_without_malloc(NULL
, 0);
1605 /* Let's not freeze right away, but keep reaping zombies. */
1609 if (waitid(P_ALL
, 0, &si
, WEXITED
) < 0 && errno
!= EINTR
)
1613 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
1619 static const char *const sigchld_code_table
[] = {
1620 [CLD_EXITED
] = "exited",
1621 [CLD_KILLED
] = "killed",
1622 [CLD_DUMPED
] = "dumped",
1623 [CLD_TRAPPED
] = "trapped",
1624 [CLD_STOPPED
] = "stopped",
1625 [CLD_CONTINUED
] = "continued",
1628 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1630 static const char* const sched_policy_table
[] = {
1631 [SCHED_OTHER
] = "other",
1632 [SCHED_BATCH
] = "batch",
1633 [SCHED_IDLE
] = "idle",
1634 [SCHED_FIFO
] = "fifo",
1638 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);