]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[thirdparty/systemd.git] / src / basic / process-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <limits.h>
6 #include <linux/oom.h>
7 #include <sched.h>
8 #include <signal.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdio_ext.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/mman.h>
15 #include <sys/mount.h>
16 #include <sys/personality.h>
17 #include <sys/prctl.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <syslog.h>
21 #include <unistd.h>
22 #if HAVE_VALGRIND_VALGRIND_H
23 #include <valgrind/valgrind.h>
24 #endif
25
26 #include "alloc-util.h"
27 #include "architecture.h"
28 #include "escape.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "ioprio.h"
33 #include "log.h"
34 #include "macro.h"
35 #include "missing.h"
36 #include "process-util.h"
37 #include "raw-clone.h"
38 #include "rlimit-util.h"
39 #include "signal-util.h"
40 #include "stat-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
43 #include "terminal-util.h"
44 #include "user-util.h"
45 #include "util.h"
46
47 int get_process_state(pid_t pid) {
48 const char *p;
49 char state;
50 int r;
51 _cleanup_free_ char *line = NULL;
52
53 assert(pid >= 0);
54
55 p = procfs_file_alloca(pid, "stat");
56
57 r = read_one_line_file(p, &line);
58 if (r == -ENOENT)
59 return -ESRCH;
60 if (r < 0)
61 return r;
62
63 p = strrchr(line, ')');
64 if (!p)
65 return -EIO;
66
67 p++;
68
69 if (sscanf(p, " %c", &state) != 1)
70 return -EIO;
71
72 return (unsigned char) state;
73 }
74
75 int get_process_comm(pid_t pid, char **ret) {
76 _cleanup_free_ char *escaped = NULL, *comm = NULL;
77 const char *p;
78 int r;
79
80 assert(ret);
81 assert(pid >= 0);
82
83 escaped = new(char, TASK_COMM_LEN);
84 if (!escaped)
85 return -ENOMEM;
86
87 p = procfs_file_alloca(pid, "comm");
88
89 r = read_one_line_file(p, &comm);
90 if (r == -ENOENT)
91 return -ESRCH;
92 if (r < 0)
93 return r;
94
95 /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
96 cellescape(escaped, TASK_COMM_LEN, comm);
97
98 *ret = TAKE_PTR(escaped);
99 return 0;
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 *k;
106 _cleanup_free_ char *ans = NULL;
107 const char *p;
108 int c;
109
110 assert(line);
111 assert(pid >= 0);
112
113 /* Retrieves a process' command line. Replaces unprintable characters while doing so by whitespace (coalescing
114 * multiple sequential ones into one). If max_length is != 0 will return a string of the specified size at most
115 * (the trailing NUL byte does count towards the length here!), abbreviated with a "..." ellipsis. If
116 * comm_fallback is true and the process has no command line set (the case for kernel threads), or has a
117 * command line that resolves to the empty string will return the "comm" name of the process instead.
118 *
119 * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and
120 * comm_fallback is false). Returns 0 and sets *line otherwise. */
121
122 p = procfs_file_alloca(pid, "cmdline");
123
124 f = fopen(p, "re");
125 if (!f) {
126 if (errno == ENOENT)
127 return -ESRCH;
128 return -errno;
129 }
130
131 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
132
133 if (max_length == 0) {
134 /* This is supposed to be a safety guard against runaway command lines. */
135 long l = sysconf(_SC_ARG_MAX);
136 assert(l > 0);
137 max_length = l;
138 }
139
140 if (max_length == 1) {
141
142 /* If there's only room for one byte, return the empty string */
143 ans = new0(char, 1);
144 if (!ans)
145 return -ENOMEM;
146
147 *line = TAKE_PTR(ans);
148 return 0;
149
150 } else {
151 bool dotdotdot = false;
152 size_t left;
153
154 ans = new(char, max_length);
155 if (!ans)
156 return -ENOMEM;
157
158 k = ans;
159 left = max_length;
160 while ((c = getc(f)) != EOF) {
161
162 if (isprint(c)) {
163
164 if (space) {
165 if (left <= 2) {
166 dotdotdot = true;
167 break;
168 }
169
170 *(k++) = ' ';
171 left--;
172 space = false;
173 }
174
175 if (left <= 1) {
176 dotdotdot = true;
177 break;
178 }
179
180 *(k++) = (char) c;
181 left--;
182 } else if (k > ans)
183 space = true;
184 }
185
186 if (dotdotdot) {
187 if (max_length <= 4) {
188 k = ans;
189 left = max_length;
190 } else {
191 k = ans + max_length - 4;
192 left = 4;
193
194 /* Eat up final spaces */
195 while (k > ans && isspace(k[-1])) {
196 k--;
197 left++;
198 }
199 }
200
201 strncpy(k, "...", left-1);
202 k[left-1] = 0;
203 } else
204 *k = 0;
205 }
206
207 /* Kernel threads have no argv[] */
208 if (isempty(ans)) {
209 _cleanup_free_ char *t = NULL;
210 int h;
211
212 ans = mfree(ans);
213
214 if (!comm_fallback)
215 return -ENOENT;
216
217 h = get_process_comm(pid, &t);
218 if (h < 0)
219 return h;
220
221 size_t l = strlen(t);
222
223 if (l + 3 <= max_length) {
224 ans = strjoin("[", t, "]");
225 if (!ans)
226 return -ENOMEM;
227
228 } else if (max_length <= 6) {
229 ans = new(char, max_length);
230 if (!ans)
231 return -ENOMEM;
232
233 memcpy(ans, "[...]", max_length-1);
234 ans[max_length-1] = 0;
235 } else {
236 t[max_length - 6] = 0;
237
238 /* Chop off final spaces */
239 delete_trailing_chars(t, WHITESPACE);
240
241 ans = strjoin("[", t, "...]");
242 if (!ans)
243 return -ENOMEM;
244 }
245
246 *line = TAKE_PTR(ans);
247 return 0;
248 }
249
250 k = realloc(ans, strlen(ans) + 1);
251 if (!k)
252 return -ENOMEM;
253
254 ans = NULL;
255 *line = k;
256
257 return 0;
258 }
259
260 int rename_process(const char name[]) {
261 static size_t mm_size = 0;
262 static char *mm = NULL;
263 bool truncated = false;
264 size_t l;
265
266 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
267 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
268 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
269 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
270 * truncated.
271 *
272 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
273
274 if (isempty(name))
275 return -EINVAL; /* let's not confuse users unnecessarily with an empty name */
276
277 if (!is_main_thread())
278 return -EPERM; /* Let's not allow setting the process name from other threads than the main one, as we
279 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
280 * process name that isn't correct on any other threads */
281
282 l = strlen(name);
283
284 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
285 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
286 if (prctl(PR_SET_NAME, name) < 0)
287 log_debug_errno(errno, "PR_SET_NAME failed: %m");
288 if (l >= TASK_COMM_LEN) /* Linux process names can be 15 chars at max */
289 truncated = true;
290
291 /* Second step, change glibc's ID of the process name. */
292 if (program_invocation_name) {
293 size_t k;
294
295 k = strlen(program_invocation_name);
296 strncpy(program_invocation_name, name, k);
297 if (l > k)
298 truncated = true;
299 }
300
301 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
302 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
303 * the end. This is the best option for changing /proc/self/cmdline. */
304
305 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
306 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
307 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
308 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
309 * mmap() is not. */
310 if (geteuid() != 0)
311 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
312 else if (mm_size < l+1) {
313 size_t nn_size;
314 char *nn;
315
316 nn_size = PAGE_ALIGN(l+1);
317 nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
318 if (nn == MAP_FAILED) {
319 log_debug_errno(errno, "mmap() failed: %m");
320 goto use_saved_argv;
321 }
322
323 strncpy(nn, name, nn_size);
324
325 /* Now, let's tell the kernel about this new memory */
326 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
327 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
328 * below the desired start address, in which case the kernel may have kicked this back due
329 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
330 * action). The proper solution would be to have a prctl() API that could set both start+end
331 * simultaneously, or at least let us query the existing address to anticipate this condition
332 * and respond accordingly. For now, we can only guess at the cause of this failure and try
333 * a workaround--which will briefly expand the arg space to something potentially huge before
334 * resizing it to what we want. */
335 log_debug_errno(errno, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
336
337 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) {
338 log_debug_errno(errno, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
339 (void) munmap(nn, nn_size);
340 goto use_saved_argv;
341 }
342
343 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
344 log_debug_errno(errno, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
345 goto use_saved_argv;
346 }
347 } else {
348 /* And update the end pointer to the new end, too. If this fails, we don't really know what
349 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
350 * and continue. */
351 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0)
352 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
353 }
354
355 if (mm)
356 (void) munmap(mm, mm_size);
357
358 mm = nn;
359 mm_size = nn_size;
360 } else {
361 strncpy(mm, name, mm_size);
362
363 /* Update the end pointer, continuing regardless of any failure. */
364 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0)
365 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
366 }
367
368 use_saved_argv:
369 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
370 * it still looks here */
371
372 if (saved_argc > 0) {
373 int i;
374
375 if (saved_argv[0]) {
376 size_t k;
377
378 k = strlen(saved_argv[0]);
379 strncpy(saved_argv[0], name, k);
380 if (l > k)
381 truncated = true;
382 }
383
384 for (i = 1; i < saved_argc; i++) {
385 if (!saved_argv[i])
386 break;
387
388 memzero(saved_argv[i], strlen(saved_argv[i]));
389 }
390 }
391
392 return !truncated;
393 }
394
395 int is_kernel_thread(pid_t pid) {
396 _cleanup_free_ char *line = NULL;
397 unsigned long long flags;
398 size_t l, i;
399 const char *p;
400 char *q;
401 int r;
402
403 if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
404 return 0;
405 if (!pid_is_valid(pid))
406 return -EINVAL;
407
408 p = procfs_file_alloca(pid, "stat");
409 r = read_one_line_file(p, &line);
410 if (r == -ENOENT)
411 return -ESRCH;
412 if (r < 0)
413 return r;
414
415 /* Skip past the comm field */
416 q = strrchr(line, ')');
417 if (!q)
418 return -EINVAL;
419 q++;
420
421 /* Skip 6 fields to reach the flags field */
422 for (i = 0; i < 6; i++) {
423 l = strspn(q, WHITESPACE);
424 if (l < 1)
425 return -EINVAL;
426 q += l;
427
428 l = strcspn(q, WHITESPACE);
429 if (l < 1)
430 return -EINVAL;
431 q += l;
432 }
433
434 /* Skip preceding whitespace */
435 l = strspn(q, WHITESPACE);
436 if (l < 1)
437 return -EINVAL;
438 q += l;
439
440 /* Truncate the rest */
441 l = strcspn(q, WHITESPACE);
442 if (l < 1)
443 return -EINVAL;
444 q[l] = 0;
445
446 r = safe_atollu(q, &flags);
447 if (r < 0)
448 return r;
449
450 return !!(flags & PF_KTHREAD);
451 }
452
453 int get_process_capeff(pid_t pid, char **capeff) {
454 const char *p;
455 int r;
456
457 assert(capeff);
458 assert(pid >= 0);
459
460 p = procfs_file_alloca(pid, "status");
461
462 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
463 if (r == -ENOENT)
464 return -ESRCH;
465
466 return r;
467 }
468
469 static int get_process_link_contents(const char *proc_file, char **name) {
470 int r;
471
472 assert(proc_file);
473 assert(name);
474
475 r = readlink_malloc(proc_file, name);
476 if (r == -ENOENT)
477 return -ESRCH;
478 if (r < 0)
479 return r;
480
481 return 0;
482 }
483
484 int get_process_exe(pid_t pid, char **name) {
485 const char *p;
486 char *d;
487 int r;
488
489 assert(pid >= 0);
490
491 p = procfs_file_alloca(pid, "exe");
492 r = get_process_link_contents(p, name);
493 if (r < 0)
494 return r;
495
496 d = endswith(*name, " (deleted)");
497 if (d)
498 *d = '\0';
499
500 return 0;
501 }
502
503 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
504 _cleanup_fclose_ FILE *f = NULL;
505 const char *p;
506 int r;
507
508 assert(field);
509 assert(uid);
510
511 if (pid < 0)
512 return -EINVAL;
513
514 p = procfs_file_alloca(pid, "status");
515 f = fopen(p, "re");
516 if (!f) {
517 if (errno == ENOENT)
518 return -ESRCH;
519 return -errno;
520 }
521
522 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
523
524 for (;;) {
525 _cleanup_free_ char *line = NULL;
526 char *l;
527
528 r = read_line(f, LONG_LINE_MAX, &line);
529 if (r < 0)
530 return r;
531 if (r == 0)
532 break;
533
534 l = strstrip(line);
535
536 if (startswith(l, field)) {
537 l += strlen(field);
538 l += strspn(l, WHITESPACE);
539
540 l[strcspn(l, WHITESPACE)] = 0;
541
542 return parse_uid(l, uid);
543 }
544 }
545
546 return -EIO;
547 }
548
549 int get_process_uid(pid_t pid, uid_t *uid) {
550
551 if (pid == 0 || pid == getpid_cached()) {
552 *uid = getuid();
553 return 0;
554 }
555
556 return get_process_id(pid, "Uid:", uid);
557 }
558
559 int get_process_gid(pid_t pid, gid_t *gid) {
560
561 if (pid == 0 || pid == getpid_cached()) {
562 *gid = getgid();
563 return 0;
564 }
565
566 assert_cc(sizeof(uid_t) == sizeof(gid_t));
567 return get_process_id(pid, "Gid:", gid);
568 }
569
570 int get_process_cwd(pid_t pid, char **cwd) {
571 const char *p;
572
573 assert(pid >= 0);
574
575 p = procfs_file_alloca(pid, "cwd");
576
577 return get_process_link_contents(p, cwd);
578 }
579
580 int get_process_root(pid_t pid, char **root) {
581 const char *p;
582
583 assert(pid >= 0);
584
585 p = procfs_file_alloca(pid, "root");
586
587 return get_process_link_contents(p, root);
588 }
589
590 #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
591
592 int get_process_environ(pid_t pid, char **env) {
593 _cleanup_fclose_ FILE *f = NULL;
594 _cleanup_free_ char *outcome = NULL;
595 size_t allocated = 0, sz = 0;
596 const char *p;
597 int r;
598
599 assert(pid >= 0);
600 assert(env);
601
602 p = procfs_file_alloca(pid, "environ");
603
604 f = fopen(p, "re");
605 if (!f) {
606 if (errno == ENOENT)
607 return -ESRCH;
608 return -errno;
609 }
610
611 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
612
613 for (;;) {
614 char c;
615
616 if (sz >= ENVIRONMENT_BLOCK_MAX)
617 return -ENOBUFS;
618
619 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
620 return -ENOMEM;
621
622 r = safe_fgetc(f, &c);
623 if (r < 0)
624 return r;
625 if (r == 0)
626 break;
627
628 if (c == '\0')
629 outcome[sz++] = '\n';
630 else
631 sz += cescape_char(c, outcome + sz);
632 }
633
634 outcome[sz] = '\0';
635 *env = TAKE_PTR(outcome);
636
637 return 0;
638 }
639
640 int get_process_ppid(pid_t pid, pid_t *_ppid) {
641 int r;
642 _cleanup_free_ char *line = NULL;
643 long unsigned ppid;
644 const char *p;
645
646 assert(pid >= 0);
647 assert(_ppid);
648
649 if (pid == 0 || pid == getpid_cached()) {
650 *_ppid = getppid();
651 return 0;
652 }
653
654 p = procfs_file_alloca(pid, "stat");
655 r = read_one_line_file(p, &line);
656 if (r == -ENOENT)
657 return -ESRCH;
658 if (r < 0)
659 return r;
660
661 /* Let's skip the pid and comm fields. The latter is enclosed
662 * in () but does not escape any () in its value, so let's
663 * skip over it manually */
664
665 p = strrchr(line, ')');
666 if (!p)
667 return -EIO;
668
669 p++;
670
671 if (sscanf(p, " "
672 "%*c " /* state */
673 "%lu ", /* ppid */
674 &ppid) != 1)
675 return -EIO;
676
677 if ((long unsigned) (pid_t) ppid != ppid)
678 return -ERANGE;
679
680 *_ppid = (pid_t) ppid;
681
682 return 0;
683 }
684
685 int wait_for_terminate(pid_t pid, siginfo_t *status) {
686 siginfo_t dummy;
687
688 assert(pid >= 1);
689
690 if (!status)
691 status = &dummy;
692
693 for (;;) {
694 zero(*status);
695
696 if (waitid(P_PID, pid, status, WEXITED) < 0) {
697
698 if (errno == EINTR)
699 continue;
700
701 return negative_errno();
702 }
703
704 return 0;
705 }
706 }
707
708 /*
709 * Return values:
710 * < 0 : wait_for_terminate() failed to get the state of the
711 * process, the process was terminated by a signal, or
712 * failed for an unknown reason.
713 * >=0 : The process terminated normally, and its exit code is
714 * returned.
715 *
716 * That is, success is indicated by a return value of zero, and an
717 * error is indicated by a non-zero value.
718 *
719 * A warning is emitted if the process terminates abnormally,
720 * and also if it returns non-zero unless check_exit_code is true.
721 */
722 int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) {
723 _cleanup_free_ char *buffer = NULL;
724 siginfo_t status;
725 int r, prio;
726
727 assert(pid > 1);
728
729 if (!name) {
730 r = get_process_comm(pid, &buffer);
731 if (r < 0)
732 log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid);
733 else
734 name = buffer;
735 }
736
737 prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
738
739 r = wait_for_terminate(pid, &status);
740 if (r < 0)
741 return log_full_errno(prio, r, "Failed to wait for %s: %m", strna(name));
742
743 if (status.si_code == CLD_EXITED) {
744 if (status.si_status != EXIT_SUCCESS)
745 log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
746 "%s failed with exit status %i.", strna(name), status.si_status);
747 else
748 log_debug("%s succeeded.", name);
749
750 return status.si_status;
751
752 } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
753
754 log_full(prio, "%s terminated by signal %s.", strna(name), signal_to_string(status.si_status));
755 return -EPROTO;
756 }
757
758 log_full(prio, "%s failed due to unknown reason.", strna(name));
759 return -EPROTO;
760 }
761
762 /*
763 * Return values:
764 *
765 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
766 * was terminated by a signal, or failed for an unknown reason.
767 *
768 * >=0 : The process terminated normally with no failures.
769 *
770 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
771 * states are indicated by error is indicated by a non-zero value.
772 *
773 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
774 * to remain entirely race-free.
775 */
776 int wait_for_terminate_with_timeout(pid_t pid, usec_t timeout) {
777 sigset_t mask;
778 int r;
779 usec_t until;
780
781 assert_se(sigemptyset(&mask) == 0);
782 assert_se(sigaddset(&mask, SIGCHLD) == 0);
783
784 /* Drop into a sigtimewait-based timeout. Waiting for the
785 * pid to exit. */
786 until = now(CLOCK_MONOTONIC) + timeout;
787 for (;;) {
788 usec_t n;
789 siginfo_t status = {};
790 struct timespec ts;
791
792 n = now(CLOCK_MONOTONIC);
793 if (n >= until)
794 break;
795
796 r = sigtimedwait(&mask, NULL, timespec_store(&ts, until - n)) < 0 ? -errno : 0;
797 /* Assuming we woke due to the child exiting. */
798 if (waitid(P_PID, pid, &status, WEXITED|WNOHANG) == 0) {
799 if (status.si_pid == pid) {
800 /* This is the correct child.*/
801 if (status.si_code == CLD_EXITED)
802 return (status.si_status == 0) ? 0 : -EPROTO;
803 else
804 return -EPROTO;
805 }
806 }
807 /* Not the child, check for errors and proceed appropriately */
808 if (r < 0) {
809 switch (r) {
810 case -EAGAIN:
811 /* Timed out, child is likely hung. */
812 return -ETIMEDOUT;
813 case -EINTR:
814 /* Received a different signal and should retry */
815 continue;
816 default:
817 /* Return any unexpected errors */
818 return r;
819 }
820 }
821 }
822
823 return -EPROTO;
824 }
825
826 void sigkill_wait(pid_t pid) {
827 assert(pid > 1);
828
829 if (kill(pid, SIGKILL) >= 0)
830 (void) wait_for_terminate(pid, NULL);
831 }
832
833 void sigkill_waitp(pid_t *pid) {
834 PROTECT_ERRNO;
835
836 if (!pid)
837 return;
838 if (*pid <= 1)
839 return;
840
841 sigkill_wait(*pid);
842 }
843
844 void sigterm_wait(pid_t pid) {
845 assert(pid > 1);
846
847 if (kill_and_sigcont(pid, SIGTERM) >= 0)
848 (void) wait_for_terminate(pid, NULL);
849 }
850
851 int kill_and_sigcont(pid_t pid, int sig) {
852 int r;
853
854 r = kill(pid, sig) < 0 ? -errno : 0;
855
856 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
857 * affected by a process being suspended anyway. */
858 if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
859 (void) kill(pid, SIGCONT);
860
861 return r;
862 }
863
864 int getenv_for_pid(pid_t pid, const char *field, char **ret) {
865 _cleanup_fclose_ FILE *f = NULL;
866 char *value = NULL;
867 const char *path;
868 size_t l, sum = 0;
869 int r;
870
871 assert(pid >= 0);
872 assert(field);
873 assert(ret);
874
875 if (pid == 0 || pid == getpid_cached()) {
876 const char *e;
877
878 e = getenv(field);
879 if (!e) {
880 *ret = NULL;
881 return 0;
882 }
883
884 value = strdup(e);
885 if (!value)
886 return -ENOMEM;
887
888 *ret = value;
889 return 1;
890 }
891
892 if (!pid_is_valid(pid))
893 return -EINVAL;
894
895 path = procfs_file_alloca(pid, "environ");
896
897 f = fopen(path, "re");
898 if (!f) {
899 if (errno == ENOENT)
900 return -ESRCH;
901
902 return -errno;
903 }
904
905 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
906
907 l = strlen(field);
908 for (;;) {
909 _cleanup_free_ char *line = NULL;
910
911 if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
912 return -ENOBUFS;
913
914 r = read_nul_string(f, LONG_LINE_MAX, &line);
915 if (r < 0)
916 return r;
917 if (r == 0) /* EOF */
918 break;
919
920 sum += r;
921
922 if (strneq(line, field, l) && line[l] == '=') {
923 value = strdup(line + l + 1);
924 if (!value)
925 return -ENOMEM;
926
927 *ret = value;
928 return 1;
929 }
930 }
931
932 *ret = NULL;
933 return 0;
934 }
935
936 bool pid_is_unwaited(pid_t pid) {
937 /* Checks whether a PID is still valid at all, including a zombie */
938
939 if (pid < 0)
940 return false;
941
942 if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */
943 return true;
944
945 if (pid == getpid_cached())
946 return true;
947
948 if (kill(pid, 0) >= 0)
949 return true;
950
951 return errno != ESRCH;
952 }
953
954 bool pid_is_alive(pid_t pid) {
955 int r;
956
957 /* Checks whether a PID is still valid and not a zombie */
958
959 if (pid < 0)
960 return false;
961
962 if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */
963 return true;
964
965 if (pid == getpid_cached())
966 return true;
967
968 r = get_process_state(pid);
969 if (IN_SET(r, -ESRCH, 'Z'))
970 return false;
971
972 return true;
973 }
974
975 int pid_from_same_root_fs(pid_t pid) {
976 const char *root;
977
978 if (pid < 0)
979 return false;
980
981 if (pid == 0 || pid == getpid_cached())
982 return true;
983
984 root = procfs_file_alloca(pid, "root");
985
986 return files_same(root, "/proc/1/root", 0);
987 }
988
989 bool is_main_thread(void) {
990 static thread_local int cached = 0;
991
992 if (_unlikely_(cached == 0))
993 cached = getpid_cached() == gettid() ? 1 : -1;
994
995 return cached > 0;
996 }
997
998 _noreturn_ void freeze(void) {
999
1000 log_close();
1001
1002 /* Make sure nobody waits for us on a socket anymore */
1003 close_all_fds(NULL, 0);
1004
1005 sync();
1006
1007 /* Let's not freeze right away, but keep reaping zombies. */
1008 for (;;) {
1009 int r;
1010 siginfo_t si = {};
1011
1012 r = waitid(P_ALL, 0, &si, WEXITED);
1013 if (r < 0 && errno != EINTR)
1014 break;
1015 }
1016
1017 /* waitid() failed with an unexpected error, things are really borked. Freeze now! */
1018 for (;;)
1019 pause();
1020 }
1021
1022 bool oom_score_adjust_is_valid(int oa) {
1023 return oa >= OOM_SCORE_ADJ_MIN && oa <= OOM_SCORE_ADJ_MAX;
1024 }
1025
1026 unsigned long personality_from_string(const char *p) {
1027 int architecture;
1028
1029 if (!p)
1030 return PERSONALITY_INVALID;
1031
1032 /* Parse a personality specifier. We use our own identifiers that indicate specific ABIs, rather than just
1033 * hints regarding the register size, since we want to keep things open for multiple locally supported ABIs for
1034 * the same register size. */
1035
1036 architecture = architecture_from_string(p);
1037 if (architecture < 0)
1038 return PERSONALITY_INVALID;
1039
1040 if (architecture == native_architecture())
1041 return PER_LINUX;
1042 #ifdef SECONDARY_ARCHITECTURE
1043 if (architecture == SECONDARY_ARCHITECTURE)
1044 return PER_LINUX32;
1045 #endif
1046
1047 return PERSONALITY_INVALID;
1048 }
1049
1050 const char* personality_to_string(unsigned long p) {
1051 int architecture = _ARCHITECTURE_INVALID;
1052
1053 if (p == PER_LINUX)
1054 architecture = native_architecture();
1055 #ifdef SECONDARY_ARCHITECTURE
1056 else if (p == PER_LINUX32)
1057 architecture = SECONDARY_ARCHITECTURE;
1058 #endif
1059
1060 if (architecture < 0)
1061 return NULL;
1062
1063 return architecture_to_string(architecture);
1064 }
1065
1066 int safe_personality(unsigned long p) {
1067 int ret;
1068
1069 /* So here's the deal, personality() is weirdly defined by glibc. In some cases it returns a failure via errno,
1070 * and in others as negative return value containing an errno-like value. Let's work around this: this is a
1071 * wrapper that uses errno if it is set, and uses the return value otherwise. And then it sets both errno and
1072 * the return value indicating the same issue, so that we are definitely on the safe side.
1073 *
1074 * See https://github.com/systemd/systemd/issues/6737 */
1075
1076 errno = 0;
1077 ret = personality(p);
1078 if (ret < 0) {
1079 if (errno != 0)
1080 return -errno;
1081
1082 errno = -ret;
1083 }
1084
1085 return ret;
1086 }
1087
1088 int opinionated_personality(unsigned long *ret) {
1089 int current;
1090
1091 /* Returns the current personality, or PERSONALITY_INVALID if we can't determine it. This function is a bit
1092 * opinionated though, and ignores all the finer-grained bits and exotic personalities, only distinguishing the
1093 * two most relevant personalities: PER_LINUX and PER_LINUX32. */
1094
1095 current = safe_personality(PERSONALITY_INVALID);
1096 if (current < 0)
1097 return current;
1098
1099 if (((unsigned long) current & 0xffff) == PER_LINUX32)
1100 *ret = PER_LINUX32;
1101 else
1102 *ret = PER_LINUX;
1103
1104 return 0;
1105 }
1106
1107 void valgrind_summary_hack(void) {
1108 #if HAVE_VALGRIND_VALGRIND_H
1109 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
1110 pid_t pid;
1111 pid = raw_clone(SIGCHLD);
1112 if (pid < 0)
1113 log_emergency_errno(errno, "Failed to fork off valgrind helper: %m");
1114 else if (pid == 0)
1115 exit(EXIT_SUCCESS);
1116 else {
1117 log_info("Spawned valgrind helper as PID "PID_FMT".", pid);
1118 (void) wait_for_terminate(pid, NULL);
1119 }
1120 }
1121 #endif
1122 }
1123
1124 int pid_compare_func(const pid_t *a, const pid_t *b) {
1125 /* Suitable for usage in qsort() */
1126 return CMP(*a, *b);
1127 }
1128
1129 int ioprio_parse_priority(const char *s, int *ret) {
1130 int i, r;
1131
1132 assert(s);
1133 assert(ret);
1134
1135 r = safe_atoi(s, &i);
1136 if (r < 0)
1137 return r;
1138
1139 if (!ioprio_priority_is_valid(i))
1140 return -EINVAL;
1141
1142 *ret = i;
1143 return 0;
1144 }
1145
1146 /* The cached PID, possible values:
1147 *
1148 * == UNSET [0] → cache not initialized yet
1149 * == BUSY [-1] → some thread is initializing it at the moment
1150 * any other → the cached PID
1151 */
1152
1153 #define CACHED_PID_UNSET ((pid_t) 0)
1154 #define CACHED_PID_BUSY ((pid_t) -1)
1155
1156 static pid_t cached_pid = CACHED_PID_UNSET;
1157
1158 void reset_cached_pid(void) {
1159 /* Invoked in the child after a fork(), i.e. at the first moment the PID changed */
1160 cached_pid = CACHED_PID_UNSET;
1161 }
1162
1163 /* We use glibc __register_atfork() + __dso_handle directly here, as they are not included in the glibc
1164 * headers. __register_atfork() is mostly equivalent to pthread_atfork(), but doesn't require us to link against
1165 * libpthread, as it is part of glibc anyway. */
1166 extern int __register_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void), void *dso_handle);
1167 extern void* __dso_handle _weak_;
1168
1169 pid_t getpid_cached(void) {
1170 static bool installed = false;
1171 pid_t current_value;
1172
1173 /* getpid_cached() is much like getpid(), but caches the value in local memory, to avoid having to invoke a
1174 * system call each time. This restores glibc behaviour from before 2.24, when getpid() was unconditionally
1175 * cached. Starting with 2.24 getpid() started to become prohibitively expensive when used for detecting when
1176 * objects were used across fork()s. With this caching the old behaviour is somewhat restored.
1177 *
1178 * https://bugzilla.redhat.com/show_bug.cgi?id=1443976
1179 * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e
1180 */
1181
1182 current_value = __sync_val_compare_and_swap(&cached_pid, CACHED_PID_UNSET, CACHED_PID_BUSY);
1183
1184 switch (current_value) {
1185
1186 case CACHED_PID_UNSET: { /* Not initialized yet, then do so now */
1187 pid_t new_pid;
1188
1189 new_pid = raw_getpid();
1190
1191 if (!installed) {
1192 /* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's
1193 * only half-documented (glibc doesn't document it but LSB does — though only superficially)
1194 * we'll check for errors only in the most generic fashion possible. */
1195
1196 if (__register_atfork(NULL, NULL, reset_cached_pid, __dso_handle) != 0) {
1197 /* OOM? Let's try again later */
1198 cached_pid = CACHED_PID_UNSET;
1199 return new_pid;
1200 }
1201
1202 installed = true;
1203 }
1204
1205 cached_pid = new_pid;
1206 return new_pid;
1207 }
1208
1209 case CACHED_PID_BUSY: /* Somebody else is currently initializing */
1210 return raw_getpid();
1211
1212 default: /* Properly initialized */
1213 return current_value;
1214 }
1215 }
1216
1217 int must_be_root(void) {
1218
1219 if (geteuid() == 0)
1220 return 0;
1221
1222 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to be root.");
1223 }
1224
1225 int safe_fork_full(
1226 const char *name,
1227 const int except_fds[],
1228 size_t n_except_fds,
1229 ForkFlags flags,
1230 pid_t *ret_pid) {
1231
1232 pid_t original_pid, pid;
1233 sigset_t saved_ss, ss;
1234 bool block_signals = false;
1235 int prio, r;
1236
1237 /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always
1238 * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */
1239
1240 prio = flags & FORK_LOG ? LOG_ERR : LOG_DEBUG;
1241
1242 original_pid = getpid_cached();
1243
1244 if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG)) {
1245 /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can
1246 * be sure that SIGTERMs are not lost we might send to the child. */
1247
1248 assert_se(sigfillset(&ss) >= 0);
1249 block_signals = true;
1250
1251 } else if (flags & FORK_WAIT) {
1252 /* Let's block SIGCHLD at least, so that we can safely watch for the child process */
1253
1254 assert_se(sigemptyset(&ss) >= 0);
1255 assert_se(sigaddset(&ss, SIGCHLD) >= 0);
1256 block_signals = true;
1257 }
1258
1259 if (block_signals)
1260 if (sigprocmask(SIG_SETMASK, &ss, &saved_ss) < 0)
1261 return log_full_errno(prio, errno, "Failed to set signal mask: %m");
1262
1263 if (flags & FORK_NEW_MOUNTNS)
1264 pid = raw_clone(SIGCHLD|CLONE_NEWNS);
1265 else
1266 pid = fork();
1267 if (pid < 0) {
1268 r = -errno;
1269
1270 if (block_signals) /* undo what we did above */
1271 (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL);
1272
1273 return log_full_errno(prio, r, "Failed to fork: %m");
1274 }
1275 if (pid > 0) {
1276 /* We are in the parent process */
1277
1278 log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid);
1279
1280 if (flags & FORK_WAIT) {
1281 r = wait_for_terminate_and_check(name, pid, (flags & FORK_LOG ? WAIT_LOG : 0));
1282 if (r < 0)
1283 return r;
1284 if (r != EXIT_SUCCESS) /* exit status > 0 should be treated as failure, too */
1285 return -EPROTO;
1286 }
1287
1288 if (block_signals) /* undo what we did above */
1289 (void) sigprocmask(SIG_SETMASK, &saved_ss, NULL);
1290
1291 if (ret_pid)
1292 *ret_pid = pid;
1293
1294 return 1;
1295 }
1296
1297 /* We are in the child process */
1298
1299 if (flags & FORK_REOPEN_LOG) {
1300 /* Close the logs if requested, before we log anything. And make sure we reopen it if needed. */
1301 log_close();
1302 log_set_open_when_needed(true);
1303 }
1304
1305 if (name) {
1306 r = rename_process(name);
1307 if (r < 0)
1308 log_full_errno(flags & FORK_LOG ? LOG_WARNING : LOG_DEBUG,
1309 r, "Failed to rename process, ignoring: %m");
1310 }
1311
1312 if (flags & FORK_DEATHSIG)
1313 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) {
1314 log_full_errno(prio, errno, "Failed to set death signal: %m");
1315 _exit(EXIT_FAILURE);
1316 }
1317
1318 if (flags & FORK_RESET_SIGNALS) {
1319 r = reset_all_signal_handlers();
1320 if (r < 0) {
1321 log_full_errno(prio, r, "Failed to reset signal handlers: %m");
1322 _exit(EXIT_FAILURE);
1323 }
1324
1325 /* This implicitly undoes the signal mask stuff we did before the fork()ing above */
1326 r = reset_signal_mask();
1327 if (r < 0) {
1328 log_full_errno(prio, r, "Failed to reset signal mask: %m");
1329 _exit(EXIT_FAILURE);
1330 }
1331 } else if (block_signals) { /* undo what we did above */
1332 if (sigprocmask(SIG_SETMASK, &saved_ss, NULL) < 0) {
1333 log_full_errno(prio, errno, "Failed to restore signal mask: %m");
1334 _exit(EXIT_FAILURE);
1335 }
1336 }
1337
1338 if (flags & FORK_DEATHSIG) {
1339 pid_t ppid;
1340 /* Let's see if the parent PID is still the one we started from? If not, then the parent
1341 * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */
1342
1343 ppid = getppid();
1344 if (ppid == 0)
1345 /* Parent is in a differn't PID namespace. */;
1346 else if (ppid != original_pid) {
1347 log_debug("Parent died early, raising SIGTERM.");
1348 (void) raise(SIGTERM);
1349 _exit(EXIT_FAILURE);
1350 }
1351 }
1352
1353 if (FLAGS_SET(flags, FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE)) {
1354
1355 /* Optionally, make sure we never propagate mounts to the host. */
1356
1357 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
1358 log_full_errno(prio, errno, "Failed to remount root directory as MS_SLAVE: %m");
1359 _exit(EXIT_FAILURE);
1360 }
1361 }
1362
1363 if (flags & FORK_CLOSE_ALL_FDS) {
1364 /* Close the logs here in case it got reopened above, as close_all_fds() would close them for us */
1365 log_close();
1366
1367 r = close_all_fds(except_fds, n_except_fds);
1368 if (r < 0) {
1369 log_full_errno(prio, r, "Failed to close all file descriptors: %m");
1370 _exit(EXIT_FAILURE);
1371 }
1372 }
1373
1374 /* When we were asked to reopen the logs, do so again now */
1375 if (flags & FORK_REOPEN_LOG) {
1376 log_open();
1377 log_set_open_when_needed(false);
1378 }
1379
1380 if (flags & FORK_NULL_STDIO) {
1381 r = make_null_stdio();
1382 if (r < 0) {
1383 log_full_errno(prio, r, "Failed to connect stdin/stdout to /dev/null: %m");
1384 _exit(EXIT_FAILURE);
1385 }
1386 }
1387
1388 if (flags & FORK_RLIMIT_NOFILE_SAFE) {
1389 r = rlimit_nofile_safe();
1390 if (r < 0) {
1391 log_full_errno(prio, r, "Failed to lower RLIMIT_NOFILE's soft limit to 1K: %m");
1392 _exit(EXIT_FAILURE);
1393 }
1394 }
1395
1396 if (ret_pid)
1397 *ret_pid = getpid_cached();
1398
1399 return 0;
1400 }
1401
1402 int namespace_fork(
1403 const char *outer_name,
1404 const char *inner_name,
1405 const int except_fds[],
1406 size_t n_except_fds,
1407 ForkFlags flags,
1408 int pidns_fd,
1409 int mntns_fd,
1410 int netns_fd,
1411 int userns_fd,
1412 int root_fd,
1413 pid_t *ret_pid) {
1414
1415 int r;
1416
1417 /* This is much like safe_fork(), but forks twice, and joins the specified namespaces in the middle
1418 * process. This ensures that we are fully a member of the destination namespace, with pidns an all, so that
1419 * /proc/self/fd works correctly. */
1420
1421 r = safe_fork_full(outer_name, except_fds, n_except_fds, (flags|FORK_DEATHSIG) & ~(FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE), ret_pid);
1422 if (r < 0)
1423 return r;
1424 if (r == 0) {
1425 pid_t pid;
1426
1427 /* Child */
1428
1429 r = namespace_enter(pidns_fd, mntns_fd, netns_fd, userns_fd, root_fd);
1430 if (r < 0) {
1431 log_full_errno(FLAGS_SET(flags, FORK_LOG) ? LOG_ERR : LOG_DEBUG, r, "Failed to join namespace: %m");
1432 _exit(EXIT_FAILURE);
1433 }
1434
1435 /* We mask a few flags here that either make no sense for the grandchild, or that we don't have to do again */
1436 r = safe_fork_full(inner_name, except_fds, n_except_fds, flags & ~(FORK_WAIT|FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_NULL_STDIO), &pid);
1437 if (r < 0)
1438 _exit(EXIT_FAILURE);
1439 if (r == 0) {
1440 /* Child */
1441 if (ret_pid)
1442 *ret_pid = pid;
1443 return 0;
1444 }
1445
1446 r = wait_for_terminate_and_check(inner_name, pid, FLAGS_SET(flags, FORK_LOG) ? WAIT_LOG : 0);
1447 if (r < 0)
1448 _exit(EXIT_FAILURE);
1449
1450 _exit(r);
1451 }
1452
1453 return 1;
1454 }
1455
1456 int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) {
1457 bool stdout_is_tty, stderr_is_tty;
1458 size_t n, i;
1459 va_list ap;
1460 char **l;
1461 int r;
1462
1463 assert(path);
1464
1465 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
1466
1467 r = safe_fork_full(name, except, n_except, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS, ret_pid);
1468 if (r < 0)
1469 return r;
1470 if (r > 0)
1471 return 0;
1472
1473 /* In the child: */
1474
1475 stdout_is_tty = isatty(STDOUT_FILENO);
1476 stderr_is_tty = isatty(STDERR_FILENO);
1477
1478 if (!stdout_is_tty || !stderr_is_tty) {
1479 int fd;
1480
1481 /* Detach from stdout/stderr. and reopen
1482 * /dev/tty for them. This is important to
1483 * ensure that when systemctl is started via
1484 * popen() or a similar call that expects to
1485 * read EOF we actually do generate EOF and
1486 * not delay this indefinitely by because we
1487 * keep an unused copy of stdin around. */
1488 fd = open("/dev/tty", O_WRONLY);
1489 if (fd < 0) {
1490 log_error_errno(errno, "Failed to open /dev/tty: %m");
1491 _exit(EXIT_FAILURE);
1492 }
1493
1494 if (!stdout_is_tty && dup2(fd, STDOUT_FILENO) < 0) {
1495 log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1496 _exit(EXIT_FAILURE);
1497 }
1498
1499 if (!stderr_is_tty && dup2(fd, STDERR_FILENO) < 0) {
1500 log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
1501 _exit(EXIT_FAILURE);
1502 }
1503
1504 safe_close_above_stdio(fd);
1505 }
1506
1507 (void) rlimit_nofile_safe();
1508
1509 /* Count arguments */
1510 va_start(ap, path);
1511 for (n = 0; va_arg(ap, char*); n++)
1512 ;
1513 va_end(ap);
1514
1515 /* Allocate strv */
1516 l = newa(char*, n + 1);
1517
1518 /* Fill in arguments */
1519 va_start(ap, path);
1520 for (i = 0; i <= n; i++)
1521 l[i] = va_arg(ap, char*);
1522 va_end(ap);
1523
1524 execv(path, l);
1525 _exit(EXIT_FAILURE);
1526 }
1527
1528 int set_oom_score_adjust(int value) {
1529 char t[DECIMAL_STR_MAX(int)];
1530
1531 sprintf(t, "%i", value);
1532
1533 return write_string_file("/proc/self/oom_score_adj", t,
1534 WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
1535 }
1536
1537 static const char *const ioprio_class_table[] = {
1538 [IOPRIO_CLASS_NONE] = "none",
1539 [IOPRIO_CLASS_RT] = "realtime",
1540 [IOPRIO_CLASS_BE] = "best-effort",
1541 [IOPRIO_CLASS_IDLE] = "idle"
1542 };
1543
1544 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, IOPRIO_N_CLASSES);
1545
1546 static const char *const sigchld_code_table[] = {
1547 [CLD_EXITED] = "exited",
1548 [CLD_KILLED] = "killed",
1549 [CLD_DUMPED] = "dumped",
1550 [CLD_TRAPPED] = "trapped",
1551 [CLD_STOPPED] = "stopped",
1552 [CLD_CONTINUED] = "continued",
1553 };
1554
1555 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1556
1557 static const char* const sched_policy_table[] = {
1558 [SCHED_OTHER] = "other",
1559 [SCHED_BATCH] = "batch",
1560 [SCHED_IDLE] = "idle",
1561 [SCHED_FIFO] = "fifo",
1562 [SCHED_RR] = "rr"
1563 };
1564
1565 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);