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"
39 #include "parse-util.h"
40 #include "process-util.h"
41 #include "signal-util.h"
42 #include "socket-util.h"
44 #include "stacktrace.h"
45 #include "string-table.h"
46 #include "string-util.h"
48 #include "tmpfile-util.h"
49 #include "user-util.h"
51 /* The maximum size up to which we process coredumps */
52 #define PROCESS_SIZE_MAX ((uint64_t) (2LLU*1024LLU*1024LLU*1024LLU))
54 /* The maximum size up to which we leave the coredump around on disk */
55 #define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
57 /* The maximum size up to which we store the coredump in the journal */
58 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
59 #define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
61 /* oss-fuzz limits memory usage. */
62 #define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
65 /* Make sure to not make this larger than the maximum journal entry
66 * size. See DATA_SIZE_MAX in journal-importer.h. */
67 assert_cc(JOURNAL_SIZE_MAX
<= DATA_SIZE_MAX
);
70 /* We use these as array indexes for our process metadata cache.
72 * The first indices of the cache stores the same metadata as the ones passed by
73 * the kernel via argv[], ie the strings array passed by the kernel according to
74 * our pattern defined in /proc/sys/kernel/core_pattern (see man:core(5)). */
76 META_ARGV_PID
, /* %P: as seen in the initial pid namespace */
77 META_ARGV_UID
, /* %u: as seen in the initial user namespace */
78 META_ARGV_GID
, /* %g: as seen in the initial user namespace */
79 META_ARGV_SIGNAL
, /* %s: number of signal causing dump */
80 META_ARGV_TIMESTAMP
, /* %t: time of dump, expressed as seconds since the Epoch */
81 META_ARGV_RLIMIT
, /* %c: core file size soft resource limit */
82 META_ARGV_HOSTNAME
, /* %h: hostname */
85 /* The following indexes are cached for a couple of special fields we use (and
86 * thereby need to be retrieved quickly) for naming coredump files, and attaching
87 * xattrs. Unlike the previous ones they are retrieved from the runtime
90 META_COMM
= _META_ARGV_MAX
,
93 /* The rest are similar to the previous ones except that we won't fail if one of
96 META_EXE
= _META_MANDATORY_MAX
,
101 static const char * const meta_field_names
[_META_MAX
] = {
102 [META_ARGV_PID
] = "COREDUMP_PID=",
103 [META_ARGV_UID
] = "COREDUMP_UID=",
104 [META_ARGV_GID
] = "COREDUMP_GID=",
105 [META_ARGV_SIGNAL
] = "COREDUMP_SIGNAL=",
106 [META_ARGV_TIMESTAMP
] = "COREDUMP_TIMESTAMP=",
107 [META_ARGV_RLIMIT
] = "COREDUMP_RLIMIT=",
108 [META_ARGV_HOSTNAME
] = "COREDUMP_HOSTNAME=",
109 [META_COMM
] = "COREDUMP_COMM=",
110 [META_EXE
] = "COREDUMP_EXE=",
111 [META_UNIT
] = "COREDUMP_UNIT=",
114 typedef struct Context
{
115 const char *meta
[_META_MAX
];
121 typedef enum CoredumpStorage
{
122 COREDUMP_STORAGE_NONE
,
123 COREDUMP_STORAGE_EXTERNAL
,
124 COREDUMP_STORAGE_JOURNAL
,
125 _COREDUMP_STORAGE_MAX
,
126 _COREDUMP_STORAGE_INVALID
= -1
129 static const char* const coredump_storage_table
[_COREDUMP_STORAGE_MAX
] = {
130 [COREDUMP_STORAGE_NONE
] = "none",
131 [COREDUMP_STORAGE_EXTERNAL
] = "external",
132 [COREDUMP_STORAGE_JOURNAL
] = "journal",
135 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage
, CoredumpStorage
);
136 static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage
, coredump_storage
, CoredumpStorage
, "Failed to parse storage setting");
138 static CoredumpStorage arg_storage
= COREDUMP_STORAGE_EXTERNAL
;
139 static bool arg_compress
= true;
140 static uint64_t arg_process_size_max
= PROCESS_SIZE_MAX
;
141 static uint64_t arg_external_size_max
= EXTERNAL_SIZE_MAX
;
142 static uint64_t arg_journal_size_max
= JOURNAL_SIZE_MAX
;
143 static uint64_t arg_keep_free
= (uint64_t) -1;
144 static uint64_t arg_max_use
= (uint64_t) -1;
146 static int parse_config(void) {
147 static const ConfigTableItem items
[] = {
148 { "Coredump", "Storage", config_parse_coredump_storage
, 0, &arg_storage
},
149 { "Coredump", "Compress", config_parse_bool
, 0, &arg_compress
},
150 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64
, 0, &arg_process_size_max
},
151 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64
, 0, &arg_external_size_max
},
152 { "Coredump", "JournalSizeMax", config_parse_iec_size
, 0, &arg_journal_size_max
},
153 { "Coredump", "KeepFree", config_parse_iec_uint64
, 0, &arg_keep_free
},
154 { "Coredump", "MaxUse", config_parse_iec_uint64
, 0, &arg_max_use
},
158 return config_parse_many_nulstr(PKGSYSCONFDIR
"/coredump.conf",
159 CONF_PATHS_NULSTR("systemd/coredump.conf.d"),
161 config_item_table_lookup
, items
,
162 CONFIG_PARSE_WARN
, NULL
);
165 static uint64_t storage_size_max(void) {
166 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
)
167 return arg_external_size_max
;
168 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
)
169 return arg_journal_size_max
;
170 assert(arg_storage
== COREDUMP_STORAGE_NONE
);
174 static int fix_acl(int fd
, uid_t uid
) {
177 _cleanup_(acl_freep
) acl_t acl
= NULL
;
179 acl_permset_t permset
;
184 if (uid_is_system(uid
) || uid_is_dynamic(uid
) || uid
== UID_NOBODY
)
187 /* Make sure normal users can read (but not write or delete)
188 * their own coredumps */
190 acl
= acl_get_fd(fd
);
192 return log_error_errno(errno
, "Failed to get ACL: %m");
194 if (acl_create_entry(&acl
, &entry
) < 0 ||
195 acl_set_tag_type(entry
, ACL_USER
) < 0 ||
196 acl_set_qualifier(entry
, &uid
) < 0)
197 return log_error_errno(errno
, "Failed to patch ACL: %m");
199 if (acl_get_permset(entry
, &permset
) < 0 ||
200 acl_add_perm(permset
, ACL_READ
) < 0)
201 return log_warning_errno(errno
, "Failed to patch ACL: %m");
203 r
= calc_acl_mask_if_needed(&acl
);
205 return log_warning_errno(r
, "Failed to patch ACL: %m");
207 if (acl_set_fd(fd
, acl
) < 0)
208 return log_error_errno(errno
, "Failed to apply ACL: %m");
214 static int fix_xattr(int fd
, const Context
*context
) {
216 static const char * const xattrs
[_META_MAX
] = {
217 [META_ARGV_PID
] = "user.coredump.pid",
218 [META_ARGV_UID
] = "user.coredump.uid",
219 [META_ARGV_GID
] = "user.coredump.gid",
220 [META_ARGV_SIGNAL
] = "user.coredump.signal",
221 [META_ARGV_TIMESTAMP
] = "user.coredump.timestamp",
222 [META_ARGV_RLIMIT
] = "user.coredump.rlimit",
223 [META_ARGV_HOSTNAME
] = "user.coredump.hostname",
224 [META_COMM
] = "user.coredump.comm",
225 [META_EXE
] = "user.coredump.exe",
233 /* Attach some metadata to coredumps via extended
234 * attributes. Just because we can. */
236 for (i
= 0; i
< _META_MAX
; i
++) {
239 if (isempty(context
->meta
[i
]) || !xattrs
[i
])
242 k
= fsetxattr(fd
, xattrs
[i
], context
->meta
[i
], strlen(context
->meta
[i
]), XATTR_CREATE
);
250 #define filename_escape(s) xescape((s), "./ ")
252 static const char *coredump_tmpfile_name(const char *s
) {
253 return s
? s
: "(unnamed temporary file)";
256 static int fix_permissions(
258 const char *filename
,
260 const Context
*context
,
269 /* Ignore errors on these */
270 (void) fchmod(fd
, 0640);
271 (void) fix_acl(fd
, uid
);
272 (void) fix_xattr(fd
, context
);
275 return log_error_errno(errno
, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename
));
277 (void) fsync_directory_of_file(fd
);
279 r
= link_tmpfile(fd
, filename
, target
);
281 return log_error_errno(r
, "Failed to move coredump %s into place: %m", target
);
286 static int maybe_remove_external_coredump(const char *filename
, uint64_t size
) {
288 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
290 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
&&
291 size
<= arg_external_size_max
)
297 if (unlink(filename
) < 0 && errno
!= ENOENT
)
298 return log_error_errno(errno
, "Failed to unlink %s: %m", filename
);
303 static int make_filename(const Context
*context
, char **ret
) {
304 _cleanup_free_
char *c
= NULL
, *u
= NULL
, *p
= NULL
, *t
= NULL
;
305 sd_id128_t boot
= {};
310 c
= filename_escape(context
->meta
[META_COMM
]);
314 u
= filename_escape(context
->meta
[META_ARGV_UID
]);
318 r
= sd_id128_get_boot(&boot
);
322 p
= filename_escape(context
->meta
[META_ARGV_PID
]);
326 t
= filename_escape(context
->meta
[META_ARGV_TIMESTAMP
]);
331 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR
".%s.%s000000",
334 SD_ID128_FORMAT_VAL(boot
),
342 static int save_external_coredump(
343 const Context
*context
,
349 bool *ret_truncated
) {
351 _cleanup_free_
char *fn
= NULL
, *tmp
= NULL
;
352 _cleanup_close_
int fd
= -1;
353 uint64_t rlimit
, process_limit
, max_size
;
359 assert(ret_filename
);
364 r
= parse_uid(context
->meta
[META_ARGV_UID
], &uid
);
366 return log_error_errno(r
, "Failed to parse UID: %m");
368 r
= safe_atou64(context
->meta
[META_ARGV_RLIMIT
], &rlimit
);
370 return log_error_errno(r
, "Failed to parse resource limit '%s': %m",
371 context
->meta
[META_ARGV_RLIMIT
]);
372 if (rlimit
< page_size()) {
373 /* Is coredumping disabled? Then don't bother saving/processing the
374 * coredump. Anything below PAGE_SIZE cannot give a readable coredump
375 * (the kernel uses ELF_EXEC_PAGESIZE which is not easily accessible, but
376 * is usually the same as PAGE_SIZE. */
377 return log_info_errno(SYNTHETIC_ERRNO(EBADSLT
),
378 "Resource limits disable core dumping for process %s (%s).",
379 context
->meta
[META_ARGV_PID
], context
->meta
[META_COMM
]);
382 process_limit
= MAX(arg_process_size_max
, storage_size_max());
383 if (process_limit
== 0)
384 return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT
),
385 "Limits for coredump processing and storage are both 0, not dumping core.");
387 /* Never store more than the process configured, or than we actually shall keep or process */
388 max_size
= MIN(rlimit
, process_limit
);
390 r
= make_filename(context
, &fn
);
392 return log_error_errno(r
, "Failed to determine coredump file name: %m");
394 (void) mkdir_p_label("/var/lib/systemd/coredump", 0755);
396 fd
= open_tmpfile_linkable(fn
, O_RDWR
|O_CLOEXEC
, &tmp
);
398 return log_error_errno(fd
, "Failed to create temporary file for coredump %s: %m", fn
);
400 r
= copy_bytes(input_fd
, fd
, max_size
, 0);
402 log_error_errno(r
, "Cannot store coredump of %s (%s): %m",
403 context
->meta
[META_ARGV_PID
], context
->meta
[META_COMM
]);
406 *ret_truncated
= r
== 1;
409 LOG_MESSAGE("Core file was truncated to %zu bytes.", max_size
),
410 "SIZE_LIMIT=%zu", max_size
,
411 "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR
);
413 if (fstat(fd
, &st
) < 0) {
414 log_error_errno(errno
, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp
));
418 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1) {
419 log_error_errno(errno
, "Failed to seek on %s: %m", coredump_tmpfile_name(tmp
));
423 #if HAVE_XZ || HAVE_LZ4 || HAVE_ZSTD
424 /* If we will remove the coredump anyway, do not compress. */
425 if (arg_compress
&& !maybe_remove_external_coredump(NULL
, st
.st_size
)) {
427 _cleanup_free_
char *fn_compressed
= NULL
, *tmp_compressed
= NULL
;
428 _cleanup_close_
int fd_compressed
= -1;
430 fn_compressed
= strjoin(fn
, COMPRESSED_EXT
);
431 if (!fn_compressed
) {
436 fd_compressed
= open_tmpfile_linkable(fn_compressed
, O_RDWR
|O_CLOEXEC
, &tmp_compressed
);
437 if (fd_compressed
< 0) {
438 log_error_errno(fd_compressed
, "Failed to create temporary file for coredump %s: %m", fn_compressed
);
442 r
= compress_stream(fd
, fd_compressed
, -1);
444 log_error_errno(r
, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed
));
445 goto fail_compressed
;
448 r
= fix_permissions(fd_compressed
, tmp_compressed
, fn_compressed
, context
, uid
);
450 goto fail_compressed
;
452 /* OK, this worked, we can get rid of the uncompressed version now */
456 *ret_filename
= TAKE_PTR(fn_compressed
); /* compressed */
457 *ret_node_fd
= TAKE_FD(fd_compressed
); /* compressed */
458 *ret_data_fd
= TAKE_FD(fd
); /* uncompressed */
459 *ret_size
= (uint64_t) st
.st_size
; /* uncompressed */
465 (void) unlink(tmp_compressed
);
471 r
= fix_permissions(fd
, tmp
, fn
, context
, uid
);
475 *ret_filename
= TAKE_PTR(fn
);
476 *ret_data_fd
= TAKE_FD(fd
);
478 *ret_size
= (uint64_t) st
.st_size
;
488 static int allocate_journal_field(int fd
, size_t size
, char **ret
, size_t *ret_size
) {
489 _cleanup_free_
char *field
= NULL
;
496 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1)
497 return log_warning_errno(errno
, "Failed to seek: %m");
499 field
= malloc(9 + size
);
501 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
505 memcpy(field
, "COREDUMP=", 9);
507 n
= read(fd
, field
+ 9, size
);
509 return log_error_errno((int) n
, "Failed to read core data: %m");
510 if ((size_t) n
< size
)
511 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
512 "Core data too short.");
514 *ret
= TAKE_PTR(field
);
515 *ret_size
= size
+ 9;
520 /* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
534 static int compose_open_fds(pid_t pid
, char **open_fds
) {
535 _cleanup_closedir_
DIR *proc_fd_dir
= NULL
;
536 _cleanup_close_
int proc_fdinfo_fd
= -1;
537 _cleanup_free_
char *buffer
= NULL
;
538 _cleanup_fclose_
FILE *stream
= NULL
;
539 const char *fddelim
= "", *path
;
540 struct dirent
*dent
= NULL
;
545 assert(open_fds
!= NULL
);
547 path
= procfs_file_alloca(pid
, "fd");
548 proc_fd_dir
= opendir(path
);
552 proc_fdinfo_fd
= openat(dirfd(proc_fd_dir
), "../fdinfo", O_DIRECTORY
|O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
553 if (proc_fdinfo_fd
< 0)
556 stream
= open_memstream_unlocked(&buffer
, &size
);
560 FOREACH_DIRENT(dent
, proc_fd_dir
, return -errno
) {
561 _cleanup_fclose_
FILE *fdinfo
= NULL
;
562 _cleanup_free_
char *fdname
= NULL
;
563 _cleanup_close_
int fd
= -1;
565 r
= readlinkat_malloc(dirfd(proc_fd_dir
), dent
->d_name
, &fdname
);
569 fprintf(stream
, "%s%s:%s\n", fddelim
, dent
->d_name
, fdname
);
572 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
573 fd
= openat(proc_fdinfo_fd
, dent
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_RDONLY
);
577 fdinfo
= take_fdopen(&fd
, "r");
582 _cleanup_free_
char *line
= NULL
;
584 r
= read_line(fdinfo
, LONG_LINE_MAX
, &line
);
596 stream
= safe_fclose(stream
);
601 *open_fds
= TAKE_PTR(buffer
);
606 static int get_process_ns(pid_t pid
, const char *namespace, ino_t
*ns
) {
609 _cleanup_close_
int proc_ns_dir_fd
;
611 p
= procfs_file_alloca(pid
, "ns");
613 proc_ns_dir_fd
= open(p
, O_DIRECTORY
| O_CLOEXEC
| O_RDONLY
);
614 if (proc_ns_dir_fd
< 0)
617 if (fstatat(proc_ns_dir_fd
, namespace, &stbuf
, /* flags */0) < 0)
624 static int get_mount_namespace_leader(pid_t pid
, pid_t
*container_pid
) {
625 pid_t cpid
= pid
, ppid
= 0;
629 r
= get_process_ns(pid
, "mnt", &proc_mntns
);
636 r
= get_process_ppid(cpid
, &ppid
);
640 r
= get_process_ns(ppid
, "mnt", &parent_mntns
);
644 if (proc_mntns
!= parent_mntns
)
653 *container_pid
= ppid
;
657 /* Returns 1 if the parent was found.
658 * Returns 0 if there is not a process we can call the pid's
659 * container parent (the pid's process isn't 'containerized').
660 * Returns a negative number on errors.
662 static int get_process_container_parent_cmdline(pid_t pid
, char** cmdline
) {
665 const char *proc_root_path
;
666 struct stat root_stat
, proc_root_stat
;
668 /* To compare inodes of / and /proc/[pid]/root */
669 if (stat("/", &root_stat
) < 0)
672 proc_root_path
= procfs_file_alloca(pid
, "root");
673 if (stat(proc_root_path
, &proc_root_stat
) < 0)
676 /* The process uses system root. */
677 if (proc_root_stat
.st_ino
== root_stat
.st_ino
) {
682 r
= get_mount_namespace_leader(pid
, &container_pid
);
686 r
= get_process_cmdline(container_pid
, SIZE_MAX
, 0, cmdline
);
693 static int change_uid_gid(const Context
*context
) {
698 r
= parse_uid(context
->meta
[META_ARGV_UID
], &uid
);
702 if (uid
<= SYSTEM_UID_MAX
) {
703 const char *user
= "systemd-coredump";
705 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
707 log_warning_errno(r
, "Cannot resolve %s user. Proceeding to dump core as root: %m", user
);
711 r
= parse_gid(context
->meta
[META_ARGV_GID
], &gid
);
716 return drop_privileges(uid
, gid
, 0);
719 static int submit_coredump(
721 struct iovec_wrapper
*iovw
,
724 _cleanup_close_
int coredump_fd
= -1, coredump_node_fd
= -1;
725 _cleanup_free_
char *filename
= NULL
, *coredump_data
= NULL
;
726 _cleanup_free_
char *stacktrace
= NULL
;
728 uint64_t coredump_size
= UINT64_MAX
;
729 bool truncated
= false;
734 assert(input_fd
>= 0);
736 /* Vacuum before we write anything again */
737 (void) coredump_vacuum(-1, arg_keep_free
, arg_max_use
);
739 /* Always stream the coredump to disk, if that's possible */
740 r
= save_external_coredump(context
, input_fd
,
741 &filename
, &coredump_node_fd
, &coredump_fd
, &coredump_size
, &truncated
);
743 /* Skip whole core dumping part */
746 /* If we don't want to keep the coredump on disk, remove it now, as later on we
747 * will lack the privileges for it. However, we keep the fd to it, so that we can
748 * still process it and log it. */
749 r
= maybe_remove_external_coredump(filename
, coredump_size
);
753 (void) iovw_put_string_field(iovw
, "COREDUMP_FILENAME=", filename
);
755 } else if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
)
756 log_info("The core will not be stored: size %"PRIu64
" is greater than %"PRIu64
" (the configured maximum)",
757 coredump_size
, arg_external_size_max
);
759 /* Vacuum again, but exclude the coredump we just created */
760 (void) coredump_vacuum(coredump_node_fd
>= 0 ? coredump_node_fd
: coredump_fd
, arg_keep_free
, arg_max_use
);
762 /* Now, let's drop privileges to become the user who owns the segfaulted process
763 * and allocate the coredump memory under the user's uid. This also ensures that
764 * the credentials journald will see are the ones of the coredumping user, thus
765 * making sure the user gets access to the core dump. Let's also get rid of all
766 * capabilities, if we run as root, we won't need them anymore. */
767 r
= change_uid_gid(context
);
769 return log_error_errno(r
, "Failed to drop privileges: %m");
772 /* Try to get a stack trace if we can */
773 if (coredump_size
> arg_process_size_max
) {
774 log_debug("Not generating stack trace: core size %"PRIu64
" is greater "
775 "than %"PRIu64
" (the configured maximum)",
776 coredump_size
, arg_process_size_max
);
778 coredump_make_stack_trace(coredump_fd
, context
->meta
[META_EXE
], &stacktrace
);
782 core_message
= strjoina("Process ", context
->meta
[META_ARGV_PID
],
783 " (", context
->meta
[META_COMM
], ") of user ",
784 context
->meta
[META_ARGV_UID
], " dumped core.",
785 context
->is_journald
&& filename
? "\nCoredump diverted to " : NULL
,
786 context
->is_journald
&& filename
? filename
: NULL
);
788 core_message
= strjoina(core_message
, stacktrace
? "\n\n" : NULL
, stacktrace
);
790 if (context
->is_journald
) {
791 /* We cannot log to the journal, so just print the message.
792 * The target was set previously to something safe. */
793 log_dispatch(LOG_ERR
, 0, core_message
);
797 (void) iovw_put_string_field(iovw
, "MESSAGE=", core_message
);
800 (void) iovw_put_string_field(iovw
, "COREDUMP_TRUNCATED=", "1");
802 /* Optionally store the entire coredump in the journal */
803 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
) {
804 if (coredump_size
<= arg_journal_size_max
) {
807 /* Store the coredump itself in the journal */
809 r
= allocate_journal_field(coredump_fd
, (size_t) coredump_size
, &coredump_data
, &sz
);
811 if (iovw_put(iovw
, coredump_data
, sz
) >= 0)
812 TAKE_PTR(coredump_data
);
814 log_warning_errno(r
, "Failed to attach the core to the journal entry: %m");
816 log_info("The core will not be stored: size %"PRIu64
" is greater than %"PRIu64
" (the configured maximum)",
817 coredump_size
, arg_journal_size_max
);
820 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
822 return log_error_errno(r
, "Failed to log coredump: %m");
827 static int save_context(Context
*context
, const struct iovec_wrapper
*iovw
) {
828 unsigned n
, i
, count
= 0;
834 assert(iovw
->count
>= _META_ARGV_MAX
);
836 /* The context does not allocate any memory on its own */
838 for (n
= 0; n
< iovw
->count
; n
++) {
839 struct iovec
*iovec
= iovw
->iovec
+ n
;
841 for (i
= 0; i
< ELEMENTSOF(meta_field_names
); i
++) {
844 /* Note that these strings are NUL terminated, because we made sure that a
845 * trailing NUL byte is in the buffer, though not included in the iov_len
846 * count (see process_socket() and gather_pid_metadata_*()) */
847 assert(((char*) iovec
->iov_base
)[iovec
->iov_len
] == 0);
849 p
= startswith(iovec
->iov_base
, meta_field_names
[i
]);
851 context
->meta
[i
] = p
;
858 if (!context
->meta
[META_ARGV_PID
])
859 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
860 "Failed to find the PID of crashing process");
862 r
= parse_pid(context
->meta
[META_ARGV_PID
], &context
->pid
);
864 return log_error_errno(r
, "Failed to parse PID \"%s\": %m", context
->meta
[META_ARGV_PID
]);
866 unit
= context
->meta
[META_UNIT
];
867 context
->is_pid1
= streq(context
->meta
[META_ARGV_PID
], "1") || streq_ptr(unit
, SPECIAL_INIT_SCOPE
);
868 context
->is_journald
= streq_ptr(unit
, SPECIAL_JOURNALD_SERVICE
);
873 static int process_socket(int fd
) {
874 _cleanup_close_
int input_fd
= -1;
875 Context context
= {};
876 struct iovec_wrapper iovw
= {};
884 log_debug("Processing coredump received on stdin...");
888 struct cmsghdr cmsghdr
;
889 uint8_t buf
[CMSG_SPACE(sizeof(int))];
892 .msg_control
= &control
,
893 .msg_controllen
= sizeof(control
),
899 l
= next_datagram_size_fd(fd
);
901 r
= log_error_errno(l
, "Failed to determine datagram size to read: %m");
906 iovec
.iov_base
= malloc(l
+ 1);
907 if (!iovec
.iov_base
) {
914 n
= recvmsg_safe(fd
, &mh
, MSG_CMSG_CLOEXEC
);
916 free(iovec
.iov_base
);
917 r
= log_error_errno(n
, "Failed to receive datagram: %m");
921 /* The final zero-length datagram carries the file descriptor and tells us
922 * that we're done. */
924 struct cmsghdr
*found
;
926 free(iovec
.iov_base
);
928 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
931 r
= log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
932 "Coredump file descriptor missing.");
936 assert(input_fd
< 0);
937 input_fd
= *(int*) CMSG_DATA(found
);
942 /* Add trailing NUL byte, in case these are strings */
943 ((char*) iovec
.iov_base
)[n
] = 0;
944 iovec
.iov_len
= (size_t) n
;
946 r
= iovw_put(&iovw
, iovec
.iov_base
, iovec
.iov_len
);
951 /* Make sure we got all data we really need */
952 assert(input_fd
>= 0);
954 r
= save_context(&context
, &iovw
);
958 /* Make sure we received at least all fields we need. */
959 for (i
= 0; i
< _META_MANDATORY_MAX
; i
++)
960 if (!context
.meta
[i
]) {
961 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
962 "A mandatory argument (%i) has not been sent, aborting.",
967 r
= submit_coredump(&context
, &iovw
, input_fd
);
970 iovw_free_contents(&iovw
, true);
974 static int send_iovec(const struct iovec_wrapper
*iovw
, int input_fd
) {
976 static const union sockaddr_union sa
= {
977 .un
.sun_family
= AF_UNIX
,
978 .un
.sun_path
= "/run/systemd/coredump",
980 _cleanup_close_
int fd
= -1;
985 assert(input_fd
>= 0);
987 fd
= socket(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0);
989 return log_error_errno(errno
, "Failed to create coredump socket: %m");
991 if (connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
992 return log_error_errno(errno
, "Failed to connect to coredump service: %m");
994 for (i
= 0; i
< iovw
->count
; i
++) {
996 .msg_iov
= iovw
->iovec
+ i
,
999 struct iovec copy
[2];
1002 if (sendmsg(fd
, &mh
, MSG_NOSIGNAL
) >= 0)
1005 if (errno
== EMSGSIZE
&& mh
.msg_iov
[0].iov_len
> 0) {
1006 /* This field didn't fit? That's a pity. Given that this is
1007 * just metadata, let's truncate the field at half, and try
1008 * again. We append three dots, in order to show that this is
1011 if (mh
.msg_iov
!= copy
) {
1012 /* We don't want to modify the caller's iovec, hence
1013 * let's create our own array, consisting of two new
1014 * iovecs, where the first is a (truncated) copy of
1015 * what we want to send, and the second one contains
1016 * the trailing dots. */
1017 copy
[0] = iovw
->iovec
[i
];
1018 copy
[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);
1024 copy
[0].iov_len
/= 2; /* halve it, and try again */
1028 return log_error_errno(errno
, "Failed to send coredump datagram: %m");
1032 r
= send_one_fd(fd
, input_fd
, 0);
1034 return log_error_errno(r
, "Failed to send coredump fd: %m");
1039 static int gather_pid_metadata_from_argv(struct iovec_wrapper
*iovw
, Context
*context
,
1040 int argc
, char **argv
) {
1041 _cleanup_free_
char *free_timestamp
= NULL
;
1045 /* We gather all metadata that were passed via argv[] into an array of iovecs that
1046 * we'll forward to the socket unit */
1048 if (argc
< _META_ARGV_MAX
)
1049 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1050 "Not enough arguments passed by the kernel (%i, expected %i).",
1051 argc
, _META_ARGV_MAX
);
1053 for (i
= 0; i
< _META_ARGV_MAX
; i
++) {
1058 case META_ARGV_TIMESTAMP
:
1059 /* The journal fields contain the timestamp padded with six
1060 * zeroes, so that the kernel-supplied 1s granularity timestamps
1061 * becomes 1µs granularity, i.e. the granularity systemd usually
1063 t
= free_timestamp
= strjoin(argv
[i
], "000000");
1067 case META_ARGV_SIGNAL
:
1068 /* For signal, record its pretty name too */
1069 if (safe_atoi(argv
[i
], &signo
) >= 0 && SIGNAL_VALID(signo
))
1070 (void) iovw_put_string_field(iovw
, "COREDUMP_SIGNAL_NAME=SIG",
1071 signal_to_string(signo
));
1077 r
= iovw_put_string_field(iovw
, meta_field_names
[i
], t
);
1082 /* Cache some of the process metadata we collected so far and that we'll need to
1084 return save_context(context
, iovw
);
1087 static int gather_pid_metadata(struct iovec_wrapper
*iovw
, Context
*context
) {
1094 /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
1095 * structure. (It remains valid, with the first iovec fields initialized.) */
1099 /* The following is mandatory */
1100 r
= get_process_comm(pid
, &t
);
1102 return log_error_errno(r
, "Failed to get COMM: %m");
1104 r
= iovw_put_string_field_free(iovw
, "COREDUMP_COMM=", t
);
1108 /* The following are optional but we used them if present */
1109 r
= get_process_exe(pid
, &t
);
1111 r
= iovw_put_string_field_free(iovw
, "COREDUMP_EXE=", t
);
1113 log_warning_errno(r
, "Failed to get EXE, ignoring: %m");
1115 if (cg_pid_get_unit(pid
, &t
) >= 0)
1116 (void) iovw_put_string_field_free(iovw
, "COREDUMP_UNIT=", t
);
1118 /* The next are optional */
1119 if (cg_pid_get_user_unit(pid
, &t
) >= 0)
1120 (void) iovw_put_string_field_free(iovw
, "COREDUMP_USER_UNIT=", t
);
1122 if (sd_pid_get_session(pid
, &t
) >= 0)
1123 (void) iovw_put_string_field_free(iovw
, "COREDUMP_SESSION=", t
);
1125 if (sd_pid_get_owner_uid(pid
, &owner_uid
) >= 0) {
1126 r
= asprintf(&t
, UID_FMT
, owner_uid
);
1128 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OWNER_UID=", t
);
1131 if (sd_pid_get_slice(pid
, &t
) >= 0)
1132 (void) iovw_put_string_field_free(iovw
, "COREDUMP_SLICE=", t
);
1134 if (get_process_cmdline(pid
, SIZE_MAX
, 0, &t
) >= 0)
1135 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CMDLINE=", t
);
1137 if (cg_pid_get_path_shifted(pid
, NULL
, &t
) >= 0)
1138 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CGROUP=", t
);
1140 if (compose_open_fds(pid
, &t
) >= 0)
1141 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OPEN_FDS=", t
);
1143 p
= procfs_file_alloca(pid
, "status");
1144 if (read_full_file(p
, &t
, NULL
) >= 0)
1145 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_STATUS=", t
);
1147 p
= procfs_file_alloca(pid
, "maps");
1148 if (read_full_file(p
, &t
, NULL
) >= 0)
1149 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_MAPS=", t
);
1151 p
= procfs_file_alloca(pid
, "limits");
1152 if (read_full_file(p
, &t
, NULL
) >= 0)
1153 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_LIMITS=", t
);
1155 p
= procfs_file_alloca(pid
, "cgroup");
1156 if (read_full_file(p
, &t
, NULL
) >=0)
1157 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_CGROUP=", t
);
1159 p
= procfs_file_alloca(pid
, "mountinfo");
1160 if (read_full_file(p
, &t
, NULL
) >=0)
1161 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_MOUNTINFO=", t
);
1163 if (get_process_cwd(pid
, &t
) >= 0)
1164 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CWD=", t
);
1166 if (get_process_root(pid
, &t
) >= 0) {
1167 bool proc_self_root_is_slash
;
1169 proc_self_root_is_slash
= strcmp(t
, "/") == 0;
1171 (void) iovw_put_string_field_free(iovw
, "COREDUMP_ROOT=", t
);
1173 /* If the process' root is "/", then there is a chance it has
1174 * mounted own root and hence being containerized. */
1175 if (proc_self_root_is_slash
&& get_process_container_parent_cmdline(pid
, &t
) > 0)
1176 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CONTAINER_CMDLINE=", t
);
1179 if (get_process_environ(pid
, &t
) >= 0)
1180 (void) iovw_put_string_field_free(iovw
, "COREDUMP_ENVIRON=", t
);
1182 /* we successfully acquired all metadata */
1183 return save_context(context
, iovw
);
1186 static int process_kernel(int argc
, char* argv
[]) {
1187 Context context
= {};
1188 struct iovec_wrapper
*iovw
;
1191 log_debug("Processing coredump received from the kernel...");
1197 (void) iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR
);
1198 (void) iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1200 /* Collect all process metadata passed by the kernel through argv[] */
1201 r
= gather_pid_metadata_from_argv(iovw
, &context
, argc
- 1, argv
+ 1);
1205 /* Collect the rest of the process metadata retrieved from the runtime */
1206 r
= gather_pid_metadata(iovw
, &context
);
1210 if (!context
.is_journald
) {
1211 /* OK, now we know it's not the journal, hence we can make use of it now. */
1212 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
1216 /* If this is PID 1 disable coredump collection, we'll unlikely be able to process
1219 * FIXME: maybe we should disable coredumps generation from the beginning and
1220 * re-enable it only when we know it's either safe (ie we're not running OOM) or
1221 * it's not pid1 ? */
1222 if (context
.is_pid1
) {
1223 log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
1224 disable_coredumps();
1227 if (context
.is_journald
|| context
.is_pid1
)
1228 r
= submit_coredump(&context
, iovw
, STDIN_FILENO
);
1230 r
= send_iovec(iovw
, STDIN_FILENO
);
1233 iovw
= iovw_free_free(iovw
);
1237 static int process_backtrace(int argc
, char *argv
[]) {
1238 Context context
= {};
1239 struct iovec_wrapper
*iovw
;
1243 _cleanup_(journal_importer_cleanup
) JournalImporter importer
= JOURNAL_IMPORTER_INIT(STDIN_FILENO
);
1245 log_debug("Processing backtrace on stdin...");
1251 (void) iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR
);
1252 (void) iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1254 /* Collect all process metadata from argv[] by making sure to skip the
1255 * '--backtrace' option */
1256 r
= gather_pid_metadata_from_argv(iovw
, &context
, argc
- 2, argv
+ 2);
1260 /* Collect the rest of the process metadata retrieved from the runtime */
1261 r
= gather_pid_metadata(iovw
, &context
);
1266 r
= journal_importer_process_data(&importer
);
1268 log_error_errno(r
, "Failed to parse journal entry on stdin: %m");
1271 if (r
== 1 || /* complete entry */
1272 journal_importer_eof(&importer
)) /* end of data */
1276 if (journal_importer_eof(&importer
)) {
1277 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
1279 message
= strjoina("Process ", context
.meta
[META_ARGV_PID
],
1280 " (", context
.meta
[META_COMM
], ")"
1281 " of user ", context
.meta
[META_ARGV_UID
],
1282 " failed with ", context
.meta
[META_ARGV_SIGNAL
]);
1284 r
= iovw_put_string_field(iovw
, "MESSAGE=", message
);
1288 /* The imported iovecs are not supposed to be freed by us so let's store
1289 * them at the end of the array so we can skip them while freeing the
1291 for (i
= 0; i
< importer
.iovw
.count
; i
++) {
1292 struct iovec
*iovec
= importer
.iovw
.iovec
+ i
;
1294 iovw_put(iovw
, iovec
->iov_base
, iovec
->iov_len
);
1298 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
1300 log_error_errno(r
, "Failed to log backtrace: %m");
1303 iovw
->count
-= importer
.iovw
.count
;
1304 iovw
= iovw_free_free(iovw
);
1308 static int run(int argc
, char *argv
[]) {
1311 /* First, log to a safe place, since we don't know what crashed and it might
1312 * be journald which we'd rather not log to then. */
1314 log_set_target(LOG_TARGET_KMSG
);
1317 /* Make sure we never enter a loop */
1318 (void) prctl(PR_SET_DUMPABLE
, 0);
1320 /* Ignore all parse errors */
1321 (void) parse_config();
1323 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage
));
1324 log_debug("Selected compression %s.", yes_no(arg_compress
));
1326 r
= sd_listen_fds(false);
1328 return log_error_errno(r
, "Failed to determine the number of file descriptors: %m");
1330 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1331 * are invoked from the kernel as coredump handler. */
1333 if (streq_ptr(argv
[1], "--backtrace"))
1334 return process_backtrace(argc
, argv
);
1336 return process_kernel(argc
, argv
);
1338 return process_socket(SD_LISTEN_FDS_START
);
1340 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1341 "Received unexpected number of file descriptors.");
1344 DEFINE_MAIN_FUNCTION(run
);