]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
Merge pull request #3762 from poettering/sigkill-log
[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 this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
629 * affected by a process being suspended anyway. */
630 if (r >= 0 && !IN_SET(SIGCONT, SIGKILL))
631 (void) kill(pid, SIGCONT);
632
633 return r;
634 }
635
636 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
637 _cleanup_fclose_ FILE *f = NULL;
638 char *value = NULL;
639 int r;
640 bool done = false;
641 size_t l;
642 const char *path;
643
644 assert(pid >= 0);
645 assert(field);
646 assert(_value);
647
648 path = procfs_file_alloca(pid, "environ");
649
650 f = fopen(path, "re");
651 if (!f) {
652 if (errno == ENOENT)
653 return -ESRCH;
654 return -errno;
655 }
656
657 l = strlen(field);
658 r = 0;
659
660 do {
661 char line[LINE_MAX];
662 unsigned i;
663
664 for (i = 0; i < sizeof(line)-1; i++) {
665 int c;
666
667 c = getc(f);
668 if (_unlikely_(c == EOF)) {
669 done = true;
670 break;
671 } else if (c == 0)
672 break;
673
674 line[i] = c;
675 }
676 line[i] = 0;
677
678 if (memcmp(line, field, l) == 0 && line[l] == '=') {
679 value = strdup(line + l + 1);
680 if (!value)
681 return -ENOMEM;
682
683 r = 1;
684 break;
685 }
686
687 } while (!done);
688
689 *_value = value;
690 return r;
691 }
692
693 bool pid_is_unwaited(pid_t pid) {
694 /* Checks whether a PID is still valid at all, including a zombie */
695
696 if (pid < 0)
697 return false;
698
699 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
700 return true;
701
702 if (kill(pid, 0) >= 0)
703 return true;
704
705 return errno != ESRCH;
706 }
707
708 bool pid_is_alive(pid_t pid) {
709 int r;
710
711 /* Checks whether a PID is still valid and not a zombie */
712
713 if (pid < 0)
714 return false;
715
716 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
717 return true;
718
719 r = get_process_state(pid);
720 if (r == -ESRCH || r == 'Z')
721 return false;
722
723 return true;
724 }
725
726 int pid_from_same_root_fs(pid_t pid) {
727 const char *root;
728
729 if (pid < 0)
730 return 0;
731
732 root = procfs_file_alloca(pid, "root");
733
734 return files_same(root, "/proc/1/root");
735 }
736
737 bool is_main_thread(void) {
738 static thread_local int cached = 0;
739
740 if (_unlikely_(cached == 0))
741 cached = getpid() == gettid() ? 1 : -1;
742
743 return cached > 0;
744 }
745
746 noreturn void freeze(void) {
747
748 log_close();
749
750 /* Make sure nobody waits for us on a socket anymore */
751 close_all_fds(NULL, 0);
752
753 sync();
754
755 for (;;)
756 pause();
757 }
758
759 bool oom_score_adjust_is_valid(int oa) {
760 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
761 }
762
763 unsigned long personality_from_string(const char *p) {
764 int architecture;
765
766 if (!p)
767 return PERSONALITY_INVALID;
768
769 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
770 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
771 * the same register size. */
772
773 architecture = architecture_from_string(p);
774 if (architecture < 0)
775 return PERSONALITY_INVALID;
776
777 if (architecture == native_architecture())
778 return PER_LINUX;
779 #ifdef SECONDARY_ARCHITECTURE
780 if (architecture == SECONDARY_ARCHITECTURE)
781 return PER_LINUX32;
782 #endif
783
784 return PERSONALITY_INVALID;
785 }
786
787 const char* personality_to_string(unsigned long p) {
788 int architecture = _ARCHITECTURE_INVALID;
789
790 if (p == PER_LINUX)
791 architecture = native_architecture();
792 #ifdef SECONDARY_ARCHITECTURE
793 else if (p == PER_LINUX32)
794 architecture = SECONDARY_ARCHITECTURE;
795 #endif
796
797 if (architecture < 0)
798 return NULL;
799
800 return architecture_to_string(architecture);
801 }
802
803 void valgrind_summary_hack(void) {
804 #ifdef HAVE_VALGRIND_VALGRIND_H
805 if (getpid() == 1 && RUNNING_ON_VALGRIND) {
806 pid_t pid;
807 pid = raw_clone(SIGCHLD);
808 if (pid < 0)
809 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
810 else if (pid == 0)
811 exit(EXIT_SUCCESS);
812 else {
813 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
814 (void) wait_for_terminate(pid, NULL);
815 }
816 }
817 #endif
818 }
819
820 int pid_compare_func(const void *a, const void *b) {
821 const pid_t *p = a, *q = b;
822
823 /* Suitable for usage in qsort() */
824
825 if (*p < *q)
826 return -1;
827 if (*p > *q)
828 return 1;
829 return 0;
830 }
831
832 static const char *const ioprio_class_table[] = {
833 [IOPRIO_CLASS_NONE] = "none",
834 [IOPRIO_CLASS_RT] = "realtime",
835 [IOPRIO_CLASS_BE] = "best-effort",
836 [IOPRIO_CLASS_IDLE] = "idle"
837 };
838
839 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
840
841 static const char *const sigchld_code_table[] = {
842 [CLD_EXITED] = "exited",
843 [CLD_KILLED] = "killed",
844 [CLD_DUMPED] = "dumped",
845 [CLD_TRAPPED] = "trapped",
846 [CLD_STOPPED] = "stopped",
847 [CLD_CONTINUED] = "continued",
848 };
849
850 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
851
852 static const char* const sched_policy_table[] = {
853 [SCHED_OTHER] = "other",
854 [SCHED_BATCH] = "batch",
855 [SCHED_IDLE] = "idle",
856 [SCHED_FIFO] = "fifo",
857 [SCHED_RR] = "rr"
858 };
859
860 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);