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