]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/coredump/coredumpctl.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / coredump / coredumpctl.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2012 Zbigniew Jędrzejewski-Szmek
4 ***/
5
6 #include <fcntl.h>
7 #include <getopt.h>
8 #include <locale.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <unistd.h>
12
13 #include "sd-bus.h"
14 #include "sd-journal.h"
15 #include "sd-messages.h"
16
17 #include "alloc-util.h"
18 #include "bus-error.h"
19 #include "bus-util.h"
20 #include "compress.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "fs-util.h"
24 #include "journal-internal.h"
25 #include "journal-util.h"
26 #include "log.h"
27 #include "macro.h"
28 #include "pager.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 #include "sigbus.h"
33 #include "signal-util.h"
34 #include "string-util.h"
35 #include "strv.h"
36 #include "terminal-util.h"
37 #include "user-util.h"
38 #include "util.h"
39 #include "verbs.h"
40
41 #define SHORT_BUS_CALL_TIMEOUT_USEC (3 * USEC_PER_SEC)
42
43 static usec_t arg_since = USEC_INFINITY, arg_until = USEC_INFINITY;
44 static const char* arg_field = NULL;
45 static const char *arg_debugger = NULL;
46 static const char *arg_directory = NULL;
47 static bool arg_no_pager = false;
48 static int arg_no_legend = false;
49 static int arg_one = false;
50 static FILE* arg_output = NULL;
51 static bool arg_reverse = false;
52 static bool arg_quiet = false;
53
54 static int add_match(sd_journal *j, const char *match) {
55 _cleanup_free_ char *p = NULL;
56 const char* prefix, *pattern;
57 pid_t pid;
58 int r;
59
60 if (strchr(match, '='))
61 prefix = "";
62 else if (strchr(match, '/')) {
63 r = path_make_absolute_cwd(match, &p);
64 if (r < 0)
65 return log_error_errno(r, "path_make_absolute_cwd(\"%s\"): %m", match);
66
67 match = p;
68 prefix = "COREDUMP_EXE=";
69 } else if (parse_pid(match, &pid) >= 0)
70 prefix = "COREDUMP_PID=";
71 else
72 prefix = "COREDUMP_COMM=";
73
74 pattern = strjoina(prefix, match);
75 log_debug("Adding match: %s", pattern);
76 r = sd_journal_add_match(j, pattern, 0);
77 if (r < 0)
78 return log_error_errno(r, "Failed to add match \"%s\": %m", match);
79
80 return 0;
81 }
82
83 static int add_matches(sd_journal *j, char **matches) {
84 char **match;
85 int r;
86
87 r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR, 0);
88 if (r < 0)
89 return log_error_errno(r, "Failed to add match \"%s\": %m", "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR);
90
91 r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_BACKTRACE_STR, 0);
92 if (r < 0)
93 return log_error_errno(r, "Failed to add match \"%s\": %m", "MESSAGE_ID=" SD_MESSAGE_BACKTRACE_STR);
94
95 STRV_FOREACH(match, matches) {
96 r = add_match(j, *match);
97 if (r < 0)
98 return r;
99 }
100
101 return 0;
102 }
103
104 static int acquire_journal(sd_journal **ret, char **matches) {
105 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
106 int r;
107
108 assert(ret);
109
110 if (arg_directory) {
111 r = sd_journal_open_directory(&j, arg_directory, 0);
112 if (r < 0)
113 return log_error_errno(r, "Failed to open journals in directory: %s: %m", arg_directory);
114 } else {
115 r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY);
116 if (r < 0)
117 return log_error_errno(r, "Failed to open journal: %m");
118 }
119
120 r = journal_access_check_and_warn(j, arg_quiet, true);
121 if (r < 0)
122 return r;
123
124 r = add_matches(j, matches);
125 if (r < 0)
126 return r;
127
128 if (DEBUG_LOGGING) {
129 _cleanup_free_ char *filter;
130
131 filter = journal_make_match_string(j);
132 log_debug("Journal filter: %s", filter);
133 }
134
135 *ret = TAKE_PTR(j);
136
137 return 0;
138 }
139
140 static int help(void) {
141 printf("%s [OPTIONS...]\n\n"
142 "List or retrieve coredumps from the journal.\n\n"
143 "Flags:\n"
144 " -h --help Show this help\n"
145 " --version Print version string\n"
146 " --no-pager Do not pipe output into a pager\n"
147 " --no-legend Do not print the column headers\n"
148 " --debugger=DEBUGGER Use the given debugger\n"
149 " -1 Show information about most recent entry only\n"
150 " -S --since=DATE Only print coredumps since the date\n"
151 " -U --until=DATE Only print coredumps until the date\n"
152 " -r --reverse Show the newest entries first\n"
153 " -F --field=FIELD List all values a certain field takes\n"
154 " -o --output=FILE Write output to FILE\n"
155 " -D --directory=DIR Use journal files from directory\n\n"
156 " -q --quiet Do not show info messages and privilege warning\n"
157 "Commands:\n"
158 " list [MATCHES...] List available coredumps (default)\n"
159 " info [MATCHES...] Show detailed information about one or more coredumps\n"
160 " dump [MATCHES...] Print first matching coredump to stdout\n"
161 " debug [MATCHES...] Start a debugger for the first matching coredump\n"
162 , program_invocation_short_name);
163
164 return 0;
165 }
166
167 static int parse_argv(int argc, char *argv[]) {
168 enum {
169 ARG_VERSION = 0x100,
170 ARG_NO_PAGER,
171 ARG_NO_LEGEND,
172 ARG_DEBUGGER,
173 };
174
175 int c, r;
176
177 static const struct option options[] = {
178 { "help", no_argument, NULL, 'h' },
179 { "version" , no_argument, NULL, ARG_VERSION },
180 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
181 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
182 { "debugger", required_argument, NULL, ARG_DEBUGGER },
183 { "output", required_argument, NULL, 'o' },
184 { "field", required_argument, NULL, 'F' },
185 { "directory", required_argument, NULL, 'D' },
186 { "reverse", no_argument, NULL, 'r' },
187 { "since", required_argument, NULL, 'S' },
188 { "until", required_argument, NULL, 'U' },
189 { "quiet", no_argument, NULL, 'q' },
190 {}
191 };
192
193 assert(argc >= 0);
194 assert(argv);
195
196 while ((c = getopt_long(argc, argv, "ho:F:1D:rS:U:q", options, NULL)) >= 0)
197 switch(c) {
198 case 'h':
199 return help();
200
201 case ARG_VERSION:
202 return version();
203
204 case ARG_NO_PAGER:
205 arg_no_pager = true;
206 break;
207
208 case ARG_NO_LEGEND:
209 arg_no_legend = true;
210 break;
211
212 case ARG_DEBUGGER:
213 arg_debugger = optarg;
214 break;
215
216 case 'o':
217 if (arg_output) {
218 log_error("Cannot set output more than once.");
219 return -EINVAL;
220 }
221
222 arg_output = fopen(optarg, "we");
223 if (!arg_output)
224 return log_error_errno(errno, "writing to '%s': %m", optarg);
225
226 break;
227
228 case 'S':
229 r = parse_timestamp(optarg, &arg_since);
230 if (r < 0)
231 return log_error_errno(r, "Failed to parse timestamp: %s", optarg);
232 break;
233
234 case 'U':
235 r = parse_timestamp(optarg, &arg_until);
236 if (r < 0)
237 return log_error_errno(r, "Failed to parse timestamp: %s", optarg);
238 break;
239
240 case 'F':
241 if (arg_field) {
242 log_error("Cannot use --field/-F more than once.");
243 return -EINVAL;
244 }
245 arg_field = optarg;
246 break;
247
248 case '1':
249 arg_one = true;
250 break;
251
252 case 'D':
253 arg_directory = optarg;
254 break;
255
256 case 'r':
257 arg_reverse = true;
258 break;
259
260 case 'q':
261 arg_quiet = true;
262 break;
263
264 case '?':
265 return -EINVAL;
266
267 default:
268 assert_not_reached("Unhandled option");
269 }
270
271 if (arg_since != USEC_INFINITY && arg_until != USEC_INFINITY &&
272 arg_since > arg_until) {
273 log_error("--since= must be before --until=.");
274 return -EINVAL;
275 }
276
277 return 1;
278 }
279
280 static int retrieve(const void *data,
281 size_t len,
282 const char *name,
283 char **var) {
284
285 size_t ident;
286 char *v;
287
288 ident = strlen(name) + 1; /* name + "=" */
289
290 if (len < ident)
291 return 0;
292
293 if (memcmp(data, name, ident - 1) != 0)
294 return 0;
295
296 if (((const char*) data)[ident - 1] != '=')
297 return 0;
298
299 v = strndup((const char*)data + ident, len - ident);
300 if (!v)
301 return log_oom();
302
303 free(*var);
304 *var = v;
305
306 return 1;
307 }
308
309 static int print_field(FILE* file, sd_journal *j) {
310 const void *d;
311 size_t l;
312
313 assert(file);
314 assert(j);
315
316 assert(arg_field);
317
318 /* A (user-specified) field may appear more than once for a given entry.
319 * We will print all of the occurences.
320 * This is different below for fields that systemd-coredump uses,
321 * because they cannot meaningfully appear more than once.
322 */
323 SD_JOURNAL_FOREACH_DATA(j, d, l) {
324 _cleanup_free_ char *value = NULL;
325 int r;
326
327 r = retrieve(d, l, arg_field, &value);
328 if (r < 0)
329 return r;
330 if (r > 0)
331 fprintf(file, "%s\n", value);
332 }
333
334 return 0;
335 }
336
337 #define RETRIEVE(d, l, name, arg) \
338 { \
339 int _r = retrieve(d, l, name, &arg); \
340 if (_r < 0) \
341 return _r; \
342 if (_r > 0) \
343 continue; \
344 }
345
346 static int print_list(FILE* file, sd_journal *j, int had_legend) {
347 _cleanup_free_ char
348 *mid = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
349 *sgnl = NULL, *exe = NULL, *comm = NULL, *cmdline = NULL,
350 *filename = NULL, *truncated = NULL, *coredump = NULL;
351 const void *d;
352 size_t l;
353 usec_t t;
354 char buf[FORMAT_TIMESTAMP_MAX];
355 int r;
356 const char *present;
357 bool normal_coredump;
358
359 assert(file);
360 assert(j);
361
362 SD_JOURNAL_FOREACH_DATA(j, d, l) {
363 RETRIEVE(d, l, "MESSAGE_ID", mid);
364 RETRIEVE(d, l, "COREDUMP_PID", pid);
365 RETRIEVE(d, l, "COREDUMP_UID", uid);
366 RETRIEVE(d, l, "COREDUMP_GID", gid);
367 RETRIEVE(d, l, "COREDUMP_SIGNAL", sgnl);
368 RETRIEVE(d, l, "COREDUMP_EXE", exe);
369 RETRIEVE(d, l, "COREDUMP_COMM", comm);
370 RETRIEVE(d, l, "COREDUMP_CMDLINE", cmdline);
371 RETRIEVE(d, l, "COREDUMP_FILENAME", filename);
372 RETRIEVE(d, l, "COREDUMP_TRUNCATED", truncated);
373 RETRIEVE(d, l, "COREDUMP", coredump);
374 }
375
376 if (!pid && !uid && !gid && !sgnl && !exe && !comm && !cmdline && !filename) {
377 log_warning("Empty coredump log entry");
378 return -EINVAL;
379 }
380
381 r = sd_journal_get_realtime_usec(j, &t);
382 if (r < 0)
383 return log_error_errno(r, "Failed to get realtime timestamp: %m");
384
385 format_timestamp(buf, sizeof(buf), t);
386
387 if (!had_legend && !arg_no_legend)
388 fprintf(file, "%-*s %*s %*s %*s %*s %-*s %s\n",
389 FORMAT_TIMESTAMP_WIDTH, "TIME",
390 6, "PID",
391 5, "UID",
392 5, "GID",
393 3, "SIG",
394 9, "COREFILE",
395 "EXE");
396
397 normal_coredump = streq_ptr(mid, SD_MESSAGE_COREDUMP_STR);
398
399 if (filename)
400 if (access(filename, R_OK) == 0)
401 present = "present";
402 else if (errno == ENOENT)
403 present = "missing";
404 else
405 present = "error";
406 else if (coredump)
407 present = "journal";
408 else if (normal_coredump)
409 present = "none";
410 else
411 present = "-";
412
413 if (STR_IN_SET(present, "present", "journal") && truncated && parse_boolean(truncated) > 0)
414 present = "truncated";
415
416 fprintf(file, "%-*s %*s %*s %*s %*s %-*s %s\n",
417 FORMAT_TIMESTAMP_WIDTH, buf,
418 6, strna(pid),
419 5, strna(uid),
420 5, strna(gid),
421 3, normal_coredump ? strna(sgnl) : "-",
422 9, present,
423 strna(exe ?: (comm ?: cmdline)));
424
425 return 0;
426 }
427
428 static int print_info(FILE *file, sd_journal *j, bool need_space) {
429 _cleanup_free_ char
430 *mid = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
431 *sgnl = NULL, *exe = NULL, *comm = NULL, *cmdline = NULL,
432 *unit = NULL, *user_unit = NULL, *session = NULL,
433 *boot_id = NULL, *machine_id = NULL, *hostname = NULL,
434 *slice = NULL, *cgroup = NULL, *owner_uid = NULL,
435 *message = NULL, *timestamp = NULL, *filename = NULL,
436 *truncated = NULL, *coredump = NULL;
437 const void *d;
438 size_t l;
439 bool normal_coredump;
440 int r;
441
442 assert(file);
443 assert(j);
444
445 SD_JOURNAL_FOREACH_DATA(j, d, l) {
446 RETRIEVE(d, l, "MESSAGE_ID", mid);
447 RETRIEVE(d, l, "COREDUMP_PID", pid);
448 RETRIEVE(d, l, "COREDUMP_UID", uid);
449 RETRIEVE(d, l, "COREDUMP_GID", gid);
450 RETRIEVE(d, l, "COREDUMP_SIGNAL", sgnl);
451 RETRIEVE(d, l, "COREDUMP_EXE", exe);
452 RETRIEVE(d, l, "COREDUMP_COMM", comm);
453 RETRIEVE(d, l, "COREDUMP_CMDLINE", cmdline);
454 RETRIEVE(d, l, "COREDUMP_UNIT", unit);
455 RETRIEVE(d, l, "COREDUMP_USER_UNIT", user_unit);
456 RETRIEVE(d, l, "COREDUMP_SESSION", session);
457 RETRIEVE(d, l, "COREDUMP_OWNER_UID", owner_uid);
458 RETRIEVE(d, l, "COREDUMP_SLICE", slice);
459 RETRIEVE(d, l, "COREDUMP_CGROUP", cgroup);
460 RETRIEVE(d, l, "COREDUMP_TIMESTAMP", timestamp);
461 RETRIEVE(d, l, "COREDUMP_FILENAME", filename);
462 RETRIEVE(d, l, "COREDUMP_TRUNCATED", truncated);
463 RETRIEVE(d, l, "COREDUMP", coredump);
464 RETRIEVE(d, l, "_BOOT_ID", boot_id);
465 RETRIEVE(d, l, "_MACHINE_ID", machine_id);
466 RETRIEVE(d, l, "_HOSTNAME", hostname);
467 RETRIEVE(d, l, "MESSAGE", message);
468 }
469
470 if (need_space)
471 fputs("\n", file);
472
473 normal_coredump = streq_ptr(mid, SD_MESSAGE_COREDUMP_STR);
474
475 if (comm)
476 fprintf(file,
477 " PID: %s%s%s (%s)\n",
478 ansi_highlight(), strna(pid), ansi_normal(), comm);
479 else
480 fprintf(file,
481 " PID: %s%s%s\n",
482 ansi_highlight(), strna(pid), ansi_normal());
483
484 if (uid) {
485 uid_t n;
486
487 if (parse_uid(uid, &n) >= 0) {
488 _cleanup_free_ char *u = NULL;
489
490 u = uid_to_name(n);
491 fprintf(file,
492 " UID: %s (%s)\n",
493 uid, u);
494 } else {
495 fprintf(file,
496 " UID: %s\n",
497 uid);
498 }
499 }
500
501 if (gid) {
502 gid_t n;
503
504 if (parse_gid(gid, &n) >= 0) {
505 _cleanup_free_ char *g = NULL;
506
507 g = gid_to_name(n);
508 fprintf(file,
509 " GID: %s (%s)\n",
510 gid, g);
511 } else {
512 fprintf(file,
513 " GID: %s\n",
514 gid);
515 }
516 }
517
518 if (sgnl) {
519 int sig;
520 const char *name = normal_coredump ? "Signal" : "Reason";
521
522 if (normal_coredump && safe_atoi(sgnl, &sig) >= 0)
523 fprintf(file, " %s: %s (%s)\n", name, sgnl, signal_to_string(sig));
524 else
525 fprintf(file, " %s: %s\n", name, sgnl);
526 }
527
528 if (timestamp) {
529 usec_t u;
530
531 r = safe_atou64(timestamp, &u);
532 if (r >= 0) {
533 char absolute[FORMAT_TIMESTAMP_MAX], relative[FORMAT_TIMESPAN_MAX];
534
535 fprintf(file,
536 " Timestamp: %s (%s)\n",
537 format_timestamp(absolute, sizeof(absolute), u),
538 format_timestamp_relative(relative, sizeof(relative), u));
539
540 } else
541 fprintf(file, " Timestamp: %s\n", timestamp);
542 }
543
544 if (cmdline)
545 fprintf(file, " Command Line: %s\n", cmdline);
546 if (exe)
547 fprintf(file, " Executable: %s%s%s\n", ansi_highlight(), exe, ansi_normal());
548 if (cgroup)
549 fprintf(file, " Control Group: %s\n", cgroup);
550 if (unit)
551 fprintf(file, " Unit: %s\n", unit);
552 if (user_unit)
553 fprintf(file, " User Unit: %s\n", user_unit);
554 if (slice)
555 fprintf(file, " Slice: %s\n", slice);
556 if (session)
557 fprintf(file, " Session: %s\n", session);
558 if (owner_uid) {
559 uid_t n;
560
561 if (parse_uid(owner_uid, &n) >= 0) {
562 _cleanup_free_ char *u = NULL;
563
564 u = uid_to_name(n);
565 fprintf(file,
566 " Owner UID: %s (%s)\n",
567 owner_uid, u);
568 } else {
569 fprintf(file,
570 " Owner UID: %s\n",
571 owner_uid);
572 }
573 }
574 if (boot_id)
575 fprintf(file, " Boot ID: %s\n", boot_id);
576 if (machine_id)
577 fprintf(file, " Machine ID: %s\n", machine_id);
578 if (hostname)
579 fprintf(file, " Hostname: %s\n", hostname);
580
581 if (filename) {
582 bool inacc, trunc;
583
584 inacc = access(filename, R_OK) < 0;
585 trunc = truncated && parse_boolean(truncated) > 0;
586
587 if (inacc || trunc)
588 fprintf(file, " Storage: %s%s (%s%s%s)%s\n",
589 ansi_highlight_red(),
590 filename,
591 inacc ? "inaccessible" : "",
592 inacc && trunc ? ", " : "",
593 trunc ? "truncated" : "",
594 ansi_normal());
595 else
596 fprintf(file, " Storage: %s\n", filename);
597 }
598
599 else if (coredump)
600 fprintf(file, " Storage: journal\n");
601 else
602 fprintf(file, " Storage: none\n");
603
604 if (message) {
605 _cleanup_free_ char *m = NULL;
606
607 m = strreplace(message, "\n", "\n ");
608
609 fprintf(file, " Message: %s\n", strstrip(m ?: message));
610 }
611
612 return 0;
613 }
614
615 static int focus(sd_journal *j) {
616 int r;
617
618 r = sd_journal_seek_tail(j);
619 if (r == 0)
620 r = sd_journal_previous(j);
621 if (r < 0)
622 return log_error_errno(r, "Failed to search journal: %m");
623 if (r == 0) {
624 log_error("No match found.");
625 return -ESRCH;
626 }
627 return r;
628 }
629
630 static int print_entry(sd_journal *j, unsigned n_found, bool verb_is_info) {
631 assert(j);
632
633 if (verb_is_info)
634 return print_info(stdout, j, n_found);
635 else if (arg_field)
636 return print_field(stdout, j);
637 else
638 return print_list(stdout, j, n_found);
639 }
640
641 static int dump_list(int argc, char **argv, void *userdata) {
642 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
643 unsigned n_found = 0;
644 bool verb_is_info;
645 int r;
646
647 verb_is_info = (argc >= 1 && streq(argv[0], "info"));
648
649 r = acquire_journal(&j, argv + 1);
650 if (r < 0)
651 return r;
652
653 (void) pager_open(arg_no_pager, false);
654
655 /* The coredumps are likely to compressed, and for just
656 * listing them we don't need to decompress them, so let's
657 * pick a fairly low data threshold here */
658 sd_journal_set_data_threshold(j, 4096);
659
660 if (arg_one) {
661 r = focus(j);
662 if (r < 0)
663 return r;
664
665 return print_entry(j, 0, verb_is_info);
666 } else {
667 if (arg_since != USEC_INFINITY && !arg_reverse)
668 r = sd_journal_seek_realtime_usec(j, arg_since);
669 else if (arg_until != USEC_INFINITY && arg_reverse)
670 r = sd_journal_seek_realtime_usec(j, arg_until);
671 else if (arg_reverse)
672 r = sd_journal_seek_tail(j);
673 else
674 r = sd_journal_seek_head(j);
675 if (r < 0)
676 return log_error_errno(r, "Failed to seek to date: %m");
677
678 for (;;) {
679 if (!arg_reverse)
680 r = sd_journal_next(j);
681 else
682 r = sd_journal_previous(j);
683
684 if (r < 0)
685 return log_error_errno(r, "Failed to iterate through journal: %m");
686
687 if (r == 0)
688 break;
689
690 if (arg_until != USEC_INFINITY && !arg_reverse) {
691 usec_t usec;
692
693 r = sd_journal_get_realtime_usec(j, &usec);
694 if (r < 0)
695 return log_error_errno(r, "Failed to determine timestamp: %m");
696 if (usec > arg_until)
697 continue;
698 }
699
700 if (arg_since != USEC_INFINITY && arg_reverse) {
701 usec_t usec;
702
703 r = sd_journal_get_realtime_usec(j, &usec);
704 if (r < 0)
705 return log_error_errno(r, "Failed to determine timestamp: %m");
706 if (usec < arg_since)
707 continue;
708 }
709
710 r = print_entry(j, n_found++, verb_is_info);
711 if (r < 0)
712 return r;
713 }
714
715 if (!arg_field && n_found <= 0) {
716 if (!arg_quiet)
717 log_notice("No coredumps found.");
718 return -ESRCH;
719 }
720 }
721
722 return 0;
723 }
724
725 static int save_core(sd_journal *j, FILE *file, char **path, bool *unlink_temp) {
726 const char *data;
727 _cleanup_free_ char *filename = NULL;
728 size_t len;
729 int r, fd;
730 _cleanup_close_ int fdt = -1;
731 char *temp = NULL;
732
733 assert(!(file && path)); /* At most one can be specified */
734 assert(!!path == !!unlink_temp); /* Those must be specified together */
735
736 /* Look for a coredump on disk first. */
737 r = sd_journal_get_data(j, "COREDUMP_FILENAME", (const void**) &data, &len);
738 if (r == 0)
739 retrieve(data, len, "COREDUMP_FILENAME", &filename);
740 else {
741 if (r != -ENOENT)
742 return log_error_errno(r, "Failed to retrieve COREDUMP_FILENAME field: %m");
743 /* Check that we can have a COREDUMP field. We still haven't set a high
744 * data threshold, so we'll get a few kilobytes at most.
745 */
746
747 r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
748 if (r == -ENOENT)
749 return log_error_errno(r, "Coredump entry has no core attached (neither internally in the journal nor externally on disk).");
750 if (r < 0)
751 return log_error_errno(r, "Failed to retrieve COREDUMP field: %m");
752 }
753
754 if (filename) {
755 if (access(filename, R_OK) < 0)
756 return log_error_errno(errno, "File \"%s\" is not readable: %m", filename);
757
758 if (path && !endswith(filename, ".xz") && !endswith(filename, ".lz4")) {
759 *path = TAKE_PTR(filename);
760
761 return 0;
762 }
763 }
764
765 if (path) {
766 const char *vt;
767
768 /* Create a temporary file to write the uncompressed core to. */
769
770 r = var_tmp_dir(&vt);
771 if (r < 0)
772 return log_error_errno(r, "Failed to acquire temporary directory path: %m");
773
774 temp = strjoin(vt, "/coredump-XXXXXX");
775 if (!temp)
776 return log_oom();
777
778 fdt = mkostemp_safe(temp);
779 if (fdt < 0)
780 return log_error_errno(fdt, "Failed to create temporary file: %m");
781 log_debug("Created temporary file %s", temp);
782
783 fd = fdt;
784 } else {
785 /* If neither path or file are specified, we will write to stdout. Let's now check
786 * if stdout is connected to a tty. We checked that the file exists, or that the
787 * core might be stored in the journal. In this second case, if we found the entry,
788 * in all likelyhood we will be able to access the COREDUMP= field. In either case,
789 * we stop before doing any "real" work, i.e. before starting decompression or
790 * reading from the file or creating temporary files.
791 */
792 if (!file) {
793 if (on_tty())
794 return log_error_errno(ENOTTY, "Refusing to dump core to tty"
795 " (use shell redirection or specify --output).");
796 file = stdout;
797 }
798
799 fd = fileno(file);
800 }
801
802 if (filename) {
803 #if HAVE_XZ || HAVE_LZ4
804 _cleanup_close_ int fdf;
805
806 fdf = open(filename, O_RDONLY | O_CLOEXEC);
807 if (fdf < 0) {
808 r = log_error_errno(errno, "Failed to open %s: %m", filename);
809 goto error;
810 }
811
812 r = decompress_stream(filename, fdf, fd, -1);
813 if (r < 0) {
814 log_error_errno(r, "Failed to decompress %s: %m", filename);
815 goto error;
816 }
817 #else
818 log_error("Cannot decompress file. Compiled without compression support.");
819 r = -EOPNOTSUPP;
820 goto error;
821 #endif
822 } else {
823 ssize_t sz;
824
825 /* We want full data, nothing truncated. */
826 sd_journal_set_data_threshold(j, 0);
827
828 r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
829 if (r < 0)
830 return log_error_errno(r, "Failed to retrieve COREDUMP field: %m");
831
832 assert(len >= 9);
833 data += 9;
834 len -= 9;
835
836 sz = write(fd, data, len);
837 if (sz < 0) {
838 r = log_error_errno(errno, "Failed to write output: %m");
839 goto error;
840 }
841 if (sz != (ssize_t) len) {
842 log_error("Short write to output.");
843 r = -EIO;
844 goto error;
845 }
846 }
847
848 if (temp) {
849 *path = temp;
850 *unlink_temp = true;
851 }
852 return 0;
853
854 error:
855 if (temp) {
856 unlink(temp);
857 log_debug("Removed temporary file %s", temp);
858 }
859 return r;
860 }
861
862 static int dump_core(int argc, char **argv, void *userdata) {
863 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
864 int r;
865
866 if (arg_field) {
867 log_error("Option --field/-F only makes sense with list");
868 return -EINVAL;
869 }
870
871 r = acquire_journal(&j, argv + 1);
872 if (r < 0)
873 return r;
874
875 r = focus(j);
876 if (r < 0)
877 return r;
878
879 print_info(arg_output ? stdout : stderr, j, false);
880
881 r = save_core(j, arg_output, NULL, NULL);
882 if (r < 0)
883 return r;
884
885 r = sd_journal_previous(j);
886 if (r > 0 && !arg_quiet)
887 log_notice("More than one entry matches, ignoring rest.");
888
889 return 0;
890 }
891
892 static int run_debug(int argc, char **argv, void *userdata) {
893 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
894 _cleanup_free_ char *exe = NULL, *path = NULL;
895 bool unlink_path = false;
896 const char *data, *fork_name;
897 size_t len;
898 pid_t pid;
899 int r;
900
901 if (!arg_debugger) {
902 char *env_debugger;
903
904 env_debugger = getenv("SYSTEMD_DEBUGGER");
905 if (env_debugger)
906 arg_debugger = env_debugger;
907 else
908 arg_debugger = "gdb";
909 }
910
911 if (arg_field) {
912 log_error("Option --field/-F only makes sense with list");
913 return -EINVAL;
914 }
915
916 r = acquire_journal(&j, argv + 1);
917 if (r < 0)
918 return r;
919
920 r = focus(j);
921 if (r < 0)
922 return r;
923
924 print_info(stdout, j, false);
925 fputs("\n", stdout);
926
927 r = sd_journal_get_data(j, "COREDUMP_EXE", (const void**) &data, &len);
928 if (r < 0)
929 return log_error_errno(r, "Failed to retrieve COREDUMP_EXE field: %m");
930
931 assert(len > STRLEN("COREDUMP_EXE="));
932 data += STRLEN("COREDUMP_EXE=");
933 len -= STRLEN("COREDUMP_EXE=");
934
935 exe = strndup(data, len);
936 if (!exe)
937 return log_oom();
938
939 if (endswith(exe, " (deleted)")) {
940 log_error("Binary already deleted.");
941 return -ENOENT;
942 }
943
944 if (!path_is_absolute(exe)) {
945 log_error("Binary is not an absolute path.");
946 return -ENOENT;
947 }
948
949 r = save_core(j, NULL, &path, &unlink_path);
950 if (r < 0)
951 return r;
952
953 /* Don't interfere with gdb and its handling of SIGINT. */
954 (void) ignore_signals(SIGINT, -1);
955
956 fork_name = strjoina("(", arg_debugger, ")");
957
958 r = safe_fork(fork_name, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_LOG, &pid);
959 if (r < 0)
960 goto finish;
961 if (r == 0) {
962 execlp(arg_debugger, arg_debugger, exe, "-c", path, NULL);
963 log_open();
964 log_error_errno(errno, "Failed to invoke %s: %m", arg_debugger);
965 _exit(EXIT_FAILURE);
966 }
967
968 r = wait_for_terminate_and_check(arg_debugger, pid, WAIT_LOG_ABNORMAL);
969
970 finish:
971 (void) default_signals(SIGINT, -1);
972
973 if (unlink_path) {
974 log_debug("Removed temporary file %s", path);
975 unlink(path);
976 }
977
978 return r;
979 }
980
981 static int check_units_active(void) {
982 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
983 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
984 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
985 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
986 int c = 0, r;
987 const char *id, *state, *substate;
988
989 if (arg_quiet)
990 return false;
991
992 r = sd_bus_default_system(&bus);
993 if (r < 0)
994 return log_error_errno(r, "Failed to acquire bus: %m");
995
996 r = sd_bus_message_new_method_call(
997 bus,
998 &m,
999 "org.freedesktop.systemd1",
1000 "/org/freedesktop/systemd1",
1001 "org.freedesktop.systemd1.Manager",
1002 "ListUnitsByPatterns");
1003 if (r < 0)
1004 return bus_log_create_error(r);
1005
1006 r = sd_bus_message_append_strv(m, NULL);
1007 if (r < 0)
1008 return bus_log_create_error(r);
1009
1010 r = sd_bus_message_append_strv(m, STRV_MAKE("systemd-coredump@*.service"));
1011 if (r < 0)
1012 return bus_log_create_error(r);
1013
1014 r = sd_bus_call(bus, m, SHORT_BUS_CALL_TIMEOUT_USEC, &error, &reply);
1015 if (r < 0)
1016 return log_error_errno(r, "Failed to check if any systemd-coredump@.service units are running: %s",
1017 bus_error_message(&error, r));
1018
1019 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
1020 if (r < 0)
1021 return bus_log_parse_error(r);
1022
1023 while ((r = sd_bus_message_read(
1024 reply, "(ssssssouso)",
1025 &id, NULL, NULL, &state, &substate,
1026 NULL, NULL, NULL, NULL, NULL)) > 0) {
1027 bool found = !STR_IN_SET(state, "inactive", "dead", "failed");
1028 log_debug("Unit %s is %s/%s, %scounting it.", id, state, substate, found ? "" : "not ");
1029 c += found;
1030 }
1031 if (r < 0)
1032 return bus_log_parse_error(r);
1033
1034 r = sd_bus_message_exit_container(reply);
1035 if (r < 0)
1036 return bus_log_parse_error(r);
1037
1038 return c;
1039 }
1040
1041 static int coredumpctl_main(int argc, char *argv[]) {
1042
1043 static const Verb verbs[] = {
1044 { "list", VERB_ANY, VERB_ANY, VERB_DEFAULT, dump_list },
1045 { "info", VERB_ANY, VERB_ANY, 0, dump_list },
1046 { "dump", VERB_ANY, VERB_ANY, 0, dump_core },
1047 { "debug", VERB_ANY, VERB_ANY, 0, run_debug },
1048 { "gdb", VERB_ANY, VERB_ANY, 0, run_debug },
1049 {}
1050 };
1051
1052 return dispatch_verb(argc, argv, verbs, NULL);
1053 }
1054
1055 int main(int argc, char *argv[]) {
1056 int r, units_active;
1057
1058 setlocale(LC_ALL, "");
1059 log_parse_environment();
1060 log_open();
1061
1062 r = parse_argv(argc, argv);
1063 if (r <= 0)
1064 goto end;
1065
1066 sigbus_install();
1067
1068 units_active = check_units_active(); /* error is treated the same as 0 */
1069
1070 r = coredumpctl_main(argc, argv);
1071
1072 if (units_active > 0)
1073 printf("%s-- Notice: %d systemd-coredump@.service %s, output may be incomplete.%s\n",
1074 ansi_highlight_red(),
1075 units_active, units_active == 1 ? "unit is running" : "units are running",
1076 ansi_normal());
1077 end:
1078 pager_close();
1079
1080 safe_fclose(arg_output);
1081
1082 return r >= 0 ? r : EXIT_FAILURE;
1083 }