1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include <elfutils/libdwfl.h>
14 #include "sd-daemon.h"
15 #include "sd-journal.h"
17 #include "sd-messages.h"
20 #include "alloc-util.h"
21 #include "capability-util.h"
22 #include "cgroup-util.h"
24 #include "conf-parser.h"
26 #include "coredump-vacuum.h"
27 #include "dirent-util.h"
33 #include "journal-importer.h"
36 #include "main-func.h"
37 #include "memory-util.h"
40 #include "parse-util.h"
41 #include "process-util.h"
42 #include "signal-util.h"
43 #include "socket-util.h"
45 #include "stacktrace.h"
46 #include "string-table.h"
47 #include "string-util.h"
49 #include "tmpfile-util.h"
50 #include "user-util.h"
52 /* The maximum size up to which we process coredumps */
53 #define PROCESS_SIZE_MAX ((uint64_t) (2LLU*1024LLU*1024LLU*1024LLU))
55 /* The maximum size up to which we leave the coredump around on disk */
56 #define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
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))
62 /* oss-fuzz limits memory usage. */
63 #define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
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
);
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[].
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.
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
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",
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");
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;
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
},
130 return config_parse_many_nulstr(PKGSYSCONFDIR
"/coredump.conf",
131 CONF_PATHS_NULSTR("systemd/coredump.conf.d"),
133 config_item_table_lookup
, items
,
134 CONFIG_PARSE_WARN
, NULL
);
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
);
146 static int fix_acl(int fd
, uid_t uid
) {
149 _cleanup_(acl_freep
) acl_t acl
= NULL
;
151 acl_permset_t permset
;
156 if (uid_is_system(uid
) || uid_is_dynamic(uid
) || uid
== UID_NOBODY
)
159 /* Make sure normal users can read (but not write or delete)
160 * their own coredumps */
162 acl
= acl_get_fd(fd
);
164 return log_error_errno(errno
, "Failed to get ACL: %m");
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");
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");
175 r
= calc_acl_mask_if_needed(&acl
);
177 return log_warning_errno(r
, "Failed to patch ACL: %m");
179 if (acl_set_fd(fd
, acl
) < 0)
180 return log_error_errno(errno
, "Failed to apply ACL: %m");
186 static int fix_xattr(int fd
, const char *context
[_CONTEXT_MAX
]) {
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",
205 /* Attach some metadata to coredumps via extended
206 * attributes. Just because we can. */
208 for (i
= 0; i
< _CONTEXT_MAX
; i
++) {
211 if (isempty(context
[i
]) || !xattrs
[i
])
214 k
= fsetxattr(fd
, xattrs
[i
], context
[i
], strlen(context
[i
]), XATTR_CREATE
);
222 #define filename_escape(s) xescape((s), "./ ")
224 static const char *coredump_tmpfile_name(const char *s
) {
225 return s
? s
: "(unnamed temporary file)";
228 static int fix_permissions(
230 const char *filename
,
232 const char *context
[_CONTEXT_MAX
],
241 /* Ignore errors on these */
242 (void) fchmod(fd
, 0640);
243 (void) fix_acl(fd
, uid
);
244 (void) fix_xattr(fd
, context
);
247 return log_error_errno(errno
, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename
));
249 (void) fsync_directory_of_file(fd
);
251 r
= link_tmpfile(fd
, filename
, target
);
253 return log_error_errno(r
, "Failed to move coredump %s into place: %m", target
);
258 static int maybe_remove_external_coredump(const char *filename
, uint64_t size
) {
260 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
262 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
&&
263 size
<= arg_external_size_max
)
269 if (unlink(filename
) < 0 && errno
!= ENOENT
)
270 return log_error_errno(errno
, "Failed to unlink %s: %m", filename
);
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
= {};
282 c
= filename_escape(context
[CONTEXT_COMM
]);
286 u
= filename_escape(context
[CONTEXT_UID
]);
290 r
= sd_id128_get_boot(&boot
);
294 p
= filename_escape(context
[CONTEXT_PID
]);
298 t
= filename_escape(context
[CONTEXT_TIMESTAMP
]);
303 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR
".%s.%s000000",
306 SD_ID128_FORMAT_VAL(boot
),
314 static int save_external_coredump(
315 const char *context
[_CONTEXT_MAX
],
321 bool *ret_truncated
) {
323 _cleanup_free_
char *fn
= NULL
, *tmp
= NULL
;
324 _cleanup_close_
int fd
= -1;
325 uint64_t rlimit
, process_limit
, max_size
;
331 assert(ret_filename
);
336 r
= parse_uid(context
[CONTEXT_UID
], &uid
);
338 return log_error_errno(r
, "Failed to parse UID: %m");
340 r
= safe_atou64(context
[CONTEXT_RLIMIT
], &rlimit
);
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
]);
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.");
357 /* Never store more than the process configured, or than we actually shall keep or process */
358 max_size
= MIN(rlimit
, process_limit
);
360 r
= make_filename(context
, &fn
);
362 return log_error_errno(r
, "Failed to determine coredump file name: %m");
364 (void) mkdir_p_label("/var/lib/systemd/coredump", 0755);
366 fd
= open_tmpfile_linkable(fn
, O_RDWR
|O_CLOEXEC
, &tmp
);
368 return log_error_errno(fd
, "Failed to create temporary file for coredump %s: %m", fn
);
370 r
= copy_bytes(input_fd
, fd
, max_size
, 0);
372 log_error_errno(r
, "Cannot store coredump of %s (%s): %m", context
[CONTEXT_PID
], context
[CONTEXT_COMM
]);
375 *ret_truncated
= r
== 1;
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
);
382 if (fstat(fd
, &st
) < 0) {
383 log_error_errno(errno
, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp
));
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
));
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
)) {
396 _cleanup_free_
char *fn_compressed
= NULL
, *tmp_compressed
= NULL
;
397 _cleanup_close_
int fd_compressed
= -1;
399 fn_compressed
= strjoin(fn
, COMPRESSED_EXT
);
400 if (!fn_compressed
) {
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
);
411 r
= compress_stream(fd
, fd_compressed
, -1);
413 log_error_errno(r
, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed
));
414 goto fail_compressed
;
417 r
= fix_permissions(fd_compressed
, tmp_compressed
, fn_compressed
, context
, uid
);
419 goto fail_compressed
;
421 /* OK, this worked, we can get rid of the uncompressed version now */
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 */
434 (void) unlink(tmp_compressed
);
440 r
= fix_permissions(fd
, tmp
, fn
, context
, uid
);
444 *ret_filename
= TAKE_PTR(fn
);
445 *ret_data_fd
= TAKE_FD(fd
);
447 *ret_size
= (uint64_t) st
.st_size
;
457 static int allocate_journal_field(int fd
, size_t size
, char **ret
, size_t *ret_size
) {
458 _cleanup_free_
char *field
= NULL
;
465 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1)
466 return log_warning_errno(errno
, "Failed to seek: %m");
468 field
= malloc(9 + size
);
470 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
474 memcpy(field
, "COREDUMP=", 9);
476 n
= read(fd
, field
+ 9, size
);
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.");
483 *ret
= TAKE_PTR(field
);
484 *ret_size
= size
+ 9;
489 /* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
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
;
514 assert(open_fds
!= NULL
);
516 path
= procfs_file_alloca(pid
, "fd");
517 proc_fd_dir
= opendir(path
);
521 proc_fdinfo_fd
= openat(dirfd(proc_fd_dir
), "../fdinfo", O_DIRECTORY
|O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
522 if (proc_fdinfo_fd
< 0)
525 stream
= open_memstream_unlocked(&buffer
, &size
);
529 FOREACH_DIRENT(dent
, proc_fd_dir
, return -errno
) {
530 _cleanup_fclose_
FILE *fdinfo
= NULL
;
531 _cleanup_free_
char *fdname
= NULL
;
534 r
= readlinkat_malloc(dirfd(proc_fd_dir
), dent
->d_name
, &fdname
);
538 fprintf(stream
, "%s%s:%s\n", fddelim
, dent
->d_name
, fdname
);
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
);
546 fdinfo
= fdopen(fd
, "r");
553 _cleanup_free_
char *line
= NULL
;
555 r
= read_line(fdinfo
, LONG_LINE_MAX
, &line
);
567 stream
= safe_fclose(stream
);
572 *open_fds
= TAKE_PTR(buffer
);
577 static int get_process_ns(pid_t pid
, const char *namespace, ino_t
*ns
) {
580 _cleanup_close_
int proc_ns_dir_fd
;
582 p
= procfs_file_alloca(pid
, "ns");
584 proc_ns_dir_fd
= open(p
, O_DIRECTORY
| O_CLOEXEC
| O_RDONLY
);
585 if (proc_ns_dir_fd
< 0)
588 if (fstatat(proc_ns_dir_fd
, namespace, &stbuf
, /* flags */0) < 0)
595 static int get_mount_namespace_leader(pid_t pid
, pid_t
*container_pid
) {
596 pid_t cpid
= pid
, ppid
= 0;
600 r
= get_process_ns(pid
, "mnt", &proc_mntns
);
607 r
= get_process_ppid(cpid
, &ppid
);
611 r
= get_process_ns(ppid
, "mnt", &parent_mntns
);
615 if (proc_mntns
!= parent_mntns
)
624 *container_pid
= ppid
;
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.
633 static int get_process_container_parent_cmdline(pid_t pid
, char** cmdline
) {
636 const char *proc_root_path
;
637 struct stat root_stat
, proc_root_stat
;
639 /* To compare inodes of / and /proc/[pid]/root */
640 if (stat("/", &root_stat
) < 0)
643 proc_root_path
= procfs_file_alloca(pid
, "root");
644 if (stat(proc_root_path
, &proc_root_stat
) < 0)
647 /* The process uses system root. */
648 if (proc_root_stat
.st_ino
== root_stat
.st_ino
) {
653 r
= get_mount_namespace_leader(pid
, &container_pid
);
657 r
= get_process_cmdline(container_pid
, SIZE_MAX
, 0, cmdline
);
664 static int change_uid_gid(const char *context
[]) {
669 r
= parse_uid(context
[CONTEXT_UID
], &uid
);
673 if (uid
<= SYSTEM_UID_MAX
) {
674 const char *user
= "systemd-coredump";
676 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
678 log_warning_errno(r
, "Cannot resolve %s user. Proceeding to dump core as root: %m", user
);
682 r
= parse_gid(context
[CONTEXT_GID
], &gid
);
687 return drop_privileges(uid
, gid
, 0);
690 static bool is_journald_crash(const char *context
[_CONTEXT_MAX
]) {
693 return streq_ptr(context
[CONTEXT_UNIT
], SPECIAL_JOURNALD_SERVICE
);
696 static bool is_pid1_crash(const char *context
[_CONTEXT_MAX
]) {
699 return streq_ptr(context
[CONTEXT_UNIT
], SPECIAL_INIT_SCOPE
) ||
700 streq_ptr(context
[CONTEXT_PID
], "1");
703 static int submit_coredump(
704 const char *context
[_CONTEXT_MAX
],
705 struct iovec_wrapper
*iovw
,
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
;
712 uint64_t coredump_size
= UINT64_MAX
;
713 bool truncated
= false, journald_crash
;
718 assert(input_fd
>= 0);
720 journald_crash
= is_journald_crash(context
);
722 /* Vacuum before we write anything again */
723 (void) coredump_vacuum(-1, arg_keep_free
, arg_max_use
);
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
);
729 /* Skip whole core dumping part */
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
);
739 iovw_put_string_field(iovw
, "COREDUMP_FILENAME=", filename
);
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
);
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
);
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
);
755 return log_error_errno(r
, "Failed to drop privileges: %m");
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
);
764 coredump_make_stack_trace(coredump_fd
, context
[CONTEXT_EXE
], &stacktrace
);
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
);
774 core_message
= strjoina(core_message
, stacktrace
? "\n\n" : NULL
, stacktrace
);
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
);
783 iovw_put_string_field(iovw
, "MESSAGE=", core_message
);
786 iovw_put_string_field(iovw
, "COREDUMP_TRUNCATED=", "1");
788 /* Optionally store the entire coredump in the journal */
789 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
) {
790 if (coredump_size
<= arg_journal_size_max
) {
793 /* Store the coredump itself in the journal */
795 r
= allocate_journal_field(coredump_fd
, (size_t) coredump_size
, &coredump_data
, &sz
);
797 if (iovw_put(iovw
, coredump_data
, sz
) >= 0)
798 TAKE_PTR(coredump_data
);
800 log_warning_errno(r
, "Failed to attach the core to the journal entry: %m");
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
);
806 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
808 return log_error_errno(r
, "Failed to log coredump: %m");
813 static void map_context_fields(const struct iovec
*iovec
, const char* context
[]) {
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=",
832 for (i
= 0; i
< ELEMENTSOF(context_field_names
); i
++) {
835 if (!context_field_names
[i
])
838 p
= memory_startswith(iovec
->iov_base
, iovec
->iov_len
, context_field_names
[i
]);
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) */
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
= {};
861 log_debug("Processing coredump received on stdin...");
865 struct cmsghdr cmsghdr
;
866 uint8_t buf
[CMSG_SPACE(sizeof(int))];
869 .msg_control
= &control
,
870 .msg_controllen
= sizeof(control
),
876 l
= next_datagram_size_fd(fd
);
878 r
= log_error_errno(l
, "Failed to determine datagram size to read: %m");
883 iovec
.iov_base
= malloc(l
+ 1);
884 if (!iovec
.iov_base
) {
891 n
= recvmsg(fd
, &mh
, MSG_CMSG_CLOEXEC
);
893 free(iovec
.iov_base
);
894 r
= log_error_errno(errno
, "Failed to receive datagram: %m");
898 /* The final zero-length datagram carries the file descriptor and tells us
899 * that we're done. */
901 struct cmsghdr
*cmsg
, *found
= NULL
;
903 free(iovec
.iov_base
);
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))) {
915 log_error("Coredump file descriptor missing.");
920 assert(coredump_fd
< 0);
921 coredump_fd
= *(int*) CMSG_DATA(found
);
925 /* Add trailing NUL byte, in case these are strings */
926 ((char*) iovec
.iov_base
)[n
] = 0;
927 iovec
.iov_len
= (size_t) n
;
929 r
= iovw_put(&iovw
, iovec
.iov_base
, iovec
.iov_len
);
934 map_context_fields(&iovec
, context
);
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);
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
]);
954 context
[CONTEXT_TIMESTAMP
] = strndupa(context
[CONTEXT_TIMESTAMP
], k
- 6);
956 r
= submit_coredump(context
, &iovw
, coredump_fd
);
959 iovw_free_contents(&iovw
, true);
963 static int send_iovec(const struct iovec_wrapper
*iovw
, int input_fd
) {
965 static const union sockaddr_union sa
= {
966 .un
.sun_family
= AF_UNIX
,
967 .un
.sun_path
= "/run/systemd/coredump",
969 _cleanup_close_
int fd
= -1;
974 assert(input_fd
>= 0);
976 fd
= socket(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0);
978 return log_error_errno(errno
, "Failed to create coredump socket: %m");
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");
983 for (i
= 0; i
< iovw
->count
; i
++) {
985 .msg_iov
= iovw
->iovec
+ i
,
988 struct iovec copy
[2];
991 if (sendmsg(fd
, &mh
, MSG_NOSIGNAL
) >= 0)
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. */
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);
1011 copy
[0].iov_len
/= 2; /* halve it, and try again */
1015 return log_error_errno(errno
, "Failed to send coredump datagram: %m");
1019 r
= send_one_fd(fd
, input_fd
, 0);
1021 return log_error_errno(r
, "Failed to send coredump fd: %m");
1026 static int gather_pid_metadata(char *context
[_CONTEXT_MAX
], struct iovec_wrapper
*iovw
) {
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.) */
1037 r
= parse_pid(context
[CONTEXT_PID
], &pid
);
1039 return log_error_errno(r
, "Failed to parse PID \"%s\": %m", context
[CONTEXT_PID
]);
1041 r
= get_process_comm(pid
, &context
[CONTEXT_COMM
]);
1043 return log_error_errno(r
, "Failed to get COMM: %m");
1045 r
= get_process_exe(pid
, &context
[CONTEXT_EXE
]);
1047 log_warning_errno(r
, "Failed to get EXE, ignoring: %m");
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
);
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();
1062 iovw_put_string_field(iovw
, "COREDUMP_UNIT=", context
[CONTEXT_UNIT
]);
1065 if (cg_pid_get_user_unit(pid
, &t
) >= 0)
1066 iovw_put_string_field_free(iovw
, "COREDUMP_USER_UNIT=", t
);
1068 /* The next few are mandatory */
1069 r
= iovw_put_string_field(iovw
, "COREDUMP_PID=", context
[CONTEXT_PID
]);
1073 r
= iovw_put_string_field(iovw
, "COREDUMP_UID=", context
[CONTEXT_UID
]);
1077 r
= iovw_put_string_field(iovw
, "COREDUMP_GID=", context
[CONTEXT_GID
]);
1081 r
= iovw_put_string_field(iovw
, "COREDUMP_SIGNAL=", context
[CONTEXT_SIGNAL
]);
1085 r
= iovw_put_string_field(iovw
, "COREDUMP_RLIMIT=", context
[CONTEXT_RLIMIT
]);
1089 r
= iovw_put_string_field(iovw
, "COREDUMP_HOSTNAME=", context
[CONTEXT_HOSTNAME
]);
1093 r
= iovw_put_string_field(iovw
, "COREDUMP_COMM=", context
[CONTEXT_COMM
]);
1097 if (context
[CONTEXT_EXE
]) {
1098 r
= iovw_put_string_field(iovw
, "COREDUMP_EXE=", context
[CONTEXT_EXE
]);
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
);
1107 if (sd_pid_get_owner_uid(pid
, &owner_uid
) >= 0) {
1108 r
= asprintf(&t
, UID_FMT
, owner_uid
);
1110 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OWNER_UID=", t
);
1113 if (sd_pid_get_slice(pid
, &t
) >= 0)
1114 iovw_put_string_field_free(iovw
, "COREDUMP_SLICE=", t
);
1116 if (get_process_cmdline(pid
, SIZE_MAX
, 0, &t
) >= 0)
1117 iovw_put_string_field_free(iovw
, "COREDUMP_CMDLINE=", t
);
1119 if (cg_pid_get_path_shifted(pid
, NULL
, &t
) >= 0)
1120 iovw_put_string_field_free(iovw
, "COREDUMP_CGROUP=", t
);
1122 if (compose_open_fds(pid
, &t
) >= 0)
1123 iovw_put_string_field_free(iovw
, "COREDUMP_OPEN_FDS=", t
);
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
);
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
);
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
);
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
);
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
);
1145 if (get_process_cwd(pid
, &t
) >= 0)
1146 iovw_put_string_field_free(iovw
, "COREDUMP_CWD=", t
);
1148 if (get_process_root(pid
, &t
) >= 0) {
1149 bool proc_self_root_is_slash
;
1151 proc_self_root_is_slash
= strcmp(t
, "/") == 0;
1153 iovw_put_string_field_free(iovw
, "COREDUMP_ROOT=", t
);
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
);
1161 if (get_process_environ(pid
, &t
) >= 0)
1162 iovw_put_string_field_free(iovw
, "COREDUMP_ENVIRON=", t
);
1164 t
= strjoina(context
[CONTEXT_TIMESTAMP
], "000000");
1165 (void) iovw_put_string_field(iovw
, "COREDUMP_TIMESTAMP=", t
);
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
));
1170 return 0; /* we successfully acquired all metadata */
1173 static int process_kernel(int argc
, char* argv
[]) {
1175 char* context
[_CONTEXT_MAX
] = {};
1176 struct iovec_wrapper
*iovw
;
1179 log_debug("Processing coredump received from the kernel...");
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);
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
];
1198 r
= gather_pid_metadata(context
, iovw
);
1202 iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR
);
1203 iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1205 if (is_journald_crash((const char**) context
) || is_pid1_crash((const char**) context
))
1206 r
= submit_coredump((const char**) context
, iovw
, STDIN_FILENO
);
1208 r
= send_iovec(iovw
, STDIN_FILENO
);
1211 iovw
= iovw_free_free(iovw
);
1213 /* Those fields are allocated by gather_pid_metadata */
1214 free(context
[CONTEXT_COMM
]);
1215 free(context
[CONTEXT_EXE
]);
1216 free(context
[CONTEXT_UNIT
]);
1221 static int process_backtrace(int argc
, char *argv
[]) {
1222 char *context
[_CONTEXT_MAX
] = {};
1223 struct iovec_wrapper
*iovw
;
1227 _cleanup_(journal_importer_cleanup
) JournalImporter importer
= JOURNAL_IMPORTER_INIT(STDIN_FILENO
);
1229 log_debug("Processing backtrace on stdin...");
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);
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
];
1248 r
= gather_pid_metadata(context
, iovw
);
1252 iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR
);
1253 iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1256 r
= journal_importer_process_data(&importer
);
1258 log_error_errno(r
, "Failed to parse journal entry on stdin: %m");
1261 if (r
== 1 || /* complete entry */
1262 journal_importer_eof(&importer
)) /* end of data */
1266 if (journal_importer_eof(&importer
)) {
1267 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
1269 message
= strjoina("Process ", context
[CONTEXT_PID
],
1270 " (", context
[CONTEXT_COMM
], ")"
1271 " of user ", context
[CONTEXT_UID
],
1272 " failed with ", context
[CONTEXT_SIGNAL
]);
1274 r
= iovw_put_string_field(iovw
, "MESSAGE=", message
);
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
1282 for (i
= 0; i
< importer
.iovw
.count
; i
++) {
1283 struct iovec
*iovec
= importer
.iovw
.iovec
+ i
;
1285 iovw_put(iovw
, iovec
->iov_base
, iovec
->iov_len
);
1289 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
1291 log_error_errno(r
, "Failed to log backtrace: %m");
1294 iovw
->count
-= importer
.iovw
.count
;
1295 iovw
= iovw_free_free(iovw
);
1297 /* Those fields are allocated by gather_pid_metadata */
1298 free(context
[CONTEXT_COMM
]);
1299 free(context
[CONTEXT_EXE
]);
1300 free(context
[CONTEXT_UNIT
]);
1305 static int run(int argc
, char *argv
[]) {
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. */
1311 log_set_target(LOG_TARGET_KMSG
);
1314 /* Make sure we never enter a loop */
1315 (void) prctl(PR_SET_DUMPABLE
, 0);
1317 /* Ignore all parse errors */
1318 (void) parse_config();
1320 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage
));
1321 log_debug("Selected compression %s.", yes_no(arg_compress
));
1323 r
= sd_listen_fds(false);
1325 return log_error_errno(r
, "Failed to determine the number of file descriptors: %m");
1327 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1328 * are invoked from the kernel as coredump handler. */
1330 if (streq_ptr(argv
[1], "--backtrace"))
1331 return process_backtrace(argc
, argv
);
1333 return process_kernel(argc
, argv
);
1335 return process_socket(SD_LISTEN_FDS_START
);
1337 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1338 "Received unexpected number of file descriptors.");
1341 DEFINE_MAIN_FUNCTION(run
);