]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
3afb5e0a409565355350451fe56f28f28968df27
[thirdparty/systemd.git] / src / basic / process-util.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
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.
10
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.
15
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/>.
18 ***/
19
20 #include <ctype.h>
21 #include <errno.h>
22 #include <limits.h>
23 #include <linux/oom.h>
24 #include <sched.h>
25 #include <signal.h>
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/personality.h>
31 #include <sys/prctl.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <syslog.h>
35 #include <unistd.h>
36 #ifdef HAVE_VALGRIND_VALGRIND_H
37 #include <valgrind/valgrind.h>
38 #endif
39
40 #include "alloc-util.h"
41 #include "architecture.h"
42 #include "escape.h"
43 #include "fd-util.h"
44 #include "fileio.h"
45 #include "fs-util.h"
46 #include "ioprio.h"
47 #include "log.h"
48 #include "macro.h"
49 #include "missing.h"
50 #include "process-util.h"
51 #include "raw-clone.h"
52 #include "signal-util.h"
53 #include "stat-util.h"
54 #include "string-table.h"
55 #include "string-util.h"
56 #include "user-util.h"
57 #include "util.h"
58
59 int get_process_state(pid_t pid) {
60 const char *p;
61 char state;
62 int r;
63 _cleanup_free_ char *line = NULL;
64
65 assert(pid >= 0);
66
67 p = procfs_file_alloca(pid, "stat");
68
69 r = read_one_line_file(p, &line);
70 if (r == -ENOENT)
71 return -ESRCH;
72 if (r < 0)
73 return r;
74
75 p = strrchr(line, ')');
76 if (!p)
77 return -EIO;
78
79 p++;
80
81 if (sscanf(p, " %c", &state) != 1)
82 return -EIO;
83
84 return (unsigned char) state;
85 }
86
87 int get_process_comm(pid_t pid, char **name) {
88 const char *p;
89 int r;
90
91 assert(name);
92 assert(pid >= 0);
93
94 p = procfs_file_alloca(pid, "comm");
95
96 r = read_one_line_file(p, name);
97 if (r == -ENOENT)
98 return -ESRCH;
99
100 return r;
101 }
102
103 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
104 _cleanup_fclose_ FILE *f = NULL;
105 bool space = false;
106 char *r = NULL, *k;
107 const char *p;
108 int c;
109
110 assert(line);
111 assert(pid >= 0);
112
113 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
114 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
115 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
116 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
117 * command line that resolves to the empty string will return the "comm" name of the process instead.
118 *
119 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
120 * comm_fallback is false). */
121
122 p = procfs_file_alloca(pid, "cmdline");
123
124 f = fopen(p, "re");
125 if (!f) {
126 if (errno == ENOENT)
127 return -ESRCH;
128 return -errno;
129 }
130
131 if (max_length == 1) {
132
133 /* If there's only room for one byte, return the empty string */
134 r = new0(char, 1);
135 if (!r)
136 return -ENOMEM;
137
138 *line = r;
139 return 0;
140
141 } else if (max_length == 0) {
142 size_t len = 0, allocated = 0;
143
144 while ((c = getc(f)) != EOF) {
145
146 if (!GREEDY_REALLOC(r, allocated, len+3)) {
147 free(r);
148 return -ENOMEM;
149 }
150
151 if (isprint(c)) {
152 if (space) {
153 r[len++] = ' ';
154 space = false;
155 }
156
157 r[len++] = c;
158 } else if (len > 0)
159 space = true;
160 }
161
162 if (len > 0)
163 r[len] = 0;
164 else
165 r = mfree(r);
166
167 } else {
168 bool dotdotdot = false;
169 size_t left;
170
171 r = new(char, max_length);
172 if (!r)
173 return -ENOMEM;
174
175 k = r;
176 left = max_length;
177 while ((c = getc(f)) != EOF) {
178
179 if (isprint(c)) {
180
181 if (space) {
182 if (left <= 2) {
183 dotdotdot = true;
184 break;
185 }
186
187 *(k++) = ' ';
188 left--;
189 space = false;
190 }
191
192 if (left <= 1) {
193 dotdotdot = true;
194 break;
195 }
196
197 *(k++) = (char) c;
198 left--;
199 } else if (k > r)
200 space = true;
201 }
202
203 if (dotdotdot) {
204 if (max_length <= 4) {
205 k = r;
206 left = max_length;
207 } else {
208 k = r + max_length - 4;
209 left = 4;
210
211 /* Eat up final spaces */
212 while (k > r && isspace(k[-1])) {
213 k--;
214 left++;
215 }
216 }
217
218 strncpy(k, "...", left-1);
219 k[left-1] = 0;
220 } else
221 *k = 0;
222 }
223
224 /* Kernel threads have no argv[] */
225 if (isempty(r)) {
226 _cleanup_free_ char *t = NULL;
227 int h;
228
229 free(r);
230
231 if (!comm_fallback)
232 return -ENOENT;
233
234 h = get_process_comm(pid, &t);
235 if (h < 0)
236 return h;
237
238 if (max_length == 0)
239 r = strjoin("[", t, "]", NULL);
240 else {
241 size_t l;
242
243 l = strlen(t);
244
245 if (l + 3 <= max_length)
246 r = strjoin("[", t, "]", NULL);
247 else if (max_length <= 6) {
248
249 r = new(char, max_length);
250 if (!r)
251 return -ENOMEM;
252
253 memcpy(r, "[...]", max_length-1);
254 r[max_length-1] = 0;
255 } else {
256 char *e;
257
258 t[max_length - 6] = 0;
259
260 /* Chop off final spaces */
261 e = strchr(t, 0);
262 while (e > t && isspace(e[-1]))
263 e--;
264 *e = 0;
265
266 r = strjoin("[", t, "...]", NULL);
267 }
268 }
269 if (!r)
270 return -ENOMEM;
271 }
272
273 *line = r;
274 return 0;
275 }
276
277 void rename_process(const char name[8]) {
278 assert(name);
279
280 /* This is a like a poor man's setproctitle(). It changes the
281 * comm field, argv[0], and also the glibc's internally used
282 * name of the process. For the first one a limit of 16 chars
283 * applies, to the second one usually one of 10 (i.e. length
284 * of "/sbin/init"), to the third one one of 7 (i.e. length of
285 * "systemd"). If you pass a longer string it will be
286 * truncated */
287
288 (void) prctl(PR_SET_NAME, name);
289
290 if (program_invocation_name)
291 strncpy(program_invocation_name, name, strlen(program_invocation_name));
292
293 if (saved_argc > 0) {
294 int i;
295
296 if (saved_argv[0])
297 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
298
299 for (i = 1; i < saved_argc; i++) {
300 if (!saved_argv[i])
301 break;
302
303 memzero(saved_argv[i], strlen(saved_argv[i]));
304 }
305 }
306 }
307
308 int is_kernel_thread(pid_t pid) {
309 const char *p;
310 size_t count;
311 char c;
312 bool eof;
313 FILE *f;
314
315 if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
316 return 0;
317
318 assert(pid > 1);
319
320 p = procfs_file_alloca(pid, "cmdline");
321 f = fopen(p, "re");
322 if (!f) {
323 if (errno == ENOENT)
324 return -ESRCH;
325 return -errno;
326 }
327
328 count = fread(&c, 1, 1, f);
329 eof = feof(f);
330 fclose(f);
331
332 /* Kernel threads have an empty cmdline */
333
334 if (count <= 0)
335 return eof ? 1 : -errno;
336
337 return 0;
338 }
339
340 int get_process_capeff(pid_t pid, char **capeff) {
341 const char *p;
342 int r;
343
344 assert(capeff);
345 assert(pid >= 0);
346
347 p = procfs_file_alloca(pid, "status");
348
349 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
350 if (r == -ENOENT)
351 return -ESRCH;
352
353 return r;
354 }
355
356 static int get_process_link_contents(const char *proc_file, char **name) {
357 int r;
358
359 assert(proc_file);
360 assert(name);
361
362 r = readlink_malloc(proc_file, name);
363 if (r == -ENOENT)
364 return -ESRCH;
365 if (r < 0)
366 return r;
367
368 return 0;
369 }
370
371 int get_process_exe(pid_t pid, char **name) {
372 const char *p;
373 char *d;
374 int r;
375
376 assert(pid >= 0);
377
378 p = procfs_file_alloca(pid, "exe");
379 r = get_process_link_contents(p, name);
380 if (r < 0)
381 return r;
382
383 d = endswith(*name, " (deleted)");
384 if (d)
385 *d = '\0';
386
387 return 0;
388 }
389
390 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
391 _cleanup_fclose_ FILE *f = NULL;
392 char line[LINE_MAX];
393 const char *p;
394
395 assert(field);
396 assert(uid);
397
398 p = procfs_file_alloca(pid, "status");
399 f = fopen(p, "re");
400 if (!f) {
401 if (errno == ENOENT)
402 return -ESRCH;
403 return -errno;
404 }
405
406 FOREACH_LINE(line, f, return -errno) {
407 char *l;
408
409 l = strstrip(line);
410
411 if (startswith(l, field)) {
412 l += strlen(field);
413 l += strspn(l, WHITESPACE);
414
415 l[strcspn(l, WHITESPACE)] = 0;
416
417 return parse_uid(l, uid);
418 }
419 }
420
421 return -EIO;
422 }
423
424 int get_process_uid(pid_t pid, uid_t *uid) {
425 return get_process_id(pid, "Uid:", uid);
426 }
427
428 int get_process_gid(pid_t pid, gid_t *gid) {
429 assert_cc(sizeof(uid_t) == sizeof(gid_t));
430 return get_process_id(pid, "Gid:", gid);
431 }
432
433 int get_process_cwd(pid_t pid, char **cwd) {
434 const char *p;
435
436 assert(pid >= 0);
437
438 p = procfs_file_alloca(pid, "cwd");
439
440 return get_process_link_contents(p, cwd);
441 }
442
443 int get_process_root(pid_t pid, char **root) {
444 const char *p;
445
446 assert(pid >= 0);
447
448 p = procfs_file_alloca(pid, "root");
449
450 return get_process_link_contents(p, root);
451 }
452
453 int get_process_environ(pid_t pid, char **env) {
454 _cleanup_fclose_ FILE *f = NULL;
455 _cleanup_free_ char *outcome = NULL;
456 int c;
457 const char *p;
458 size_t allocated = 0, sz = 0;
459
460 assert(pid >= 0);
461 assert(env);
462
463 p = procfs_file_alloca(pid, "environ");
464
465 f = fopen(p, "re");
466 if (!f) {
467 if (errno == ENOENT)
468 return -ESRCH;
469 return -errno;
470 }
471
472 while ((c = fgetc(f)) != EOF) {
473 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
474 return -ENOMEM;
475
476 if (c == '\0')
477 outcome[sz++] = '\n';
478 else
479 sz += cescape_char(c, outcome + sz);
480 }
481
482 if (!outcome) {
483 outcome = strdup("");
484 if (!outcome)
485 return -ENOMEM;
486 } else
487 outcome[sz] = '\0';
488
489 *env = outcome;
490 outcome = NULL;
491
492 return 0;
493 }
494
495 int get_process_ppid(pid_t pid, pid_t *_ppid) {
496 int r;
497 _cleanup_free_ char *line = NULL;
498 long unsigned ppid;
499 const char *p;
500
501 assert(pid >= 0);
502 assert(_ppid);
503
504 if (pid == 0) {
505 *_ppid = getppid();
506 return 0;
507 }
508
509 p = procfs_file_alloca(pid, "stat");
510 r = read_one_line_file(p, &line);
511 if (r == -ENOENT)
512 return -ESRCH;
513 if (r < 0)
514 return r;
515
516 /* Let's skip the pid and comm fields. The latter is enclosed
517 * in () but does not escape any () in its value, so let's
518 * skip over it manually */
519
520 p = strrchr(line, ')');
521 if (!p)
522 return -EIO;
523
524 p++;
525
526 if (sscanf(p, " "
527 "%*c " /* state */
528 "%lu ", /* ppid */
529 &ppid) != 1)
530 return -EIO;
531
532 if ((long unsigned) (pid_t) ppid != ppid)
533 return -ERANGE;
534
535 *_ppid = (pid_t) ppid;
536
537 return 0;
538 }
539
540 int wait_for_terminate(pid_t pid, siginfo_t *status) {
541 siginfo_t dummy;
542
543 assert(pid >= 1);
544
545 if (!status)
546 status = &dummy;
547
548 for (;;) {
549 zero(*status);
550
551 if (waitid(P_PID, pid, status, WEXITED) < 0) {
552
553 if (errno == EINTR)
554 continue;
555
556 return negative_errno();
557 }
558
559 return 0;
560 }
561 }
562
563 /*
564 * Return values:
565 * < 0 : wait_for_terminate() failed to get the state of the
566 * process, the process was terminated by a signal, or
567 * failed for an unknown reason.
568 * >=0 : The process terminated normally, and its exit code is
569 * returned.
570 *
571 * That is, success is indicated by a return value of zero, and an
572 * error is indicated by a non-zero value.
573 *
574 * A warning is emitted if the process terminates abnormally,
575 * and also if it returns non-zero unless check_exit_code is true.
576 */
577 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
578 int r;
579 siginfo_t status;
580
581 assert(name);
582 assert(pid > 1);
583
584 r = wait_for_terminate(pid, &status);
585 if (r < 0)
586 return log_warning_errno(r, "Failed to wait for %s: %m", name);
587
588 if (status.si_code == CLD_EXITED) {
589 if (status.si_status != 0)
590 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
591 "%s failed with error code %i.", name, status.si_status);
592 else
593 log_debug("%s succeeded.", name);
594
595 return status.si_status;
596 } else if (status.si_code == CLD_KILLED ||
597 status.si_code == CLD_DUMPED) {
598
599 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
600 return -EPROTO;
601 }
602
603 log_warning("%s failed due to unknown reason.", name);
604 return -EPROTO;
605 }
606
607 void sigkill_wait(pid_t pid) {
608 assert(pid > 1);
609
610 if (kill(pid, SIGKILL) > 0)
611 (void) wait_for_terminate(pid, NULL);
612 }
613
614 void sigkill_waitp(pid_t *pid) {
615 if (!pid)
616 return;
617 if (*pid <= 1)
618 return;
619
620 sigkill_wait(*pid);
621 }
622
623 int kill_and_sigcont(pid_t pid, int sig) {
624 int r;
625
626 r = kill(pid, sig) < 0 ? -errno : 0;
627
628 if (r >= 0)
629 kill(pid, SIGCONT);
630
631 return r;
632 }
633
634 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
635 _cleanup_fclose_ FILE *f = NULL;
636 char *value = NULL;
637 int r;
638 bool done = false;
639 size_t l;
640 const char *path;
641
642 assert(pid >= 0);
643 assert(field);
644 assert(_value);
645
646 path = procfs_file_alloca(pid, "environ");
647
648 f = fopen(path, "re");
649 if (!f) {
650 if (errno == ENOENT)
651 return -ESRCH;
652 return -errno;
653 }
654
655 l = strlen(field);
656 r = 0;
657
658 do {
659 char line[LINE_MAX];
660 unsigned i;
661
662 for (i = 0; i < sizeof(line)-1; i++) {
663 int c;
664
665 c = getc(f);
666 if (_unlikely_(c == EOF)) {
667 done = true;
668 break;
669 } else if (c == 0)
670 break;
671
672 line[i] = c;
673 }
674 line[i] = 0;
675
676 if (memcmp(line, field, l) == 0 && line[l] == '=') {
677 value = strdup(line + l + 1);
678 if (!value)
679 return -ENOMEM;
680
681 r = 1;
682 break;
683 }
684
685 } while (!done);
686
687 *_value = value;
688 return r;
689 }
690
691 bool pid_is_unwaited(pid_t pid) {
692 /* Checks whether a PID is still valid at all, including a zombie */
693
694 if (pid < 0)
695 return false;
696
697 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
698 return true;
699
700 if (kill(pid, 0) >= 0)
701 return true;
702
703 return errno != ESRCH;
704 }
705
706 bool pid_is_alive(pid_t pid) {
707 int r;
708
709 /* Checks whether a PID is still valid and not a zombie */
710
711 if (pid < 0)
712 return false;
713
714 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
715 return true;
716
717 r = get_process_state(pid);
718 if (r == -ESRCH || r == 'Z')
719 return false;
720
721 return true;
722 }
723
724 int pid_from_same_root_fs(pid_t pid) {
725 const char *root;
726
727 if (pid < 0)
728 return 0;
729
730 root = procfs_file_alloca(pid, "root");
731
732 return files_same(root, "/proc/1/root");
733 }
734
735 bool is_main_thread(void) {
736 static thread_local int cached = 0;
737
738 if (_unlikely_(cached == 0))
739 cached = getpid() == gettid() ? 1 : -1;
740
741 return cached > 0;
742 }
743
744 noreturn void freeze(void) {
745
746 log_close();
747
748 /* Make sure nobody waits for us on a socket anymore */
749 close_all_fds(NULL, 0);
750
751 sync();
752
753 for (;;)
754 pause();
755 }
756
757 bool oom_score_adjust_is_valid(int oa) {
758 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
759 }
760
761 unsigned long personality_from_string(const char *p) {
762 int architecture;
763
764 if (!p)
765 return PERSONALITY_INVALID;
766
767 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
768 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
769 * the same register size. */
770
771 architecture = architecture_from_string(p);
772 if (architecture < 0)
773 return PERSONALITY_INVALID;
774
775 if (architecture == native_architecture())
776 return PER_LINUX;
777 #ifdef SECONDARY_ARCHITECTURE
778 if (architecture == SECONDARY_ARCHITECTURE)
779 return PER_LINUX32;
780 #endif
781
782 return PERSONALITY_INVALID;
783 }
784
785 const char* personality_to_string(unsigned long p) {
786 int architecture = _ARCHITECTURE_INVALID;
787
788 if (p == PER_LINUX)
789 architecture = native_architecture();
790 #ifdef SECONDARY_ARCHITECTURE
791 else if (p == PER_LINUX32)
792 architecture = SECONDARY_ARCHITECTURE;
793 #endif
794
795 if (architecture < 0)
796 return NULL;
797
798 return architecture_to_string(architecture);
799 }
800
801 void valgrind_summary_hack(void) {
802 #ifdef HAVE_VALGRIND_VALGRIND_H
803 if (getpid() == 1 && RUNNING_ON_VALGRIND) {
804 pid_t pid;
805 pid = raw_clone(SIGCHLD);
806 if (pid < 0)
807 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
808 else if (pid == 0)
809 exit(EXIT_SUCCESS);
810 else {
811 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
812 (void) wait_for_terminate(pid, NULL);
813 }
814 }
815 #endif
816 }
817
818 int pid_compare_func(const void *a, const void *b) {
819 const pid_t *p = a, *q = b;
820
821 /* Suitable for usage in qsort() */
822
823 if (*p < *q)
824 return -1;
825 if (*p > *q)
826 return 1;
827 return 0;
828 }
829
830 static const char *const ioprio_class_table[] = {
831 [IOPRIO_CLASS_NONE] = "none",
832 [IOPRIO_CLASS_RT] = "realtime",
833 [IOPRIO_CLASS_BE] = "best-effort",
834 [IOPRIO_CLASS_IDLE] = "idle"
835 };
836
837 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
838
839 static const char *const sigchld_code_table[] = {
840 [CLD_EXITED] = "exited",
841 [CLD_KILLED] = "killed",
842 [CLD_DUMPED] = "dumped",
843 [CLD_TRAPPED] = "trapped",
844 [CLD_STOPPED] = "stopped",
845 [CLD_CONTINUED] = "continued",
846 };
847
848 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
849
850 static const char* const sched_policy_table[] = {
851 [SCHED_OTHER] = "other",
852 [SCHED_BATCH] = "batch",
853 [SCHED_IDLE] = "idle",
854 [SCHED_FIFO] = "fifo",
855 [SCHED_RR] = "rr"
856 };
857
858 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);