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