]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/process-util.c
process-util: add new helper cpus_in_affinity_mask()
[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;
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
125 f = fopen(p, "re");
126 if (!f) {
127 if (errno == ENOENT)
128 return -ESRCH;
129 return -errno;
130 }
131
132 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
133
134 if (max_length == 0) {
135 /* This is supposed to be a safety guard against runaway command lines. */
136 long l = sysconf(_SC_ARG_MAX);
137 assert(l > 0);
138 max_length = l;
139 }
140
141 if (max_length == 1) {
142
143 /* If there's only room for one byte, return the empty string */
144 ans = new0(char, 1);
145 if (!ans)
146 return -ENOMEM;
147
148 *line = TAKE_PTR(ans);
149 return 0;
150
151 } else {
152 bool dotdotdot = false;
153 size_t left;
154
155 ans = new(char, max_length);
156 if (!ans)
157 return -ENOMEM;
158
159 k = ans;
160 left = max_length;
161 while ((c = getc(f)) != EOF) {
162
163 if (isprint(c)) {
164
165 if (space) {
166 if (left <= 2) {
167 dotdotdot = true;
168 break;
169 }
170
171 *(k++) = ' ';
172 left--;
173 space = false;
174 }
175
176 if (left <= 1) {
177 dotdotdot = true;
178 break;
179 }
180
181 *(k++) = (char) c;
182 left--;
183 } else if (k > ans)
184 space = true;
185 }
186
187 if (dotdotdot) {
188 if (max_length <= 4) {
189 k = ans;
190 left = max_length;
191 } else {
192 k = ans + max_length - 4;
193 left = 4;
194
195 /* Eat up final spaces */
196 while (k > ans && isspace(k[-1])) {
197 k--;
198 left++;
199 }
200 }
201
202 strncpy(k, "...", left-1);
203 k[left-1] = 0;
204 } else
205 *k = 0;
206 }
207
208 /* Kernel threads have no argv[] */
209 if (isempty(ans)) {
210 _cleanup_free_ char *t = NULL;
211 int h;
212
213 ans = mfree(ans);
214
215 if (!comm_fallback)
216 return -ENOENT;
217
218 h = get_process_comm(pid, &t);
219 if (h < 0)
220 return h;
221
222 size_t l = strlen(t);
223
224 if (l + 3 <= max_length) {
225 ans = strjoin("[", t, "]");
226 if (!ans)
227 return -ENOMEM;
228
229 } else if (max_length <= 6) {
230 ans = new(char, max_length);
231 if (!ans)
232 return -ENOMEM;
233
234 memcpy(ans, "[...]", max_length-1);
235 ans[max_length-1] = 0;
236 } else {
237 t[max_length - 6] = 0;
238
239 /* Chop off final spaces */
240 delete_trailing_chars(t, WHITESPACE);
241
242 ans = strjoin("[", t, "...]");
243 if (!ans)
244 return -ENOMEM;
245 }
246
247 *line = TAKE_PTR(ans);
248 return 0;
249 }
250
251 k = realloc(ans, strlen(ans) + 1);
252 if (!k)
253 return -ENOMEM;
254
255 ans = NULL;
256 *line = k;
257
258 return 0;
259 }
260
261 int rename_process(const char name[]) {
262 static size_t mm_size = 0;
263 static char *mm = NULL;
264 bool truncated = false;
265 size_t l;
266
267 /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's
268 * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in
269 * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded;
270 * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be
271 * truncated.
272 *
273 * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */
274
275 if (isempty(name))
276 return -EINVAL; /* let's not confuse users unnecessarily with an empty name */
277
278 if (!is_main_thread())
279 return -EPERM; /* Let's not allow setting the process name from other threads than the main one, as we
280 * cache things without locking, and we make assumptions that PR_SET_NAME sets the
281 * process name that isn't correct on any other threads */
282
283 l = strlen(name);
284
285 /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we
286 * can use PR_SET_NAME, which sets the thread name for the calling thread. */
287 if (prctl(PR_SET_NAME, name) < 0)
288 log_debug_errno(errno, "PR_SET_NAME failed: %m");
289 if (l >= TASK_COMM_LEN) /* Linux process names can be 15 chars at max */
290 truncated = true;
291
292 /* Second step, change glibc's ID of the process name. */
293 if (program_invocation_name) {
294 size_t k;
295
296 k = strlen(program_invocation_name);
297 strncpy(program_invocation_name, name, k);
298 if (l > k)
299 truncated = true;
300 }
301
302 /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but
303 * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at
304 * the end. This is the best option for changing /proc/self/cmdline. */
305
306 /* Let's not bother with this if we don't have euid == 0. Strictly speaking we should check for the
307 * CAP_SYS_RESOURCE capability which is independent of the euid. In our own code the capability generally is
308 * present only for euid == 0, hence let's use this as quick bypass check, to avoid calling mmap() if
309 * PR_SET_MM_ARG_{START,END} fails with EPERM later on anyway. After all geteuid() is dead cheap to call, but
310 * mmap() is not. */
311 if (geteuid() != 0)
312 log_debug("Skipping PR_SET_MM, as we don't have privileges.");
313 else if (mm_size < l+1) {
314 size_t nn_size;
315 char *nn;
316
317 nn_size = PAGE_ALIGN(l+1);
318 nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
319 if (nn == MAP_FAILED) {
320 log_debug_errno(errno, "mmap() failed: %m");
321 goto use_saved_argv;
322 }
323
324 strncpy(nn, name, nn_size);
325
326 /* Now, let's tell the kernel about this new memory */
327 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
328 /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be
329 * below the desired start address, in which case the kernel may have kicked this back due
330 * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in
331 * action). The proper solution would be to have a prctl() API that could set both start+end
332 * simultaneously, or at least let us query the existing address to anticipate this condition
333 * and respond accordingly. For now, we can only guess at the cause of this failure and try
334 * a workaround--which will briefly expand the arg space to something potentially huge before
335 * resizing it to what we want. */
336 log_debug_errno(errno, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m");
337
338 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) {
339 log_debug_errno(errno, "PR_SET_MM_ARG_END hack failed, proceeding without: %m");
340 (void) munmap(nn, nn_size);
341 goto use_saved_argv;
342 }
343
344 if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) {
345 log_debug_errno(errno, "PR_SET_MM_ARG_START still failed, proceeding without: %m");
346 goto use_saved_argv;
347 }
348 } else {
349 /* And update the end pointer to the new end, too. If this fails, we don't really know what
350 * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure,
351 * and continue. */
352 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0)
353 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
354 }
355
356 if (mm)
357 (void) munmap(mm, mm_size);
358
359 mm = nn;
360 mm_size = nn_size;
361 } else {
362 strncpy(mm, name, mm_size);
363
364 /* Update the end pointer, continuing regardless of any failure. */
365 if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0)
366 log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m");
367 }
368
369 use_saved_argv:
370 /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if
371 * it still looks here */
372
373 if (saved_argc > 0) {
374 int i;
375
376 if (saved_argv[0]) {
377 size_t k;
378
379 k = strlen(saved_argv[0]);
380 strncpy(saved_argv[0], name, k);
381 if (l > k)
382 truncated = true;
383 }
384
385 for (i = 1; i < saved_argc; i++) {
386 if (!saved_argv[i])
387 break;
388
389 memzero(saved_argv[i], strlen(saved_argv[i]));
390 }
391 }
392
393 return !truncated;
394 }
395
396 int is_kernel_thread(pid_t pid) {
397 _cleanup_free_ char *line = NULL;
398 unsigned long long flags;
399 size_t l, i;
400 const char *p;
401 char *q;
402 int r;
403
404 if (IN_SET(pid, 0, 1) || pid == getpid_cached()) /* pid 1, and we ourselves certainly aren't a kernel thread */
405 return 0;
406 if (!pid_is_valid(pid))
407 return -EINVAL;
408
409 p = procfs_file_alloca(pid, "stat");
410 r = read_one_line_file(p, &line);
411 if (r == -ENOENT)
412 return -ESRCH;
413 if (r < 0)
414 return r;
415
416 /* Skip past the comm field */
417 q = strrchr(line, ')');
418 if (!q)
419 return -EINVAL;
420 q++;
421
422 /* Skip 6 fields to reach the flags field */
423 for (i = 0; i < 6; i++) {
424 l = strspn(q, WHITESPACE);
425 if (l < 1)
426 return -EINVAL;
427 q += l;
428
429 l = strcspn(q, WHITESPACE);
430 if (l < 1)
431 return -EINVAL;
432 q += l;
433 }
434
435 /* Skip preceding whitespace */
436 l = strspn(q, WHITESPACE);
437 if (l < 1)
438 return -EINVAL;
439 q += l;
440
441 /* Truncate the rest */
442 l = strcspn(q, WHITESPACE);
443 if (l < 1)
444 return -EINVAL;
445 q[l] = 0;
446
447 r = safe_atollu(q, &flags);
448 if (r < 0)
449 return r;
450
451 return !!(flags & PF_KTHREAD);
452 }
453
454 int get_process_capeff(pid_t pid, char **capeff) {
455 const char *p;
456 int r;
457
458 assert(capeff);
459 assert(pid >= 0);
460
461 p = procfs_file_alloca(pid, "status");
462
463 r = get_proc_field(p, "CapEff", WHITESPACE, capeff);
464 if (r == -ENOENT)
465 return -ESRCH;
466
467 return r;
468 }
469
470 static int get_process_link_contents(const char *proc_file, char **name) {
471 int r;
472
473 assert(proc_file);
474 assert(name);
475
476 r = readlink_malloc(proc_file, name);
477 if (r == -ENOENT)
478 return -ESRCH;
479 if (r < 0)
480 return r;
481
482 return 0;
483 }
484
485 int get_process_exe(pid_t pid, char **name) {
486 const char *p;
487 char *d;
488 int r;
489
490 assert(pid >= 0);
491
492 p = procfs_file_alloca(pid, "exe");
493 r = get_process_link_contents(p, name);
494 if (r < 0)
495 return r;
496
497 d = endswith(*name, " (deleted)");
498 if (d)
499 *d = '\0';
500
501 return 0;
502 }
503
504 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
505 _cleanup_fclose_ FILE *f = NULL;
506 const char *p;
507 int r;
508
509 assert(field);
510 assert(uid);
511
512 if (pid < 0)
513 return -EINVAL;
514
515 p = procfs_file_alloca(pid, "status");
516 f = fopen(p, "re");
517 if (!f) {
518 if (errno == ENOENT)
519 return -ESRCH;
520 return -errno;
521 }
522
523 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
524
525 for (;;) {
526 _cleanup_free_ char *line = NULL;
527 char *l;
528
529 r = read_line(f, LONG_LINE_MAX, &line);
530 if (r < 0)
531 return r;
532 if (r == 0)
533 break;
534
535 l = strstrip(line);
536
537 if (startswith(l, field)) {
538 l += strlen(field);
539 l += strspn(l, WHITESPACE);
540
541 l[strcspn(l, WHITESPACE)] = 0;
542
543 return parse_uid(l, uid);
544 }
545 }
546
547 return -EIO;
548 }
549
550 int get_process_uid(pid_t pid, uid_t *uid) {
551
552 if (pid == 0 || pid == getpid_cached()) {
553 *uid = getuid();
554 return 0;
555 }
556
557 return get_process_id(pid, "Uid:", uid);
558 }
559
560 int get_process_gid(pid_t pid, gid_t *gid) {
561
562 if (pid == 0 || pid == getpid_cached()) {
563 *gid = getgid();
564 return 0;
565 }
566
567 assert_cc(sizeof(uid_t) == sizeof(gid_t));
568 return get_process_id(pid, "Gid:", gid);
569 }
570
571 int get_process_cwd(pid_t pid, char **cwd) {
572 const char *p;
573
574 assert(pid >= 0);
575
576 p = procfs_file_alloca(pid, "cwd");
577
578 return get_process_link_contents(p, cwd);
579 }
580
581 int get_process_root(pid_t pid, char **root) {
582 const char *p;
583
584 assert(pid >= 0);
585
586 p = procfs_file_alloca(pid, "root");
587
588 return get_process_link_contents(p, root);
589 }
590
591 #define ENVIRONMENT_BLOCK_MAX (5U*1024U*1024U)
592
593 int get_process_environ(pid_t pid, char **env) {
594 _cleanup_fclose_ FILE *f = NULL;
595 _cleanup_free_ char *outcome = NULL;
596 size_t allocated = 0, sz = 0;
597 const char *p;
598 int r;
599
600 assert(pid >= 0);
601 assert(env);
602
603 p = procfs_file_alloca(pid, "environ");
604
605 f = fopen(p, "re");
606 if (!f) {
607 if (errno == ENOENT)
608 return -ESRCH;
609 return -errno;
610 }
611
612 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
613
614 for (;;) {
615 char c;
616
617 if (sz >= ENVIRONMENT_BLOCK_MAX)
618 return -ENOBUFS;
619
620 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
621 return -ENOMEM;
622
623 r = safe_fgetc(f, &c);
624 if (r < 0)
625 return r;
626 if (r == 0)
627 break;
628
629 if (c == '\0')
630 outcome[sz++] = '\n';
631 else
632 sz += cescape_char(c, outcome + sz);
633 }
634
635 outcome[sz] = '\0';
636 *env = TAKE_PTR(outcome);
637
638 return 0;
639 }
640
641 int get_process_ppid(pid_t pid, pid_t *_ppid) {
642 int r;
643 _cleanup_free_ char *line = NULL;
644 long unsigned ppid;
645 const char *p;
646
647 assert(pid >= 0);
648 assert(_ppid);
649
650 if (pid == 0 || pid == getpid_cached()) {
651 *_ppid = getppid();
652 return 0;
653 }
654
655 p = procfs_file_alloca(pid, "stat");
656 r = read_one_line_file(p, &line);
657 if (r == -ENOENT)
658 return -ESRCH;
659 if (r < 0)
660 return r;
661
662 /* Let's skip the pid and comm fields. The latter is enclosed
663 * in () but does not escape any () in its value, so let's
664 * skip over it manually */
665
666 p = strrchr(line, ')');
667 if (!p)
668 return -EIO;
669
670 p++;
671
672 if (sscanf(p, " "
673 "%*c " /* state */
674 "%lu ", /* ppid */
675 &ppid) != 1)
676 return -EIO;
677
678 if ((long unsigned) (pid_t) ppid != ppid)
679 return -ERANGE;
680
681 *_ppid = (pid_t) ppid;
682
683 return 0;
684 }
685
686 int wait_for_terminate(pid_t pid, siginfo_t *status) {
687 siginfo_t dummy;
688
689 assert(pid >= 1);
690
691 if (!status)
692 status = &dummy;
693
694 for (;;) {
695 zero(*status);
696
697 if (waitid(P_PID, pid, status, WEXITED) < 0) {
698
699 if (errno == EINTR)
700 continue;
701
702 return negative_errno();
703 }
704
705 return 0;
706 }
707 }
708
709 /*
710 * Return values:
711 * < 0 : wait_for_terminate() failed to get the state of the
712 * process, the process was terminated by a signal, or
713 * failed for an unknown reason.
714 * >=0 : The process terminated normally, and its exit code is
715 * returned.
716 *
717 * That is, success is indicated by a return value of zero, and an
718 * error is indicated by a non-zero value.
719 *
720 * A warning is emitted if the process terminates abnormally,
721 * and also if it returns non-zero unless check_exit_code is true.
722 */
723 int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) {
724 _cleanup_free_ char *buffer = NULL;
725 siginfo_t status;
726 int r, prio;
727
728 assert(pid > 1);
729
730 if (!name) {
731 r = get_process_comm(pid, &buffer);
732 if (r < 0)
733 log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid);
734 else
735 name = buffer;
736 }
737
738 prio = flags & WAIT_LOG_ABNORMAL ? LOG_ERR : LOG_DEBUG;
739
740 r = wait_for_terminate(pid, &status);
741 if (r < 0)
742 return log_full_errno(prio, r, "Failed to wait for %s: %m", strna(name));
743
744 if (status.si_code == CLD_EXITED) {
745 if (status.si_status != EXIT_SUCCESS)
746 log_full(flags & WAIT_LOG_NON_ZERO_EXIT_STATUS ? LOG_ERR : LOG_DEBUG,
747 "%s failed with exit status %i.", strna(name), status.si_status);
748 else
749 log_debug("%s succeeded.", name);
750
751 return status.si_status;
752
753 } else if (IN_SET(status.si_code, CLD_KILLED, CLD_DUMPED)) {
754
755 log_full(prio, "%s terminated by signal %s.", strna(name), signal_to_string(status.si_status));
756 return -EPROTO;
757 }
758
759 log_full(prio, "%s failed due to unknown reason.", strna(name));
760 return -EPROTO;
761 }
762
763 /*
764 * Return values:
765 *
766 * < 0 : wait_for_terminate_with_timeout() failed to get the state of the process, the process timed out, the process
767 * was terminated by a signal, or failed for an unknown reason.
768 *
769 * >=0 : The process terminated normally with no failures.
770 *
771 * Success is indicated by a return value of zero, a timeout is indicated by ETIMEDOUT, and all other child failure
772 * states are indicated by error is indicated by a non-zero value.
773 *
774 * This call assumes SIGCHLD has been blocked already, in particular before the child to wait for has been forked off
775 * to remain entirely race-free.
776 */
777 int wait_for_terminate_with_timeout(pid_t pid, usec_t timeout) {
778 sigset_t mask;
779 int r;
780 usec_t until;
781
782 assert_se(sigemptyset(&mask) == 0);
783 assert_se(sigaddset(&mask, SIGCHLD) == 0);
784
785 /* Drop into a sigtimewait-based timeout. Waiting for the
786 * pid to exit. */
787 until = now(CLOCK_MONOTONIC) + timeout;
788 for (;;) {
789 usec_t n;
790 siginfo_t status = {};
791 struct timespec ts;
792
793 n = now(CLOCK_MONOTONIC);
794 if (n >= until)
795 break;
796
797 r = sigtimedwait(&mask, NULL, timespec_store(&ts, until - n)) < 0 ? -errno : 0;
798 /* Assuming we woke due to the child exiting. */
799 if (waitid(P_PID, pid, &status, WEXITED|WNOHANG) == 0) {
800 if (status.si_pid == pid) {
801 /* This is the correct child.*/
802 if (status.si_code == CLD_EXITED)
803 return (status.si_status == 0) ? 0 : -EPROTO;
804 else
805 return -EPROTO;
806 }
807 }
808 /* Not the child, check for errors and proceed appropriately */
809 if (r < 0) {
810 switch (r) {
811 case -EAGAIN:
812 /* Timed out, child is likely hung. */
813 return -ETIMEDOUT;
814 case -EINTR:
815 /* Received a different signal and should retry */
816 continue;
817 default:
818 /* Return any unexpected errors */
819 return r;
820 }
821 }
822 }
823
824 return -EPROTO;
825 }
826
827 void sigkill_wait(pid_t pid) {
828 assert(pid > 1);
829
830 if (kill(pid, SIGKILL) >= 0)
831 (void) wait_for_terminate(pid, NULL);
832 }
833
834 void sigkill_waitp(pid_t *pid) {
835 PROTECT_ERRNO;
836
837 if (!pid)
838 return;
839 if (*pid <= 1)
840 return;
841
842 sigkill_wait(*pid);
843 }
844
845 void sigterm_wait(pid_t pid) {
846 assert(pid > 1);
847
848 if (kill_and_sigcont(pid, SIGTERM) >= 0)
849 (void) wait_for_terminate(pid, NULL);
850 }
851
852 int kill_and_sigcont(pid_t pid, int sig) {
853 int r;
854
855 r = kill(pid, sig) < 0 ? -errno : 0;
856
857 /* If this worked, also send SIGCONT, unless we already just sent a SIGCONT, or SIGKILL was sent which isn't
858 * affected by a process being suspended anyway. */
859 if (r >= 0 && !IN_SET(sig, SIGCONT, SIGKILL))
860 (void) kill(pid, SIGCONT);
861
862 return r;
863 }
864
865 int getenv_for_pid(pid_t pid, const char *field, char **ret) {
866 _cleanup_fclose_ FILE *f = NULL;
867 char *value = NULL;
868 const char *path;
869 size_t l, sum = 0;
870 int r;
871
872 assert(pid >= 0);
873 assert(field);
874 assert(ret);
875
876 if (pid == 0 || pid == getpid_cached()) {
877 const char *e;
878
879 e = getenv(field);
880 if (!e) {
881 *ret = NULL;
882 return 0;
883 }
884
885 value = strdup(e);
886 if (!value)
887 return -ENOMEM;
888
889 *ret = value;
890 return 1;
891 }
892
893 if (!pid_is_valid(pid))
894 return -EINVAL;
895
896 path = procfs_file_alloca(pid, "environ");
897
898 f = fopen(path, "re");
899 if (!f) {
900 if (errno == ENOENT)
901 return -ESRCH;
902
903 return -errno;
904 }
905
906 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
907
908 l = strlen(field);
909 for (;;) {
910 _cleanup_free_ char *line = NULL;
911
912 if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */
913 return -ENOBUFS;
914
915 r = read_nul_string(f, LONG_LINE_MAX, &line);
916 if (r < 0)
917 return r;
918 if (r == 0) /* EOF */
919 break;
920
921 sum += r;
922
923 if (strneq(line, field, l) && line[l] == '=') {
924 value = strdup(line + l + 1);
925 if (!value)
926 return -ENOMEM;
927
928 *ret = value;
929 return 1;
930 }
931 }
932
933 *ret = NULL;
934 return 0;
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);