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>
30 #include <sys/personality.h>
31 #include <sys/prctl.h>
32 #include <sys/types.h>
36 #ifdef HAVE_VALGRIND_VALGRIND_H
37 #include <valgrind/valgrind.h>
40 #include "alloc-util.h"
41 //#include "architecture.h"
50 #include "process-util.h"
51 #include "signal-util.h"
52 //#include "stat-util.h"
53 #include "string-table.h"
54 #include "string-util.h"
55 #include "user-util.h"
58 int get_process_state(pid_t pid) {
62 _cleanup_free_ char *line = NULL;
66 p = procfs_file_alloca(pid, "stat");
68 r = read_one_line_file(p, &line);
74 p = strrchr(line, ')');
80 if (sscanf(p, " %c", &state) != 1)
83 return (unsigned char) state;
86 int get_process_comm(pid_t pid, char **name) {
93 p = procfs_file_alloca(pid, "comm");
95 r = read_one_line_file(p, name);
102 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
103 _cleanup_fclose_ FILE *f = NULL;
105 char *k, *ans = NULL;
112 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
113 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
114 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
115 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
116 * command line that resolves to the empty string will return the "comm" name of the process instead.
118 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
119 * comm_fallback is false). Returns 0 and sets *line otherwise. */
121 p = procfs_file_alloca(pid, "cmdline");
130 if (max_length == 1) {
132 /* If there's only room for one byte, return the empty string */
140 } else if (max_length == 0) {
141 size_t len = 0, allocated = 0;
143 while ((c = getc(f)) != EOF) {
145 if (!GREEDY_REALLOC(ans, allocated, len+3)) {
167 bool dotdotdot = false;
170 ans = new(char, max_length);
176 while ((c = getc(f)) != EOF) {
203 if (max_length <= 4) {
207 k = ans + max_length - 4;
210 /* Eat up final spaces */
211 while (k > ans && isspace(k[-1])) {
217 strncpy(k, "...", left-1);
223 /* Kernel threads have no argv[] */
225 _cleanup_free_ char *t = NULL;
233 h = get_process_comm(pid, &t);
238 ans = strjoin("[", t, "]");
244 if (l + 3 <= max_length)
245 ans = strjoin("[", t, "]");
246 else if (max_length <= 6) {
248 ans = new(char, max_length);
252 memcpy(ans, "[...]", max_length-1);
253 ans[max_length-1] = 0;
257 t[max_length - 6] = 0;
259 /* Chop off final spaces */
261 while (e > t && isspace(e[-1]))
265 ans = strjoin("[", t, "...]");
276 #if 0 /// UNNEEDED by elogind
277 int rename_process(const char name[]) {
278 static size_t mm_size = 0;
279 static char *mm = NULL;
280 bool truncated = false;
283 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
284 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
285 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
286 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
289 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
292 return -EINVAL; /* let's not confuse users unnecessarily with an empty name */
296 /* First step, change the comm field. */
297 (void) prctl(PR_SET_NAME, name);
298 if (l > 15) /* Linux process names can be 15 chars at max */
301 /* Second step, change glibc's ID of the process name. */
302 if (program_invocation_name) {
305 k = strlen(program_invocation_name);
306 strncpy(program_invocation_name, name, k);
311 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
312 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
313 * the end. This is the best option for changing /proc/self/cmdline. */
315 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
316 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
317 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
318 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
321 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
322 else if (mm_size < l+1) {
326 nn_size = PAGE_ALIGN(l+1);
327 nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
328 if (nn == MAP_FAILED) {
329 log_debug_errno(errno, "mmap() failed: %m");
333 strncpy(nn, name, nn_size);
335 /* Now, let's tell the kernel about this new memory */
336 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
337 log_debug_errno(errno, "PR_SET_MM_ARG_START failed, proceeding without: %m");
338 (void) munmap(nn, nn_size);
342 /* And update the end pointer to the new end, too. If this fails, we don't really know what to do, it's
343 * pretty unlikely that we can rollback, hence we'll just accept the failure, and continue. */
344 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0)
345 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
348 (void) munmap(mm, mm_size);
353 strncpy(mm, name, mm_size);
355 /* Update the end pointer, continuing regardless of any failure. */
356 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0)
357 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
361 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
362 * it still looks here */
364 if (saved_argc > 0) {
370 k = strlen(saved_argv[0]);
371 strncpy(saved_argv[0], name, k);
376 for (i = 1; i < saved_argc; i++) {
380 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 #if 0 /// UNNEEDED by elogind
421 int get_process_capeff(pid_t pid, char **capeff) {
428 p = procfs_file_alloca(pid, "status");
430 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
438 static int get_process_link_contents(const char *proc_file, char **name) {
444 r = readlink_malloc(proc_file, name);
453 int get_process_exe(pid_t pid, char **name) {
460 p = procfs_file_alloca(pid, "exe");
461 r = get_process_link_contents(p, name);
465 d = endswith(*name, " (deleted)");
472 #if 0 /// UNNEEDED by elogind
473 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
474 _cleanup_fclose_ FILE *f = NULL;
481 if (!pid_is_valid(pid))
484 p = procfs_file_alloca(pid, "status");
492 FOREACH_LINE(line, f, return -errno) {
497 if (startswith(l, field)) {
499 l += strspn(l, WHITESPACE);
501 l[strcspn(l, WHITESPACE)] = 0;
503 return parse_uid(l, uid);
510 int get_process_uid(pid_t pid, uid_t *uid) {
512 if (pid == 0 || pid == getpid_cached()) {
517 return get_process_id(pid, "Uid:", uid);
520 int get_process_gid(pid_t pid, gid_t *gid) {
522 if (pid == 0 || pid == getpid_cached()) {
527 assert_cc(sizeof(uid_t) == sizeof(gid_t));
528 return get_process_id(pid, "Gid:", gid);
531 int get_process_cwd(pid_t pid, char **cwd) {
536 p = procfs_file_alloca(pid, "cwd");
538 return get_process_link_contents(p, cwd);
541 int get_process_root(pid_t pid, char **root) {
546 p = procfs_file_alloca(pid, "root");
548 return get_process_link_contents(p, root);
551 int get_process_environ(pid_t pid, char **env) {
552 _cleanup_fclose_ FILE *f = NULL;
553 _cleanup_free_ char *outcome = NULL;
556 size_t allocated = 0, sz = 0;
561 p = procfs_file_alloca(pid, "environ");
570 while ((c = fgetc(f)) != EOF) {
571 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
575 outcome[sz++] = '\n';
577 sz += cescape_char(c, outcome + sz);
581 outcome = strdup("");
593 int get_process_ppid(pid_t pid, pid_t *_ppid) {
595 _cleanup_free_ char *line = NULL;
602 if (pid == 0 || pid == getpid_cached()) {
607 p = procfs_file_alloca(pid, "stat");
608 r = read_one_line_file(p, &line);
614 /* Let's skip the pid and comm fields. The latter is enclosed
615 * in () but does not escape any () in its value, so let's
616 * skip over it manually */
618 p = strrchr(line, ')');
630 if ((long unsigned) (pid_t) ppid != ppid)
633 *_ppid = (pid_t) ppid;
639 int wait_for_terminate(pid_t pid, siginfo_t *status) {
650 if (waitid(P_PID, pid, status, WEXITED) < 0) {
655 return negative_errno();
664 * < 0 : wait_for_terminate() failed to get the state of the
665 * process, the process was terminated by a signal, or
666 * failed for an unknown reason.
667 * >=0 : The process terminated normally, and its exit code is
670 * That is, success is indicated by a return value of zero, and an
671 * error is indicated by a non-zero value.
673 * A warning is emitted if the process terminates abnormally,
674 * and also if it returns non-zero unless check_exit_code is true.
676 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
683 r = wait_for_terminate(pid, &status);
685 return log_warning_errno(r, "Failed to wait for %s: %m", name);
687 if (status.si_code == CLD_EXITED) {
688 if (status.si_status != 0)
689 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
690 "%s failed with error code %i.", name, status.si_status);
692 log_debug("%s succeeded.", name);
694 return status.si_status;
695 } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
697 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
701 log_warning("%s failed due to unknown reason.", name);
705 #if 0 /// UNNEEDED by elogind
706 void sigkill_wait(pid_t pid) {
709 if (kill(pid, SIGKILL) > 0)
710 (void) wait_for_terminate(pid, NULL);
713 void sigkill_waitp(pid_t *pid) {
722 int kill_and_sigcont(pid_t pid, int sig) {
725 r = kill(pid, sig) < 0 ? -errno : 0;
727 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
728 * affected by a process being suspended anyway. */
729 if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
730 (void) kill(pid, SIGCONT);
736 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
737 _cleanup_fclose_ FILE *f = NULL;
748 path = procfs_file_alloca(pid, "environ");
750 f = fopen(path, "re");
764 for (i = 0; i < sizeof(line)-1; i++) {
768 if (_unlikely_(c == EOF)) {
778 if (strneq(line, field, l) && line[l] == '=') {
779 value = strdup(line + l + 1);
793 bool pid_is_unwaited(pid_t pid) {
794 /* Checks whether a PID is still valid at all, including a zombie */
796 if (!pid_is_valid(pid))
799 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
802 if (pid == getpid_cached())
805 if (kill(pid, 0) >= 0)
808 return errno != ESRCH;
811 bool pid_is_alive(pid_t pid) {
814 /* Checks whether a PID is still valid and not a zombie */
816 if (!pid_is_valid(pid))
819 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
822 if (pid == getpid_cached())
825 r = get_process_state(pid);
826 if (r == -ESRCH || r == 'Z')
832 #if 0 /// UNNEEDED by elogind
833 int pid_from_same_root_fs(pid_t pid) {
836 if (!pid_is_valid(pid))
839 if (pid == 0 || pid == getpid_cached())
842 root = procfs_file_alloca(pid, "root");
844 return files_same(root, "/proc/1/root", 0);
848 bool is_main_thread(void) {
849 static thread_local int cached = 0;
851 if (_unlikely_(cached == 0))
852 cached = getpid_cached() == gettid() ? 1 : -1;
857 #if 0 /// UNNEEDED by elogind
858 noreturn void freeze(void) {
862 /* Make sure nobody waits for us on a socket anymore */
863 close_all_fds(NULL, 0);
871 bool oom_score_adjust_is_valid(int oa) {
872 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
875 unsigned long personality_from_string(const char *p) {
879 return PERSONALITY_INVALID;
881 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
882 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
883 * the same register size. */
885 architecture = architecture_from_string(p);
886 if (architecture < 0)
887 return PERSONALITY_INVALID;
889 if (architecture == native_architecture())
891 #ifdef SECONDARY_ARCHITECTURE
892 if (architecture == SECONDARY_ARCHITECTURE)
896 return PERSONALITY_INVALID;
899 const char* personality_to_string(unsigned long p) {
900 int architecture = _ARCHITECTURE_INVALID;
903 architecture = native_architecture();
904 #ifdef SECONDARY_ARCHITECTURE
905 else if (p == PER_LINUX32)
906 architecture = SECONDARY_ARCHITECTURE;
909 if (architecture < 0)
912 return architecture_to_string(architecture);
915 int safe_personality(unsigned long p) {
918 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
919 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
920 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
921 * the return value indicating the same issue, so that we are definitely on the safe side.
923 * See https://github.com/elogind/elogind/issues/6737 */
926 ret = personality(p);
937 int opinionated_personality(unsigned long *ret) {
940 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
941 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
942 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
944 current = safe_personality(PERSONALITY_INVALID);
948 if (((unsigned long) current & 0xffff) == PER_LINUX32)
956 void valgrind_summary_hack(void) {
957 #ifdef HAVE_VALGRIND_VALGRIND_H
958 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
960 pid = raw_clone(SIGCHLD);
962 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
966 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
967 (void) wait_for_terminate(pid, NULL);
973 int pid_compare_func(const void *a, const void *b) {
974 const pid_t *p = a, *q = b;
976 /* Suitable for usage in qsort() */
985 int ioprio_parse_priority(const char *s, int *ret) {
991 r = safe_atoi(s, &i);
995 if (!ioprio_priority_is_valid(i))
1003 /* The cached PID, possible values:
1005 * == UNSET [0] → cache not initialized yet
1006 * == BUSY [-1] → some thread is initializing it at the moment
1007 * any other → the cached PID
1010 #define CACHED_PID_UNSET ((pid_t) 0)
1011 #define CACHED_PID_BUSY ((pid_t) -1)
1013 static pid_t cached_pid = CACHED_PID_UNSET;
1015 static void reset_cached_pid(void) {
1016 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1017 cached_pid = CACHED_PID_UNSET;
1020 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1021 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1022 * libpthread, as it is part of glibc anyway. */
1023 extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void * __dso_handle);
1024 extern void* __dso_handle __attribute__ ((__weak__));
1026 pid_t getpid_cached(void) {
1027 pid_t current_value;
1029 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1030 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1031 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1032 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1034 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1035 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1038 current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1040 switch (current_value) {
1042 case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1047 if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) {
1048 /* OOM? Let's try again later */
1049 cached_pid = CACHED_PID_UNSET;
1053 cached_pid = new_pid;
1057 case CACHED_PID_BUSY: /* Somebody else is currently initializing */
1060 default: /* Properly initialized */
1061 return current_value;
1065 #if 0 /// UNNEEDED by elogind
1066 static const char *const ioprio_class_table[] = {
1067 [IOPRIO_CLASS_NONE] = "none",
1068 [IOPRIO_CLASS_RT] = "realtime",
1069 [IOPRIO_CLASS_BE] = "best-effort",
1070 [IOPRIO_CLASS_IDLE] = "idle"
1073 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
1075 static const char *const sigchld_code_table[] = {
1076 [CLD_EXITED] = "exited",
1077 [CLD_KILLED] = "killed",
1078 [CLD_DUMPED] = "dumped",
1079 [CLD_TRAPPED] = "trapped",
1080 [CLD_STOPPED] = "stopped",
1081 [CLD_CONTINUED] = "continued",
1084 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1086 static const char* const sched_policy_table[] = {
1087 [SCHED_OTHER] = "other",
1088 [SCHED_BATCH] = "batch",
1089 [SCHED_IDLE] = "idle",
1090 [SCHED_FIFO] = "fifo",
1094 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);