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