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