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