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