]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
e4cde6561bc3a4205fedecef97077e65fe717b85
2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
23 #include <linux/oom.h>
31 #include <sys/personality.h>
32 #include <sys/prctl.h>
33 #include <sys/types.h>
37 #ifdef HAVE_VALGRIND_VALGRIND_H
38 #include <valgrind/valgrind.h>
41 #include "alloc-util.h"
42 #include "architecture.h"
51 #include "process-util.h"
52 #include "raw-clone.h"
53 #include "signal-util.h"
54 #include "stat-util.h"
55 #include "string-table.h"
56 #include "string-util.h"
57 #include "user-util.h"
60 int get_process_state(pid_t pid
) {
64 _cleanup_free_
char *line
= NULL
;
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 **name
) {
95 p
= procfs_file_alloca(pid
, "comm");
97 r
= read_one_line_file(p
, name
);
104 int get_process_cmdline(pid_t pid
, size_t max_length
, bool comm_fallback
, char **line
) {
105 _cleanup_fclose_
FILE *f
= NULL
;
107 char *k
, *ans
= NULL
;
114 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
115 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
116 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
117 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
118 * command line that resolves to the empty string will return the "comm" name of the process instead.
120 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
121 * comm_fallback is false). Returns 0 and sets *line otherwise. */
123 p
= procfs_file_alloca(pid
, "cmdline");
132 if (max_length
== 1) {
134 /* If there's only room for one byte, return the empty string */
142 } else if (max_length
== 0) {
143 size_t len
= 0, allocated
= 0;
145 while ((c
= getc(f
)) != EOF
) {
147 if (!GREEDY_REALLOC(ans
, allocated
, len
+3)) {
169 bool dotdotdot
= false;
172 ans
= new(char, max_length
);
178 while ((c
= getc(f
)) != EOF
) {
205 if (max_length
<= 4) {
209 k
= ans
+ max_length
- 4;
212 /* Eat up final spaces */
213 while (k
> ans
&& isspace(k
[-1])) {
219 strncpy(k
, "...", left
-1);
225 /* Kernel threads have no argv[] */
227 _cleanup_free_
char *t
= NULL
;
235 h
= get_process_comm(pid
, &t
);
240 ans
= strjoin("[", t
, "]");
246 if (l
+ 3 <= max_length
)
247 ans
= strjoin("[", t
, "]");
248 else if (max_length
<= 6) {
250 ans
= new(char, max_length
);
254 memcpy(ans
, "[...]", max_length
-1);
255 ans
[max_length
-1] = 0;
259 t
[max_length
- 6] = 0;
261 /* Chop off final spaces */
263 while (e
> t
&& isspace(e
[-1]))
267 ans
= strjoin("[", t
, "...]");
278 int rename_process(const char name
[]) {
279 static size_t mm_size
= 0;
280 static char *mm
= NULL
;
281 bool truncated
= false;
284 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
285 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
286 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
287 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
290 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
293 return -EINVAL
; /* let's not confuse users unnecessarily with an empty name */
297 /* First step, change the comm field. */
298 (void) prctl(PR_SET_NAME
, name
);
299 if (l
> 15) /* Linux process names can be 15 chars at max */
302 /* Second step, change glibc's ID of the process name. */
303 if (program_invocation_name
) {
306 k
= strlen(program_invocation_name
);
307 strncpy(program_invocation_name
, name
, k
);
312 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
313 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
314 * the end. This is the best option for changing /proc/self/cmdline. */
316 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
317 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
318 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
319 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
322 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
323 else if (mm_size
< l
+1) {
327 nn_size
= PAGE_ALIGN(l
+1);
328 nn
= mmap(NULL
, nn_size
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
329 if (nn
== MAP_FAILED
) {
330 log_debug_errno(errno
, "mmap() failed: %m");
334 strncpy(nn
, name
, nn_size
);
336 /* Now, let's tell the kernel about this new memory */
337 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_START
, (unsigned long) nn
, 0, 0) < 0) {
338 log_debug_errno(errno
, "PR_SET_MM_ARG_START failed, proceeding without: %m");
339 (void) munmap(nn
, nn_size
);
343 /* And update the end pointer to the new end, too. If this fails, we don't really know what to do, it's
344 * pretty unlikely that we can rollback, hence we'll just accept the failure, and continue. */
345 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) nn
+ l
+ 1, 0, 0) < 0)
346 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
349 (void) munmap(mm
, mm_size
);
354 strncpy(mm
, name
, mm_size
);
356 /* Update the end pointer, continuing regardless of any failure. */
357 if (prctl(PR_SET_MM
, PR_SET_MM_ARG_END
, (unsigned long) mm
+ l
+ 1, 0, 0) < 0)
358 log_debug_errno(errno
, "PR_SET_MM_ARG_END failed, proceeding without: %m");
362 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
363 * it still looks here */
365 if (saved_argc
> 0) {
371 k
= strlen(saved_argv
[0]);
372 strncpy(saved_argv
[0], name
, k
);
377 for (i
= 1; i
< saved_argc
; i
++) {
381 memzero(saved_argv
[i
], strlen(saved_argv
[i
]));
388 int is_kernel_thread(pid_t pid
) {
395 if (pid
== 0 || pid
== 1 || pid
== getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
400 p
= procfs_file_alloca(pid
, "cmdline");
408 count
= fread(&c
, 1, 1, f
);
412 /* Kernel threads have an empty cmdline */
415 return eof
? 1 : -errno
;
420 int get_process_capeff(pid_t pid
, char **capeff
) {
427 p
= procfs_file_alloca(pid
, "status");
429 r
= get_proc_field(p
, "CapEff", WHITESPACE
, capeff
);
436 static int get_process_link_contents(const char *proc_file
, char **name
) {
442 r
= readlink_malloc(proc_file
, name
);
451 int get_process_exe(pid_t pid
, char **name
) {
458 p
= procfs_file_alloca(pid
, "exe");
459 r
= get_process_link_contents(p
, name
);
463 d
= endswith(*name
, " (deleted)");
470 static int get_process_id(pid_t pid
, const char *field
, uid_t
*uid
) {
471 _cleanup_fclose_
FILE *f
= NULL
;
478 if (!pid_is_valid(pid
))
481 p
= procfs_file_alloca(pid
, "status");
489 FOREACH_LINE(line
, f
, return -errno
) {
494 if (startswith(l
, field
)) {
496 l
+= strspn(l
, WHITESPACE
);
498 l
[strcspn(l
, WHITESPACE
)] = 0;
500 return parse_uid(l
, uid
);
507 int get_process_uid(pid_t pid
, uid_t
*uid
) {
509 if (pid
== 0 || pid
== getpid_cached()) {
514 return get_process_id(pid
, "Uid:", uid
);
517 int get_process_gid(pid_t pid
, gid_t
*gid
) {
519 if (pid
== 0 || pid
== getpid_cached()) {
524 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
525 return get_process_id(pid
, "Gid:", gid
);
528 int get_process_cwd(pid_t pid
, char **cwd
) {
533 p
= procfs_file_alloca(pid
, "cwd");
535 return get_process_link_contents(p
, cwd
);
538 int get_process_root(pid_t pid
, char **root
) {
543 p
= procfs_file_alloca(pid
, "root");
545 return get_process_link_contents(p
, root
);
548 int get_process_environ(pid_t pid
, char **env
) {
549 _cleanup_fclose_
FILE *f
= NULL
;
550 _cleanup_free_
char *outcome
= NULL
;
553 size_t allocated
= 0, sz
= 0;
558 p
= procfs_file_alloca(pid
, "environ");
567 while ((c
= fgetc(f
)) != EOF
) {
568 if (!GREEDY_REALLOC(outcome
, allocated
, sz
+ 5))
572 outcome
[sz
++] = '\n';
574 sz
+= cescape_char(c
, outcome
+ sz
);
578 outcome
= strdup("");
590 int get_process_ppid(pid_t pid
, pid_t
*_ppid
) {
592 _cleanup_free_
char *line
= NULL
;
599 if (pid
== 0 || pid
== getpid_cached()) {
604 p
= procfs_file_alloca(pid
, "stat");
605 r
= read_one_line_file(p
, &line
);
611 /* Let's skip the pid and comm fields. The latter is enclosed
612 * in () but does not escape any () in its value, so let's
613 * skip over it manually */
615 p
= strrchr(line
, ')');
627 if ((long unsigned) (pid_t
) ppid
!= ppid
)
630 *_ppid
= (pid_t
) ppid
;
635 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
646 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
651 return negative_errno();
660 * < 0 : wait_for_terminate() failed to get the state of the
661 * process, the process was terminated by a signal, or
662 * failed for an unknown reason.
663 * >=0 : The process terminated normally, and its exit code is
666 * That is, success is indicated by a return value of zero, and an
667 * error is indicated by a non-zero value.
669 * A warning is emitted if the process terminates abnormally,
670 * and also if it returns non-zero unless check_exit_code is true.
672 int wait_for_terminate_and_warn(const char *name
, pid_t pid
, bool check_exit_code
) {
679 r
= wait_for_terminate(pid
, &status
);
681 return log_warning_errno(r
, "Failed to wait for %s: %m", name
);
683 if (status
.si_code
== CLD_EXITED
) {
684 if (status
.si_status
!= 0)
685 log_full(check_exit_code
? LOG_WARNING
: LOG_DEBUG
,
686 "%s failed with error code %i.", name
, status
.si_status
);
688 log_debug("%s succeeded.", name
);
690 return status
.si_status
;
691 } else if (status
.si_code
== CLD_KILLED
||
692 status
.si_code
== CLD_DUMPED
) {
694 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
698 log_warning("%s failed due to unknown reason.", name
);
702 void sigkill_wait(pid_t pid
) {
705 if (kill(pid
, SIGKILL
) > 0)
706 (void) wait_for_terminate(pid
, NULL
);
709 void sigkill_waitp(pid_t
*pid
) {
718 int kill_and_sigcont(pid_t pid
, int sig
) {
721 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
723 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
724 * affected by a process being suspended anyway. */
725 if (r
>= 0 && !IN_SET(sig
, SIGCONT
, SIGKILL
))
726 (void) kill(pid
, SIGCONT
);
731 int getenv_for_pid(pid_t pid
, const char *field
, char **_value
) {
732 _cleanup_fclose_
FILE *f
= NULL
;
743 path
= procfs_file_alloca(pid
, "environ");
745 f
= fopen(path
, "re");
759 for (i
= 0; i
< sizeof(line
)-1; i
++) {
763 if (_unlikely_(c
== EOF
)) {
773 if (strneq(line
, field
, l
) && line
[l
] == '=') {
774 value
= strdup(line
+ l
+ 1);
788 bool pid_is_unwaited(pid_t pid
) {
789 /* Checks whether a PID is still valid at all, including a zombie */
791 if (!pid_is_valid(pid
))
794 if (pid
<= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
797 if (pid
== getpid_cached())
800 if (kill(pid
, 0) >= 0)
803 return errno
!= ESRCH
;
806 bool pid_is_alive(pid_t pid
) {
809 /* Checks whether a PID is still valid and not a zombie */
811 if (!pid_is_valid(pid
))
814 if (pid
<= 1) /* If we or PID 1 would be a zombie, this code would not be running */
817 if (pid
== getpid_cached())
820 r
= get_process_state(pid
);
821 if (r
== -ESRCH
|| r
== 'Z')
827 int pid_from_same_root_fs(pid_t pid
) {
830 if (!pid_is_valid(pid
))
833 if (pid
== 0 || pid
== getpid_cached())
836 root
= procfs_file_alloca(pid
, "root");
838 return files_same(root
, "/proc/1/root", 0);
841 bool is_main_thread(void) {
842 static thread_local
int cached
= 0;
844 if (_unlikely_(cached
== 0))
845 cached
= getpid_cached() == gettid() ? 1 : -1;
850 noreturn
void freeze(void) {
854 /* Make sure nobody waits for us on a socket anymore */
855 close_all_fds(NULL
, 0);
863 bool oom_score_adjust_is_valid(int oa
) {
864 return oa
>= OOM_SCORE_ADJ_MIN
&& oa
<= OOM_SCORE_ADJ_MAX
;
867 unsigned long personality_from_string(const char *p
) {
871 return PERSONALITY_INVALID
;
873 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
874 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
875 * the same register size. */
877 architecture
= architecture_from_string(p
);
878 if (architecture
< 0)
879 return PERSONALITY_INVALID
;
881 if (architecture
== native_architecture())
883 #ifdef SECONDARY_ARCHITECTURE
884 if (architecture
== SECONDARY_ARCHITECTURE
)
888 return PERSONALITY_INVALID
;
891 const char* personality_to_string(unsigned long p
) {
892 int architecture
= _ARCHITECTURE_INVALID
;
895 architecture
= native_architecture();
896 #ifdef SECONDARY_ARCHITECTURE
897 else if (p
== PER_LINUX32
)
898 architecture
= SECONDARY_ARCHITECTURE
;
901 if (architecture
< 0)
904 return architecture_to_string(architecture
);
907 int opinionated_personality(unsigned long *ret
) {
910 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
911 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
912 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
914 current
= personality(PERSONALITY_INVALID
);
918 if (((unsigned long) current
& 0xffff) == PER_LINUX32
)
926 void valgrind_summary_hack(void) {
927 #ifdef HAVE_VALGRIND_VALGRIND_H
928 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
930 pid
= raw_clone(SIGCHLD
);
932 log_emergency_errno(errno
, "Failed to fork off valgrind helper: %m");
936 log_info("Spawned valgrind helper as PID "PID_FMT
".", pid
);
937 (void) wait_for_terminate(pid
, NULL
);
943 int pid_compare_func(const void *a
, const void *b
) {
944 const pid_t
*p
= a
, *q
= b
;
946 /* Suitable for usage in qsort() */
955 int ioprio_parse_priority(const char *s
, int *ret
) {
961 r
= safe_atoi(s
, &i
);
965 if (!ioprio_priority_is_valid(i
))
972 /* The cached PID, possible values:
974 * == UNSET [0] → cache not initialized yet
975 * == BUSY [-1] → some thread is initializing it at the moment
976 * any other → the cached PID
979 #define CACHED_PID_UNSET ((pid_t) 0)
980 #define CACHED_PID_BUSY ((pid_t) -1)
982 static pid_t cached_pid
= CACHED_PID_UNSET
;
984 static void reset_cached_pid(void) {
985 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
986 cached_pid
= CACHED_PID_UNSET
;
989 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
990 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
991 * libpthread, as it is part of glibc anyway. */
992 extern int __register_atfork(void (*prepare
) (void), void (*parent
) (void), void (*child
) (void), void * __dso_handle
);
993 extern void* __dso_handle
__attribute__ ((__weak__
));
995 pid_t
getpid_cached(void) {
998 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
999 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1000 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1001 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1003 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1004 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=1d2bc2eae969543b89850e35e532f3144122d80a
1007 current_value
= __sync_val_compare_and_swap(&cached_pid
, CACHED_PID_UNSET
, CACHED_PID_BUSY
);
1009 switch (current_value
) {
1011 case CACHED_PID_UNSET
: { /* Not initialized yet, then do so now */
1016 if (__register_atfork(NULL
, NULL
, reset_cached_pid
, __dso_handle
) != 0) {
1017 /* OOM? Let's try again later */
1018 cached_pid
= CACHED_PID_UNSET
;
1022 cached_pid
= new_pid
;
1026 case CACHED_PID_BUSY
: /* Somebody else is currently initializing */
1029 default: /* Properly initialized */
1030 return current_value
;
1034 static const char *const ioprio_class_table
[] = {
1035 [IOPRIO_CLASS_NONE
] = "none",
1036 [IOPRIO_CLASS_RT
] = "realtime",
1037 [IOPRIO_CLASS_BE
] = "best-effort",
1038 [IOPRIO_CLASS_IDLE
] = "idle"
1041 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class
, int, INT_MAX
);
1043 static const char *const sigchld_code_table
[] = {
1044 [CLD_EXITED
] = "exited",
1045 [CLD_KILLED
] = "killed",
1046 [CLD_DUMPED
] = "dumped",
1047 [CLD_TRAPPED
] = "trapped",
1048 [CLD_STOPPED
] = "stopped",
1049 [CLD_CONTINUED
] = "continued",
1052 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1054 static const char* const sched_policy_table
[] = {
1055 [SCHED_OTHER
] = "other",
1056 [SCHED_BATCH
] = "batch",
1057 [SCHED_IDLE
] = "idle",
1058 [SCHED_FIFO
] = "fifo",
1062 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy
, int, INT_MAX
);