chiark / gitweb /
Prep v230: Apply missing upstream fixes and updates (2/8) src/basic.
[elogind.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 #if 0 /// UNNEEDED by elogind
199 void rename_process(const char name[8]) {
200         assert(name);
201
202         /* This is a like a poor man's setproctitle(). It changes the
203          * comm field, argv[0], and also the glibc's internally used
204          * name of the process. For the first one a limit of 16 chars
205          * applies, to the second one usually one of 10 (i.e. length
206          * of "/sbin/init"), to the third one one of 7 (i.e. length of
207          * "systemd"). If you pass a longer string it will be
208          * truncated */
209
210         (void) prctl(PR_SET_NAME, name);
211
212         if (program_invocation_name)
213                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
214
215         if (saved_argc > 0) {
216                 int i;
217
218                 if (saved_argv[0])
219                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
220
221                 for (i = 1; i < saved_argc; i++) {
222                         if (!saved_argv[i])
223                                 break;
224
225                         memzero(saved_argv[i], strlen(saved_argv[i]));
226                 }
227         }
228 }
229 #endif // 0
230
231 int is_kernel_thread(pid_t pid) {
232         const char *p;
233         size_t count;
234         char c;
235         bool eof;
236         FILE *f;
237
238         if (pid == 0 || pid == 1) /* pid 1, and we ourselves certainly aren't a kernel thread */
239                 return 0;
240
241         assert(pid > 1);
242
243         p = procfs_file_alloca(pid, "cmdline");
244         f = fopen(p, "re");
245         if (!f) {
246                 if (errno == ENOENT)
247                         return -ESRCH;
248                 return -errno;
249         }
250
251         count = fread(&c, 1, 1, f);
252         eof = feof(f);
253         fclose(f);
254
255         /* Kernel threads have an empty cmdline */
256
257         if (count <= 0)
258                 return eof ? 1 : -errno;
259
260         return 0;
261 }
262
263 #if 0 /// UNNEEDED by elogind
264 int get_process_capeff(pid_t pid, char **capeff) {
265         const char *p;
266         int r;
267
268         assert(capeff);
269         assert(pid >= 0);
270
271         p = procfs_file_alloca(pid, "status");
272
273         r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
274         if (r == -ENOENT)
275                 return -ESRCH;
276
277         return r;
278 }
279 #endif // 0
280
281 static int get_process_link_contents(const char *proc_file, char **name) {
282         int r;
283
284         assert(proc_file);
285         assert(name);
286
287         r = readlink_malloc(proc_file, name);
288         if (r == -ENOENT)
289                 return -ESRCH;
290         if (r < 0)
291                 return r;
292
293         return 0;
294 }
295
296 int get_process_exe(pid_t pid, char **name) {
297         const char *p;
298         char *d;
299         int r;
300
301         assert(pid >= 0);
302
303         p = procfs_file_alloca(pid, "exe");
304         r = get_process_link_contents(p, name);
305         if (r < 0)
306                 return r;
307
308         d = endswith(*name, " (deleted)");
309         if (d)
310                 *d = '\0';
311
312         return 0;
313 }
314
315 #if 0 /// UNNEEDED by elogind
316 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
317         _cleanup_fclose_ FILE *f = NULL;
318         char line[LINE_MAX];
319         const char *p;
320
321         assert(field);
322         assert(uid);
323
324         if (pid == 0)
325                 return getuid();
326
327         p = procfs_file_alloca(pid, "status");
328         f = fopen(p, "re");
329         if (!f) {
330                 if (errno == ENOENT)
331                         return -ESRCH;
332                 return -errno;
333         }
334
335         FOREACH_LINE(line, f, return -errno) {
336                 char *l;
337
338                 l = strstrip(line);
339
340                 if (startswith(l, field)) {
341                         l += strlen(field);
342                         l += strspn(l, WHITESPACE);
343
344                         l[strcspn(l, WHITESPACE)] = 0;
345
346                         return parse_uid(l, uid);
347                 }
348         }
349
350         return -EIO;
351 }
352
353 int get_process_uid(pid_t pid, uid_t *uid) {
354         return get_process_id(pid, "Uid:", uid);
355 }
356
357 int get_process_gid(pid_t pid, gid_t *gid) {
358         assert_cc(sizeof(uid_t) == sizeof(gid_t));
359         return get_process_id(pid, "Gid:", gid);
360 }
361
362 int get_process_cwd(pid_t pid, char **cwd) {
363         const char *p;
364
365         assert(pid >= 0);
366
367         p = procfs_file_alloca(pid, "cwd");
368
369         return get_process_link_contents(p, cwd);
370 }
371
372 int get_process_root(pid_t pid, char **root) {
373         const char *p;
374
375         assert(pid >= 0);
376
377         p = procfs_file_alloca(pid, "root");
378
379         return get_process_link_contents(p, root);
380 }
381
382 int get_process_environ(pid_t pid, char **env) {
383         _cleanup_fclose_ FILE *f = NULL;
384         _cleanup_free_ char *outcome = NULL;
385         int c;
386         const char *p;
387         size_t allocated = 0, sz = 0;
388
389         assert(pid >= 0);
390         assert(env);
391
392         p = procfs_file_alloca(pid, "environ");
393
394         f = fopen(p, "re");
395         if (!f) {
396                 if (errno == ENOENT)
397                         return -ESRCH;
398                 return -errno;
399         }
400
401         while ((c = fgetc(f)) != EOF) {
402                 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
403                         return -ENOMEM;
404
405                 if (c == '\0')
406                         outcome[sz++] = '\n';
407                 else
408                         sz += cescape_char(c, outcome + sz);
409         }
410
411         if (!outcome) {
412                 outcome = strdup("");
413                 if (!outcome)
414                         return -ENOMEM;
415         } else
416                 outcome[sz] = '\0';
417
418         *env = outcome;
419         outcome = NULL;
420
421         return 0;
422 }
423
424 int get_process_ppid(pid_t pid, pid_t *_ppid) {
425         int r;
426         _cleanup_free_ char *line = NULL;
427         long unsigned ppid;
428         const char *p;
429
430         assert(pid >= 0);
431         assert(_ppid);
432
433         if (pid == 0) {
434                 *_ppid = getppid();
435                 return 0;
436         }
437
438         p = procfs_file_alloca(pid, "stat");
439         r = read_one_line_file(p, &line);
440         if (r == -ENOENT)
441                 return -ESRCH;
442         if (r < 0)
443                 return r;
444
445         /* Let's skip the pid and comm fields. The latter is enclosed
446          * in () but does not escape any () in its value, so let's
447          * skip over it manually */
448
449         p = strrchr(line, ')');
450         if (!p)
451                 return -EIO;
452
453         p++;
454
455         if (sscanf(p, " "
456                    "%*c "  /* state */
457                    "%lu ", /* ppid */
458                    &ppid) != 1)
459                 return -EIO;
460
461         if ((long unsigned) (pid_t) ppid != ppid)
462                 return -ERANGE;
463
464         *_ppid = (pid_t) ppid;
465
466         return 0;
467 }
468 #endif // 0
469
470 int wait_for_terminate(pid_t pid, siginfo_t *status) {
471         siginfo_t dummy;
472
473         assert(pid >= 1);
474
475         if (!status)
476                 status = &dummy;
477
478         for (;;) {
479                 zero(*status);
480
481                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
482
483                         if (errno == EINTR)
484                                 continue;
485
486                         return -errno;
487                 }
488
489                 return 0;
490         }
491 }
492
493 /*
494  * Return values:
495  * < 0 : wait_for_terminate() failed to get the state of the
496  *       process, the process was terminated by a signal, or
497  *       failed for an unknown reason.
498  * >=0 : The process terminated normally, and its exit code is
499  *       returned.
500  *
501  * That is, success is indicated by a return value of zero, and an
502  * error is indicated by a non-zero value.
503  *
504  * A warning is emitted if the process terminates abnormally,
505  * and also if it returns non-zero unless check_exit_code is true.
506  */
507 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
508         int r;
509         siginfo_t status;
510
511         assert(name);
512         assert(pid > 1);
513
514         r = wait_for_terminate(pid, &status);
515         if (r < 0)
516                 return log_warning_errno(r, "Failed to wait for %s: %m", name);
517
518         if (status.si_code == CLD_EXITED) {
519                 if (status.si_status != 0)
520                         log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
521                                  "%s failed with error code %i.", name, status.si_status);
522                 else
523                         log_debug("%s succeeded.", name);
524
525                 return status.si_status;
526         } else if (status.si_code == CLD_KILLED ||
527                    status.si_code == CLD_DUMPED) {
528
529                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
530                 return -EPROTO;
531         }
532
533         log_warning("%s failed due to unknown reason.", name);
534         return -EPROTO;
535 }
536
537 #if 0 /// UNNEEDED by elogind
538 void sigkill_wait(pid_t pid) {
539         assert(pid > 1);
540
541         if (kill(pid, SIGKILL) > 0)
542                 (void) wait_for_terminate(pid, NULL);
543 }
544
545 void sigkill_waitp(pid_t *pid) {
546         if (!pid)
547                 return;
548         if (*pid <= 1)
549                 return;
550
551         sigkill_wait(*pid);
552 }
553
554 int kill_and_sigcont(pid_t pid, int sig) {
555         int r;
556
557         r = kill(pid, sig) < 0 ? -errno : 0;
558
559         if (r >= 0)
560                 kill(pid, SIGCONT);
561
562         return r;
563 }
564 #endif // 0
565
566 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
567         _cleanup_fclose_ FILE *f = NULL;
568         char *value = NULL;
569         int r;
570         bool done = false;
571         size_t l;
572         const char *path;
573
574         assert(pid >= 0);
575         assert(field);
576         assert(_value);
577
578         path = procfs_file_alloca(pid, "environ");
579
580         f = fopen(path, "re");
581         if (!f) {
582                 if (errno == ENOENT)
583                         return -ESRCH;
584                 return -errno;
585         }
586
587         l = strlen(field);
588         r = 0;
589
590         do {
591                 char line[LINE_MAX];
592                 unsigned i;
593
594                 for (i = 0; i < sizeof(line)-1; i++) {
595                         int c;
596
597                         c = getc(f);
598                         if (_unlikely_(c == EOF)) {
599                                 done = true;
600                                 break;
601                         } else if (c == 0)
602                                 break;
603
604                         line[i] = c;
605                 }
606                 line[i] = 0;
607
608                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
609                         value = strdup(line + l + 1);
610                         if (!value)
611                                 return -ENOMEM;
612
613                         r = 1;
614                         break;
615                 }
616
617         } while (!done);
618
619         *_value = value;
620         return r;
621 }
622
623 bool pid_is_unwaited(pid_t pid) {
624         /* Checks whether a PID is still valid at all, including a zombie */
625
626         if (pid < 0)
627                 return false;
628
629         if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
630                 return true;
631
632         if (kill(pid, 0) >= 0)
633                 return true;
634
635         return errno != ESRCH;
636 }
637
638 bool pid_is_alive(pid_t pid) {
639         int r;
640
641         /* Checks whether a PID is still valid and not a zombie */
642
643         if (pid < 0)
644                 return false;
645
646         if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
647                 return true;
648
649         r = get_process_state(pid);
650         if (r == -ESRCH || r == 'Z')
651                 return false;
652
653         return true;
654 }
655
656 #if 0 /// UNNEEDED by elogind
657 int pid_from_same_root_fs(pid_t pid) {
658         const char *root;
659
660         if (pid < 0)
661                 return 0;
662
663         root = procfs_file_alloca(pid, "root");
664
665         return files_same(root, "/proc/1/root");
666 }
667 #endif // 0
668
669 bool is_main_thread(void) {
670         static thread_local int cached = 0;
671
672         if (_unlikely_(cached == 0))
673                 cached = getpid() == gettid() ? 1 : -1;
674
675         return cached > 0;
676 }
677
678 #if 0 /// UNNEEDED by elogind
679 noreturn void freeze(void) {
680
681         log_close();
682
683         /* Make sure nobody waits for us on a socket anymore */
684         close_all_fds(NULL, 0);
685
686         sync();
687
688         for (;;)
689                 pause();
690 }
691
692 bool oom_score_adjust_is_valid(int oa) {
693         return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
694 }
695
696 unsigned long personality_from_string(const char *p) {
697         int architecture;
698
699         if (!p)
700                 return PERSONALITY_INVALID;
701
702         /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
703          * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
704          * the same register size. */
705
706         architecture = architecture_from_string(p);
707         if (architecture < 0)
708                 return PERSONALITY_INVALID;
709
710         if (architecture == native_architecture())
711                 return PER_LINUX;
712 #ifdef SECONDARY_ARCHITECTURE
713         if (architecture == SECONDARY_ARCHITECTURE)
714                 return PER_LINUX32;
715 #endif
716
717         return PERSONALITY_INVALID;
718 }
719
720 const char* personality_to_string(unsigned long p) {
721         int architecture = _ARCHITECTURE_INVALID;
722
723         if (p == PER_LINUX)
724                 architecture = native_architecture();
725 #ifdef SECONDARY_ARCHITECTURE
726         else if (p == PER_LINUX32)
727                 architecture = SECONDARY_ARCHITECTURE;
728 #endif
729
730         if (architecture < 0)
731                 return NULL;
732
733         return architecture_to_string(architecture);
734 }
735
736 void valgrind_summary_hack(void) {
737 #ifdef HAVE_VALGRIND_VALGRIND_H
738         if (getpid() == 1 && RUNNING_ON_VALGRIND) {
739                 pid_t pid;
740                 pid = raw_clone(SIGCHLD, NULL);
741                 if (pid < 0)
742                         log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
743                 else if (pid == 0)
744                         exit(EXIT_SUCCESS);
745                 else {
746                         log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
747                         (void) wait_for_terminate(pid, NULL);
748                 }
749         }
750 #endif
751 }
752
753 int pid_compare_func(const void *a, const void *b) {
754         const pid_t *p = a, *q = b;
755
756         /* Suitable for usage in qsort() */
757
758         if (*p < *q)
759                 return -1;
760         if (*p > *q)
761                 return 1;
762         return 0;
763 }
764
765 static 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
772 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
773
774 static 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
783 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
784
785 static 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
793 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
794 #endif // 0