1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include <sys/statvfs.h>
11 #include "sd-daemon.h"
12 #include "sd-journal.h"
14 #include "sd-messages.h"
17 #include "alloc-util.h"
18 #include "bus-error.h"
19 #include "capability-util.h"
20 #include "cgroup-util.h"
22 #include "conf-parser.h"
24 #include "coredump-util.h"
25 #include "coredump-vacuum.h"
26 #include "dirent-util.h"
33 #include "journal-importer.h"
34 #include "journal-send.h"
37 #include "main-func.h"
38 #include "memory-util.h"
39 #include "memstream-util.h"
40 #include "mkdir-label.h"
41 #include "parse-util.h"
42 #include "process-util.h"
43 #include "signal-util.h"
44 #include "socket-util.h"
46 #include "stat-util.h"
47 #include "string-table.h"
48 #include "string-util.h"
50 #include "sync-util.h"
51 #include "tmpfile-util.h"
52 #include "uid-alloc-range.h"
53 #include "user-util.h"
55 /* The maximum size up to which we process coredumps. We use 1G on 32-bit systems, and 32G on 64-bit systems */
56 #if __SIZEOF_POINTER__ == 4
57 #define PROCESS_SIZE_MAX ((uint64_t) (1LLU*1024LLU*1024LLU*1024LLU))
58 #elif __SIZEOF_POINTER__ == 8
59 #define PROCESS_SIZE_MAX ((uint64_t) (32LLU*1024LLU*1024LLU*1024LLU))
61 #error "Unexpected pointer size"
64 /* The maximum size up to which we leave the coredump around on disk */
65 #define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
67 /* The maximum size up to which we store the coredump in the journal */
68 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
69 #define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
71 /* oss-fuzz limits memory usage. */
72 #define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
75 /* When checking for available memory and setting lower limits, don't
76 * go below 4MB for writing core files to storage. */
77 #define PROCESS_SIZE_MIN (4U*1024U*1024U)
79 /* Make sure to not make this larger than the maximum journal entry
80 * size. See DATA_SIZE_MAX in journal-importer.h. */
81 assert_cc(JOURNAL_SIZE_MAX
<= DATA_SIZE_MAX
);
84 /* We use these as array indexes for our process metadata cache.
86 * The first indices of the cache stores the same metadata as the ones passed by
87 * the kernel via argv[], ie the strings array passed by the kernel according to
88 * our pattern defined in /proc/sys/kernel/core_pattern (see man:core(5)). */
90 META_ARGV_PID
, /* %P: as seen in the initial pid namespace */
91 META_ARGV_UID
, /* %u: as seen in the initial user namespace */
92 META_ARGV_GID
, /* %g: as seen in the initial user namespace */
93 META_ARGV_SIGNAL
, /* %s: number of signal causing dump */
94 META_ARGV_TIMESTAMP
, /* %t: time of dump, expressed as seconds since the Epoch (we expand this to μs granularity) */
95 META_ARGV_RLIMIT
, /* %c: core file size soft resource limit */
96 META_ARGV_HOSTNAME
, /* %h: hostname */
99 /* The following indexes are cached for a couple of special fields we use (and
100 * thereby need to be retrieved quickly) for naming coredump files, and attaching
101 * xattrs. Unlike the previous ones they are retrieved from the runtime
104 META_COMM
= _META_ARGV_MAX
,
107 /* The rest are similar to the previous ones except that we won't fail if one of
108 * them is missing. */
110 META_EXE
= _META_MANDATORY_MAX
,
116 static const char * const meta_field_names
[_META_MAX
] = {
117 [META_ARGV_PID
] = "COREDUMP_PID=",
118 [META_ARGV_UID
] = "COREDUMP_UID=",
119 [META_ARGV_GID
] = "COREDUMP_GID=",
120 [META_ARGV_SIGNAL
] = "COREDUMP_SIGNAL=",
121 [META_ARGV_TIMESTAMP
] = "COREDUMP_TIMESTAMP=",
122 [META_ARGV_RLIMIT
] = "COREDUMP_RLIMIT=",
123 [META_ARGV_HOSTNAME
] = "COREDUMP_HOSTNAME=",
124 [META_COMM
] = "COREDUMP_COMM=",
125 [META_EXE
] = "COREDUMP_EXE=",
126 [META_UNIT
] = "COREDUMP_UNIT=",
127 [META_PROC_AUXV
] = "COREDUMP_PROC_AUXV=",
130 typedef struct Context
{
131 const char *meta
[_META_MAX
];
132 size_t meta_size
[_META_MAX
];
138 typedef enum CoredumpStorage
{
139 COREDUMP_STORAGE_NONE
,
140 COREDUMP_STORAGE_EXTERNAL
,
141 COREDUMP_STORAGE_JOURNAL
,
142 _COREDUMP_STORAGE_MAX
,
143 _COREDUMP_STORAGE_INVALID
= -EINVAL
,
146 static const char* const coredump_storage_table
[_COREDUMP_STORAGE_MAX
] = {
147 [COREDUMP_STORAGE_NONE
] = "none",
148 [COREDUMP_STORAGE_EXTERNAL
] = "external",
149 [COREDUMP_STORAGE_JOURNAL
] = "journal",
152 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage
, CoredumpStorage
);
153 static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage
, coredump_storage
, CoredumpStorage
, "Failed to parse storage setting");
155 static CoredumpStorage arg_storage
= COREDUMP_STORAGE_EXTERNAL
;
156 static bool arg_compress
= true;
157 static uint64_t arg_process_size_max
= PROCESS_SIZE_MAX
;
158 static uint64_t arg_external_size_max
= EXTERNAL_SIZE_MAX
;
159 static uint64_t arg_journal_size_max
= JOURNAL_SIZE_MAX
;
160 static uint64_t arg_keep_free
= UINT64_MAX
;
161 static uint64_t arg_max_use
= UINT64_MAX
;
163 static int parse_config(void) {
164 static const ConfigTableItem items
[] = {
165 { "Coredump", "Storage", config_parse_coredump_storage
, 0, &arg_storage
},
166 { "Coredump", "Compress", config_parse_bool
, 0, &arg_compress
},
167 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64
, 0, &arg_process_size_max
},
168 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64_infinity
, 0, &arg_external_size_max
},
169 { "Coredump", "JournalSizeMax", config_parse_iec_size
, 0, &arg_journal_size_max
},
170 { "Coredump", "KeepFree", config_parse_iec_uint64
, 0, &arg_keep_free
},
171 { "Coredump", "MaxUse", config_parse_iec_uint64
, 0, &arg_max_use
},
177 r
= config_parse_config_file(
180 config_item_table_lookup
,
183 /* userdata= */ NULL
);
187 /* Let's make sure we fix up the maximum size we send to the journal here on the client side, for
188 * efficiency reasons. journald wouldn't accept anything larger anyway. */
189 if (arg_journal_size_max
> JOURNAL_SIZE_MAX
) {
190 log_warning("JournalSizeMax= set to larger value (%s) than journald would accept (%s), lowering automatically.",
191 FORMAT_BYTES(arg_journal_size_max
), FORMAT_BYTES(JOURNAL_SIZE_MAX
));
192 arg_journal_size_max
= JOURNAL_SIZE_MAX
;
198 static uint64_t storage_size_max(void) {
199 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
)
200 return arg_external_size_max
;
201 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
)
202 return arg_journal_size_max
;
203 assert(arg_storage
== COREDUMP_STORAGE_NONE
);
207 static int fix_acl(int fd
, uid_t uid
, bool allow_user
) {
209 assert(uid_is_valid(uid
));
214 /* We don't allow users to read coredumps if the uid or capabilities were changed. */
218 if (uid_is_system(uid
) || uid_is_dynamic(uid
) || uid
== UID_NOBODY
)
221 /* Make sure normal users can read (but not write or delete) their own coredumps */
222 r
= fd_add_uid_acl_permission(fd
, uid
, ACL_READ
);
224 return log_error_errno(r
, "Failed to adjust ACL of the coredump: %m");
230 static int fix_xattr(int fd
, const Context
*context
) {
232 static const char * const xattrs
[_META_MAX
] = {
233 [META_ARGV_PID
] = "user.coredump.pid",
234 [META_ARGV_UID
] = "user.coredump.uid",
235 [META_ARGV_GID
] = "user.coredump.gid",
236 [META_ARGV_SIGNAL
] = "user.coredump.signal",
237 [META_ARGV_TIMESTAMP
] = "user.coredump.timestamp",
238 [META_ARGV_RLIMIT
] = "user.coredump.rlimit",
239 [META_ARGV_HOSTNAME
] = "user.coredump.hostname",
240 [META_COMM
] = "user.coredump.comm",
241 [META_EXE
] = "user.coredump.exe",
248 /* Attach some metadata to coredumps via extended
249 * attributes. Just because we can. */
251 for (unsigned i
= 0; i
< _META_MAX
; i
++) {
254 if (isempty(context
->meta
[i
]) || !xattrs
[i
])
257 k
= fsetxattr(fd
, xattrs
[i
], context
->meta
[i
], strlen(context
->meta
[i
]), XATTR_CREATE
);
265 #define filename_escape(s) xescape((s), "./ ")
267 static const char *coredump_tmpfile_name(const char *s
) {
268 return s
?: "(unnamed temporary file)";
271 static int fix_permissions(
273 const char *filename
,
275 const Context
*context
,
285 /* Ignore errors on these */
286 (void) fchmod(fd
, 0640);
287 (void) fix_acl(fd
, uid
, allow_user
);
288 (void) fix_xattr(fd
, context
);
290 r
= link_tmpfile(fd
, filename
, target
, LINK_TMPFILE_SYNC
);
292 return log_error_errno(r
, "Failed to move coredump %s into place: %m", target
);
297 static int maybe_remove_external_coredump(const char *filename
, uint64_t size
) {
299 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
301 if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
&&
302 size
<= arg_external_size_max
)
308 if (unlink(filename
) < 0 && errno
!= ENOENT
)
309 return log_error_errno(errno
, "Failed to unlink %s: %m", filename
);
314 static int make_filename(const Context
*context
, char **ret
) {
315 _cleanup_free_
char *c
= NULL
, *u
= NULL
, *p
= NULL
, *t
= NULL
;
316 sd_id128_t boot
= {};
321 c
= filename_escape(context
->meta
[META_COMM
]);
325 u
= filename_escape(context
->meta
[META_ARGV_UID
]);
329 r
= sd_id128_get_boot(&boot
);
333 p
= filename_escape(context
->meta
[META_ARGV_PID
]);
337 t
= filename_escape(context
->meta
[META_ARGV_TIMESTAMP
]);
342 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR
".%s.%s",
345 SD_ID128_FORMAT_VAL(boot
),
353 static int grant_user_access(int core_fd
, const Context
*context
) {
355 uid_t uid
= UID_INVALID
, euid
= UID_INVALID
;
356 uid_t gid
= GID_INVALID
, egid
= GID_INVALID
;
359 assert(core_fd
>= 0);
362 if (!context
->meta
[META_PROC_AUXV
])
363 return log_warning_errno(SYNTHETIC_ERRNO(ENODATA
), "No auxv data, not adjusting permissions.");
365 uint8_t elf
[EI_NIDENT
];
367 if (pread(core_fd
, &elf
, sizeof(elf
), 0) != sizeof(elf
))
368 return log_warning_errno(errno_or_else(EIO
),
369 "Failed to pread from coredump fd: %s", STRERROR_OR_EOF(errno
));
371 if (elf
[EI_MAG0
] != ELFMAG0
||
372 elf
[EI_MAG1
] != ELFMAG1
||
373 elf
[EI_MAG2
] != ELFMAG2
||
374 elf
[EI_MAG3
] != ELFMAG3
||
375 elf
[EI_VERSION
] != EV_CURRENT
)
376 return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN
),
377 "Core file does not have ELF header, not adjusting permissions.");
378 if (!IN_SET(elf
[EI_CLASS
], ELFCLASS32
, ELFCLASS64
) ||
379 !IN_SET(elf
[EI_DATA
], ELFDATA2LSB
, ELFDATA2MSB
))
380 return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN
),
381 "Core file has strange ELF class, not adjusting permissions.");
383 if ((elf
[EI_DATA
] == ELFDATA2LSB
) != (__BYTE_ORDER
== __LITTLE_ENDIAN
))
384 return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN
),
385 "Core file has non-native endianness, not adjusting permissions.");
387 r
= parse_auxv(LOG_WARNING
,
388 /* elf_class= */ elf
[EI_CLASS
],
389 context
->meta
[META_PROC_AUXV
],
390 context
->meta_size
[META_PROC_AUXV
],
391 &at_secure
, &uid
, &euid
, &gid
, &egid
);
395 /* We allow access if we got all the data and at_secure is not set and
396 * the uid/gid matches euid/egid. */
399 uid
!= UID_INVALID
&& euid
!= UID_INVALID
&& uid
== euid
&&
400 gid
!= GID_INVALID
&& egid
!= GID_INVALID
&& gid
== egid
;
401 log_debug("Will %s access (uid="UID_FMT
" euid="UID_FMT
" gid="GID_FMT
" egid="GID_FMT
" at_secure=%s)",
402 ret
? "permit" : "restrict",
403 uid
, euid
, gid
, egid
, yes_no(at_secure
));
407 static int save_external_coredump(
408 const Context
*context
,
414 uint64_t *ret_compressed_size
,
415 bool *ret_truncated
) {
417 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
418 _cleanup_free_
char *fn
= NULL
;
419 _cleanup_close_
int fd
= -EBADF
;
420 uint64_t rlimit
, process_limit
, max_size
;
421 bool truncated
, storage_on_tmpfs
;
427 assert(ret_filename
);
431 assert(ret_compressed_size
);
432 assert(ret_truncated
);
434 r
= parse_uid(context
->meta
[META_ARGV_UID
], &uid
);
436 return log_error_errno(r
, "Failed to parse UID: %m");
438 r
= safe_atou64(context
->meta
[META_ARGV_RLIMIT
], &rlimit
);
440 return log_error_errno(r
, "Failed to parse resource limit '%s': %m",
441 context
->meta
[META_ARGV_RLIMIT
]);
442 if (rlimit
< page_size())
443 /* Is coredumping disabled? Then don't bother saving/processing the
444 * coredump. Anything below PAGE_SIZE cannot give a readable coredump
445 * (the kernel uses ELF_EXEC_PAGESIZE which is not easily accessible, but
446 * is usually the same as PAGE_SIZE. */
447 return log_info_errno(SYNTHETIC_ERRNO(EBADSLT
),
448 "Resource limits disable core dumping for process %s (%s).",
449 context
->meta
[META_ARGV_PID
], context
->meta
[META_COMM
]);
451 process_limit
= MAX(arg_process_size_max
, storage_size_max());
452 if (process_limit
== 0)
453 return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT
),
454 "Limits for coredump processing and storage are both 0, not dumping core.");
456 /* Never store more than the process configured, or than we actually shall keep or process */
457 max_size
= MIN(rlimit
, process_limit
);
459 r
= make_filename(context
, &fn
);
461 return log_error_errno(r
, "Failed to determine coredump file name: %m");
463 (void) mkdir_parents_label(fn
, 0755);
465 fd
= open_tmpfile_linkable(fn
, O_RDWR
|O_CLOEXEC
, &tmp
);
467 return log_error_errno(fd
, "Failed to create temporary file for coredump %s: %m", fn
);
469 /* If storage is on tmpfs, the kernel oomd might kill us if there's MemoryMax set on
470 * the service or the slice it belongs to. This is common on low-resources systems,
471 * to avoid crashing processes to take away too many system resources.
472 * Check the cgroup settings, and set max_size to a bit less than half of the
473 * available memory left to the process.
474 * Then, attempt to write the core file uncompressed first - if the write gets
475 * interrupted, we know we won't be able to write it all, so instead compress what
476 * was written so far, delete the uncompressed truncated core, and then continue
477 * compressing from STDIN. Given the compressed core cannot be larger than the
478 * uncompressed one, and 1KB for metadata is accounted for in the calculation, we
479 * should be able to at least store the full compressed core file. */
481 storage_on_tmpfs
= fd_is_temporary_fs(fd
) > 0;
482 if (storage_on_tmpfs
&& arg_compress
) {
483 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
484 uint64_t cgroup_limit
= UINT64_MAX
;
487 /* If we can't get the cgroup limit, just ignore it, but don't fail,
488 * try anyway with the config settings. */
489 r
= sd_bus_default_system(&bus
);
491 log_info_errno(r
, "Failed to connect to system bus, skipping MemoryAvailable check: %m");
493 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
495 r
= sd_bus_get_property_trivial(
497 "org.freedesktop.systemd1",
498 "/org/freedesktop/systemd1/unit/self",
499 "org.freedesktop.systemd1.Service",
505 "Failed to query MemoryAvailable for current unit, "
506 "falling back to static config settings: %s",
507 bus_error_message(&error
, r
));
510 max_size
= MIN(cgroup_limit
, max_size
);
511 max_size
= LESS_BY(max_size
, 1024U) / 2; /* Account for 1KB metadata overhead for compressing */
512 max_size
= MAX(PROCESS_SIZE_MIN
, max_size
); /* Impose a lower minimum */
514 /* tmpfs might get full quickly, so check the available space too.
515 * But don't worry about errors here, failing to access the storage
516 * location will be better logged when writing to it. */
517 if (fstatvfs(fd
, &sv
) >= 0)
518 max_size
= MIN((uint64_t)sv
.f_frsize
* (uint64_t)sv
.f_bfree
, max_size
);
520 log_debug("Limiting core file size to %" PRIu64
" bytes due to cgroup memory limits.", max_size
);
523 r
= copy_bytes(input_fd
, fd
, max_size
, 0);
525 return log_error_errno(r
, "Cannot store coredump of %s (%s): %m",
526 context
->meta
[META_ARGV_PID
], context
->meta
[META_COMM
]);
529 bool allow_user
= grant_user_access(fd
, context
) > 0;
533 _cleanup_(unlink_and_freep
) char *tmp_compressed
= NULL
;
534 _cleanup_free_
char *fn_compressed
= NULL
;
535 _cleanup_close_
int fd_compressed
= -EBADF
;
536 uint64_t uncompressed_size
= 0;
538 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1)
539 return log_error_errno(errno
, "Failed to seek on coredump %s: %m", fn
);
541 fn_compressed
= strjoin(fn
, default_compression_extension());
545 fd_compressed
= open_tmpfile_linkable(fn_compressed
, O_RDWR
|O_CLOEXEC
, &tmp_compressed
);
546 if (fd_compressed
< 0)
547 return log_error_errno(fd_compressed
, "Failed to create temporary file for coredump %s: %m", fn_compressed
);
549 r
= compress_stream(fd
, fd_compressed
, max_size
, &uncompressed_size
);
551 return log_error_errno(r
, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed
));
553 if (truncated
&& storage_on_tmpfs
) {
554 uint64_t partial_uncompressed_size
= 0;
556 /* Uncompressed write was truncated and we are writing to tmpfs: delete
557 * the uncompressed core, and compress the remaining part from STDIN. */
559 tmp
= unlink_and_free(tmp
);
562 r
= compress_stream(input_fd
, fd_compressed
, max_size
, &partial_uncompressed_size
);
564 return log_error_errno(r
, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed
));
565 uncompressed_size
+= partial_uncompressed_size
;
568 r
= fix_permissions(fd_compressed
, tmp_compressed
, fn_compressed
, context
, uid
, allow_user
);
572 if (fstat(fd_compressed
, &st
) < 0)
573 return log_error_errno(errno
,
574 "Failed to fstat core file %s: %m",
575 coredump_tmpfile_name(tmp_compressed
));
577 *ret_filename
= TAKE_PTR(fn_compressed
); /* compressed */
578 *ret_node_fd
= TAKE_FD(fd_compressed
); /* compressed */
579 *ret_compressed_size
= (uint64_t) st
.st_size
; /* compressed */
580 *ret_data_fd
= TAKE_FD(fd
);
581 *ret_size
= uncompressed_size
;
582 *ret_truncated
= truncated
;
583 tmp_compressed
= mfree(tmp_compressed
);
591 LOG_MESSAGE("Core file was truncated to %"PRIu64
" bytes.", max_size
),
592 "SIZE_LIMIT=%"PRIu64
, max_size
,
593 "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR
);
595 r
= fix_permissions(fd
, tmp
, fn
, context
, uid
, allow_user
);
597 return log_error_errno(r
, "Failed to fix permissions and finalize coredump %s into %s: %m", coredump_tmpfile_name(tmp
), fn
);
599 if (fstat(fd
, &st
) < 0)
600 return log_error_errno(errno
, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp
));
602 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1)
603 return log_error_errno(errno
, "Failed to seek on coredump %s: %m", fn
);
605 *ret_filename
= TAKE_PTR(fn
);
606 *ret_data_fd
= TAKE_FD(fd
);
607 *ret_size
= (uint64_t) st
.st_size
;
608 *ret_truncated
= truncated
;
613 static int allocate_journal_field(int fd
, size_t size
, char **ret
, size_t *ret_size
) {
614 _cleanup_free_
char *field
= NULL
;
621 if (lseek(fd
, 0, SEEK_SET
) == (off_t
) -1)
622 return log_warning_errno(errno
, "Failed to seek: %m");
624 field
= malloc(9 + size
);
626 return log_warning_errno(SYNTHETIC_ERRNO(ENOMEM
),
627 "Failed to allocate memory for coredump, coredump will not be stored.");
629 memcpy(field
, "COREDUMP=", 9);
631 /* NB: simple read() would fail for overly large coredumps, since read() on Linux can only deal with
632 * 0x7ffff000 bytes max. Hence call things in a loop. */
633 n
= loop_read(fd
, field
+ 9, size
, /* do_poll= */ false);
635 return log_error_errno((int) n
, "Failed to read core data: %m");
636 if ((size_t) n
< size
)
637 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
638 "Core data too short.");
640 *ret
= TAKE_PTR(field
);
641 *ret_size
= size
+ 9;
646 /* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
660 static int compose_open_fds(pid_t pid
, char **ret
) {
661 _cleanup_(memstream_done
) MemStream m
= {};
662 _cleanup_closedir_
DIR *proc_fd_dir
= NULL
;
663 _cleanup_close_
int proc_fdinfo_fd
= -EBADF
;
664 const char *fddelim
= "", *path
;
671 path
= procfs_file_alloca(pid
, "fd");
672 proc_fd_dir
= opendir(path
);
676 proc_fdinfo_fd
= openat(dirfd(proc_fd_dir
), "../fdinfo", O_DIRECTORY
|O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
677 if (proc_fdinfo_fd
< 0)
680 stream
= memstream_init(&m
);
684 FOREACH_DIRENT(de
, proc_fd_dir
, return -errno
) {
685 _cleanup_fclose_
FILE *fdinfo
= NULL
;
686 _cleanup_free_
char *fdname
= NULL
;
687 _cleanup_close_
int fd
= -EBADF
;
689 r
= readlinkat_malloc(dirfd(proc_fd_dir
), de
->d_name
, &fdname
);
693 fprintf(stream
, "%s%s:%s\n", fddelim
, de
->d_name
, fdname
);
696 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
697 fd
= openat(proc_fdinfo_fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_RDONLY
);
701 fdinfo
= take_fdopen(&fd
, "r");
706 _cleanup_free_
char *line
= NULL
;
708 r
= read_line(fdinfo
, LONG_LINE_MAX
, &line
);
719 return memstream_finalize(&m
, ret
, NULL
);
722 static int get_process_ns(pid_t pid
, const char *namespace, ino_t
*ns
) {
725 _cleanup_close_
int proc_ns_dir_fd
= -EBADF
;
727 p
= procfs_file_alloca(pid
, "ns");
729 proc_ns_dir_fd
= open(p
, O_DIRECTORY
| O_CLOEXEC
| O_RDONLY
);
730 if (proc_ns_dir_fd
< 0)
733 if (fstatat(proc_ns_dir_fd
, namespace, &stbuf
, /* flags */0) < 0)
740 static int get_mount_namespace_leader(pid_t pid
, pid_t
*ret
) {
744 r
= get_process_ns(pid
, "mnt", &proc_mntns
);
752 r
= get_process_ppid(pid
, &ppid
);
753 if (r
== -EADDRNOTAVAIL
) /* Reached the top (i.e. typically PID 1, but could also be a process
754 * whose parent is not in our pidns) */
759 r
= get_process_ns(ppid
, "mnt", &parent_mntns
);
763 if (proc_mntns
!= parent_mntns
) {
772 /* Returns 1 if the parent was found.
773 * Returns 0 if there is not a process we can call the pid's
774 * container parent (the pid's process isn't 'containerized').
775 * Returns a negative number on errors.
777 static int get_process_container_parent_cmdline(pid_t pid
, char** cmdline
) {
779 const char *proc_root_path
;
780 struct stat root_stat
, proc_root_stat
;
783 /* To compare inodes of / and /proc/[pid]/root */
784 if (stat("/", &root_stat
) < 0)
787 proc_root_path
= procfs_file_alloca(pid
, "root");
788 if (stat(proc_root_path
, &proc_root_stat
) < 0)
791 /* The process uses system root. */
792 if (stat_inode_same(&proc_root_stat
, &root_stat
)) {
797 r
= get_mount_namespace_leader(pid
, &container_pid
);
801 r
= get_process_cmdline(container_pid
, SIZE_MAX
, PROCESS_CMDLINE_QUOTE_POSIX
, cmdline
);
808 static int change_uid_gid(const Context
*context
) {
813 r
= parse_uid(context
->meta
[META_ARGV_UID
], &uid
);
817 if (uid_is_system(uid
)) {
818 const char *user
= "systemd-coredump";
820 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
822 log_warning_errno(r
, "Cannot resolve %s user. Proceeding to dump core as root: %m", user
);
826 r
= parse_gid(context
->meta
[META_ARGV_GID
], &gid
);
831 return drop_privileges(uid
, gid
, 0);
834 static int submit_coredump(
835 const Context
*context
,
836 struct iovec_wrapper
*iovw
,
839 _cleanup_(json_variant_unrefp
) JsonVariant
*json_metadata
= NULL
;
840 _cleanup_close_
int coredump_fd
= -EBADF
, coredump_node_fd
= -EBADF
;
841 _cleanup_free_
char *filename
= NULL
, *coredump_data
= NULL
;
842 _cleanup_free_
char *stacktrace
= NULL
;
844 const char *module_name
;
845 uint64_t coredump_size
= UINT64_MAX
, coredump_compressed_size
= UINT64_MAX
;
846 bool truncated
= false;
847 JsonVariant
*module_json
;
852 assert(input_fd
>= 0);
854 /* Vacuum before we write anything again */
855 (void) coredump_vacuum(-1, arg_keep_free
, arg_max_use
);
857 /* Always stream the coredump to disk, if that's possible */
858 r
= save_external_coredump(context
, input_fd
,
859 &filename
, &coredump_node_fd
, &coredump_fd
,
860 &coredump_size
, &coredump_compressed_size
, &truncated
);
862 /* Skip whole core dumping part */
865 /* If we don't want to keep the coredump on disk, remove it now, as later on we
866 * will lack the privileges for it. However, we keep the fd to it, so that we can
867 * still process it and log it. */
868 r
= maybe_remove_external_coredump(filename
, coredump_node_fd
>= 0 ? coredump_compressed_size
: coredump_size
);
872 (void) iovw_put_string_field(iovw
, "COREDUMP_FILENAME=", filename
);
873 else if (arg_storage
== COREDUMP_STORAGE_EXTERNAL
)
874 log_info("The core will not be stored: size %"PRIu64
" is greater than %"PRIu64
" (the configured maximum)",
875 coredump_node_fd
>= 0 ? coredump_compressed_size
: coredump_size
, arg_external_size_max
);
877 /* Vacuum again, but exclude the coredump we just created */
878 (void) coredump_vacuum(coredump_node_fd
>= 0 ? coredump_node_fd
: coredump_fd
, arg_keep_free
, arg_max_use
);
880 /* Now, let's drop privileges to become the user who owns the segfaulted process
881 * and allocate the coredump memory under the user's uid. This also ensures that
882 * the credentials journald will see are the ones of the coredumping user, thus
883 * making sure the user gets access to the core dump. Let's also get rid of all
884 * capabilities, if we run as root, we won't need them anymore. */
885 r
= change_uid_gid(context
);
887 return log_error_errno(r
, "Failed to drop privileges: %m");
889 /* Try to get a stack trace if we can */
890 if (coredump_size
> arg_process_size_max
)
891 log_debug("Not generating stack trace: core size %"PRIu64
" is greater "
892 "than %"PRIu64
" (the configured maximum)",
893 coredump_size
, arg_process_size_max
);
894 else if (coredump_fd
>= 0) {
895 bool skip
= startswith(context
->meta
[META_COMM
], "systemd-coredum"); /* COMM is 16 bytes usually */
897 (void) parse_elf_object(coredump_fd
,
898 context
->meta
[META_EXE
],
899 /* fork_disable_dump= */ skip
, /* avoid loops */
905 core_message
= strjoina("Process ", context
->meta
[META_ARGV_PID
],
906 " (", context
->meta
[META_COMM
], ") of user ",
907 context
->meta
[META_ARGV_UID
], " dumped core.",
908 context
->is_journald
&& filename
? "\nCoredump diverted to " : NULL
,
909 context
->is_journald
&& filename
? filename
: NULL
);
911 core_message
= strjoina(core_message
, stacktrace
? "\n\n" : NULL
, stacktrace
);
913 if (context
->is_journald
)
914 /* We might not be able to log to the journal, so let's always print the message to another
915 * log target. The target was set previously to something safe. */
916 log_dispatch(LOG_ERR
, 0, core_message
);
918 (void) iovw_put_string_field(iovw
, "MESSAGE=", core_message
);
921 (void) iovw_put_string_field(iovw
, "COREDUMP_TRUNCATED=", "1");
923 /* If we managed to parse any ELF metadata (build-id, ELF package meta),
924 * attach it as journal metadata. */
926 _cleanup_free_
char *formatted_json
= NULL
;
928 r
= json_variant_format(json_metadata
, 0, &formatted_json
);
930 return log_error_errno(r
, "Failed to format JSON package metadata: %m");
932 (void) iovw_put_string_field(iovw
, "COREDUMP_PACKAGE_JSON=", formatted_json
);
935 /* In the unlikely scenario that context->meta[META_EXE] is not available,
936 * let's avoid guessing the module name and skip the loop. */
937 if (context
->meta
[META_EXE
])
938 JSON_VARIANT_OBJECT_FOREACH(module_name
, module_json
, json_metadata
) {
941 /* We only add structured fields for the 'main' ELF module, and only if we can identify it. */
942 if (!path_equal_filename(module_name
, context
->meta
[META_EXE
]))
945 t
= json_variant_by_key(module_json
, "name");
947 (void) iovw_put_string_field(iovw
, "COREDUMP_PACKAGE_NAME=", json_variant_string(t
));
949 t
= json_variant_by_key(module_json
, "version");
951 (void) iovw_put_string_field(iovw
, "COREDUMP_PACKAGE_VERSION=", json_variant_string(t
));
954 /* Optionally store the entire coredump in the journal */
955 if (arg_storage
== COREDUMP_STORAGE_JOURNAL
&& coredump_fd
>= 0) {
956 if (coredump_size
<= arg_journal_size_max
) {
959 /* Store the coredump itself in the journal */
961 r
= allocate_journal_field(coredump_fd
, (size_t) coredump_size
, &coredump_data
, &sz
);
963 if (iovw_put(iovw
, coredump_data
, sz
) >= 0)
964 TAKE_PTR(coredump_data
);
966 log_warning_errno(r
, "Failed to attach the core to the journal entry: %m");
968 log_info("The core will not be stored: size %"PRIu64
" is greater than %"PRIu64
" (the configured maximum)",
969 coredump_size
, arg_journal_size_max
);
972 /* If journald is coredumping, we have to be careful that we don't deadlock when trying to write the
973 * coredump to the journal, so we put the journal socket in nonblocking mode before trying to write
974 * the coredump to the socket. */
976 if (context
->is_journald
) {
977 r
= journal_fd_nonblock(true);
979 return log_error_errno(r
, "Failed to make journal socket non-blocking: %m");
982 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
984 if (context
->is_journald
) {
987 k
= journal_fd_nonblock(false);
989 return log_error_errno(k
, "Failed to make journal socket blocking: %m");
992 if (r
== -EAGAIN
&& context
->is_journald
)
993 log_warning_errno(r
, "Failed to log journal coredump, ignoring: %m");
995 return log_error_errno(r
, "Failed to log coredump: %m");
1000 static int save_context(Context
*context
, const struct iovec_wrapper
*iovw
) {
1006 assert(iovw
->count
>= _META_ARGV_MAX
);
1008 /* The context does not allocate any memory on its own */
1010 for (size_t n
= 0; n
< iovw
->count
; n
++) {
1011 struct iovec
*iovec
= iovw
->iovec
+ n
;
1013 for (size_t i
= 0; i
< ELEMENTSOF(meta_field_names
); i
++) {
1014 /* Note that these strings are NUL terminated, because we made sure that a
1015 * trailing NUL byte is in the buffer, though not included in the iov_len
1016 * count (see process_socket() and gather_pid_metadata_*()) */
1017 assert(((char*) iovec
->iov_base
)[iovec
->iov_len
] == 0);
1019 const char *p
= startswith(iovec
->iov_base
, meta_field_names
[i
]);
1021 context
->meta
[i
] = p
;
1022 context
->meta_size
[i
] = iovec
->iov_len
- strlen(meta_field_names
[i
]);
1028 if (!context
->meta
[META_ARGV_PID
])
1029 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1030 "Failed to find the PID of crashing process");
1032 r
= parse_pid(context
->meta
[META_ARGV_PID
], &context
->pid
);
1034 return log_error_errno(r
, "Failed to parse PID \"%s\": %m", context
->meta
[META_ARGV_PID
]);
1036 unit
= context
->meta
[META_UNIT
];
1037 context
->is_pid1
= streq(context
->meta
[META_ARGV_PID
], "1") || streq_ptr(unit
, SPECIAL_INIT_SCOPE
);
1038 context
->is_journald
= streq_ptr(unit
, SPECIAL_JOURNALD_SERVICE
);
1043 static int process_socket(int fd
) {
1044 _cleanup_close_
int input_fd
= -EBADF
;
1045 Context context
= {};
1046 struct iovec_wrapper iovw
= {};
1054 log_debug("Processing coredump received on stdin...");
1057 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
1058 struct msghdr mh
= {
1059 .msg_control
= &control
,
1060 .msg_controllen
= sizeof(control
),
1066 l
= next_datagram_size_fd(fd
);
1068 r
= log_error_errno(l
, "Failed to determine datagram size to read: %m");
1073 iovec
.iov_base
= malloc(l
+ 1);
1074 if (!iovec
.iov_base
) {
1079 mh
.msg_iov
= &iovec
;
1081 n
= recvmsg_safe(fd
, &mh
, MSG_CMSG_CLOEXEC
);
1083 free(iovec
.iov_base
);
1084 r
= log_error_errno(n
, "Failed to receive datagram: %m");
1088 /* The final zero-length datagram carries the file descriptor and tells us
1089 * that we're done. */
1091 struct cmsghdr
*found
;
1093 free(iovec
.iov_base
);
1095 found
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, CMSG_LEN(sizeof(int)));
1097 cmsg_close_all(&mh
);
1098 r
= log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
1099 "Coredump file descriptor missing.");
1103 assert(input_fd
< 0);
1104 input_fd
= *CMSG_TYPED_DATA(found
, int);
1107 cmsg_close_all(&mh
);
1109 /* Add trailing NUL byte, in case these are strings */
1110 ((char*) iovec
.iov_base
)[n
] = 0;
1111 iovec
.iov_len
= (size_t) n
;
1113 r
= iovw_put(&iovw
, iovec
.iov_base
, iovec
.iov_len
);
1118 /* Make sure we got all data we really need */
1119 assert(input_fd
>= 0);
1121 r
= save_context(&context
, &iovw
);
1125 /* Make sure we received at least all fields we need. */
1126 for (int i
= 0; i
< _META_MANDATORY_MAX
; i
++)
1127 if (!context
.meta
[i
]) {
1128 r
= log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1129 "A mandatory argument (%i) has not been sent, aborting.",
1134 r
= submit_coredump(&context
, &iovw
, input_fd
);
1137 iovw_free_contents(&iovw
, true);
1141 static int send_iovec(const struct iovec_wrapper
*iovw
, int input_fd
) {
1142 _cleanup_close_
int fd
= -EBADF
;
1146 assert(input_fd
>= 0);
1148 fd
= socket(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0);
1150 return log_error_errno(errno
, "Failed to create coredump socket: %m");
1152 r
= connect_unix_path(fd
, AT_FDCWD
, "/run/systemd/coredump");
1154 return log_error_errno(r
, "Failed to connect to coredump service: %m");
1156 for (size_t i
= 0; i
< iovw
->count
; i
++) {
1157 struct msghdr mh
= {
1158 .msg_iov
= iovw
->iovec
+ i
,
1161 struct iovec copy
[2];
1164 if (sendmsg(fd
, &mh
, MSG_NOSIGNAL
) >= 0)
1167 if (errno
== EMSGSIZE
&& mh
.msg_iov
[0].iov_len
> 0) {
1168 /* This field didn't fit? That's a pity. Given that this is
1169 * just metadata, let's truncate the field at half, and try
1170 * again. We append three dots, in order to show that this is
1173 if (mh
.msg_iov
!= copy
) {
1174 /* We don't want to modify the caller's iovec, hence
1175 * let's create our own array, consisting of two new
1176 * iovecs, where the first is a (truncated) copy of
1177 * what we want to send, and the second one contains
1178 * the trailing dots. */
1179 copy
[0] = iovw
->iovec
[i
];
1180 copy
[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);
1186 copy
[0].iov_len
/= 2; /* halve it, and try again */
1190 return log_error_errno(errno
, "Failed to send coredump datagram: %m");
1194 r
= send_one_fd(fd
, input_fd
, 0);
1196 return log_error_errno(r
, "Failed to send coredump fd: %m");
1201 static int gather_pid_metadata_from_argv(
1202 struct iovec_wrapper
*iovw
,
1204 int argc
, char **argv
) {
1206 _cleanup_free_
char *free_timestamp
= NULL
;
1210 /* We gather all metadata that were passed via argv[] into an array of iovecs that
1211 * we'll forward to the socket unit */
1213 if (argc
< _META_ARGV_MAX
)
1214 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1215 "Not enough arguments passed by the kernel (%i, expected %i).",
1216 argc
, _META_ARGV_MAX
);
1218 for (int i
= 0; i
< _META_ARGV_MAX
; i
++) {
1224 case META_ARGV_TIMESTAMP
:
1225 /* The journal fields contain the timestamp padded with six
1226 * zeroes, so that the kernel-supplied 1s granularity timestamps
1227 * becomes 1μs granularity, i.e. the granularity systemd usually
1229 t
= free_timestamp
= strjoin(argv
[i
], "000000");
1234 case META_ARGV_SIGNAL
:
1235 /* For signal, record its pretty name too */
1236 if (safe_atoi(argv
[i
], &signo
) >= 0 && SIGNAL_VALID(signo
))
1237 (void) iovw_put_string_field(iovw
, "COREDUMP_SIGNAL_NAME=SIG",
1238 signal_to_string(signo
));
1245 r
= iovw_put_string_field(iovw
, meta_field_names
[i
], t
);
1250 /* Cache some of the process metadata we collected so far and that we'll need to
1252 return save_context(context
, iovw
);
1255 static int gather_pid_metadata(struct iovec_wrapper
*iovw
, Context
*context
) {
1263 /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
1264 * structure. (It remains valid, with the first iovec fields initialized.) */
1268 /* The following is mandatory */
1269 r
= get_process_comm(pid
, &t
);
1271 return log_error_errno(r
, "Failed to get COMM: %m");
1273 r
= iovw_put_string_field_free(iovw
, "COREDUMP_COMM=", t
);
1277 /* The following are optional, but we use them if present. */
1278 r
= get_process_exe(pid
, &t
);
1280 r
= iovw_put_string_field_free(iovw
, "COREDUMP_EXE=", t
);
1282 log_warning_errno(r
, "Failed to get EXE, ignoring: %m");
1284 if (cg_pid_get_unit(pid
, &t
) >= 0)
1285 (void) iovw_put_string_field_free(iovw
, "COREDUMP_UNIT=", t
);
1287 if (cg_pid_get_user_unit(pid
, &t
) >= 0)
1288 (void) iovw_put_string_field_free(iovw
, "COREDUMP_USER_UNIT=", t
);
1290 if (sd_pid_get_session(pid
, &t
) >= 0)
1291 (void) iovw_put_string_field_free(iovw
, "COREDUMP_SESSION=", t
);
1293 if (sd_pid_get_owner_uid(pid
, &owner_uid
) >= 0) {
1294 r
= asprintf(&t
, UID_FMT
, owner_uid
);
1296 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OWNER_UID=", t
);
1299 if (sd_pid_get_slice(pid
, &t
) >= 0)
1300 (void) iovw_put_string_field_free(iovw
, "COREDUMP_SLICE=", t
);
1302 if (get_process_cmdline(pid
, SIZE_MAX
, PROCESS_CMDLINE_QUOTE_POSIX
, &t
) >= 0)
1303 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CMDLINE=", t
);
1305 if (cg_pid_get_path_shifted(pid
, NULL
, &t
) >= 0)
1306 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CGROUP=", t
);
1308 if (compose_open_fds(pid
, &t
) >= 0)
1309 (void) iovw_put_string_field_free(iovw
, "COREDUMP_OPEN_FDS=", t
);
1311 p
= procfs_file_alloca(pid
, "status");
1312 if (read_full_virtual_file(p
, &t
, NULL
) >= 0)
1313 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_STATUS=", t
);
1315 p
= procfs_file_alloca(pid
, "maps");
1316 if (read_full_virtual_file(p
, &t
, NULL
) >= 0)
1317 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_MAPS=", t
);
1319 p
= procfs_file_alloca(pid
, "limits");
1320 if (read_full_virtual_file(p
, &t
, NULL
) >= 0)
1321 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_LIMITS=", t
);
1323 p
= procfs_file_alloca(pid
, "cgroup");
1324 if (read_full_virtual_file(p
, &t
, NULL
) >= 0)
1325 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_CGROUP=", t
);
1327 p
= procfs_file_alloca(pid
, "mountinfo");
1328 if (read_full_virtual_file(p
, &t
, NULL
) >= 0)
1329 (void) iovw_put_string_field_free(iovw
, "COREDUMP_PROC_MOUNTINFO=", t
);
1331 /* We attach /proc/auxv here. ELF coredumps also contain a note for this (NT_AUXV), see elf(5). */
1332 p
= procfs_file_alloca(pid
, "auxv");
1333 if (read_full_virtual_file(p
, &t
, &size
) >= 0) {
1334 char *buf
= malloc(strlen("COREDUMP_PROC_AUXV=") + size
+ 1);
1336 /* Add a dummy terminator to make save_context() happy. */
1337 *((uint8_t*) mempcpy(stpcpy(buf
, "COREDUMP_PROC_AUXV="), t
, size
)) = '\0';
1338 (void) iovw_consume(iovw
, buf
, size
+ strlen("COREDUMP_PROC_AUXV="));
1344 if (get_process_cwd(pid
, &t
) >= 0)
1345 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CWD=", t
);
1347 if (get_process_root(pid
, &t
) >= 0) {
1348 bool proc_self_root_is_slash
;
1350 proc_self_root_is_slash
= strcmp(t
, "/") == 0;
1352 (void) iovw_put_string_field_free(iovw
, "COREDUMP_ROOT=", t
);
1354 /* If the process' root is "/", then there is a chance it has
1355 * mounted own root and hence being containerized. */
1356 if (proc_self_root_is_slash
&& get_process_container_parent_cmdline(pid
, &t
) > 0)
1357 (void) iovw_put_string_field_free(iovw
, "COREDUMP_CONTAINER_CMDLINE=", t
);
1360 if (get_process_environ(pid
, &t
) >= 0)
1361 (void) iovw_put_string_field_free(iovw
, "COREDUMP_ENVIRON=", t
);
1363 /* we successfully acquired all metadata */
1364 return save_context(context
, iovw
);
1367 static int process_kernel(int argc
, char* argv
[]) {
1368 Context context
= {};
1369 struct iovec_wrapper
*iovw
;
1372 /* When we're invoked by the kernel, stdout/stderr are closed which is dangerous because the fds
1373 * could get reallocated. To avoid hard to debug issues, let's instead bind stdout/stderr to
1375 r
= rearrange_stdio(STDIN_FILENO
, -EBADF
, -EBADF
);
1377 return log_error_errno(r
, "Failed to connect stdout/stderr to /dev/null: %m");
1379 log_debug("Processing coredump received from the kernel...");
1385 (void) iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR
);
1386 (void) iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1388 /* Collect all process metadata passed by the kernel through argv[] */
1389 r
= gather_pid_metadata_from_argv(iovw
, &context
, argc
- 1, argv
+ 1);
1393 /* Collect the rest of the process metadata retrieved from the runtime */
1394 r
= gather_pid_metadata(iovw
, &context
);
1398 if (!context
.is_journald
)
1399 /* OK, now we know it's not the journal, hence we can make use of it now. */
1400 log_set_target_and_open(LOG_TARGET_JOURNAL_OR_KMSG
);
1402 /* If this is PID 1 disable coredump collection, we'll unlikely be able to process
1405 * FIXME: maybe we should disable coredumps generation from the beginning and
1406 * re-enable it only when we know it's either safe (ie we're not running OOM) or
1407 * it's not pid1 ? */
1408 if (context
.is_pid1
) {
1409 log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
1410 disable_coredumps();
1413 if (context
.is_journald
|| context
.is_pid1
)
1414 r
= submit_coredump(&context
, iovw
, STDIN_FILENO
);
1416 r
= send_iovec(iovw
, STDIN_FILENO
);
1419 iovw
= iovw_free_free(iovw
);
1423 static int process_backtrace(int argc
, char *argv
[]) {
1424 Context context
= {};
1425 struct iovec_wrapper
*iovw
;
1428 _cleanup_(journal_importer_cleanup
) JournalImporter importer
= JOURNAL_IMPORTER_INIT(STDIN_FILENO
);
1430 log_debug("Processing backtrace on stdin...");
1436 (void) iovw_put_string_field(iovw
, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR
);
1437 (void) iovw_put_string_field(iovw
, "PRIORITY=", STRINGIFY(LOG_CRIT
));
1439 /* Collect all process metadata from argv[] by making sure to skip the
1440 * '--backtrace' option */
1441 r
= gather_pid_metadata_from_argv(iovw
, &context
, argc
- 2, argv
+ 2);
1445 /* Collect the rest of the process metadata retrieved from the runtime */
1446 r
= gather_pid_metadata(iovw
, &context
);
1451 r
= journal_importer_process_data(&importer
);
1453 log_error_errno(r
, "Failed to parse journal entry on stdin: %m");
1456 if (r
== 1 || /* complete entry */
1457 journal_importer_eof(&importer
)) /* end of data */
1461 if (journal_importer_eof(&importer
)) {
1462 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
1464 message
= strjoina("Process ", context
.meta
[META_ARGV_PID
],
1465 " (", context
.meta
[META_COMM
], ")"
1466 " of user ", context
.meta
[META_ARGV_UID
],
1467 " failed with ", context
.meta
[META_ARGV_SIGNAL
]);
1469 r
= iovw_put_string_field(iovw
, "MESSAGE=", message
);
1473 /* The imported iovecs are not supposed to be freed by us so let's store
1474 * them at the end of the array so we can skip them while freeing the
1476 for (size_t i
= 0; i
< importer
.iovw
.count
; i
++) {
1477 struct iovec
*iovec
= importer
.iovw
.iovec
+ i
;
1479 iovw_put(iovw
, iovec
->iov_base
, iovec
->iov_len
);
1483 r
= sd_journal_sendv(iovw
->iovec
, iovw
->count
);
1485 log_error_errno(r
, "Failed to log backtrace: %m");
1488 iovw
->count
-= importer
.iovw
.count
;
1489 iovw
= iovw_free_free(iovw
);
1493 static int run(int argc
, char *argv
[]) {
1496 /* First, log to a safe place, since we don't know what crashed and it might
1497 * be journald which we'd rather not log to then. */
1499 log_set_target_and_open(LOG_TARGET_KMSG
);
1501 /* Make sure we never enter a loop */
1502 (void) prctl(PR_SET_DUMPABLE
, 0);
1504 /* Ignore all parse errors */
1505 (void) parse_config();
1507 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage
));
1508 log_debug("Selected compression %s.", yes_no(arg_compress
));
1510 r
= sd_listen_fds(false);
1512 return log_error_errno(r
, "Failed to determine the number of file descriptors: %m");
1514 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1515 * are invoked from the kernel as coredump handler. */
1517 if (streq_ptr(argv
[1], "--backtrace"))
1518 return process_backtrace(argc
, argv
);
1520 return process_kernel(argc
, argv
);
1522 return process_socket(SD_LISTEN_FDS_START
);
1524 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1525 "Received unexpected number of file descriptors.");
1528 DEFINE_MAIN_FUNCTION(run
);