1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
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-record.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 these as array indexes for our process metadata cache.
73 * The first indices of the cache stores the same metadata as the ones passed by
74 * the kernel via argv[], ie the strings array passed by the kernel according to
75 * our pattern defined in /proc/sys/kernel/core_pattern (see man:core(5)). */
77 META_ARGV_PID
, /* %P: as seen in the initial pid namespace */
78 META_ARGV_UID
, /* %u: as seen in the initial user namespace */
79 META_ARGV_GID
, /* %g: as seen in the initial user namespace */
80 META_ARGV_SIGNAL
, /* %s: number of signal causing dump */
81 META_ARGV_TIMESTAMP
, /* %t: time of dump, expressed as seconds since the Epoch (we expand this to µs granularity) */
82 META_ARGV_RLIMIT
, /* %c: core file size soft resource limit */
83 META_ARGV_HOSTNAME
, /* %h: hostname */
86 /* The following indexes are cached for a couple of special fields we use (and
87 * thereby need to be retrieved quickly) for naming coredump files, and attaching
88 * xattrs. Unlike the previous ones they are retrieved from the runtime
91 META_COMM
= _META_ARGV_MAX
,
94 /* The rest are similar to the previous ones except that we won't fail if one of
97 META_EXE
= _META_MANDATORY_MAX
,
102 static const char * const meta_field_names
[_META_MAX
] = {
103 [META_ARGV_PID
] = "COREDUMP_PID=",
104 [META_ARGV_UID
] = "COREDUMP_UID=",
105 [META_ARGV_GID
] = "COREDUMP_GID=",
106 [META_ARGV_SIGNAL
] = "COREDUMP_SIGNAL=",
107 [META_ARGV_TIMESTAMP
] = "COREDUMP_TIMESTAMP=",
108 [META_ARGV_RLIMIT
] = "COREDUMP_RLIMIT=",
109 [META_ARGV_HOSTNAME
] = "COREDUMP_HOSTNAME=",
110 [META_COMM
] = "COREDUMP_COMM=",
111 [META_EXE
] = "COREDUMP_EXE=",
112 [META_UNIT
] = "COREDUMP_UNIT=",
115 typedef struct Context
{
116 const char *meta
[_META_MAX
];
122 typedef enum CoredumpStorage
{
123 COREDUMP_STORAGE_NONE
,
124 COREDUMP_STORAGE_EXTERNAL
,
125 COREDUMP_STORAGE_JOURNAL
,
126 _COREDUMP_STORAGE_MAX
,
127 _COREDUMP_STORAGE_INVALID
= -EINVAL
,
130 static const char* const coredump_storage_table
[_COREDUMP_STORAGE_MAX
] = {
131 [COREDUMP_STORAGE_NONE
] = "none",
132 [COREDUMP_STORAGE_EXTERNAL
] = "external",
133 [COREDUMP_STORAGE_JOURNAL
] = "journal",
136 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage
, CoredumpStorage
);
137 static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage
, coredump_storage
, CoredumpStorage
, "Failed to parse storage setting");
139 static CoredumpStorage arg_storage
= COREDUMP_STORAGE_EXTERNAL
;
140 static bool arg_compress
= true;
141 static uint64_t arg_process_size_max
= PROCESS_SIZE_MAX
;
142 static uint64_t arg_external_size_max
= EXTERNAL_SIZE_MAX
;
143 static uint64_t arg_journal_size_max
= JOURNAL_SIZE_MAX
;
144 static uint64_t arg_keep_free
= UINT64_MAX
;
145 static uint64_t arg_max_use
= UINT64_MAX
;
147 static int parse_config(void) {
148 static const ConfigTableItem items
[] = {
149 { "Coredump", "Storage", config_parse_coredump_storage
, 0, &arg_storage
},
150 { "Coredump", "Compress", config_parse_bool
, 0, &arg_compress
},
151 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64
, 0, &arg_process_size_max
},
152 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64
, 0, &arg_external_size_max
},
153 { "Coredump", "JournalSizeMax", config_parse_iec_size
, 0, &arg_journal_size_max
},
154 { "Coredump", "KeepFree", config_parse_iec_uint64
, 0, &arg_keep_free
},
155 { "Coredump", "MaxUse", config_parse_iec_uint64
, 0, &arg_max_use
},
159 return config_parse_many_nulstr(
160 PKGSYSCONFDIR
"/coredump.conf",
161 CONF_PATHS_NULSTR("systemd/coredump.conf.d"),
163 config_item_table_lookup
, items
,
169 static uint64_t storage_size_max(void) {
170 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
)
171 return arg_external_size_max
;
172 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
)
173 return arg_journal_size_max
;
174 assert(arg_storage
== COREDUMP_STORAGE_NONE
);
178 static int fix_acl(int fd
, uid_t uid
) {
184 assert(uid_is_valid(uid
));
186 if (uid_is_system(uid
) || uid_is_dynamic(uid
) || uid
== UID_NOBODY
)
189 /* Make sure normal users can read (but not write or delete) their own coredumps */
190 r
= fd_add_uid_acl_permission(fd
, uid
, ACL_READ
);
192 return log_error_errno(r
, "Failed to adjust ACL of the coredump: %m");
198 static int fix_xattr(int fd
, const Context
*context
) {
200 static const char * const xattrs
[_META_MAX
] = {
201 [META_ARGV_PID
] = "user.coredump.pid",
202 [META_ARGV_UID
] = "user.coredump.uid",
203 [META_ARGV_GID
] = "user.coredump.gid",
204 [META_ARGV_SIGNAL
] = "user.coredump.signal",
205 [META_ARGV_TIMESTAMP
] = "user.coredump.timestamp",
206 [META_ARGV_RLIMIT
] = "user.coredump.rlimit",
207 [META_ARGV_HOSTNAME
] = "user.coredump.hostname",
208 [META_COMM
] = "user.coredump.comm",
209 [META_EXE
] = "user.coredump.exe",
216 /* Attach some metadata to coredumps via extended
217 * attributes. Just because we can. */
219 for (unsigned i
= 0; i
< _META_MAX
; i
++) {
222 if (isempty(context
->meta
[i
]) || !xattrs
[i
])
225 k
= fsetxattr(fd
, xattrs
[i
], context
->meta
[i
], strlen(context
->meta
[i
]), XATTR_CREATE
);
233 #define filename_escape(s) xescape((s), "./ ")
235 static const char *coredump_tmpfile_name(const char *s
) {
236 return s
? s
: "(unnamed temporary file)";
239 static int fix_permissions(
241 const char *filename
,
243 const Context
*context
,
252 /* Ignore errors on these */
253 (void) fchmod(fd
, 0640);
254 (void) fix_acl(fd
, uid
);
255 (void) fix_xattr(fd
, context
);
258 return log_error_errno(errno
, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename
));
260 (void) fsync_directory_of_file(fd
);
262 r
= link_tmpfile(fd
, filename
, target
);
264 return log_error_errno(r
, "Failed to move coredump %s into place: %m", target
);
269 static int maybe_remove_external_coredump(const char *filename
, uint64_t size
) {
271 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
273 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
&&
274 size
<= arg_external_size_max
)
280 if (unlink(filename
) < 0 && errno
!= ENOENT
)
281 return log_error_errno(errno
, "Failed to unlink %s: %m", filename
);
286 static int make_filename(const Context
*context
, char **ret
) {
287 _cleanup_free_
char *c
= NULL
, *u
= NULL
, *p
= NULL
, *t
= NULL
;
288 sd_id128_t boot
= {};
293 c
= filename_escape(context
->meta
[META_COMM
]);
297 u
= filename_escape(context
->meta
[META_ARGV_UID
]);
301 r
= sd_id128_get_boot(&boot
);
305 p
= filename_escape(context
->meta
[META_ARGV_PID
]);
309 t
= filename_escape(context
->meta
[META_ARGV_TIMESTAMP
]);
314 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR
".%s.%s",
317 SD_ID128_FORMAT_VAL(boot
),
325 static int save_external_coredump(
326 const Context
*context
,
332 bool *ret_truncated
) {
334 _cleanup_free_
char *fn
= NULL
, *tmp
= NULL
;
335 _cleanup_close_
int fd
= -1;
336 uint64_t rlimit
, process_limit
, max_size
;
342 assert(ret_filename
);
347 r
= parse_uid(context
->meta
[META_ARGV_UID
], &uid
);
349 return log_error_errno(r
, "Failed to parse UID: %m");
351 r
= safe_atou64(context
->meta
[META_ARGV_RLIMIT
], &rlimit
);
353 return log_error_errno(r
, "Failed to parse resource limit '%s': %m",
354 context
->meta
[META_ARGV_RLIMIT
]);
355 if (rlimit
< page_size())
356 /* Is coredumping disabled? Then don't bother saving/processing the
357 * coredump. Anything below PAGE_SIZE cannot give a readable coredump
358 * (the kernel uses ELF_EXEC_PAGESIZE which is not easily accessible, but
359 * is usually the same as PAGE_SIZE. */
360 return log_info_errno(SYNTHETIC_ERRNO(EBADSLT
),
361 "Resource limits disable core dumping for process %s (%s).",
362 context
->meta
[META_ARGV_PID
], context
->meta
[META_COMM
]);
364 process_limit
= MAX(arg_process_size_max
, storage_size_max());
365 if (process_limit
== 0)
366 return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT
),
367 "Limits for coredump processing and storage are both 0, not dumping core.");
369 /* Never store more than the process configured, or than we actually shall keep or process */
370 max_size
= MIN(rlimit
, process_limit
);
372 r
= make_filename(context
, &fn
);
374 return log_error_errno(r
, "Failed to determine coredump file name: %m");
376 (void) mkdir_p_label("/var/lib/systemd/coredump", 0755);
378 fd
= open_tmpfile_linkable(fn
, O_RDWR
|O_CLOEXEC
, &tmp
);
380 return log_error_errno(fd
, "Failed to create temporary file for coredump %s: %m", fn
);
382 r
= copy_bytes(input_fd
, fd
, max_size
, 0);
384 log_error_errno(r
, "Cannot store coredump of %s (%s): %m",
385 context
->meta
[META_ARGV_PID
], context
->meta
[META_COMM
]);
388 *ret_truncated
= r
== 1;
391 LOG_MESSAGE("Core file was truncated to %zu bytes.", max_size
),
392 "SIZE_LIMIT=%zu", max_size
,
393 "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR
);
395 if (fstat(fd
, &st
) < 0) {
396 log_error_errno(errno
, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp
));
400 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1) {
401 log_error_errno(errno
, "Failed to seek on %s: %m", coredump_tmpfile_name(tmp
));
406 /* If we will remove the coredump anyway, do not compress. */
407 if (arg_compress
&& !maybe_remove_external_coredump(NULL
, st
.st_size
)) {
409 _cleanup_free_
char *fn_compressed
= NULL
, *tmp_compressed
= NULL
;
410 _cleanup_close_
int fd_compressed
= -1;
412 fn_compressed
= strjoin(fn
, COMPRESSED_EXT
);
413 if (!fn_compressed
) {
418 fd_compressed
= open_tmpfile_linkable(fn_compressed
, O_RDWR
|O_CLOEXEC
, &tmp_compressed
);
419 if (fd_compressed
< 0) {
420 log_error_errno(fd_compressed
, "Failed to create temporary file for coredump %s: %m", fn_compressed
);
424 r
= compress_stream(fd
, fd_compressed
, -1);
426 log_error_errno(r
, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed
));
427 goto fail_compressed
;
430 r
= fix_permissions(fd_compressed
, tmp_compressed
, fn_compressed
, context
, uid
);
432 goto fail_compressed
;
434 /* OK, this worked, we can get rid of the uncompressed version now */
438 *ret_filename
= TAKE_PTR(fn_compressed
); /* compressed */
439 *ret_node_fd
= TAKE_FD(fd_compressed
); /* compressed */
440 *ret_data_fd
= TAKE_FD(fd
); /* uncompressed */
441 *ret_size
= (uint64_t) st
.st_size
; /* uncompressed */
447 (void) unlink(tmp_compressed
);
453 r
= fix_permissions(fd
, tmp
, fn
, context
, uid
);
457 *ret_filename
= TAKE_PTR(fn
);
458 *ret_data_fd
= TAKE_FD(fd
);
460 *ret_size
= (uint64_t) st
.st_size
;
470 static int allocate_journal_field(int fd
, size_t size
, char **ret
, size_t *ret_size
) {
471 _cleanup_free_
char *field
= NULL
;
478 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1)
479 return log_warning_errno(errno
, "Failed to seek: %m");
481 field
= malloc(9 + size
);
483 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
487 memcpy(field
, "COREDUMP=", 9);
489 n
= read(fd
, field
+ 9, size
);
491 return log_error_errno((int) n
, "Failed to read core data: %m");
492 if ((size_t) n
< size
)
493 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
494 "Core data too short.");
496 *ret
= TAKE_PTR(field
);
497 *ret_size
= size
+ 9;
502 /* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
516 static int compose_open_fds(pid_t pid
, char **open_fds
) {
517 _cleanup_closedir_
DIR *proc_fd_dir
= NULL
;
518 _cleanup_close_
int proc_fdinfo_fd
= -1;
519 _cleanup_free_
char *buffer
= NULL
;
520 _cleanup_fclose_
FILE *stream
= NULL
;
521 const char *fddelim
= "", *path
;
522 struct dirent
*dent
= NULL
;
527 assert(open_fds
!= NULL
);
529 path
= procfs_file_alloca(pid
, "fd");
530 proc_fd_dir
= opendir(path
);
534 proc_fdinfo_fd
= openat(dirfd(proc_fd_dir
), "../fdinfo", O_DIRECTORY
|O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
535 if (proc_fdinfo_fd
< 0)
538 stream
= open_memstream_unlocked(&buffer
, &size
);
542 FOREACH_DIRENT(dent
, proc_fd_dir
, return -errno
) {
543 _cleanup_fclose_
FILE *fdinfo
= NULL
;
544 _cleanup_free_
char *fdname
= NULL
;
545 _cleanup_close_
int fd
= -1;
547 r
= readlinkat_malloc(dirfd(proc_fd_dir
), dent
->d_name
, &fdname
);
551 fprintf(stream
, "%s%s:%s\n", fddelim
, dent
->d_name
, fdname
);
554 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
555 fd
= openat(proc_fdinfo_fd
, dent
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_RDONLY
);
559 fdinfo
= take_fdopen(&fd
, "r");
564 _cleanup_free_
char *line
= NULL
;
566 r
= read_line(fdinfo
, LONG_LINE_MAX
, &line
);
578 stream
= safe_fclose(stream
);
583 *open_fds
= TAKE_PTR(buffer
);
588 static int get_process_ns(pid_t pid
, const char *namespace, ino_t
*ns
) {
591 _cleanup_close_
int proc_ns_dir_fd
;
593 p
= procfs_file_alloca(pid
, "ns");
595 proc_ns_dir_fd
= open(p
, O_DIRECTORY
| O_CLOEXEC
| O_RDONLY
);
596 if (proc_ns_dir_fd
< 0)
599 if (fstatat(proc_ns_dir_fd
, namespace, &stbuf
, /* flags */0) < 0)
606 static int get_mount_namespace_leader(pid_t pid
, pid_t
*container_pid
) {
607 pid_t cpid
= pid
, ppid
= 0;
611 r
= get_process_ns(pid
, "mnt", &proc_mntns
);
618 r
= get_process_ppid(cpid
, &ppid
);
622 r
= get_process_ns(ppid
, "mnt", &parent_mntns
);
626 if (proc_mntns
!= parent_mntns
)
635 *container_pid
= ppid
;
639 /* Returns 1 if the parent was found.
640 * Returns 0 if there is not a process we can call the pid's
641 * container parent (the pid's process isn't 'containerized').
642 * Returns a negative number on errors.
644 static int get_process_container_parent_cmdline(pid_t pid
, char** cmdline
) {
647 const char *proc_root_path
;
648 struct stat root_stat
, proc_root_stat
;
650 /* To compare inodes of / and /proc/[pid]/root */
651 if (stat("/", &root_stat
) < 0)
654 proc_root_path
= procfs_file_alloca(pid
, "root");
655 if (stat(proc_root_path
, &proc_root_stat
) < 0)
658 /* The process uses system root. */
659 if (proc_root_stat
.st_ino
== root_stat
.st_ino
) {
664 r
= get_mount_namespace_leader(pid
, &container_pid
);
668 r
= get_process_cmdline(container_pid
, SIZE_MAX
, 0, cmdline
);
675 static int change_uid_gid(const Context
*context
) {
680 r
= parse_uid(context
->meta
[META_ARGV_UID
], &uid
);
684 if (uid_is_system(uid
)) {
685 const char *user
= "systemd-coredump";
687 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
689 log_warning_errno(r
, "Cannot resolve %s user. Proceeding to dump core as root: %m", user
);
693 r
= parse_gid(context
->meta
[META_ARGV_GID
], &gid
);
698 return drop_privileges(uid
, gid
, 0);
701 static int submit_coredump(
703 struct iovec_wrapper
*iovw
,
706 _cleanup_close_
int coredump_fd
= -1, coredump_node_fd
= -1;
707 _cleanup_free_
char *filename
= NULL
, *coredump_data
= NULL
;
708 _cleanup_free_
char *stacktrace
= NULL
;
710 uint64_t coredump_size
= UINT64_MAX
;
711 bool truncated
= false;
716 assert(input_fd
>= 0);
718 /* Vacuum before we write anything again */
719 (void) coredump_vacuum(-1, arg_keep_free
, arg_max_use
);
721 /* Always stream the coredump to disk, if that's possible */
722 r
= save_external_coredump(context
, input_fd
,
723 &filename
, &coredump_node_fd
, &coredump_fd
, &coredump_size
, &truncated
);
725 /* Skip whole core dumping part */
728 /* If we don't want to keep the coredump on disk, remove it now, as later on we
729 * will lack the privileges for it. However, we keep the fd to it, so that we can
730 * still process it and log it. */
731 r
= maybe_remove_external_coredump(filename
, coredump_size
);
735 (void) iovw_put_string_field(iovw
, "COREDUMP_FILENAME=", filename
);
737 } else if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
)
738 log_info("The core will not be stored: size %"PRIu64
" is greater than %"PRIu64
" (the configured maximum)",
739 coredump_size
, arg_external_size_max
);
741 /* Vacuum again, but exclude the coredump we just created */
742 (void) coredump_vacuum(coredump_node_fd
>= 0 ? coredump_node_fd
: coredump_fd
, arg_keep_free
, arg_max_use
);
744 /* Now, let's drop privileges to become the user who owns the segfaulted process
745 * and allocate the coredump memory under the user's uid. This also ensures that
746 * the credentials journald will see are the ones of the coredumping user, thus
747 * making sure the user gets access to the core dump. Let's also get rid of all
748 * capabilities, if we run as root, we won't need them anymore. */
749 r
= change_uid_gid(context
);
751 return log_error_errno(r
, "Failed to drop privileges: %m");
754 /* Try to get a stack trace if we can */
755 if (coredump_size
> arg_process_size_max
) {
756 log_debug("Not generating stack trace: core size %"PRIu64
" is greater "
757 "than %"PRIu64
" (the configured maximum)",
758 coredump_size
, arg_process_size_max
);
760 coredump_make_stack_trace(coredump_fd
, context
->meta
[META_EXE
], &stacktrace
);
764 core_message
= strjoina("Process ", context
->meta
[META_ARGV_PID
],
765 " (", context
->meta
[META_COMM
], ") of user ",
766 context
->meta
[META_ARGV_UID
], " dumped core.",
767 context
->is_journald
&& filename
? "\nCoredump diverted to " : NULL
,
768 context
->is_journald
&& filename
? filename
: NULL
);
770 core_message
= strjoina(core_message
, stacktrace
? "\n\n" : NULL
, stacktrace
);
772 if (context
->is_journald
) {
773 /* We cannot log to the journal, so just print the message.
774 * The target was set previously to something safe. */
775 log_dispatch(LOG_ERR
, 0, core_message
);
779 (void) iovw_put_string_field(iovw
, "MESSAGE=", core_message
);
782 (void) iovw_put_string_field(iovw
, "COREDUMP_TRUNCATED=", "1");
784 /* Optionally store the entire coredump in the journal */
785 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
) {
786 if (coredump_size
<= arg_journal_size_max
) {
789 /* Store the coredump itself in the journal */
791 r
= allocate_journal_field(coredump_fd
, (size_t) coredump_size
, &coredump_data
, &sz
);
793 if (iovw_put(iovw
, coredump_data
, sz
) >= 0)
794 TAKE_PTR(coredump_data
);
796 log_warning_errno(r
, "Failed to attach the core to the journal entry: %m");
798 log_info("The core will not be stored: size %"PRIu64
" is greater than %"PRIu64
" (the configured maximum)",
799 coredump_size
, arg_journal_size_max
);
802 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
804 return log_error_errno(r
, "Failed to log coredump: %m");
809 static int save_context(Context
*context
, const struct iovec_wrapper
*iovw
) {
816 assert(iovw
->count
>= _META_ARGV_MAX
);
818 /* The context does not allocate any memory on its own */
820 for (size_t n
= 0; n
< iovw
->count
; n
++) {
821 struct iovec
*iovec
= iovw
->iovec
+ n
;
823 for (size_t i
= 0; i
< ELEMENTSOF(meta_field_names
); i
++) {
826 /* Note that these strings are NUL terminated, because we made sure that a
827 * trailing NUL byte is in the buffer, though not included in the iov_len
828 * count (see process_socket() and gather_pid_metadata_*()) */
829 assert(((char*) iovec
->iov_base
)[iovec
->iov_len
] == 0);
831 p
= startswith(iovec
->iov_base
, meta_field_names
[i
]);
833 context
->meta
[i
] = p
;
840 if (!context
->meta
[META_ARGV_PID
])
841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
842 "Failed to find the PID of crashing process");
844 r
= parse_pid(context
->meta
[META_ARGV_PID
], &context
->pid
);
846 return log_error_errno(r
, "Failed to parse PID \"%s\": %m", context
->meta
[META_ARGV_PID
]);
848 unit
= context
->meta
[META_UNIT
];
849 context
->is_pid1
= streq(context
->meta
[META_ARGV_PID
], "1") || streq_ptr(unit
, SPECIAL_INIT_SCOPE
);
850 context
->is_journald
= streq_ptr(unit
, SPECIAL_JOURNALD_SERVICE
);
855 static int process_socket(int fd
) {
856 _cleanup_close_
int input_fd
= -1;
857 Context context
= {};
858 struct iovec_wrapper iovw
= {};
866 log_debug("Processing coredump received on stdin...");
869 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
871 .msg_control
= &control
,
872 .msg_controllen
= sizeof(control
),
878 l
= next_datagram_size_fd(fd
);
880 r
= log_error_errno(l
, "Failed to determine datagram size to read: %m");
885 iovec
.iov_base
= malloc(l
+ 1);
886 if (!iovec
.iov_base
) {
893 n
= recvmsg_safe(fd
, &mh
, MSG_CMSG_CLOEXEC
);
895 free(iovec
.iov_base
);
896 r
= log_error_errno(n
, "Failed to receive datagram: %m");
900 /* The final zero-length datagram carries the file descriptor and tells us
901 * that we're done. */
903 struct cmsghdr
*found
;
905 free(iovec
.iov_base
);
907 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
910 r
= log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
911 "Coredump file descriptor missing.");
915 assert(input_fd
< 0);
916 input_fd
= *(int*) CMSG_DATA(found
);
921 /* Add trailing NUL byte, in case these are strings */
922 ((char*) iovec
.iov_base
)[n
] = 0;
923 iovec
.iov_len
= (size_t) n
;
925 r
= iovw_put(&iovw
, iovec
.iov_base
, iovec
.iov_len
);
930 /* Make sure we got all data we really need */
931 assert(input_fd
>= 0);
933 r
= save_context(&context
, &iovw
);
937 /* Make sure we received at least all fields we need. */
938 for (int i
= 0; i
< _META_MANDATORY_MAX
; i
++)
939 if (!context
.meta
[i
]) {
940 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
941 "A mandatory argument (%i) has not been sent, aborting.",
946 r
= submit_coredump(&context
, &iovw
, input_fd
);
949 iovw_free_contents(&iovw
, true);
953 static int send_iovec(const struct iovec_wrapper
*iovw
, int input_fd
) {
955 static const union sockaddr_union sa
= {
956 .un
.sun_family
= AF_UNIX
,
957 .un
.sun_path
= "/run/systemd/coredump",
959 _cleanup_close_
int fd
= -1;
963 assert(input_fd
>= 0);
965 fd
= socket(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0);
967 return log_error_errno(errno
, "Failed to create coredump socket: %m");
969 if (connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
970 return log_error_errno(errno
, "Failed to connect to coredump service: %m");
972 for (size_t i
= 0; i
< iovw
->count
; i
++) {
974 .msg_iov
= iovw
->iovec
+ i
,
977 struct iovec copy
[2];
980 if (sendmsg(fd
, &mh
, MSG_NOSIGNAL
) >= 0)
983 if (errno
== EMSGSIZE
&& mh
.msg_iov
[0].iov_len
> 0) {
984 /* This field didn't fit? That's a pity. Given that this is
985 * just metadata, let's truncate the field at half, and try
986 * again. We append three dots, in order to show that this is
989 if (mh
.msg_iov
!= copy
) {
990 /* We don't want to modify the caller's iovec, hence
991 * let's create our own array, consisting of two new
992 * iovecs, where the first is a (truncated) copy of
993 * what we want to send, and the second one contains
994 * the trailing dots. */
995 copy
[0] = iovw
->iovec
[i
];
996 copy
[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);
1002 copy
[0].iov_len
/= 2; /* halve it, and try again */
1006 return log_error_errno(errno
, "Failed to send coredump datagram: %m");
1010 r
= send_one_fd(fd
, input_fd
, 0);
1012 return log_error_errno(r
, "Failed to send coredump fd: %m");
1017 static int gather_pid_metadata_from_argv(
1018 struct iovec_wrapper
*iovw
,
1020 int argc
, char **argv
) {
1022 _cleanup_free_
char *free_timestamp
= NULL
;
1026 /* We gather all metadata that were passed via argv[] into an array of iovecs that
1027 * we'll forward to the socket unit */
1029 if (argc
< _META_ARGV_MAX
)
1030 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1031 "Not enough arguments passed by the kernel (%i, expected %i).",
1032 argc
, _META_ARGV_MAX
);
1034 for (int i
= 0; i
< _META_ARGV_MAX
; i
++) {
1040 case META_ARGV_TIMESTAMP
:
1041 /* The journal fields contain the timestamp padded with six
1042 * zeroes, so that the kernel-supplied 1s granularity timestamps
1043 * becomes 1µs granularity, i.e. the granularity systemd usually
1045 t
= free_timestamp
= strjoin(argv
[i
], "000000");
1050 case META_ARGV_SIGNAL
:
1051 /* For signal, record its pretty name too */
1052 if (safe_atoi(argv
[i
], &signo
) >= 0 && SIGNAL_VALID(signo
))
1053 (void) iovw_put_string_field(iovw
, "COREDUMP_SIGNAL_NAME=SIG",
1054 signal_to_string(signo
));
1061 r
= iovw_put_string_field(iovw
, meta_field_names
[i
], t
);
1066 /* Cache some of the process metadata we collected so far and that we'll need to
1068 return save_context(context
, iovw
);
1071 static int gather_pid_metadata(struct iovec_wrapper
*iovw
, Context
*context
) {
1078 /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
1079 * structure. (It remains valid, with the first iovec fields initialized.) */
1083 /* The following is mandatory */
1084 r
= get_process_comm(pid
, &t
);
1086 return log_error_errno(r
, "Failed to get COMM: %m");
1088 r
= iovw_put_string_field_free(iovw
, "COREDUMP_COMM=", t
);
1092 /* The following are optional but we used them if present */
1093 r
= get_process_exe(pid
, &t
);
1095 r
= iovw_put_string_field_free(iovw
, "COREDUMP_EXE=", t
);
1097 log_warning_errno(r
, "Failed to get EXE, ignoring: %m");
1099 if (cg_pid_get_unit(pid
, &t
) >= 0)
1100 (void) iovw_put_string_field_free(iovw
, "COREDUMP_UNIT=", t
);
1102 /* The next are optional */
1103 if (cg_pid_get_user_unit(pid
, &t
) >= 0)
1104 (void) iovw_put_string_field_free(iovw
, "COREDUMP_USER_UNIT=", t
);
1106 if (sd_pid_get_session(pid
, &t
) >= 0)
1107 (void) iovw_put_string_field_free(iovw
, "COREDUMP_SESSION=", t
);
1109 if (sd_pid_get_owner_uid(pid
, &owner_uid
) >= 0) {
1110 r
= asprintf(&t
, UID_FMT
, owner_uid
);
1112 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OWNER_UID=", t
);
1115 if (sd_pid_get_slice(pid
, &t
) >= 0)
1116 (void) iovw_put_string_field_free(iovw
, "COREDUMP_SLICE=", t
);
1118 if (get_process_cmdline(pid
, SIZE_MAX
, 0, &t
) >= 0)
1119 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CMDLINE=", t
);
1121 if (cg_pid_get_path_shifted(pid
, NULL
, &t
) >= 0)
1122 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CGROUP=", t
);
1124 if (compose_open_fds(pid
, &t
) >= 0)
1125 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OPEN_FDS=", t
);
1127 p
= procfs_file_alloca(pid
, "status");
1128 if (read_full_file(p
, &t
, NULL
) >= 0)
1129 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_STATUS=", t
);
1131 p
= procfs_file_alloca(pid
, "maps");
1132 if (read_full_file(p
, &t
, NULL
) >= 0)
1133 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_MAPS=", t
);
1135 p
= procfs_file_alloca(pid
, "limits");
1136 if (read_full_file(p
, &t
, NULL
) >= 0)
1137 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_LIMITS=", t
);
1139 p
= procfs_file_alloca(pid
, "cgroup");
1140 if (read_full_file(p
, &t
, NULL
) >=0)
1141 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_CGROUP=", t
);
1143 p
= procfs_file_alloca(pid
, "mountinfo");
1144 if (read_full_file(p
, &t
, NULL
) >=0)
1145 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_MOUNTINFO=", t
);
1147 if (get_process_cwd(pid
, &t
) >= 0)
1148 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CWD=", t
);
1150 if (get_process_root(pid
, &t
) >= 0) {
1151 bool proc_self_root_is_slash
;
1153 proc_self_root_is_slash
= strcmp(t
, "/") == 0;
1155 (void) iovw_put_string_field_free(iovw
, "COREDUMP_ROOT=", t
);
1157 /* If the process' root is "/", then there is a chance it has
1158 * mounted own root and hence being containerized. */
1159 if (proc_self_root_is_slash
&& get_process_container_parent_cmdline(pid
, &t
) > 0)
1160 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CONTAINER_CMDLINE=", t
);
1163 if (get_process_environ(pid
, &t
) >= 0)
1164 (void) iovw_put_string_field_free(iovw
, "COREDUMP_ENVIRON=", t
);
1166 /* we successfully acquired all metadata */
1167 return save_context(context
, iovw
);
1170 static int process_kernel(int argc
, char* argv
[]) {
1171 Context context
= {};
1172 struct iovec_wrapper
*iovw
;
1175 log_debug("Processing coredump received from the kernel...");
1181 (void) iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR
);
1182 (void) iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1184 /* Collect all process metadata passed by the kernel through argv[] */
1185 r
= gather_pid_metadata_from_argv(iovw
, &context
, argc
- 1, argv
+ 1);
1189 /* Collect the rest of the process metadata retrieved from the runtime */
1190 r
= gather_pid_metadata(iovw
, &context
);
1194 if (!context
.is_journald
) {
1195 /* OK, now we know it's not the journal, hence we can make use of it now. */
1196 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
1200 /* If this is PID 1 disable coredump collection, we'll unlikely be able to process
1203 * FIXME: maybe we should disable coredumps generation from the beginning and
1204 * re-enable it only when we know it's either safe (ie we're not running OOM) or
1205 * it's not pid1 ? */
1206 if (context
.is_pid1
) {
1207 log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
1208 disable_coredumps();
1211 if (context
.is_journald
|| context
.is_pid1
)
1212 r
= submit_coredump(&context
, iovw
, STDIN_FILENO
);
1214 r
= send_iovec(iovw
, STDIN_FILENO
);
1217 iovw
= iovw_free_free(iovw
);
1221 static int process_backtrace(int argc
, char *argv
[]) {
1222 Context context
= {};
1223 struct iovec_wrapper
*iovw
;
1226 _cleanup_(journal_importer_cleanup
) JournalImporter importer
= JOURNAL_IMPORTER_INIT(STDIN_FILENO
);
1228 log_debug("Processing backtrace on stdin...");
1234 (void) iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR
);
1235 (void) iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1237 /* Collect all process metadata from argv[] by making sure to skip the
1238 * '--backtrace' option */
1239 r
= gather_pid_metadata_from_argv(iovw
, &context
, argc
- 2, argv
+ 2);
1243 /* Collect the rest of the process metadata retrieved from the runtime */
1244 r
= gather_pid_metadata(iovw
, &context
);
1249 r
= journal_importer_process_data(&importer
);
1251 log_error_errno(r
, "Failed to parse journal entry on stdin: %m");
1254 if (r
== 1 || /* complete entry */
1255 journal_importer_eof(&importer
)) /* end of data */
1259 if (journal_importer_eof(&importer
)) {
1260 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
1262 message
= strjoina("Process ", context
.meta
[META_ARGV_PID
],
1263 " (", context
.meta
[META_COMM
], ")"
1264 " of user ", context
.meta
[META_ARGV_UID
],
1265 " failed with ", context
.meta
[META_ARGV_SIGNAL
]);
1267 r
= iovw_put_string_field(iovw
, "MESSAGE=", message
);
1271 /* The imported iovecs are not supposed to be freed by us so let's store
1272 * them at the end of the array so we can skip them while freeing the
1274 for (size_t i
= 0; i
< importer
.iovw
.count
; i
++) {
1275 struct iovec
*iovec
= importer
.iovw
.iovec
+ i
;
1277 iovw_put(iovw
, iovec
->iov_base
, iovec
->iov_len
);
1281 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
1283 log_error_errno(r
, "Failed to log backtrace: %m");
1286 iovw
->count
-= importer
.iovw
.count
;
1287 iovw
= iovw_free_free(iovw
);
1291 static int run(int argc
, char *argv
[]) {
1294 /* First, log to a safe place, since we don't know what crashed and it might
1295 * be journald which we'd rather not log to then. */
1297 log_set_target(LOG_TARGET_KMSG
);
1300 /* Make sure we never enter a loop */
1301 (void) prctl(PR_SET_DUMPABLE
, 0);
1303 /* Ignore all parse errors */
1304 (void) parse_config();
1306 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage
));
1307 log_debug("Selected compression %s.", yes_no(arg_compress
));
1309 r
= sd_listen_fds(false);
1311 return log_error_errno(r
, "Failed to determine the number of file descriptors: %m");
1313 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1314 * are invoked from the kernel as coredump handler. */
1316 if (streq_ptr(argv
[1], "--backtrace"))
1317 return process_backtrace(argc
, argv
);
1319 return process_kernel(argc
, argv
);
1321 return process_socket(SD_LISTEN_FDS_START
);
1323 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1324 "Received unexpected number of file descriptors.");
1327 DEFINE_MAIN_FUNCTION(run
);