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