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