]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/coredump/coredumpctl.c
tree-wide: use -EBADF for fd initialization
[thirdparty/systemd.git] / src / coredump / coredumpctl.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <getopt.h>
5 #include <locale.h>
6 #include <stdio.h>
7 #include <unistd.h>
8
9 #include "sd-bus.h"
10 #include "sd-journal.h"
11 #include "sd-messages.h"
12
13 #include "alloc-util.h"
14 #include "build.h"
15 #include "bus-error.h"
16 #include "bus-locator.h"
17 #include "bus-util.h"
18 #include "chase-symlinks.h"
19 #include "compress.h"
20 #include "constants.h"
21 #include "dissect-image.h"
22 #include "escape.h"
23 #include "fd-util.h"
24 #include "format-table.h"
25 #include "fs-util.h"
26 #include "glob-util.h"
27 #include "journal-internal.h"
28 #include "journal-util.h"
29 #include "log.h"
30 #include "macro.h"
31 #include "main-func.h"
32 #include "mount-util.h"
33 #include "pager.h"
34 #include "parse-argument.h"
35 #include "parse-util.h"
36 #include "path-util.h"
37 #include "pretty-print.h"
38 #include "process-util.h"
39 #include "rlimit-util.h"
40 #include "sigbus.h"
41 #include "signal-util.h"
42 #include "string-util.h"
43 #include "strv.h"
44 #include "terminal-util.h"
45 #include "tmpfile-util.h"
46 #include "user-util.h"
47 #include "verbs.h"
48
49 #define SHORT_BUS_CALL_TIMEOUT_USEC (3 * USEC_PER_SEC)
50
51 static usec_t arg_since = USEC_INFINITY, arg_until = USEC_INFINITY;
52 static const char* arg_field = NULL;
53 static const char *arg_debugger = NULL;
54 static char **arg_debugger_args = NULL;
55 static const char *arg_directory = NULL;
56 static char *arg_root = NULL;
57 static char *arg_image = NULL;
58 static char **arg_file = NULL;
59 static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
60 static PagerFlags arg_pager_flags = 0;
61 static int arg_legend = true;
62 static size_t arg_rows_max = SIZE_MAX;
63 static const char* arg_output = NULL;
64 static bool arg_reverse = false;
65 static bool arg_quiet = false;
66 static bool arg_all = false;
67
68 STATIC_DESTRUCTOR_REGISTER(arg_debugger_args, strv_freep);
69 STATIC_DESTRUCTOR_REGISTER(arg_file, strv_freep);
70
71 static int add_match(sd_journal *j, const char *match) {
72 _cleanup_free_ char *p = NULL;
73 const char* prefix, *pattern;
74 pid_t pid;
75 int r;
76
77 if (strchr(match, '='))
78 prefix = "";
79 else if (strchr(match, '/')) {
80 r = path_make_absolute_cwd(match, &p);
81 if (r < 0)
82 return log_error_errno(r, "path_make_absolute_cwd(\"%s\"): %m", match);
83
84 match = p;
85 prefix = "COREDUMP_EXE=";
86 } else if (parse_pid(match, &pid) >= 0)
87 prefix = "COREDUMP_PID=";
88 else
89 prefix = "COREDUMP_COMM=";
90
91 pattern = strjoina(prefix, match);
92 log_debug("Adding match: %s", pattern);
93 r = sd_journal_add_match(j, pattern, 0);
94 if (r < 0)
95 return log_error_errno(r, "Failed to add match \"%s\": %m", match);
96
97 return 0;
98 }
99
100 static int add_matches(sd_journal *j, char **matches) {
101 int r;
102
103 r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR, 0);
104 if (r < 0)
105 return log_error_errno(r, "Failed to add match \"%s\": %m", "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR);
106
107 r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_BACKTRACE_STR, 0);
108 if (r < 0)
109 return log_error_errno(r, "Failed to add match \"%s\": %m", "MESSAGE_ID=" SD_MESSAGE_BACKTRACE_STR);
110
111 STRV_FOREACH(match, matches) {
112 r = add_match(j, *match);
113 if (r < 0)
114 return r;
115 }
116
117 return 0;
118 }
119
120 static int acquire_journal(sd_journal **ret, char **matches) {
121 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
122 int r;
123
124 assert(ret);
125
126 if (arg_directory) {
127 r = sd_journal_open_directory(&j, arg_directory, 0);
128 if (r < 0)
129 return log_error_errno(r, "Failed to open journals in directory: %s: %m", arg_directory);
130 } else if (arg_root) {
131 r = sd_journal_open_directory(&j, arg_root, SD_JOURNAL_OS_ROOT);
132 if (r < 0)
133 return log_error_errno(r, "Failed to open journals in root directory: %s: %m", arg_root);
134 } else if (arg_file) {
135 r = sd_journal_open_files(&j, (const char**)arg_file, 0);
136 if (r < 0)
137 return log_error_errno(r, "Failed to open journal files: %m");
138 } else {
139 r = sd_journal_open(&j, arg_all ? 0 : SD_JOURNAL_LOCAL_ONLY);
140 if (r < 0)
141 return log_error_errno(r, "Failed to open journal: %m");
142 }
143
144 r = journal_access_check_and_warn(j, arg_quiet, true);
145 if (r < 0)
146 return r;
147
148 r = add_matches(j, matches);
149 if (r < 0)
150 return r;
151
152 if (DEBUG_LOGGING) {
153 _cleanup_free_ char *filter = NULL;
154
155 filter = journal_make_match_string(j);
156 log_debug("Journal filter: %s", filter);
157 }
158
159 *ret = TAKE_PTR(j);
160
161 return 0;
162 }
163
164 static int verb_help(int argc, char **argv, void *userdata) {
165 _cleanup_free_ char *link = NULL;
166 int r;
167
168 r = terminal_urlify_man("coredumpctl", "1", &link);
169 if (r < 0)
170 return log_oom();
171
172 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
173 "%5$sList or retrieve coredumps from the journal.%6$s\n"
174 "\n%3$sCommands:%4$s\n"
175 " list [MATCHES...] List available coredumps (default)\n"
176 " info [MATCHES...] Show detailed information about one or more coredumps\n"
177 " dump [MATCHES...] Print first matching coredump to stdout\n"
178 " debug [MATCHES...] Start a debugger for the first matching coredump\n"
179 "\n%3$sOptions:%4$s\n"
180 " -h --help Show this help\n"
181 " --version Print version string\n"
182 " --no-pager Do not pipe output into a pager\n"
183 " --no-legend Do not print the column headers\n"
184 " --json=pretty|short|off\n"
185 " Generate JSON output\n"
186 " --debugger=DEBUGGER Use the given debugger\n"
187 " -A --debugger-arguments=ARGS Pass the given arguments to the debugger\n"
188 " -n INT Show maximum number of rows\n"
189 " -1 Show information about most recent entry only\n"
190 " -S --since=DATE Only print coredumps since the date\n"
191 " -U --until=DATE Only print coredumps until the date\n"
192 " -r --reverse Show the newest entries first\n"
193 " -F --field=FIELD List all values a certain field takes\n"
194 " -o --output=FILE Write output to FILE\n"
195 " --file=PATH Use journal file\n"
196 " -D --directory=DIR Use journal files from directory\n\n"
197 " -q --quiet Do not show info messages and privilege warning\n"
198 " --all Look at all journal files instead of local ones\n"
199 " --root=PATH Operate on an alternate filesystem root\n"
200 " --image=PATH Operate on disk image as filesystem root\n"
201 "\nSee the %2$s for details.\n",
202 program_invocation_short_name,
203 link,
204 ansi_underline(),
205 ansi_normal(),
206 ansi_highlight(),
207 ansi_normal());
208
209 return 0;
210 }
211
212 static int parse_argv(int argc, char *argv[]) {
213 enum {
214 ARG_VERSION = 0x100,
215 ARG_NO_PAGER,
216 ARG_NO_LEGEND,
217 ARG_JSON,
218 ARG_DEBUGGER,
219 ARG_FILE,
220 ARG_ROOT,
221 ARG_IMAGE,
222 ARG_ALL,
223 };
224
225 int c, r;
226
227 static const struct option options[] = {
228 { "help", no_argument, NULL, 'h' },
229 { "version" , no_argument, NULL, ARG_VERSION },
230 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
231 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
232 { "debugger", required_argument, NULL, ARG_DEBUGGER },
233 { "debugger-arguments", required_argument, NULL, 'A' },
234 { "output", required_argument, NULL, 'o' },
235 { "field", required_argument, NULL, 'F' },
236 { "file", required_argument, NULL, ARG_FILE },
237 { "directory", required_argument, NULL, 'D' },
238 { "reverse", no_argument, NULL, 'r' },
239 { "since", required_argument, NULL, 'S' },
240 { "until", required_argument, NULL, 'U' },
241 { "quiet", no_argument, NULL, 'q' },
242 { "json", required_argument, NULL, ARG_JSON },
243 { "root", required_argument, NULL, ARG_ROOT },
244 { "image", required_argument, NULL, ARG_IMAGE },
245 { "all", no_argument, NULL, ARG_ALL },
246 {}
247 };
248
249 assert(argc >= 0);
250 assert(argv);
251
252 while ((c = getopt_long(argc, argv, "hA:o:F:1D:rS:U:qn:", options, NULL)) >= 0)
253 switch (c) {
254 case 'h':
255 return verb_help(0, NULL, NULL);
256
257 case ARG_VERSION:
258 return version();
259
260 case ARG_NO_PAGER:
261 arg_pager_flags |= PAGER_DISABLE;
262 break;
263
264 case ARG_NO_LEGEND:
265 arg_legend = false;
266 break;
267
268 case ARG_DEBUGGER:
269 arg_debugger = optarg;
270 break;
271
272 case 'A': {
273 _cleanup_strv_free_ char **l = NULL;
274 r = strv_split_full(&l, optarg, WHITESPACE, EXTRACT_UNQUOTE);
275 if (r < 0)
276 return log_error_errno(r, "Failed to parse debugger arguments '%s': %m", optarg);
277 strv_free_and_replace(arg_debugger_args, l);
278 break;
279 }
280
281 case ARG_FILE:
282 r = glob_extend(&arg_file, optarg, GLOB_NOCHECK);
283 if (r < 0)
284 return log_error_errno(r, "Failed to add paths: %m");
285 break;
286
287 case 'o':
288 if (arg_output)
289 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
290 "Cannot set output more than once.");
291
292 arg_output = optarg;
293 break;
294
295 case 'S':
296 r = parse_timestamp(optarg, &arg_since);
297 if (r < 0)
298 return log_error_errno(r, "Failed to parse timestamp '%s': %m", optarg);
299 break;
300
301 case 'U':
302 r = parse_timestamp(optarg, &arg_until);
303 if (r < 0)
304 return log_error_errno(r, "Failed to parse timestamp '%s': %m", optarg);
305 break;
306
307 case 'F':
308 if (arg_field)
309 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
310 "Cannot use --field/-F more than once.");
311 arg_field = optarg;
312 break;
313
314 case '1':
315 arg_rows_max = 1;
316 arg_reverse = true;
317 break;
318
319 case 'n': {
320 unsigned n;
321
322 r = safe_atou(optarg, &n);
323 if (r < 0 || n < 1)
324 return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL),
325 "Invalid numeric parameter to -n: %s", optarg);
326
327 arg_rows_max = n;
328 break;
329 }
330
331 case 'D':
332 arg_directory = optarg;
333 break;
334
335 case ARG_ROOT:
336 r = parse_path_argument(optarg, false, &arg_root);
337 if (r < 0)
338 return r;
339 break;
340
341 case ARG_IMAGE:
342 r = parse_path_argument(optarg, false, &arg_image);
343 if (r < 0)
344 return r;
345 break;
346
347 case 'r':
348 arg_reverse = true;
349 break;
350
351 case 'q':
352 arg_quiet = true;
353 break;
354
355 case ARG_JSON:
356 r = parse_json_argument(optarg, &arg_json_format_flags);
357 if (r <= 0)
358 return r;
359
360 break;
361
362 case ARG_ALL:
363 arg_all = true;
364 break;
365
366 case '?':
367 return -EINVAL;
368
369 default:
370 assert_not_reached();
371 }
372
373 if (arg_since != USEC_INFINITY && arg_until != USEC_INFINITY &&
374 arg_since > arg_until)
375 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
376 "--since= must be before --until=.");
377
378 if ((!!arg_directory + !!arg_image + !!arg_root) > 1)
379 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root=, --image= or -D/--directory=, the combination of these options is not supported.");
380
381 return 1;
382 }
383
384 static int retrieve(const void *data,
385 size_t len,
386 const char *name,
387 char **var) {
388
389 size_t ident;
390 char *v;
391
392 ident = strlen(name) + 1; /* name + "=" */
393
394 if (len < ident)
395 return 0;
396
397 if (memcmp(data, name, ident - 1) != 0)
398 return 0;
399
400 if (((const char*) data)[ident - 1] != '=')
401 return 0;
402
403 v = strndup((const char*)data + ident, len - ident);
404 if (!v)
405 return log_oom();
406
407 free_and_replace(*var, v);
408 return 1;
409 }
410
411 static int print_field(FILE* file, sd_journal *j) {
412 const void *d;
413 size_t l;
414
415 assert(file);
416 assert(j);
417
418 assert(arg_field);
419
420 /* A (user-specified) field may appear more than once for a given entry.
421 * We will print all of the occurrences.
422 * This is different below for fields that systemd-coredump uses,
423 * because they cannot meaningfully appear more than once.
424 */
425 SD_JOURNAL_FOREACH_DATA(j, d, l) {
426 _cleanup_free_ char *value = NULL;
427 int r;
428
429 r = retrieve(d, l, arg_field, &value);
430 if (r < 0)
431 return r;
432 if (r > 0)
433 fprintf(file, "%s\n", value);
434 }
435
436 return 0;
437 }
438
439 #define RETRIEVE(d, l, name, arg) \
440 { \
441 int _r = retrieve(d, l, name, &arg); \
442 if (_r < 0) \
443 return _r; \
444 if (_r > 0) \
445 continue; \
446 }
447
448 static void analyze_coredump_file(
449 const char *path,
450 const char **ret_state,
451 const char **ret_color,
452 uint64_t *ret_size) {
453
454 _cleanup_close_ int fd = -EBADF;
455 struct stat st;
456 int r;
457
458 assert(path);
459 assert(ret_state);
460 assert(ret_color);
461 assert(ret_size);
462
463 fd = open(path, O_PATH|O_CLOEXEC);
464 if (fd < 0) {
465 if (errno == ENOENT) {
466 *ret_state = "missing";
467 *ret_color = ansi_grey();
468 *ret_size = UINT64_MAX;
469 return;
470 }
471
472 r = -errno;
473 } else
474 r = access_fd(fd, R_OK);
475 if (ERRNO_IS_PRIVILEGE(r)) {
476 *ret_state = "inaccessible";
477 *ret_color = ansi_highlight_yellow();
478 *ret_size = UINT64_MAX;
479 return;
480 }
481 if (r < 0)
482 goto error;
483
484 if (fstat(fd, &st) < 0)
485 goto error;
486
487 if (!S_ISREG(st.st_mode))
488 goto error;
489
490 *ret_state = "present";
491 *ret_color = NULL;
492 *ret_size = st.st_size;
493 return;
494
495 error:
496 *ret_state = "error";
497 *ret_color = ansi_highlight_red();
498 *ret_size = UINT64_MAX;
499 }
500
501 static int resolve_filename(const char *root, char **p) {
502 char *resolved = NULL;
503 int r;
504
505 if (!*p)
506 return 0;
507
508 r = chase_symlinks(*p, root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &resolved, NULL);
509 if (r < 0)
510 return log_error_errno(r, "Failed to resolve \"%s%s\": %m", strempty(root), *p);
511
512 free_and_replace(*p, resolved);
513
514 /* chase_symlinks() with flag CHASE_NONEXISTENT will return 0 if the file doesn't exist and 1 if it does.
515 * Return that to the caller
516 */
517 return r;
518 }
519
520 static int print_list(FILE* file, sd_journal *j, Table *t) {
521 _cleanup_free_ char
522 *mid = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
523 *sgnl = NULL, *exe = NULL, *comm = NULL, *cmdline = NULL,
524 *filename = NULL, *truncated = NULL, *coredump = NULL;
525 const void *d;
526 size_t l;
527 usec_t ts;
528 int r, signal_as_int = 0;
529 const char *present = NULL, *color = NULL;
530 uint64_t size = UINT64_MAX;
531 bool normal_coredump;
532 uid_t uid_as_int = UID_INVALID;
533 gid_t gid_as_int = GID_INVALID;
534 pid_t pid_as_int = 0;
535
536 assert(file);
537 assert(j);
538 assert(t);
539
540 SD_JOURNAL_FOREACH_DATA(j, d, l) {
541 RETRIEVE(d, l, "MESSAGE_ID", mid);
542 RETRIEVE(d, l, "COREDUMP_PID", pid);
543 RETRIEVE(d, l, "COREDUMP_UID", uid);
544 RETRIEVE(d, l, "COREDUMP_GID", gid);
545 RETRIEVE(d, l, "COREDUMP_SIGNAL", sgnl);
546 RETRIEVE(d, l, "COREDUMP_EXE", exe);
547 RETRIEVE(d, l, "COREDUMP_COMM", comm);
548 RETRIEVE(d, l, "COREDUMP_CMDLINE", cmdline);
549 RETRIEVE(d, l, "COREDUMP_FILENAME", filename);
550 RETRIEVE(d, l, "COREDUMP_TRUNCATED", truncated);
551 RETRIEVE(d, l, "COREDUMP", coredump);
552 }
553
554 if (!pid && !uid && !gid && !sgnl && !exe && !comm && !cmdline && !filename)
555 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Empty coredump log entry");
556
557 (void) parse_uid(uid, &uid_as_int);
558 (void) parse_gid(gid, &gid_as_int);
559 (void) parse_pid(pid, &pid_as_int);
560 signal_as_int = signal_from_string(sgnl);
561
562 r = sd_journal_get_realtime_usec(j, &ts);
563 if (r < 0)
564 return log_error_errno(r, "Failed to get realtime timestamp: %m");
565
566 normal_coredump = streq_ptr(mid, SD_MESSAGE_COREDUMP_STR);
567
568 if (filename) {
569 r = resolve_filename(arg_root, &filename);
570 if (r < 0)
571 return r;
572
573 analyze_coredump_file(filename, &present, &color, &size);
574 } else if (coredump)
575 present = "journal";
576 else if (normal_coredump) {
577 present = "none";
578 color = ansi_grey();
579 } else
580 present = NULL;
581
582 if (STRPTR_IN_SET(present, "present", "journal") && truncated && parse_boolean(truncated) > 0)
583 present = "truncated";
584
585 r = table_add_many(
586 t,
587 TABLE_TIMESTAMP, ts,
588 TABLE_PID, pid_as_int,
589 TABLE_UID, uid_as_int,
590 TABLE_GID, gid_as_int,
591 TABLE_SIGNAL, normal_coredump ? signal_as_int : 0,
592 TABLE_STRING, present,
593 TABLE_SET_COLOR, color,
594 TABLE_STRING, exe ?: comm ?: cmdline,
595 TABLE_SIZE, size);
596 if (r < 0)
597 return table_log_add_error(r);
598
599 return 0;
600 }
601
602 static int print_info(FILE *file, sd_journal *j, bool need_space) {
603 _cleanup_free_ char
604 *mid = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
605 *sgnl = NULL, *exe = NULL, *comm = NULL, *cmdline = NULL,
606 *unit = NULL, *user_unit = NULL, *session = NULL,
607 *boot_id = NULL, *machine_id = NULL, *hostname = NULL,
608 *slice = NULL, *cgroup = NULL, *owner_uid = NULL,
609 *message = NULL, *timestamp = NULL, *filename = NULL,
610 *truncated = NULL, *coredump = NULL,
611 *pkgmeta_name = NULL, *pkgmeta_version = NULL, *pkgmeta_json = NULL;
612 const void *d;
613 size_t l;
614 bool normal_coredump;
615 int r;
616
617 assert(file);
618 assert(j);
619
620 (void) sd_journal_set_data_threshold(j, 0);
621
622 SD_JOURNAL_FOREACH_DATA(j, d, l) {
623 RETRIEVE(d, l, "MESSAGE_ID", mid);
624 RETRIEVE(d, l, "COREDUMP_PID", pid);
625 RETRIEVE(d, l, "COREDUMP_UID", uid);
626 RETRIEVE(d, l, "COREDUMP_GID", gid);
627 RETRIEVE(d, l, "COREDUMP_SIGNAL", sgnl);
628 RETRIEVE(d, l, "COREDUMP_EXE", exe);
629 RETRIEVE(d, l, "COREDUMP_COMM", comm);
630 RETRIEVE(d, l, "COREDUMP_CMDLINE", cmdline);
631 RETRIEVE(d, l, "COREDUMP_HOSTNAME", hostname);
632 RETRIEVE(d, l, "COREDUMP_UNIT", unit);
633 RETRIEVE(d, l, "COREDUMP_USER_UNIT", user_unit);
634 RETRIEVE(d, l, "COREDUMP_SESSION", session);
635 RETRIEVE(d, l, "COREDUMP_OWNER_UID", owner_uid);
636 RETRIEVE(d, l, "COREDUMP_SLICE", slice);
637 RETRIEVE(d, l, "COREDUMP_CGROUP", cgroup);
638 RETRIEVE(d, l, "COREDUMP_TIMESTAMP", timestamp);
639 RETRIEVE(d, l, "COREDUMP_FILENAME", filename);
640 RETRIEVE(d, l, "COREDUMP_TRUNCATED", truncated);
641 RETRIEVE(d, l, "COREDUMP", coredump);
642 RETRIEVE(d, l, "COREDUMP_PACKAGE_NAME", pkgmeta_name);
643 RETRIEVE(d, l, "COREDUMP_PACKAGE_VERSION", pkgmeta_version);
644 RETRIEVE(d, l, "COREDUMP_PACKAGE_JSON", pkgmeta_json);
645 RETRIEVE(d, l, "_BOOT_ID", boot_id);
646 RETRIEVE(d, l, "_MACHINE_ID", machine_id);
647 RETRIEVE(d, l, "MESSAGE", message);
648 }
649
650 if (need_space)
651 fputs("\n", file);
652
653 normal_coredump = streq_ptr(mid, SD_MESSAGE_COREDUMP_STR);
654
655 if (comm)
656 fprintf(file,
657 " PID: %s%s%s (%s)\n",
658 ansi_highlight(), strna(pid), ansi_normal(), comm);
659 else
660 fprintf(file,
661 " PID: %s%s%s\n",
662 ansi_highlight(), strna(pid), ansi_normal());
663
664 if (uid) {
665 uid_t n;
666
667 if (parse_uid(uid, &n) >= 0) {
668 _cleanup_free_ char *u = NULL;
669
670 u = uid_to_name(n);
671 fprintf(file,
672 " UID: %s (%s)\n",
673 uid, u);
674 } else {
675 fprintf(file,
676 " UID: %s\n",
677 uid);
678 }
679 }
680
681 if (gid) {
682 gid_t n;
683
684 if (parse_gid(gid, &n) >= 0) {
685 _cleanup_free_ char *g = NULL;
686
687 g = gid_to_name(n);
688 fprintf(file,
689 " GID: %s (%s)\n",
690 gid, g);
691 } else {
692 fprintf(file,
693 " GID: %s\n",
694 gid);
695 }
696 }
697
698 if (sgnl) {
699 int sig;
700 const char *name = normal_coredump ? "Signal" : "Reason";
701
702 if (normal_coredump && safe_atoi(sgnl, &sig) >= 0)
703 fprintf(file, " %s: %s (%s)\n", name, sgnl, signal_to_string(sig));
704 else
705 fprintf(file, " %s: %s\n", name, sgnl);
706 }
707
708 if (timestamp) {
709 usec_t u;
710
711 r = safe_atou64(timestamp, &u);
712 if (r >= 0)
713 fprintf(file, " Timestamp: %s (%s)\n",
714 FORMAT_TIMESTAMP(u), FORMAT_TIMESTAMP_RELATIVE(u));
715
716 else
717 fprintf(file, " Timestamp: %s\n", timestamp);
718 }
719
720 if (cmdline)
721 fprintf(file, " Command Line: %s\n", cmdline);
722 if (exe)
723 fprintf(file, " Executable: %s%s%s\n", ansi_highlight(), exe, ansi_normal());
724 if (cgroup)
725 fprintf(file, " Control Group: %s\n", cgroup);
726 if (unit)
727 fprintf(file, " Unit: %s\n", unit);
728 if (user_unit)
729 fprintf(file, " User Unit: %s\n", user_unit);
730 if (slice)
731 fprintf(file, " Slice: %s\n", slice);
732 if (session)
733 fprintf(file, " Session: %s\n", session);
734 if (owner_uid) {
735 uid_t n;
736
737 if (parse_uid(owner_uid, &n) >= 0) {
738 _cleanup_free_ char *u = NULL;
739
740 u = uid_to_name(n);
741 fprintf(file,
742 " Owner UID: %s (%s)\n",
743 owner_uid, u);
744 } else {
745 fprintf(file,
746 " Owner UID: %s\n",
747 owner_uid);
748 }
749 }
750 if (boot_id)
751 fprintf(file, " Boot ID: %s\n", boot_id);
752 if (machine_id)
753 fprintf(file, " Machine ID: %s\n", machine_id);
754 if (hostname)
755 fprintf(file, " Hostname: %s\n", hostname);
756
757 if (filename) {
758 r = resolve_filename(arg_root, &filename);
759 if (r < 0)
760 return r;
761
762 const char *state = NULL, *color = NULL;
763 uint64_t size = UINT64_MAX;
764
765 analyze_coredump_file(filename, &state, &color, &size);
766
767 if (STRPTR_IN_SET(state, "present", "journal") && truncated && parse_boolean(truncated) > 0)
768 state = "truncated";
769
770 fprintf(file,
771 " Storage: %s%s (%s)%s\n",
772 strempty(color),
773 filename,
774 state,
775 ansi_normal());
776
777 if (size != UINT64_MAX)
778 fprintf(file, " Size on Disk: %s\n", FORMAT_BYTES(size));
779
780 } else if (coredump)
781 fprintf(file, " Storage: journal\n");
782 else
783 fprintf(file, " Storage: none\n");
784
785 if (pkgmeta_name && pkgmeta_version)
786 fprintf(file, " Package: %s/%s\n", pkgmeta_name, pkgmeta_version);
787
788 /* Print out the build-id of the 'main' ELF module, by matching the JSON key
789 * with the 'exe' field. */
790 if (exe && pkgmeta_json) {
791 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
792
793 r = json_parse(pkgmeta_json, 0, &v, NULL, NULL);
794 if (r < 0) {
795 _cleanup_free_ char *esc = cescape(pkgmeta_json);
796 log_warning_errno(r, "json_parse on \"%s\" failed, ignoring: %m", strnull(esc));
797 } else {
798 const char *module_name;
799 JsonVariant *module_json;
800
801 JSON_VARIANT_OBJECT_FOREACH(module_name, module_json, v) {
802 JsonVariant *build_id;
803
804 /* We only print the build-id for the 'main' ELF module */
805 if (!path_equal_filename(module_name, exe))
806 continue;
807
808 build_id = json_variant_by_key(module_json, "buildId");
809 if (build_id)
810 fprintf(file, " build-id: %s\n", json_variant_string(build_id));
811
812 break;
813 }
814 }
815 }
816
817 if (message) {
818 _cleanup_free_ char *m = NULL;
819
820 m = strreplace(message, "\n", "\n ");
821
822 fprintf(file, " Message: %s\n", strstrip(m ?: message));
823 }
824
825 return 0;
826 }
827
828 static int focus(sd_journal *j) {
829 int r;
830
831 r = sd_journal_seek_tail(j);
832 if (r == 0)
833 r = sd_journal_previous(j);
834 if (r < 0)
835 return log_error_errno(r, "Failed to search journal: %m");
836 if (r == 0)
837 return log_error_errno(SYNTHETIC_ERRNO(ESRCH),
838 "No match found.");
839 return r;
840 }
841
842 static int print_entry(
843 sd_journal *j,
844 size_t n_found,
845 Table *t) {
846
847 assert(j);
848
849 if (t)
850 return print_list(stdout, j, t);
851 else if (arg_field)
852 return print_field(stdout, j);
853 else
854 return print_info(stdout, j, n_found > 0);
855 }
856
857 static int dump_list(int argc, char **argv, void *userdata) {
858 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
859 _cleanup_(table_unrefp) Table *t = NULL;
860 size_t n_found = 0;
861 bool verb_is_info;
862 int r;
863
864 verb_is_info = argc >= 1 && streq(argv[0], "info");
865
866 r = acquire_journal(&j, argv + 1);
867 if (r < 0)
868 return r;
869
870 /* The coredumps are likely compressed, and for just listing them we don't need to decompress them,
871 * so let's pick a fairly low data threshold here */
872 (void) sd_journal_set_data_threshold(j, 4096);
873
874 if (!verb_is_info && !arg_field) {
875 t = table_new("time", "pid", "uid", "gid", "sig", "corefile", "exe", "size");
876 if (!t)
877 return log_oom();
878
879 (void) table_set_align_percent(t, TABLE_HEADER_CELL(1), 100);
880 (void) table_set_align_percent(t, TABLE_HEADER_CELL(2), 100);
881 (void) table_set_align_percent(t, TABLE_HEADER_CELL(3), 100);
882 (void) table_set_align_percent(t, TABLE_HEADER_CELL(7), 100);
883
884 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
885 } else
886 pager_open(arg_pager_flags);
887
888 /* "info" without pattern implies "-1" */
889 if ((arg_rows_max == 1 && arg_reverse) || (verb_is_info && argc == 1)) {
890 r = focus(j);
891 if (r < 0)
892 return r;
893
894 r = print_entry(j, 0, t);
895 if (r < 0)
896 return r;
897 } else {
898 if (arg_since != USEC_INFINITY && !arg_reverse)
899 r = sd_journal_seek_realtime_usec(j, arg_since);
900 else if (arg_until != USEC_INFINITY && arg_reverse)
901 r = sd_journal_seek_realtime_usec(j, arg_until);
902 else if (arg_reverse)
903 r = sd_journal_seek_tail(j);
904 else
905 r = sd_journal_seek_head(j);
906 if (r < 0)
907 return log_error_errno(r, "Failed to seek to date: %m");
908
909 for (;;) {
910 if (!arg_reverse)
911 r = sd_journal_next(j);
912 else
913 r = sd_journal_previous(j);
914 if (r < 0)
915 return log_error_errno(r, "Failed to iterate through journal: %m");
916 if (r == 0)
917 break;
918
919 if (arg_until != USEC_INFINITY && !arg_reverse) {
920 usec_t usec;
921
922 r = sd_journal_get_realtime_usec(j, &usec);
923 if (r < 0)
924 return log_error_errno(r, "Failed to determine timestamp: %m");
925 if (usec > arg_until)
926 continue;
927 }
928
929 if (arg_since != USEC_INFINITY && arg_reverse) {
930 usec_t usec;
931
932 r = sd_journal_get_realtime_usec(j, &usec);
933 if (r < 0)
934 return log_error_errno(r, "Failed to determine timestamp: %m");
935 if (usec < arg_since)
936 continue;
937 }
938
939 r = print_entry(j, n_found++, t);
940 if (r < 0)
941 return r;
942
943 if (arg_rows_max != SIZE_MAX && n_found >= arg_rows_max)
944 break;
945 }
946
947 if (!arg_field && n_found <= 0) {
948 if (!arg_quiet)
949 log_notice("No coredumps found.");
950 return -ESRCH;
951 }
952 }
953
954 if (t) {
955 r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
956 if (r < 0)
957 return r;
958 }
959
960 return 0;
961 }
962
963 static int save_core(sd_journal *j, FILE *file, char **path, bool *unlink_temp) {
964 const char *data;
965 _cleanup_free_ char *filename = NULL;
966 size_t len;
967 int r, fd;
968 _cleanup_close_ int fdt = -EBADF;
969 char *temp = NULL;
970
971 assert(!(file && path)); /* At most one can be specified */
972 assert(!!path == !!unlink_temp); /* Those must be specified together */
973
974 /* Look for a coredump on disk first. */
975 r = sd_journal_get_data(j, "COREDUMP_FILENAME", (const void**) &data, &len);
976 if (r == 0) {
977 _cleanup_free_ char *resolved = NULL;
978
979 r = retrieve(data, len, "COREDUMP_FILENAME", &filename);
980 if (r < 0)
981 return r;
982 assert(r > 0);
983
984 r = chase_symlinks_and_access(filename, arg_root, CHASE_PREFIX_ROOT, F_OK, &resolved, NULL);
985 if (r < 0)
986 return log_error_errno(r, "Cannot access \"%s%s\": %m", strempty(arg_root), filename);
987
988 free_and_replace(filename, resolved);
989
990 if (path && !ENDSWITH_SET(filename, ".xz", ".lz4", ".zst")) {
991 *path = TAKE_PTR(filename);
992
993 return 0;
994 }
995
996 } else {
997 if (r != -ENOENT)
998 return log_error_errno(r, "Failed to retrieve COREDUMP_FILENAME field: %m");
999 /* Check that we can have a COREDUMP field. We still haven't set a high
1000 * data threshold, so we'll get a few kilobytes at most.
1001 */
1002
1003 r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
1004 if (r == -ENOENT)
1005 return log_error_errno(r, "Coredump entry has no core attached (neither internally in the journal nor externally on disk).");
1006 if (r < 0)
1007 return log_error_errno(r, "Failed to retrieve COREDUMP field: %m");
1008 }
1009
1010 if (path) {
1011 const char *vt;
1012
1013 /* Create a temporary file to write the uncompressed core to. */
1014
1015 r = var_tmp_dir(&vt);
1016 if (r < 0)
1017 return log_error_errno(r, "Failed to acquire temporary directory path: %m");
1018
1019 temp = path_join(vt, "coredump-XXXXXX");
1020 if (!temp)
1021 return log_oom();
1022
1023 fdt = mkostemp_safe(temp);
1024 if (fdt < 0)
1025 return log_error_errno(fdt, "Failed to create temporary file: %m");
1026 log_debug("Created temporary file %s", temp);
1027
1028 fd = fdt;
1029 } else {
1030 /* If neither path or file are specified, we will write to stdout. Let's now check
1031 * if stdout is connected to a tty. We checked that the file exists, or that the
1032 * core might be stored in the journal. In this second case, if we found the entry,
1033 * in all likelihood we will be able to access the COREDUMP= field. In either case,
1034 * we stop before doing any "real" work, i.e. before starting decompression or
1035 * reading from the file or creating temporary files.
1036 */
1037 if (!file) {
1038 if (on_tty())
1039 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY),
1040 "Refusing to dump core to tty"
1041 " (use shell redirection or specify --output).");
1042 file = stdout;
1043 }
1044
1045 fd = fileno(file);
1046 }
1047
1048 if (filename) {
1049 #if HAVE_COMPRESSION
1050 _cleanup_close_ int fdf = -EBADF;
1051
1052 fdf = open(filename, O_RDONLY | O_CLOEXEC);
1053 if (fdf < 0) {
1054 r = log_error_errno(errno, "Failed to open %s: %m", filename);
1055 goto error;
1056 }
1057
1058 r = decompress_stream(filename, fdf, fd, -1);
1059 if (r < 0) {
1060 log_error_errno(r, "Failed to decompress %s: %m", filename);
1061 goto error;
1062 }
1063 #else
1064 r = log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1065 "Cannot decompress file. Compiled without compression support.");
1066 goto error;
1067 #endif
1068 } else {
1069 ssize_t sz;
1070
1071 /* We want full data, nothing truncated. */
1072 sd_journal_set_data_threshold(j, 0);
1073
1074 r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
1075 if (r < 0)
1076 return log_error_errno(r, "Failed to retrieve COREDUMP field: %m");
1077
1078 assert(len >= 9);
1079 data += 9;
1080 len -= 9;
1081
1082 sz = write(fd, data, len);
1083 if (sz < 0) {
1084 r = log_error_errno(errno, "Failed to write output: %m");
1085 goto error;
1086 }
1087 if (sz != (ssize_t) len) {
1088 log_error("Short write to output.");
1089 r = -EIO;
1090 goto error;
1091 }
1092 }
1093
1094 if (temp) {
1095 *path = temp;
1096 *unlink_temp = true;
1097 }
1098 return 0;
1099
1100 error:
1101 if (temp) {
1102 (void) unlink(temp);
1103 log_debug("Removed temporary file %s", temp);
1104 }
1105 return r;
1106 }
1107
1108 static int dump_core(int argc, char **argv, void *userdata) {
1109 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1110 _cleanup_fclose_ FILE *f = NULL;
1111 int r;
1112
1113 if (arg_field)
1114 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1115 "Option --field/-F only makes sense with list");
1116
1117 r = acquire_journal(&j, argv + 1);
1118 if (r < 0)
1119 return r;
1120
1121 r = focus(j);
1122 if (r < 0)
1123 return r;
1124
1125 if (arg_output) {
1126 f = fopen(arg_output, "we");
1127 if (!f)
1128 return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", arg_output);
1129 }
1130
1131 print_info(f ? stdout : stderr, j, false);
1132
1133 r = save_core(j, f, NULL, NULL);
1134 if (r < 0)
1135 return r;
1136
1137 r = sd_journal_previous(j);
1138 if (r > 0 && !arg_quiet)
1139 log_notice("More than one entry matches, ignoring rest.");
1140
1141 return 0;
1142 }
1143
1144 static int run_debug(int argc, char **argv, void *userdata) {
1145 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1146 _cleanup_free_ char *exe = NULL, *path = NULL;
1147 _cleanup_strv_free_ char **debugger_call = NULL;
1148 bool unlink_path = false;
1149 const char *data, *fork_name;
1150 size_t len;
1151 pid_t pid;
1152 int r;
1153
1154 if (!arg_debugger) {
1155 char *env_debugger;
1156
1157 env_debugger = getenv("SYSTEMD_DEBUGGER");
1158 if (env_debugger)
1159 arg_debugger = env_debugger;
1160 else
1161 arg_debugger = "gdb";
1162 }
1163
1164 r = strv_extend(&debugger_call, arg_debugger);
1165 if (r < 0)
1166 return log_oom();
1167
1168 r = strv_extend_strv(&debugger_call, arg_debugger_args, false);
1169 if (r < 0)
1170 return log_oom();
1171
1172 if (arg_field)
1173 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1174 "Option --field/-F only makes sense with list");
1175
1176 r = acquire_journal(&j, argv + 1);
1177 if (r < 0)
1178 return r;
1179
1180 r = focus(j);
1181 if (r < 0)
1182 return r;
1183
1184 if (!arg_quiet) {
1185 print_info(stdout, j, false);
1186 fputs("\n", stdout);
1187 }
1188
1189 r = sd_journal_get_data(j, "COREDUMP_EXE", (const void**) &data, &len);
1190 if (r < 0)
1191 return log_error_errno(r, "Failed to retrieve COREDUMP_EXE field: %m");
1192
1193 assert(len > STRLEN("COREDUMP_EXE="));
1194 data += STRLEN("COREDUMP_EXE=");
1195 len -= STRLEN("COREDUMP_EXE=");
1196
1197 exe = strndup(data, len);
1198 if (!exe)
1199 return log_oom();
1200
1201 if (endswith(exe, " (deleted)"))
1202 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
1203 "Binary already deleted.");
1204
1205 if (!path_is_absolute(exe))
1206 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
1207 "Binary is not an absolute path.");
1208
1209 r = resolve_filename(arg_root, &exe);
1210 if (r < 0)
1211 return r;
1212
1213 r = save_core(j, NULL, &path, &unlink_path);
1214 if (r < 0)
1215 return r;
1216
1217 r = strv_extend_strv(&debugger_call, STRV_MAKE(exe, "-c", path), false);
1218 if (r < 0)
1219 return log_oom();
1220
1221 if (arg_root) {
1222 if (streq(arg_debugger, "gdb")) {
1223 const char *sysroot_cmd;
1224 sysroot_cmd = strjoina("set sysroot ", arg_root);
1225
1226 r = strv_extend_strv(&debugger_call, STRV_MAKE("-iex", sysroot_cmd), false);
1227 if (r < 0)
1228 return log_oom();
1229 } else if (streq(arg_debugger, "lldb")) {
1230 const char *sysroot_cmd;
1231 sysroot_cmd = strjoina("platform select --sysroot ", arg_root, " host");
1232
1233 r = strv_extend_strv(&debugger_call, STRV_MAKE("-O", sysroot_cmd), false);
1234 if (r < 0)
1235 return log_oom();
1236 }
1237 }
1238
1239 /* Don't interfere with gdb and its handling of SIGINT. */
1240 (void) ignore_signals(SIGINT);
1241
1242 fork_name = strjoina("(", debugger_call[0], ")");
1243
1244 r = safe_fork(fork_name, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG|FORK_FLUSH_STDIO, &pid);
1245 if (r < 0)
1246 goto finish;
1247 if (r == 0) {
1248 execvp(debugger_call[0], debugger_call);
1249 log_open();
1250 log_error_errno(errno, "Failed to invoke %s: %m", debugger_call[0]);
1251 _exit(EXIT_FAILURE);
1252 }
1253
1254 r = wait_for_terminate_and_check(debugger_call[0], pid, WAIT_LOG_ABNORMAL);
1255
1256 finish:
1257 (void) default_signals(SIGINT);
1258
1259 if (unlink_path) {
1260 log_debug("Removed temporary file %s", path);
1261 (void) unlink(path);
1262 }
1263
1264 return r;
1265 }
1266
1267 static int check_units_active(void) {
1268 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1269 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1270 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1271 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1272 int c = 0, r;
1273 const char *id, *state, *substate;
1274
1275 if (arg_quiet)
1276 return false;
1277
1278 r = sd_bus_default_system(&bus);
1279 if (r == -ENOENT) {
1280 log_debug("D-Bus is not running, skipping active unit check");
1281 return 0;
1282 }
1283 if (r < 0)
1284 return log_error_errno(r, "Failed to acquire bus: %m");
1285
1286 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "ListUnitsByPatterns");
1287 if (r < 0)
1288 return bus_log_create_error(r);
1289
1290 r = sd_bus_message_append_strv(m, NULL);
1291 if (r < 0)
1292 return bus_log_create_error(r);
1293
1294 r = sd_bus_message_append_strv(m, STRV_MAKE("systemd-coredump@*.service"));
1295 if (r < 0)
1296 return bus_log_create_error(r);
1297
1298 r = sd_bus_call(bus, m, SHORT_BUS_CALL_TIMEOUT_USEC, &error, &reply);
1299 if (r < 0)
1300 return log_error_errno(r, "Failed to check if any systemd-coredump@.service units are running: %s",
1301 bus_error_message(&error, r));
1302
1303 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
1304 if (r < 0)
1305 return bus_log_parse_error(r);
1306
1307 while ((r = sd_bus_message_read(
1308 reply, "(ssssssouso)",
1309 &id, NULL, NULL, &state, &substate,
1310 NULL, NULL, NULL, NULL, NULL)) > 0) {
1311 bool found = !STR_IN_SET(state, "inactive", "dead", "failed");
1312 log_debug("Unit %s is %s/%s, %scounting it.", id, state, substate, found ? "" : "not ");
1313 c += found;
1314 }
1315 if (r < 0)
1316 return bus_log_parse_error(r);
1317
1318 r = sd_bus_message_exit_container(reply);
1319 if (r < 0)
1320 return bus_log_parse_error(r);
1321
1322 return c;
1323 }
1324
1325 static int coredumpctl_main(int argc, char *argv[]) {
1326
1327 static const Verb verbs[] = {
1328 { "list", VERB_ANY, VERB_ANY, VERB_DEFAULT, dump_list },
1329 { "info", VERB_ANY, VERB_ANY, 0, dump_list },
1330 { "dump", VERB_ANY, VERB_ANY, 0, dump_core },
1331 { "debug", VERB_ANY, VERB_ANY, 0, run_debug },
1332 { "gdb", VERB_ANY, VERB_ANY, 0, run_debug },
1333 { "help", VERB_ANY, 1, 0, verb_help },
1334 {}
1335 };
1336
1337 return dispatch_verb(argc, argv, verbs, NULL);
1338 }
1339
1340 static int run(int argc, char *argv[]) {
1341 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
1342 _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
1343 int r, units_active;
1344
1345 setlocale(LC_ALL, "");
1346 log_setup();
1347
1348 /* The journal merging logic potentially needs a lot of fds. */
1349 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
1350
1351 r = parse_argv(argc, argv);
1352 if (r <= 0)
1353 return r;
1354
1355 sigbus_install();
1356
1357 units_active = check_units_active(); /* error is treated the same as 0 */
1358
1359 if (arg_image) {
1360 assert(!arg_root);
1361
1362 r = mount_image_privately_interactively(
1363 arg_image,
1364 DISSECT_IMAGE_GENERIC_ROOT |
1365 DISSECT_IMAGE_REQUIRE_ROOT |
1366 DISSECT_IMAGE_RELAX_VAR_CHECK |
1367 DISSECT_IMAGE_VALIDATE_OS,
1368 &mounted_dir,
1369 &loop_device);
1370 if (r < 0)
1371 return r;
1372
1373 arg_root = strdup(mounted_dir);
1374 if (!arg_root)
1375 return log_oom();
1376 }
1377
1378 r = coredumpctl_main(argc, argv);
1379
1380 if (units_active > 0)
1381 printf("%s-- Notice: %d systemd-coredump@.service %s, output may be incomplete.%s\n",
1382 ansi_highlight_red(),
1383 units_active, units_active == 1 ? "unit is running" : "units are running",
1384 ansi_normal());
1385
1386 return r;
1387 }
1388
1389 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);