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