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