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