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