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"
49 #include "process-util.h"
50 #include "signal-util.h"
51 //#include "stat-util.h"
52 #include "string-table.h"
53 #include "string-util.h"
54 #include "user-util.h"
57 int get_process_state(pid_t pid) {
61 _cleanup_free_ char *line = NULL;
65 p = procfs_file_alloca(pid, "stat");
67 r = read_one_line_file(p, &line);
73 p = strrchr(line, ')');
79 if (sscanf(p, " %c", &state) != 1)
82 return (unsigned char) state;
85 int get_process_comm(pid_t pid, char **name) {
92 p = procfs_file_alloca(pid, "comm");
94 r = read_one_line_file(p, name);
101 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
102 _cleanup_fclose_ FILE *f = NULL;
110 p = procfs_file_alloca(pid, "cmdline");
119 if (max_length == 0) {
120 size_t len = 0, allocated = 0;
122 while ((c = getc(f)) != EOF) {
124 if (!GREEDY_REALLOC(r, allocated, len+2)) {
129 r[len++] = isprint(c) ? c : ' ';
139 r = new(char, max_length);
145 while ((c = getc(f)) != EOF) {
167 size_t n = MIN(left-1, 3U);
174 /* Kernel threads have no argv[] */
176 _cleanup_free_ char *t = NULL;
184 h = get_process_comm(pid, &t);
188 r = strjoin("[", t, "]", NULL);
197 #if 0 /// UNNEEDED by elogind
198 void rename_process(const char name[8]) {
201 /* This is a like a poor man's setproctitle(). It changes the
202 * comm field, argv[0], and also the glibc's internally used
203 * name of the process. For the first one a limit of 16 chars
204 * applies, to the second one usually one of 10 (i.e. length
205 * of "/sbin/init"), to the third one one of 7 (i.e. length of
206 * "systemd"). If you pass a longer string it will be
209 prctl(PR_SET_NAME, name);
211 if (program_invocation_name)
212 strncpy(program_invocation_name, name, strlen(program_invocation_name));
214 if (saved_argc > 0) {
218 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
220 for (i = 1; i < saved_argc; i++) {
224 memzero(saved_argv[i], strlen(saved_argv[i]));
230 int is_kernel_thread(pid_t pid) {
237 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
242 p = procfs_file_alloca(pid, "cmdline");
250 count = fread(&c, 1, 1, f);
254 /* Kernel threads have an empty cmdline */
257 return eof ? 1 : -errno;
262 #if 0 /// UNNEEDED by elogind
263 int get_process_capeff(pid_t pid, char **capeff) {
270 p = procfs_file_alloca(pid, "status");
272 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
280 static int get_process_link_contents(const char *proc_file, char **name) {
286 r = readlink_malloc(proc_file, name);
295 int get_process_exe(pid_t pid, char **name) {
302 p = procfs_file_alloca(pid, "exe");
303 r = get_process_link_contents(p, name);
307 d = endswith(*name, " (deleted)");
314 #if 0 /// UNNEEDED by elogind
315 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
316 _cleanup_fclose_ FILE *f = NULL;
326 p = procfs_file_alloca(pid, "status");
334 FOREACH_LINE(line, f, return -errno) {
339 if (startswith(l, field)) {
341 l += strspn(l, WHITESPACE);
343 l[strcspn(l, WHITESPACE)] = 0;
345 return parse_uid(l, uid);
352 int get_process_uid(pid_t pid, uid_t *uid) {
353 return get_process_id(pid, "Uid:", uid);
356 int get_process_gid(pid_t pid, gid_t *gid) {
357 assert_cc(sizeof(uid_t) == sizeof(gid_t));
358 return get_process_id(pid, "Gid:", gid);
361 int get_process_cwd(pid_t pid, char **cwd) {
366 p = procfs_file_alloca(pid, "cwd");
368 return get_process_link_contents(p, cwd);
371 int get_process_root(pid_t pid, char **root) {
376 p = procfs_file_alloca(pid, "root");
378 return get_process_link_contents(p, root);
381 int get_process_environ(pid_t pid, char **env) {
382 _cleanup_fclose_ FILE *f = NULL;
383 _cleanup_free_ char *outcome = NULL;
386 size_t allocated = 0, sz = 0;
391 p = procfs_file_alloca(pid, "environ");
400 while ((c = fgetc(f)) != EOF) {
401 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
405 outcome[sz++] = '\n';
407 sz += cescape_char(c, outcome + sz);
411 outcome = strdup("");
423 int get_process_ppid(pid_t pid, pid_t *_ppid) {
425 _cleanup_free_ char *line = NULL;
437 p = procfs_file_alloca(pid, "stat");
438 r = read_one_line_file(p, &line);
444 /* Let's skip the pid and comm fields. The latter is enclosed
445 * in () but does not escape any () in its value, so let's
446 * skip over it manually */
448 p = strrchr(line, ')');
460 if ((long unsigned) (pid_t) ppid != ppid)
463 *_ppid = (pid_t) ppid;
469 int wait_for_terminate(pid_t pid, siginfo_t *status) {
480 if (waitid(P_PID, pid, status, WEXITED) < 0) {
494 * < 0 : wait_for_terminate() failed to get the state of the
495 * process, the process was terminated by a signal, or
496 * failed for an unknown reason.
497 * >=0 : The process terminated normally, and its exit code is
500 * That is, success is indicated by a return value of zero, and an
501 * error is indicated by a non-zero value.
503 * A warning is emitted if the process terminates abnormally,
504 * and also if it returns non-zero unless check_exit_code is true.
506 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
513 r = wait_for_terminate(pid, &status);
515 return log_warning_errno(r, "Failed to wait for %s: %m", name);
517 if (status.si_code == CLD_EXITED) {
518 if (status.si_status != 0)
519 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
520 "%s failed with error code %i.", name, status.si_status);
522 log_debug("%s succeeded.", name);
524 return status.si_status;
525 } else if (status.si_code == CLD_KILLED ||
526 status.si_code == CLD_DUMPED) {
528 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
532 log_warning("%s failed due to unknown reason.", name);
536 void sigkill_wait(pid_t *pid) {
542 if (kill(*pid, SIGKILL) > 0)
543 (void) wait_for_terminate(*pid, NULL);
546 #if 0 /// UNNEEDED by elogind
547 int kill_and_sigcont(pid_t pid, int sig) {
550 r = kill(pid, sig) < 0 ? -errno : 0;
559 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
560 _cleanup_fclose_ FILE *f = NULL;
571 path = procfs_file_alloca(pid, "environ");
573 f = fopen(path, "re");
587 for (i = 0; i < sizeof(line)-1; i++) {
591 if (_unlikely_(c == EOF)) {
601 if (memcmp(line, field, l) == 0 && line[l] == '=') {
602 value = strdup(line + l + 1);
616 bool pid_is_unwaited(pid_t pid) {
617 /* Checks whether a PID is still valid at all, including a zombie */
622 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
625 if (kill(pid, 0) >= 0)
628 return errno != ESRCH;
631 bool pid_is_alive(pid_t pid) {
634 /* Checks whether a PID is still valid and not a zombie */
639 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
642 r = get_process_state(pid);
643 if (r == -ESRCH || r == 'Z')
649 #if 0 /// UNNEEDED by elogind
650 int pid_from_same_root_fs(pid_t pid) {
656 root = procfs_file_alloca(pid, "root");
658 return files_same(root, "/proc/1/root");
662 bool is_main_thread(void) {
663 static thread_local int cached = 0;
665 if (_unlikely_(cached == 0))
666 cached = getpid() == gettid() ? 1 : -1;
671 #if 0 /// UNNEEDED by elogind
672 noreturn void freeze(void) {
674 /* Make sure nobody waits for us on a socket anymore */
675 close_all_fds(NULL, 0);
683 bool oom_score_adjust_is_valid(int oa) {
684 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
687 unsigned long personality_from_string(const char *p) {
689 /* Parse a personality specifier. We introduce our own
690 * identifiers that indicate specific ABIs, rather than just
691 * hints regarding the register size, since we want to keep
692 * things open for multiple locally supported ABIs for the
693 * same register size. We try to reuse the ABI identifiers
694 * used by libseccomp. */
696 #if defined(__x86_64__)
701 if (streq(p, "x86-64"))
704 #elif defined(__i386__)
709 #elif defined(__s390x__)
711 if (streq(p, "s390"))
714 if (streq(p, "s390x"))
717 #elif defined(__s390__)
719 if (streq(p, "s390"))
723 return PERSONALITY_INVALID;
726 const char* personality_to_string(unsigned long p) {
728 #if defined(__x86_64__)
730 if (p == PER_LINUX32)
736 #elif defined(__i386__)
741 #elif defined(__s390x__)
746 if (p == PER_LINUX32)
749 #elif defined(__s390__)
759 void valgrind_summary_hack(void) {
760 #ifdef HAVE_VALGRIND_VALGRIND_H
761 if (getpid() == 1 && RUNNING_ON_VALGRIND) {
763 pid = raw_clone(SIGCHLD, NULL);
765 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
769 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
770 (void) wait_for_terminate(pid, NULL);
776 static const char *const ioprio_class_table[] = {
777 [IOPRIO_CLASS_NONE] = "none",
778 [IOPRIO_CLASS_RT] = "realtime",
779 [IOPRIO_CLASS_BE] = "best-effort",
780 [IOPRIO_CLASS_IDLE] = "idle"
783 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
785 static const char *const sigchld_code_table[] = {
786 [CLD_EXITED] = "exited",
787 [CLD_KILLED] = "killed",
788 [CLD_DUMPED] = "dumped",
789 [CLD_TRAPPED] = "trapped",
790 [CLD_STOPPED] = "stopped",
791 [CLD_CONTINUED] = "continued",
794 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
796 static const char* const sched_policy_table[] = {
797 [SCHED_OTHER] = "other",
798 [SCHED_BATCH] = "batch",
799 [SCHED_IDLE] = "idle",
800 [SCHED_FIFO] = "fifo",
804 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);