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