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