]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/coredump/coredump.c
tree-wide: get rid of strappend()
[thirdparty/systemd.git] / src / coredump / coredump.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <sys/prctl.h>
6 #include <sys/xattr.h>
7 #include <unistd.h>
8
9 #if HAVE_ELFUTILS
10 #include <dwarf.h>
11 #include <elfutils/libdwfl.h>
12 #endif
13
14 #include "sd-daemon.h"
15 #include "sd-journal.h"
16 #include "sd-login.h"
17 #include "sd-messages.h"
18
19 #include "acl-util.h"
20 #include "alloc-util.h"
21 #include "capability-util.h"
22 #include "cgroup-util.h"
23 #include "compress.h"
24 #include "conf-parser.h"
25 #include "copy.h"
26 #include "coredump-vacuum.h"
27 #include "dirent-util.h"
28 #include "escape.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "io-util.h"
33 #include "journal-importer.h"
34 #include "log.h"
35 #include "macro.h"
36 #include "main-func.h"
37 #include "memory-util.h"
38 #include "missing.h"
39 #include "mkdir.h"
40 #include "parse-util.h"
41 #include "process-util.h"
42 #include "signal-util.h"
43 #include "socket-util.h"
44 #include "special.h"
45 #include "stacktrace.h"
46 #include "string-table.h"
47 #include "string-util.h"
48 #include "strv.h"
49 #include "tmpfile-util.h"
50 #include "user-util.h"
51
52 /* The maximum size up to which we process coredumps */
53 #define PROCESS_SIZE_MAX ((uint64_t) (2LLU*1024LLU*1024LLU*1024LLU))
54
55 /* The maximum size up to which we leave the coredump around on disk */
56 #define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
57
58 /* The maximum size up to which we store the coredump in the journal */
59 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
60 #define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
61 #else
62 /* oss-fuzz limits memory usage. */
63 #define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
64 #endif
65
66 /* Make sure to not make this larger than the maximum journal entry
67 * size. See DATA_SIZE_MAX in journal-importer.h. */
68 assert_cc(JOURNAL_SIZE_MAX <= DATA_SIZE_MAX);
69
70 enum {
71 /* We use this as array indexes for a couple of special fields we use for naming
72 * coredump files, and attaching xattrs, and for indexing argv[].
73 *
74 * In the internal context[] array, fields before CONTEXT_COMM are the strings
75 * from argv[] passed by the kernel according to our pattern defined in
76 * /proc/sys/kernel/core_pattern (see man:core(5)). So they should not be
77 * freed. The strings at indices CONTEXT_COMM and higher are allocated by us and
78 * should be freed at the end.
79 */
80 CONTEXT_PID,
81 CONTEXT_UID,
82 CONTEXT_GID,
83 CONTEXT_SIGNAL,
84 CONTEXT_TIMESTAMP,
85 CONTEXT_RLIMIT,
86 CONTEXT_HOSTNAME,
87 CONTEXT_COMM,
88 CONTEXT_EXE,
89 CONTEXT_UNIT,
90 _CONTEXT_MAX
91 };
92
93 typedef enum CoredumpStorage {
94 COREDUMP_STORAGE_NONE,
95 COREDUMP_STORAGE_EXTERNAL,
96 COREDUMP_STORAGE_JOURNAL,
97 _COREDUMP_STORAGE_MAX,
98 _COREDUMP_STORAGE_INVALID = -1
99 } CoredumpStorage;
100
101 static const char* const coredump_storage_table[_COREDUMP_STORAGE_MAX] = {
102 [COREDUMP_STORAGE_NONE] = "none",
103 [COREDUMP_STORAGE_EXTERNAL] = "external",
104 [COREDUMP_STORAGE_JOURNAL] = "journal",
105 };
106
107 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage, CoredumpStorage);
108 static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage, coredump_storage, CoredumpStorage, "Failed to parse storage setting");
109
110 static CoredumpStorage arg_storage = COREDUMP_STORAGE_EXTERNAL;
111 static bool arg_compress = true;
112 static uint64_t arg_process_size_max = PROCESS_SIZE_MAX;
113 static uint64_t arg_external_size_max = EXTERNAL_SIZE_MAX;
114 static uint64_t arg_journal_size_max = JOURNAL_SIZE_MAX;
115 static uint64_t arg_keep_free = (uint64_t) -1;
116 static uint64_t arg_max_use = (uint64_t) -1;
117
118 static int parse_config(void) {
119 static const ConfigTableItem items[] = {
120 { "Coredump", "Storage", config_parse_coredump_storage, 0, &arg_storage },
121 { "Coredump", "Compress", config_parse_bool, 0, &arg_compress },
122 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64, 0, &arg_process_size_max },
123 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64, 0, &arg_external_size_max },
124 { "Coredump", "JournalSizeMax", config_parse_iec_size, 0, &arg_journal_size_max },
125 { "Coredump", "KeepFree", config_parse_iec_uint64, 0, &arg_keep_free },
126 { "Coredump", "MaxUse", config_parse_iec_uint64, 0, &arg_max_use },
127 {}
128 };
129
130 return config_parse_many_nulstr(PKGSYSCONFDIR "/coredump.conf",
131 CONF_PATHS_NULSTR("systemd/coredump.conf.d"),
132 "Coredump\0",
133 config_item_table_lookup, items,
134 CONFIG_PARSE_WARN, NULL);
135 }
136
137 static uint64_t storage_size_max(void) {
138 if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
139 return arg_external_size_max;
140 if (arg_storage == COREDUMP_STORAGE_JOURNAL)
141 return arg_journal_size_max;
142 assert(arg_storage == COREDUMP_STORAGE_NONE);
143 return 0;
144 }
145
146 static int fix_acl(int fd, uid_t uid) {
147
148 #if HAVE_ACL
149 _cleanup_(acl_freep) acl_t acl = NULL;
150 acl_entry_t entry;
151 acl_permset_t permset;
152 int r;
153
154 assert(fd >= 0);
155
156 if (uid_is_system(uid) || uid_is_dynamic(uid) || uid == UID_NOBODY)
157 return 0;
158
159 /* Make sure normal users can read (but not write or delete)
160 * their own coredumps */
161
162 acl = acl_get_fd(fd);
163 if (!acl)
164 return log_error_errno(errno, "Failed to get ACL: %m");
165
166 if (acl_create_entry(&acl, &entry) < 0 ||
167 acl_set_tag_type(entry, ACL_USER) < 0 ||
168 acl_set_qualifier(entry, &uid) < 0)
169 return log_error_errno(errno, "Failed to patch ACL: %m");
170
171 if (acl_get_permset(entry, &permset) < 0 ||
172 acl_add_perm(permset, ACL_READ) < 0)
173 return log_warning_errno(errno, "Failed to patch ACL: %m");
174
175 r = calc_acl_mask_if_needed(&acl);
176 if (r < 0)
177 return log_warning_errno(r, "Failed to patch ACL: %m");
178
179 if (acl_set_fd(fd, acl) < 0)
180 return log_error_errno(errno, "Failed to apply ACL: %m");
181 #endif
182
183 return 0;
184 }
185
186 static int fix_xattr(int fd, const char *context[_CONTEXT_MAX]) {
187
188 static const char * const xattrs[_CONTEXT_MAX] = {
189 [CONTEXT_PID] = "user.coredump.pid",
190 [CONTEXT_UID] = "user.coredump.uid",
191 [CONTEXT_GID] = "user.coredump.gid",
192 [CONTEXT_SIGNAL] = "user.coredump.signal",
193 [CONTEXT_TIMESTAMP] = "user.coredump.timestamp",
194 [CONTEXT_RLIMIT] = "user.coredump.rlimit",
195 [CONTEXT_HOSTNAME] = "user.coredump.hostname",
196 [CONTEXT_COMM] = "user.coredump.comm",
197 [CONTEXT_EXE] = "user.coredump.exe",
198 };
199
200 int r = 0;
201 unsigned i;
202
203 assert(fd >= 0);
204
205 /* Attach some metadata to coredumps via extended
206 * attributes. Just because we can. */
207
208 for (i = 0; i < _CONTEXT_MAX; i++) {
209 int k;
210
211 if (isempty(context[i]) || !xattrs[i])
212 continue;
213
214 k = fsetxattr(fd, xattrs[i], context[i], strlen(context[i]), XATTR_CREATE);
215 if (k < 0 && r == 0)
216 r = -errno;
217 }
218
219 return r;
220 }
221
222 #define filename_escape(s) xescape((s), "./ ")
223
224 static const char *coredump_tmpfile_name(const char *s) {
225 return s ? s : "(unnamed temporary file)";
226 }
227
228 static int fix_permissions(
229 int fd,
230 const char *filename,
231 const char *target,
232 const char *context[_CONTEXT_MAX],
233 uid_t uid) {
234
235 int r;
236
237 assert(fd >= 0);
238 assert(target);
239 assert(context);
240
241 /* Ignore errors on these */
242 (void) fchmod(fd, 0640);
243 (void) fix_acl(fd, uid);
244 (void) fix_xattr(fd, context);
245
246 if (fsync(fd) < 0)
247 return log_error_errno(errno, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename));
248
249 (void) fsync_directory_of_file(fd);
250
251 r = link_tmpfile(fd, filename, target);
252 if (r < 0)
253 return log_error_errno(r, "Failed to move coredump %s into place: %m", target);
254
255 return 0;
256 }
257
258 static int maybe_remove_external_coredump(const char *filename, uint64_t size) {
259
260 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
261
262 if (arg_storage == COREDUMP_STORAGE_EXTERNAL &&
263 size <= arg_external_size_max)
264 return 0;
265
266 if (!filename)
267 return 1;
268
269 if (unlink(filename) < 0 && errno != ENOENT)
270 return log_error_errno(errno, "Failed to unlink %s: %m", filename);
271
272 return 1;
273 }
274
275 static int make_filename(const char *context[_CONTEXT_MAX], char **ret) {
276 _cleanup_free_ char *c = NULL, *u = NULL, *p = NULL, *t = NULL;
277 sd_id128_t boot = {};
278 int r;
279
280 assert(context);
281
282 c = filename_escape(context[CONTEXT_COMM]);
283 if (!c)
284 return -ENOMEM;
285
286 u = filename_escape(context[CONTEXT_UID]);
287 if (!u)
288 return -ENOMEM;
289
290 r = sd_id128_get_boot(&boot);
291 if (r < 0)
292 return r;
293
294 p = filename_escape(context[CONTEXT_PID]);
295 if (!p)
296 return -ENOMEM;
297
298 t = filename_escape(context[CONTEXT_TIMESTAMP]);
299 if (!t)
300 return -ENOMEM;
301
302 if (asprintf(ret,
303 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR ".%s.%s000000",
304 c,
305 u,
306 SD_ID128_FORMAT_VAL(boot),
307 p,
308 t) < 0)
309 return -ENOMEM;
310
311 return 0;
312 }
313
314 static int save_external_coredump(
315 const char *context[_CONTEXT_MAX],
316 int input_fd,
317 char **ret_filename,
318 int *ret_node_fd,
319 int *ret_data_fd,
320 uint64_t *ret_size,
321 bool *ret_truncated) {
322
323 _cleanup_free_ char *fn = NULL, *tmp = NULL;
324 _cleanup_close_ int fd = -1;
325 uint64_t rlimit, process_limit, max_size;
326 struct stat st;
327 uid_t uid;
328 int r;
329
330 assert(context);
331 assert(ret_filename);
332 assert(ret_node_fd);
333 assert(ret_data_fd);
334 assert(ret_size);
335
336 r = parse_uid(context[CONTEXT_UID], &uid);
337 if (r < 0)
338 return log_error_errno(r, "Failed to parse UID: %m");
339
340 r = safe_atou64(context[CONTEXT_RLIMIT], &rlimit);
341 if (r < 0)
342 return log_error_errno(r, "Failed to parse resource limit '%s': %m", context[CONTEXT_RLIMIT]);
343 if (rlimit < page_size()) {
344 /* Is coredumping disabled? Then don't bother saving/processing the coredump.
345 * Anything below PAGE_SIZE cannot give a readable coredump (the kernel uses
346 * ELF_EXEC_PAGESIZE which is not easily accessible, but is usually the same as PAGE_SIZE. */
347 return log_info_errno(SYNTHETIC_ERRNO(EBADSLT),
348 "Resource limits disable core dumping for process %s (%s).",
349 context[CONTEXT_PID], context[CONTEXT_COMM]);
350 }
351
352 process_limit = MAX(arg_process_size_max, storage_size_max());
353 if (process_limit == 0)
354 return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT),
355 "Limits for coredump processing and storage are both 0, not dumping core.");
356
357 /* Never store more than the process configured, or than we actually shall keep or process */
358 max_size = MIN(rlimit, process_limit);
359
360 r = make_filename(context, &fn);
361 if (r < 0)
362 return log_error_errno(r, "Failed to determine coredump file name: %m");
363
364 (void) mkdir_p_label("/var/lib/systemd/coredump", 0755);
365
366 fd = open_tmpfile_linkable(fn, O_RDWR|O_CLOEXEC, &tmp);
367 if (fd < 0)
368 return log_error_errno(fd, "Failed to create temporary file for coredump %s: %m", fn);
369
370 r = copy_bytes(input_fd, fd, max_size, 0);
371 if (r < 0) {
372 log_error_errno(r, "Cannot store coredump of %s (%s): %m", context[CONTEXT_PID], context[CONTEXT_COMM]);
373 goto fail;
374 }
375 *ret_truncated = r == 1;
376 if (*ret_truncated)
377 log_struct(LOG_INFO,
378 LOG_MESSAGE("Core file was truncated to %zu bytes.", max_size),
379 "SIZE_LIMIT=%zu", max_size,
380 "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR);
381
382 if (fstat(fd, &st) < 0) {
383 log_error_errno(errno, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp));
384 goto fail;
385 }
386
387 if (lseek(fd, 0, SEEK_SET) == (off_t) -1) {
388 log_error_errno(errno, "Failed to seek on %s: %m", coredump_tmpfile_name(tmp));
389 goto fail;
390 }
391
392 #if HAVE_XZ || HAVE_LZ4
393 /* If we will remove the coredump anyway, do not compress. */
394 if (arg_compress && !maybe_remove_external_coredump(NULL, st.st_size)) {
395
396 _cleanup_free_ char *fn_compressed = NULL, *tmp_compressed = NULL;
397 _cleanup_close_ int fd_compressed = -1;
398
399 fn_compressed = strjoin(fn, COMPRESSED_EXT);
400 if (!fn_compressed) {
401 log_oom();
402 goto uncompressed;
403 }
404
405 fd_compressed = open_tmpfile_linkable(fn_compressed, O_RDWR|O_CLOEXEC, &tmp_compressed);
406 if (fd_compressed < 0) {
407 log_error_errno(fd_compressed, "Failed to create temporary file for coredump %s: %m", fn_compressed);
408 goto uncompressed;
409 }
410
411 r = compress_stream(fd, fd_compressed, -1);
412 if (r < 0) {
413 log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));
414 goto fail_compressed;
415 }
416
417 r = fix_permissions(fd_compressed, tmp_compressed, fn_compressed, context, uid);
418 if (r < 0)
419 goto fail_compressed;
420
421 /* OK, this worked, we can get rid of the uncompressed version now */
422 if (tmp)
423 unlink_noerrno(tmp);
424
425 *ret_filename = TAKE_PTR(fn_compressed); /* compressed */
426 *ret_node_fd = TAKE_FD(fd_compressed); /* compressed */
427 *ret_data_fd = TAKE_FD(fd); /* uncompressed */
428 *ret_size = (uint64_t) st.st_size; /* uncompressed */
429
430 return 0;
431
432 fail_compressed:
433 if (tmp_compressed)
434 (void) unlink(tmp_compressed);
435 }
436
437 uncompressed:
438 #endif
439
440 r = fix_permissions(fd, tmp, fn, context, uid);
441 if (r < 0)
442 goto fail;
443
444 *ret_filename = TAKE_PTR(fn);
445 *ret_data_fd = TAKE_FD(fd);
446 *ret_node_fd = -1;
447 *ret_size = (uint64_t) st.st_size;
448
449 return 0;
450
451 fail:
452 if (tmp)
453 (void) unlink(tmp);
454 return r;
455 }
456
457 static int allocate_journal_field(int fd, size_t size, char **ret, size_t *ret_size) {
458 _cleanup_free_ char *field = NULL;
459 ssize_t n;
460
461 assert(fd >= 0);
462 assert(ret);
463 assert(ret_size);
464
465 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
466 return log_warning_errno(errno, "Failed to seek: %m");
467
468 field = malloc(9 + size);
469 if (!field) {
470 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
471 return -ENOMEM;
472 }
473
474 memcpy(field, "COREDUMP=", 9);
475
476 n = read(fd, field + 9, size);
477 if (n < 0)
478 return log_error_errno((int) n, "Failed to read core data: %m");
479 if ((size_t) n < size)
480 return log_error_errno(SYNTHETIC_ERRNO(EIO),
481 "Core data too short.");
482
483 *ret = TAKE_PTR(field);
484 *ret_size = size + 9;
485
486 return 0;
487 }
488
489 /* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
490 * 0:/dev/pts/23
491 * pos: 0
492 * flags: 0100002
493 *
494 * 1:/dev/pts/23
495 * pos: 0
496 * flags: 0100002
497 *
498 * 2:/dev/pts/23
499 * pos: 0
500 * flags: 0100002
501 * EOF
502 */
503 static int compose_open_fds(pid_t pid, char **open_fds) {
504 _cleanup_closedir_ DIR *proc_fd_dir = NULL;
505 _cleanup_close_ int proc_fdinfo_fd = -1;
506 _cleanup_free_ char *buffer = NULL;
507 _cleanup_fclose_ FILE *stream = NULL;
508 const char *fddelim = "", *path;
509 struct dirent *dent = NULL;
510 size_t size = 0;
511 int r;
512
513 assert(pid >= 0);
514 assert(open_fds != NULL);
515
516 path = procfs_file_alloca(pid, "fd");
517 proc_fd_dir = opendir(path);
518 if (!proc_fd_dir)
519 return -errno;
520
521 proc_fdinfo_fd = openat(dirfd(proc_fd_dir), "../fdinfo", O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC|O_PATH);
522 if (proc_fdinfo_fd < 0)
523 return -errno;
524
525 stream = open_memstream_unlocked(&buffer, &size);
526 if (!stream)
527 return -ENOMEM;
528
529 FOREACH_DIRENT(dent, proc_fd_dir, return -errno) {
530 _cleanup_fclose_ FILE *fdinfo = NULL;
531 _cleanup_free_ char *fdname = NULL;
532 int fd;
533
534 r = readlinkat_malloc(dirfd(proc_fd_dir), dent->d_name, &fdname);
535 if (r < 0)
536 return r;
537
538 fprintf(stream, "%s%s:%s\n", fddelim, dent->d_name, fdname);
539 fddelim = "\n";
540
541 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
542 fd = openat(proc_fdinfo_fd, dent->d_name, O_NOFOLLOW|O_CLOEXEC|O_RDONLY);
543 if (fd < 0)
544 continue;
545
546 fdinfo = fdopen(fd, "r");
547 if (!fdinfo) {
548 safe_close(fd);
549 continue;
550 }
551
552 for (;;) {
553 _cleanup_free_ char *line = NULL;
554
555 r = read_line(fdinfo, LONG_LINE_MAX, &line);
556 if (r < 0)
557 return r;
558 if (r == 0)
559 break;
560
561 fputs(line, stream);
562 fputc('\n', stream);
563 }
564 }
565
566 errno = 0;
567 stream = safe_fclose(stream);
568
569 if (errno > 0)
570 return -errno;
571
572 *open_fds = TAKE_PTR(buffer);
573
574 return 0;
575 }
576
577 static int get_process_ns(pid_t pid, const char *namespace, ino_t *ns) {
578 const char *p;
579 struct stat stbuf;
580 _cleanup_close_ int proc_ns_dir_fd;
581
582 p = procfs_file_alloca(pid, "ns");
583
584 proc_ns_dir_fd = open(p, O_DIRECTORY | O_CLOEXEC | O_RDONLY);
585 if (proc_ns_dir_fd < 0)
586 return -errno;
587
588 if (fstatat(proc_ns_dir_fd, namespace, &stbuf, /* flags */0) < 0)
589 return -errno;
590
591 *ns = stbuf.st_ino;
592 return 0;
593 }
594
595 static int get_mount_namespace_leader(pid_t pid, pid_t *container_pid) {
596 pid_t cpid = pid, ppid = 0;
597 ino_t proc_mntns;
598 int r = 0;
599
600 r = get_process_ns(pid, "mnt", &proc_mntns);
601 if (r < 0)
602 return r;
603
604 for (;;) {
605 ino_t parent_mntns;
606
607 r = get_process_ppid(cpid, &ppid);
608 if (r < 0)
609 return r;
610
611 r = get_process_ns(ppid, "mnt", &parent_mntns);
612 if (r < 0)
613 return r;
614
615 if (proc_mntns != parent_mntns)
616 break;
617
618 if (ppid == 1)
619 return -ENOENT;
620
621 cpid = ppid;
622 }
623
624 *container_pid = ppid;
625 return 0;
626 }
627
628 /* Returns 1 if the parent was found.
629 * Returns 0 if there is not a process we can call the pid's
630 * container parent (the pid's process isn't 'containerized').
631 * Returns a negative number on errors.
632 */
633 static int get_process_container_parent_cmdline(pid_t pid, char** cmdline) {
634 int r = 0;
635 pid_t container_pid;
636 const char *proc_root_path;
637 struct stat root_stat, proc_root_stat;
638
639 /* To compare inodes of / and /proc/[pid]/root */
640 if (stat("/", &root_stat) < 0)
641 return -errno;
642
643 proc_root_path = procfs_file_alloca(pid, "root");
644 if (stat(proc_root_path, &proc_root_stat) < 0)
645 return -errno;
646
647 /* The process uses system root. */
648 if (proc_root_stat.st_ino == root_stat.st_ino) {
649 *cmdline = NULL;
650 return 0;
651 }
652
653 r = get_mount_namespace_leader(pid, &container_pid);
654 if (r < 0)
655 return r;
656
657 r = get_process_cmdline(container_pid, SIZE_MAX, 0, cmdline);
658 if (r < 0)
659 return r;
660
661 return 1;
662 }
663
664 static int change_uid_gid(const char *context[]) {
665 uid_t uid;
666 gid_t gid;
667 int r;
668
669 r = parse_uid(context[CONTEXT_UID], &uid);
670 if (r < 0)
671 return r;
672
673 if (uid <= SYSTEM_UID_MAX) {
674 const char *user = "systemd-coredump";
675
676 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
677 if (r < 0) {
678 log_warning_errno(r, "Cannot resolve %s user. Proceeding to dump core as root: %m", user);
679 uid = gid = 0;
680 }
681 } else {
682 r = parse_gid(context[CONTEXT_GID], &gid);
683 if (r < 0)
684 return r;
685 }
686
687 return drop_privileges(uid, gid, 0);
688 }
689
690 static bool is_journald_crash(const char *context[_CONTEXT_MAX]) {
691 assert(context);
692
693 return streq_ptr(context[CONTEXT_UNIT], SPECIAL_JOURNALD_SERVICE);
694 }
695
696 static bool is_pid1_crash(const char *context[_CONTEXT_MAX]) {
697 assert(context);
698
699 return streq_ptr(context[CONTEXT_UNIT], SPECIAL_INIT_SCOPE) ||
700 streq_ptr(context[CONTEXT_PID], "1");
701 }
702
703 static int submit_coredump(
704 const char *context[_CONTEXT_MAX],
705 struct iovec_wrapper *iovw,
706 int input_fd) {
707
708 _cleanup_close_ int coredump_fd = -1, coredump_node_fd = -1;
709 _cleanup_free_ char *filename = NULL, *coredump_data = NULL;
710 _cleanup_free_ char *stacktrace = NULL;
711 char *core_message;
712 uint64_t coredump_size = UINT64_MAX;
713 bool truncated = false, journald_crash;
714 int r;
715
716 assert(context);
717 assert(iovw);
718 assert(input_fd >= 0);
719
720 journald_crash = is_journald_crash(context);
721
722 /* Vacuum before we write anything again */
723 (void) coredump_vacuum(-1, arg_keep_free, arg_max_use);
724
725 /* Always stream the coredump to disk, if that's possible */
726 r = save_external_coredump(context, input_fd,
727 &filename, &coredump_node_fd, &coredump_fd, &coredump_size, &truncated);
728 if (r < 0)
729 /* Skip whole core dumping part */
730 goto log;
731
732 /* If we don't want to keep the coredump on disk, remove it now, as later on we
733 * will lack the privileges for it. However, we keep the fd to it, so that we can
734 * still process it and log it. */
735 r = maybe_remove_external_coredump(filename, coredump_size);
736 if (r < 0)
737 return r;
738 if (r == 0) {
739 iovw_put_string_field(iovw, "COREDUMP_FILENAME=", filename);
740
741 } else if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
742 log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
743 coredump_size, arg_external_size_max);
744
745 /* Vacuum again, but exclude the coredump we just created */
746 (void) coredump_vacuum(coredump_node_fd >= 0 ? coredump_node_fd : coredump_fd, arg_keep_free, arg_max_use);
747
748 /* Now, let's drop privileges to become the user who owns the segfaulted process
749 * and allocate the coredump memory under the user's uid. This also ensures that
750 * the credentials journald will see are the ones of the coredumping user, thus
751 * making sure the user gets access to the core dump. Let's also get rid of all
752 * capabilities, if we run as root, we won't need them anymore. */
753 r = change_uid_gid(context);
754 if (r < 0)
755 return log_error_errno(r, "Failed to drop privileges: %m");
756
757 #if HAVE_ELFUTILS
758 /* Try to get a stack trace if we can */
759 if (coredump_size > arg_process_size_max) {
760 log_debug("Not generating stack trace: core size %"PRIu64" is greater "
761 "than %"PRIu64" (the configured maximum)",
762 coredump_size, arg_process_size_max);
763 } else
764 coredump_make_stack_trace(coredump_fd, context[CONTEXT_EXE], &stacktrace);
765 #endif
766
767 log:
768 core_message = strjoina("Process ", context[CONTEXT_PID],
769 " (", context[CONTEXT_COMM], ") of user ",
770 context[CONTEXT_UID], " dumped core.",
771 journald_crash && filename ? "\nCoredump diverted to " : NULL,
772 journald_crash && filename ? filename : NULL);
773
774 core_message = strjoina(core_message, stacktrace ? "\n\n" : NULL, stacktrace);
775
776 if (journald_crash) {
777 /* We cannot log to the journal, so just print the message.
778 * The target was set previously to something safe. */
779 log_dispatch(LOG_ERR, 0, core_message);
780 return 0;
781 }
782
783 iovw_put_string_field(iovw, "MESSAGE=", core_message);
784
785 if (truncated)
786 iovw_put_string_field(iovw, "COREDUMP_TRUNCATED=", "1");
787
788 /* Optionally store the entire coredump in the journal */
789 if (arg_storage == COREDUMP_STORAGE_JOURNAL) {
790 if (coredump_size <= arg_journal_size_max) {
791 size_t sz = 0;
792
793 /* Store the coredump itself in the journal */
794
795 r = allocate_journal_field(coredump_fd, (size_t) coredump_size, &coredump_data, &sz);
796 if (r >= 0) {
797 if (iovw_put(iovw, coredump_data, sz) >= 0)
798 TAKE_PTR(coredump_data);
799 } else
800 log_warning_errno(r, "Failed to attach the core to the journal entry: %m");
801 } else
802 log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
803 coredump_size, arg_journal_size_max);
804 }
805
806 r = sd_journal_sendv(iovw->iovec, iovw->count);
807 if (r < 0)
808 return log_error_errno(r, "Failed to log coredump: %m");
809
810 return 0;
811 }
812
813 static void map_context_fields(const struct iovec *iovec, const char* context[]) {
814
815 static const char * const context_field_names[] = {
816 [CONTEXT_PID] = "COREDUMP_PID=",
817 [CONTEXT_UID] = "COREDUMP_UID=",
818 [CONTEXT_GID] = "COREDUMP_GID=",
819 [CONTEXT_SIGNAL] = "COREDUMP_SIGNAL=",
820 [CONTEXT_TIMESTAMP] = "COREDUMP_TIMESTAMP=",
821 [CONTEXT_RLIMIT] = "COREDUMP_RLIMIT=",
822 [CONTEXT_HOSTNAME] = "COREDUMP_HOSTNAME=",
823 [CONTEXT_COMM] = "COREDUMP_COMM=",
824 [CONTEXT_EXE] = "COREDUMP_EXE=",
825 };
826
827 unsigned i;
828
829 assert(iovec);
830 assert(context);
831
832 for (i = 0; i < ELEMENTSOF(context_field_names); i++) {
833 char *p;
834
835 if (!context_field_names[i])
836 continue;
837
838 p = memory_startswith(iovec->iov_base, iovec->iov_len, context_field_names[i]);
839 if (!p)
840 continue;
841
842 /* Note that these strings are NUL terminated, because we made sure that a trailing NUL byte is in the
843 * buffer, though not included in the iov_len count. (see below) */
844 context[i] = p;
845 break;
846 }
847 }
848
849 static int process_socket(int fd) {
850 _cleanup_close_ int coredump_fd = -1;
851 const char *context[_CONTEXT_MAX] = {};
852 struct iovec_wrapper iovw = {};
853 struct iovec iovec;
854 size_t k;
855 int r;
856
857 assert(fd >= 0);
858
859 log_setup_service();
860
861 log_debug("Processing coredump received on stdin...");
862
863 for (;;) {
864 union {
865 struct cmsghdr cmsghdr;
866 uint8_t buf[CMSG_SPACE(sizeof(int))];
867 } control = {};
868 struct msghdr mh = {
869 .msg_control = &control,
870 .msg_controllen = sizeof(control),
871 .msg_iovlen = 1,
872 };
873 ssize_t n;
874 ssize_t l;
875
876 l = next_datagram_size_fd(fd);
877 if (l < 0) {
878 r = log_error_errno(l, "Failed to determine datagram size to read: %m");
879 goto finish;
880 }
881
882 iovec.iov_len = l;
883 iovec.iov_base = malloc(l + 1);
884 if (!iovec.iov_base) {
885 r = log_oom();
886 goto finish;
887 }
888
889 mh.msg_iov = &iovec;
890
891 n = recvmsg(fd, &mh, MSG_CMSG_CLOEXEC);
892 if (n < 0) {
893 free(iovec.iov_base);
894 r = log_error_errno(errno, "Failed to receive datagram: %m");
895 goto finish;
896 }
897
898 /* The final zero-length datagram carries the file descriptor and tells us
899 * that we're done. */
900 if (n == 0) {
901 struct cmsghdr *cmsg, *found = NULL;
902
903 free(iovec.iov_base);
904
905 CMSG_FOREACH(cmsg, &mh) {
906 if (cmsg->cmsg_level == SOL_SOCKET &&
907 cmsg->cmsg_type == SCM_RIGHTS &&
908 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
909 assert(!found);
910 found = cmsg;
911 }
912 }
913
914 if (!found) {
915 log_error("Coredump file descriptor missing.");
916 r = -EBADMSG;
917 goto finish;
918 }
919
920 assert(coredump_fd < 0);
921 coredump_fd = *(int*) CMSG_DATA(found);
922 break;
923 }
924
925 /* Add trailing NUL byte, in case these are strings */
926 ((char*) iovec.iov_base)[n] = 0;
927 iovec.iov_len = (size_t) n;
928
929 r = iovw_put(&iovw, iovec.iov_base, iovec.iov_len);
930 if (r < 0)
931 goto finish;
932
933 cmsg_close_all(&mh);
934 map_context_fields(&iovec, context);
935 }
936
937 /* Make sure we got all data we really need */
938 assert(context[CONTEXT_PID]);
939 assert(context[CONTEXT_UID]);
940 assert(context[CONTEXT_GID]);
941 assert(context[CONTEXT_SIGNAL]);
942 assert(context[CONTEXT_TIMESTAMP]);
943 assert(context[CONTEXT_RLIMIT]);
944 assert(context[CONTEXT_HOSTNAME]);
945 assert(context[CONTEXT_COMM]);
946 assert(coredump_fd >= 0);
947
948 /* Small quirk: the journal fields contain the timestamp padded with six zeroes,
949 * so that the kernel-supplied 1s granularity timestamps becomes 1µs granularity,
950 * i.e. the granularity systemd usually operates in. Since we are reconstructing
951 * the original kernel context, we chop this off again, here. */
952 k = strlen(context[CONTEXT_TIMESTAMP]);
953 if (k > 6)
954 context[CONTEXT_TIMESTAMP] = strndupa(context[CONTEXT_TIMESTAMP], k - 6);
955
956 r = submit_coredump(context, &iovw, coredump_fd);
957
958 finish:
959 iovw_free_contents(&iovw, true);
960 return r;
961 }
962
963 static int send_iovec(const struct iovec_wrapper *iovw, int input_fd) {
964
965 static const union sockaddr_union sa = {
966 .un.sun_family = AF_UNIX,
967 .un.sun_path = "/run/systemd/coredump",
968 };
969 _cleanup_close_ int fd = -1;
970 size_t i;
971 int r;
972
973 assert(iovw);
974 assert(input_fd >= 0);
975
976 fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0);
977 if (fd < 0)
978 return log_error_errno(errno, "Failed to create coredump socket: %m");
979
980 if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
981 return log_error_errno(errno, "Failed to connect to coredump service: %m");
982
983 for (i = 0; i < iovw->count; i++) {
984 struct msghdr mh = {
985 .msg_iov = iovw->iovec + i,
986 .msg_iovlen = 1,
987 };
988 struct iovec copy[2];
989
990 for (;;) {
991 if (sendmsg(fd, &mh, MSG_NOSIGNAL) >= 0)
992 break;
993
994 if (errno == EMSGSIZE && mh.msg_iov[0].iov_len > 0) {
995 /* This field didn't fit? That's a pity. Given that this is just metadata,
996 * let's truncate the field at half, and try again. We append three dots, in
997 * order to show that this is truncated. */
998
999 if (mh.msg_iov != copy) {
1000 /* We don't want to modify the caller's iovec, hence let's create our
1001 * own array, consisting of two new iovecs, where the first is a
1002 * (truncated) copy of what we want to send, and the second one
1003 * contains the trailing dots. */
1004 copy[0] = iovw->iovec[i];
1005 copy[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);
1006
1007 mh.msg_iov = copy;
1008 mh.msg_iovlen = 2;
1009 }
1010
1011 copy[0].iov_len /= 2; /* halve it, and try again */
1012 continue;
1013 }
1014
1015 return log_error_errno(errno, "Failed to send coredump datagram: %m");
1016 }
1017 }
1018
1019 r = send_one_fd(fd, input_fd, 0);
1020 if (r < 0)
1021 return log_error_errno(r, "Failed to send coredump fd: %m");
1022
1023 return 0;
1024 }
1025
1026 static int gather_pid_metadata(char *context[_CONTEXT_MAX], struct iovec_wrapper *iovw) {
1027
1028 /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
1029 * structure. (It remains valid, with the first n_iovec fields initialized.) */
1030
1031 uid_t owner_uid;
1032 pid_t pid;
1033 char *t;
1034 const char *p;
1035 int r, signo;
1036
1037 r = parse_pid(context[CONTEXT_PID], &pid);
1038 if (r < 0)
1039 return log_error_errno(r, "Failed to parse PID \"%s\": %m", context[CONTEXT_PID]);
1040
1041 r = get_process_comm(pid, &context[CONTEXT_COMM]);
1042 if (r < 0)
1043 return log_error_errno(r, "Failed to get COMM: %m");
1044
1045 r = get_process_exe(pid, &context[CONTEXT_EXE]);
1046 if (r < 0)
1047 log_warning_errno(r, "Failed to get EXE, ignoring: %m");
1048
1049 if (cg_pid_get_unit(pid, &context[CONTEXT_UNIT]) >= 0) {
1050 if (!is_journald_crash((const char**) context)) {
1051 /* OK, now we know it's not the journal, hence we can make use of it now. */
1052 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1053 log_open();
1054 }
1055
1056 /* If this is PID 1 disable coredump collection, we'll unlikely be able to process it later on. */
1057 if (is_pid1_crash((const char**) context)) {
1058 log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
1059 disable_coredumps();
1060 }
1061
1062 iovw_put_string_field(iovw, "COREDUMP_UNIT=", context[CONTEXT_UNIT]);
1063 }
1064
1065 if (cg_pid_get_user_unit(pid, &t) >= 0)
1066 iovw_put_string_field_free(iovw, "COREDUMP_USER_UNIT=", t);
1067
1068 /* The next few are mandatory */
1069 r = iovw_put_string_field(iovw, "COREDUMP_PID=", context[CONTEXT_PID]);
1070 if (r < 0)
1071 return r;
1072
1073 r = iovw_put_string_field(iovw, "COREDUMP_UID=", context[CONTEXT_UID]);
1074 if (r < 0)
1075 return r;
1076
1077 r = iovw_put_string_field(iovw, "COREDUMP_GID=", context[CONTEXT_GID]);
1078 if (r < 0)
1079 return r;
1080
1081 r = iovw_put_string_field(iovw, "COREDUMP_SIGNAL=", context[CONTEXT_SIGNAL]);
1082 if (r < 0)
1083 return r;
1084
1085 r = iovw_put_string_field(iovw, "COREDUMP_RLIMIT=", context[CONTEXT_RLIMIT]);
1086 if (r < 0)
1087 return r;
1088
1089 r = iovw_put_string_field(iovw, "COREDUMP_HOSTNAME=", context[CONTEXT_HOSTNAME]);
1090 if (r < 0)
1091 return r;
1092
1093 r = iovw_put_string_field(iovw, "COREDUMP_COMM=", context[CONTEXT_COMM]);
1094 if (r < 0)
1095 return r;
1096
1097 if (context[CONTEXT_EXE]) {
1098 r = iovw_put_string_field(iovw, "COREDUMP_EXE=", context[CONTEXT_EXE]);
1099 if (r < 0)
1100 return r;
1101 }
1102
1103 /* The next are optional */
1104 if (sd_pid_get_session(pid, &t) >= 0)
1105 (void) iovw_put_string_field_free(iovw, "COREDUMP_SESSION=", t);
1106
1107 if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
1108 r = asprintf(&t, UID_FMT, owner_uid);
1109 if (r > 0)
1110 (void) iovw_put_string_field_free(iovw, "COREDUMP_OWNER_UID=", t);
1111 }
1112
1113 if (sd_pid_get_slice(pid, &t) >= 0)
1114 iovw_put_string_field_free(iovw, "COREDUMP_SLICE=", t);
1115
1116 if (get_process_cmdline(pid, SIZE_MAX, 0, &t) >= 0)
1117 iovw_put_string_field_free(iovw, "COREDUMP_CMDLINE=", t);
1118
1119 if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0)
1120 iovw_put_string_field_free(iovw, "COREDUMP_CGROUP=", t);
1121
1122 if (compose_open_fds(pid, &t) >= 0)
1123 iovw_put_string_field_free(iovw, "COREDUMP_OPEN_FDS=", t);
1124
1125 p = procfs_file_alloca(pid, "status");
1126 if (read_full_file(p, &t, NULL) >= 0)
1127 iovw_put_string_field_free(iovw, "COREDUMP_PROC_STATUS=", t);
1128
1129 p = procfs_file_alloca(pid, "maps");
1130 if (read_full_file(p, &t, NULL) >= 0)
1131 iovw_put_string_field_free(iovw, "COREDUMP_PROC_MAPS=", t);
1132
1133 p = procfs_file_alloca(pid, "limits");
1134 if (read_full_file(p, &t, NULL) >= 0)
1135 iovw_put_string_field_free(iovw, "COREDUMP_PROC_LIMITS=", t);
1136
1137 p = procfs_file_alloca(pid, "cgroup");
1138 if (read_full_file(p, &t, NULL) >=0)
1139 iovw_put_string_field_free(iovw, "COREDUMP_PROC_CGROUP=", t);
1140
1141 p = procfs_file_alloca(pid, "mountinfo");
1142 if (read_full_file(p, &t, NULL) >=0)
1143 iovw_put_string_field_free(iovw, "COREDUMP_PROC_MOUNTINFO=", t);
1144
1145 if (get_process_cwd(pid, &t) >= 0)
1146 iovw_put_string_field_free(iovw, "COREDUMP_CWD=", t);
1147
1148 if (get_process_root(pid, &t) >= 0) {
1149 bool proc_self_root_is_slash;
1150
1151 proc_self_root_is_slash = strcmp(t, "/") == 0;
1152
1153 iovw_put_string_field_free(iovw, "COREDUMP_ROOT=", t);
1154
1155 /* If the process' root is "/", then there is a chance it has
1156 * mounted own root and hence being containerized. */
1157 if (proc_self_root_is_slash && get_process_container_parent_cmdline(pid, &t) > 0)
1158 iovw_put_string_field_free(iovw, "COREDUMP_CONTAINER_CMDLINE=", t);
1159 }
1160
1161 if (get_process_environ(pid, &t) >= 0)
1162 iovw_put_string_field_free(iovw, "COREDUMP_ENVIRON=", t);
1163
1164 t = strjoina(context[CONTEXT_TIMESTAMP], "000000");
1165 (void) iovw_put_string_field(iovw, "COREDUMP_TIMESTAMP=", t);
1166
1167 if (safe_atoi(context[CONTEXT_SIGNAL], &signo) >= 0 && SIGNAL_VALID(signo))
1168 iovw_put_string_field(iovw, "COREDUMP_SIGNAL_NAME=SIG", signal_to_string(signo));
1169
1170 return 0; /* we successfully acquired all metadata */
1171 }
1172
1173 static int process_kernel(int argc, char* argv[]) {
1174
1175 char* context[_CONTEXT_MAX] = {};
1176 struct iovec_wrapper *iovw;
1177 int r;
1178
1179 log_debug("Processing coredump received from the kernel...");
1180
1181 if (argc < CONTEXT_COMM + 1)
1182 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1183 "Not enough arguments passed by the kernel (%i, expected %i).",
1184 argc - 1, CONTEXT_COMM + 1 - 1);
1185
1186 context[CONTEXT_PID] = argv[1 + CONTEXT_PID];
1187 context[CONTEXT_UID] = argv[1 + CONTEXT_UID];
1188 context[CONTEXT_GID] = argv[1 + CONTEXT_GID];
1189 context[CONTEXT_SIGNAL] = argv[1 + CONTEXT_SIGNAL];
1190 context[CONTEXT_TIMESTAMP] = argv[1 + CONTEXT_TIMESTAMP];
1191 context[CONTEXT_RLIMIT] = argv[1 + CONTEXT_RLIMIT];
1192 context[CONTEXT_HOSTNAME] = argv[1 + CONTEXT_HOSTNAME];
1193
1194 iovw = iovw_new();
1195 if (!iovw)
1196 return log_oom();
1197
1198 r = gather_pid_metadata(context, iovw);
1199 if (r < 0)
1200 goto finish;
1201
1202 iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR);
1203 iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
1204
1205 if (is_journald_crash((const char**) context) || is_pid1_crash((const char**) context))
1206 r = submit_coredump((const char**) context, iovw, STDIN_FILENO);
1207 else
1208 r = send_iovec(iovw, STDIN_FILENO);
1209
1210 finish:
1211 iovw = iovw_free_free(iovw);
1212
1213 /* Those fields are allocated by gather_pid_metadata */
1214 free(context[CONTEXT_COMM]);
1215 free(context[CONTEXT_EXE]);
1216 free(context[CONTEXT_UNIT]);
1217
1218 return r;
1219 }
1220
1221 static int process_backtrace(int argc, char *argv[]) {
1222 char *context[_CONTEXT_MAX] = {};
1223 struct iovec_wrapper *iovw;
1224 char *message;
1225 size_t i;
1226 int r;
1227 _cleanup_(journal_importer_cleanup) JournalImporter importer = JOURNAL_IMPORTER_INIT(STDIN_FILENO);
1228
1229 log_debug("Processing backtrace on stdin...");
1230
1231 if (argc < CONTEXT_COMM + 2)
1232 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1233 "Not enough arguments passed (%i, expected %i).",
1234 argc - 1, CONTEXT_COMM + 2 - 1);
1235
1236 context[CONTEXT_PID] = argv[2 + CONTEXT_PID];
1237 context[CONTEXT_UID] = argv[2 + CONTEXT_UID];
1238 context[CONTEXT_GID] = argv[2 + CONTEXT_GID];
1239 context[CONTEXT_SIGNAL] = argv[2 + CONTEXT_SIGNAL];
1240 context[CONTEXT_TIMESTAMP] = argv[2 + CONTEXT_TIMESTAMP];
1241 context[CONTEXT_RLIMIT] = argv[2 + CONTEXT_RLIMIT];
1242 context[CONTEXT_HOSTNAME] = argv[2 + CONTEXT_HOSTNAME];
1243
1244 iovw = iovw_new();
1245 if (!iovw)
1246 return log_oom();
1247
1248 r = gather_pid_metadata(context, iovw);
1249 if (r < 0)
1250 goto finish;
1251
1252 iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR);
1253 iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
1254
1255 for (;;) {
1256 r = journal_importer_process_data(&importer);
1257 if (r < 0) {
1258 log_error_errno(r, "Failed to parse journal entry on stdin: %m");
1259 goto finish;
1260 }
1261 if (r == 1 || /* complete entry */
1262 journal_importer_eof(&importer)) /* end of data */
1263 break;
1264 }
1265
1266 if (journal_importer_eof(&importer)) {
1267 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
1268
1269 message = strjoina("Process ", context[CONTEXT_PID],
1270 " (", context[CONTEXT_COMM], ")"
1271 " of user ", context[CONTEXT_UID],
1272 " failed with ", context[CONTEXT_SIGNAL]);
1273
1274 r = iovw_put_string_field(iovw, "MESSAGE=", message);
1275 if (r < 0)
1276 return r;
1277 } else {
1278 /* The imported iovecs are not supposed to be freed by us so let's store
1279 * them at the end of the array so we can skip them while freeing the
1280 * rest. */
1281
1282 for (i = 0; i < importer.iovw.count; i++) {
1283 struct iovec *iovec = importer.iovw.iovec + i;
1284
1285 iovw_put(iovw, iovec->iov_base, iovec->iov_len);
1286 }
1287 }
1288
1289 r = sd_journal_sendv(iovw->iovec, iovw->count);
1290 if (r < 0)
1291 log_error_errno(r, "Failed to log backtrace: %m");
1292
1293 finish:
1294 iovw->count -= importer.iovw.count;
1295 iovw = iovw_free_free(iovw);
1296
1297 /* Those fields are allocated by gather_pid_metadata */
1298 free(context[CONTEXT_COMM]);
1299 free(context[CONTEXT_EXE]);
1300 free(context[CONTEXT_UNIT]);
1301
1302 return r;
1303 }
1304
1305 static int run(int argc, char *argv[]) {
1306 int r;
1307
1308 /* First, log to a safe place, since we don't know what crashed and it might
1309 * be journald which we'd rather not log to then. */
1310
1311 log_set_target(LOG_TARGET_KMSG);
1312 log_open();
1313
1314 /* Make sure we never enter a loop */
1315 (void) prctl(PR_SET_DUMPABLE, 0);
1316
1317 /* Ignore all parse errors */
1318 (void) parse_config();
1319
1320 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
1321 log_debug("Selected compression %s.", yes_no(arg_compress));
1322
1323 r = sd_listen_fds(false);
1324 if (r < 0)
1325 return log_error_errno(r, "Failed to determine the number of file descriptors: %m");
1326
1327 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1328 * are invoked from the kernel as coredump handler. */
1329 if (r == 0) {
1330 if (streq_ptr(argv[1], "--backtrace"))
1331 return process_backtrace(argc, argv);
1332 else
1333 return process_kernel(argc, argv);
1334 } else if (r == 1)
1335 return process_socket(SD_LISTEN_FDS_START);
1336
1337 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1338 "Received unexpected number of file descriptors.");
1339 }
1340
1341 DEFINE_MAIN_FUNCTION(run);