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