Debian Codegraph @

src/shared/elf-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if HAVE_ELFUTILS
4 #include <dwarf.h>
5 #include <elfutils/libdwelf.h>
6 #include <elfutils/libdwfl.h>
7 #include <libelf.h>
8 #endif
9 #include <unistd.h>
10
11 #include "sd-dlopen.h"
12 #include "sd-json.h"
13
14 #include "alloc-util.h"
15 #include "coredump-util.h"
16 #include "dlfcn-util.h"
17 #include "elf-util.h"
18 #include "errno-util.h"
19 #include "escape.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "format-util.h"
23 #include "io-util.h"
24 #include "json-util.h"
25 #include "log.h"
26 #include "memstream-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "set.h"
30 #include "string-util.h"
31
32 #define FRAMES_MAX 64
33 #define THREADS_MAX 64
34 #define ELF_PACKAGE_METADATA_ID 0xcafe1a7e
35
36 /* The amount of data we're willing to write to each of the output pipes. */
37 #define COREDUMP_PIPE_MAX (1024*1024U)
38
39 #if HAVE_ELFUTILS
40
41 /* libdw symbols */
42 static DLSYM_PROTOTYPE(dwarf_attr_integrate) = NULL;
43 static DLSYM_PROTOTYPE(dwarf_diename) = NULL;
44 static DLSYM_PROTOTYPE(dwarf_formstring) = NULL;
45 static DLSYM_PROTOTYPE(dwarf_getscopes) = NULL;
46 static DLSYM_PROTOTYPE(dwarf_getscopes_die) = NULL;
47 static DLSYM_PROTOTYPE(dwelf_elf_begin) = NULL;
48 static DLSYM_PROTOTYPE(dwelf_elf_e_machine_string) = NULL;
49 static DLSYM_PROTOTYPE(dwelf_elf_gnu_build_id) = NULL;
50 static DLSYM_PROTOTYPE(dwarf_tag) = NULL;
51 static DLSYM_PROTOTYPE(dwfl_addrmodule) = NULL;
52 static DLSYM_PROTOTYPE(dwfl_begin) = NULL;
53 static DLSYM_PROTOTYPE(dwfl_build_id_find_elf) = NULL;
54 static DLSYM_PROTOTYPE(dwfl_core_file_attach) = NULL;
55 static DLSYM_PROTOTYPE(dwfl_core_file_report) = NULL;
56 /* New in elfutils 0.192. Always redeclare so DLSYM_PROTOTYPE's typeof() resolves on older headers; suppress
57 * the warning when newer libdw already declared it. */
58 DISABLE_WARNING_REDUNDANT_DECLS;
59 extern int dwfl_set_sysroot(Dwfl *dwfl, const char *sysroot); /* NOLINT(readability-redundant-declaration) */
60 REENABLE_WARNING;
61 static DLSYM_PROTOTYPE(dwfl_set_sysroot) = NULL;
62 static DLSYM_PROTOTYPE(dwfl_end) = NULL;
63 static DLSYM_PROTOTYPE(dwfl_errmsg) = NULL;
64 static DLSYM_PROTOTYPE(dwfl_errno) = NULL;
65 static DLSYM_PROTOTYPE(dwfl_frame_pc) = NULL;
66 static DLSYM_PROTOTYPE(dwfl_getmodules) = NULL;
67 static DLSYM_PROTOTYPE(dwfl_getthreads) = NULL;
68 static DLSYM_PROTOTYPE(dwfl_module_addrdie) = NULL;
69 static DLSYM_PROTOTYPE(dwfl_module_addrname) = NULL;
70 static DLSYM_PROTOTYPE(dwfl_module_build_id) = NULL;
71 static DLSYM_PROTOTYPE(dwfl_module_getelf) = NULL;
72 static DLSYM_PROTOTYPE(dwfl_module_info) = NULL;
73 static DLSYM_PROTOTYPE(dwfl_offline_section_address) = NULL;
74 static DLSYM_PROTOTYPE(dwfl_report_end) = NULL;
75 static DLSYM_PROTOTYPE(dwfl_standard_find_debuginfo) = NULL;
76 static DLSYM_PROTOTYPE(dwfl_thread_getframes) = NULL;
77 static DLSYM_PROTOTYPE(dwfl_thread_tid) = NULL;
78
79 /* libelf symbols */
80 static DLSYM_PROTOTYPE(elf_begin) = NULL;
81 static DLSYM_PROTOTYPE(elf_end) = NULL;
82 static DLSYM_PROTOTYPE(elf_getdata_rawchunk) = NULL;
83 static DLSYM_PROTOTYPE(gelf_getehdr) = NULL;
84 static DLSYM_PROTOTYPE(elf_getphdrnum) = NULL;
85 static DLSYM_PROTOTYPE(elf_errmsg) = NULL;
86 static DLSYM_PROTOTYPE(elf_errno) = NULL;
87 static DLSYM_PROTOTYPE(elf_memory) = NULL;
88 static DLSYM_PROTOTYPE(elf_version) = NULL;
89 static DLSYM_PROTOTYPE(gelf_getphdr) = NULL;
90 static DLSYM_PROTOTYPE(gelf_getnote) = NULL;
91
92 #endif
93
94 int dlopen_dw(int log_level) {
95 #if HAVE_ELFUTILS
96 static void *dw_dl = NULL;
97 int r;
98
99 SD_ELF_NOTE_DLOPEN(
100 "dw",
101 "Support for backtrace and ELF package metadata decoding from core files",
102 SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED,
103 "libdw.so.1");
104
105 r = dlopen_many_sym_or_warn(
106 &dw_dl, "libdw.so.1", log_level,
107 DLSYM_ARG(dwarf_getscopes),
108 DLSYM_ARG(dwarf_getscopes_die),
109 DLSYM_ARG(dwarf_tag),
110 DLSYM_ARG(dwarf_attr_integrate),
111 DLSYM_ARG(dwarf_formstring),
112 DLSYM_ARG(dwarf_diename),
113 DLSYM_ARG(dwelf_elf_gnu_build_id),
114 DLSYM_ARG(dwelf_elf_begin),
115 DLSYM_ARG(dwelf_elf_e_machine_string),
116 DLSYM_ARG(dwfl_addrmodule),
117 DLSYM_ARG(dwfl_frame_pc),
118 DLSYM_ARG(dwfl_module_addrdie),
119 DLSYM_ARG(dwfl_module_addrname),
120 DLSYM_ARG(dwfl_module_info),
121 DLSYM_ARG(dwfl_module_build_id),
122 DLSYM_ARG(dwfl_module_getelf),
123 DLSYM_ARG(dwfl_begin),
124 DLSYM_ARG(dwfl_core_file_report),
125 DLSYM_ARG(dwfl_report_end),
126 DLSYM_ARG(dwfl_getmodules),
127 DLSYM_ARG(dwfl_core_file_attach),
128 DLSYM_ARG(dwfl_end),
129 DLSYM_ARG(dwfl_errmsg),
130 DLSYM_ARG(dwfl_errno),
131 DLSYM_ARG(dwfl_build_id_find_elf),
132 DLSYM_ARG(dwfl_standard_find_debuginfo),
133 DLSYM_ARG(dwfl_thread_tid),
134 DLSYM_ARG(dwfl_thread_getframes),
135 DLSYM_ARG(dwfl_getthreads),
136 DLSYM_ARG(dwfl_offline_section_address));
137 if (r <= 0)
138 return r;
139
140 /* Optional symbol: present in libdw 0.192+. NULL pointer is fine; call sites check at use. */
141 DLSYM_OPTIONAL(dw_dl, dwfl_set_sysroot);
142
143 return 1;
144 #else
145 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
146 "libdw support is not compiled in.");
147 #endif
148 }
149
150 bool dlopen_dw_has_dwfl_set_sysroot(void) {
151 #if HAVE_ELFUTILS
152 if (dlopen_dw(LOG_DEBUG) < 0)
153 return false;
154 return sym_dwfl_set_sysroot;
155 #else
156 return false;
157 #endif
158 }
159
160 int dlopen_elf(int log_level) {
161 #if HAVE_ELFUTILS
162 static void *elf_dl = NULL;
163 int r;
164
165 SD_ELF_NOTE_DLOPEN(
166 "elf",
167 "Support for backtraces and reading ELF package metadata from core files",
168 SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED,
169 "libelf.so.1");
170
171 r = dlopen_many_sym_or_warn(
172 &elf_dl, "libelf.so.1", log_level,
173 DLSYM_ARG(elf_begin),
174 DLSYM_ARG(elf_end),
175 DLSYM_ARG(elf_getphdrnum),
176 DLSYM_ARG(elf_getdata_rawchunk),
177 DLSYM_ARG(elf_errmsg),
178 DLSYM_ARG(elf_errno),
179 DLSYM_ARG(elf_memory),
180 DLSYM_ARG(elf_version),
181 DLSYM_ARG(gelf_getehdr),
182 DLSYM_ARG(gelf_getphdr),
183 DLSYM_ARG(gelf_getnote));
184 if (r <= 0)
185 return r;
186
187 return 1;
188 #else
189 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
190 "libelf support is not compiled in.");
191 #endif
192 }
193
194 #if HAVE_ELFUTILS
195
196 typedef struct StackContext {
197 MemStream m;
198 Dwfl *dwfl;
199 Elf *elf;
200 unsigned n_thread;
201 unsigned n_frame;
202 sd_json_variant **package_metadata;
203 sd_json_variant **dlopen_metadata;
204 Set **modules;
205 } StackContext;
206
207 static void stack_context_done(StackContext *c) {
208 assert(c);
209
210 memstream_done(&c->m);
211
212 if (c->dwfl) {
213 sym_dwfl_end(c->dwfl);
214 c->dwfl = NULL;
215 }
216
217 if (c->elf) {
218 sym_elf_end(c->elf);
219 c->elf = NULL;
220 }
221 }
222
223 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(Elf *, sym_elf_end, elf_endp, NULL);
224
225 static int frame_callback(Dwfl_Frame *frame, void *userdata) {
226 StackContext *c = ASSERT_PTR(userdata);
227 Dwarf_Addr pc, pc_adjusted;
228 const char *fname = NULL, *symbol = NULL;
229 Dwfl_Module *module;
230 bool is_activation;
231 uint64_t module_offset = 0;
232
233 assert(frame);
234
235 if (c->n_frame >= FRAMES_MAX)
236 return DWARF_CB_ABORT;
237
238 if (!sym_dwfl_frame_pc(frame, &pc, &is_activation))
239 return DWARF_CB_ABORT;
240
241 pc_adjusted = pc - (is_activation ? 0 : 1);
242
243 module = sym_dwfl_addrmodule(c->dwfl, pc_adjusted);
244 if (module) {
245 Dwarf_Addr start, bias = 0;
246 Dwarf_Die *cudie;
247
248 cudie = sym_dwfl_module_addrdie(module, pc_adjusted, &bias);
249 if (cudie) {
250 _cleanup_free_ Dwarf_Die *scopes = NULL;
251 int n;
252
253 n = sym_dwarf_getscopes(cudie, pc_adjusted - bias, &scopes);
254 if (n > 0)
255 for (Dwarf_Die *s = scopes; s && s < scopes + n; s++) {
256 Dwarf_Attribute *a, space;
257
258 if (!IN_SET(sym_dwarf_tag(s), DW_TAG_subprogram, DW_TAG_inlined_subroutine, DW_TAG_entry_point))
259 continue;
260
261 a = sym_dwarf_attr_integrate(s, DW_AT_MIPS_linkage_name, &space);
262 if (!a)
263 a = sym_dwarf_attr_integrate(s, DW_AT_linkage_name, &space);
264 if (a)
265 symbol = sym_dwarf_formstring(a);
266 if (!symbol)
267 symbol = sym_dwarf_diename(s);
268
269 if (symbol)
270 break;
271 }
272 }
273
274 if (!symbol)
275 symbol = sym_dwfl_module_addrname(module, pc_adjusted);
276
277 fname = sym_dwfl_module_info(module, NULL, &start, NULL, NULL, NULL, NULL, NULL);
278 module_offset = pc - start;
279 }
280
281 if (c->m.f)
282 fprintf(c->m.f, "#%-2u 0x%016" PRIx64 " %s (%s + 0x%" PRIx64 ")\n", c->n_frame, (uint64_t) pc, strna(symbol), strna(fname), module_offset);
283 c->n_frame++;
284
285 return DWARF_CB_OK;
286 }
287
288 static int thread_callback(Dwfl_Thread *thread, void *userdata) {
289 StackContext *c = ASSERT_PTR(userdata);
290 pid_t tid;
291
292 assert(thread);
293
294 if (c->n_thread >= THREADS_MAX)
295 return DWARF_CB_ABORT;
296
297 if (c->n_thread != 0 && c->m.f)
298 fputc('\n', c->m.f);
299
300 c->n_frame = 0;
301
302 if (c->m.f) {
303 tid = sym_dwfl_thread_tid(thread);
304 fprintf(c->m.f, "Stack trace of thread " PID_FMT ":\n", tid);
305 }
306
307 if (sym_dwfl_thread_getframes(thread, frame_callback, c) < 0)
308 return DWARF_CB_ABORT;
309
310 c->n_thread++;
311
312 return DWARF_CB_OK;
313 }
314
315 static char* build_package_reference(
316 const char *type,
317 const char *name,
318 const char *version,
319 const char *arch) {
320
321 /* Construct an identifier for a specific version of the package. The syntax is most suitable for
322 * rpm: the resulting string can be used directly in queries and rpm/dnf/yum commands. For dpkg and
323 * other systems, it might not be usable directly, but users should still be able to figure out the
324 * meaning.
325 */
326
327 return strjoin(type ?: "package",
328 " ",
329 name,
330
331 version ? "-" : "",
332 strempty(version),
333
334 /* arch is meaningful even without version, so always print it */
335 arch ? "." : "",
336 strempty(arch));
337 }
338
339 static void report_module_metadata(StackContext *c, const char *name, sd_json_variant *metadata) {
340 assert(c);
341 assert(name);
342
343 if (!c->m.f)
344 return;
345
346 fprintf(c->m.f, "Module %s", name);
347
348 if (metadata) {
349 const char
350 *build_id = sd_json_variant_string(sd_json_variant_by_key(metadata, "buildId")),
351 *type = sd_json_variant_string(sd_json_variant_by_key(metadata, "type")),
352 *package = sd_json_variant_string(sd_json_variant_by_key(metadata, "name")),
353 *version = sd_json_variant_string(sd_json_variant_by_key(metadata, "version")),
354 *arch = sd_json_variant_string(sd_json_variant_by_key(metadata, "architecture"));
355
356 if (package) {
357 /* Version/architecture is only meaningful with a package name.
358 * Skip the detailed fields if package is unknown. */
359 _cleanup_free_ char *id = build_package_reference(type, package, version, arch);
360 fprintf(c->m.f, " from %s", strnull(id));
361 }
362
363 if (build_id && !(package && version))
364 fprintf(c->m.f, ", build-id=%s", build_id);
365 }
366
367 fputs("\n", c->m.f);
368 }
369
370 static int parse_metadata(const char *name, sd_json_variant *id_json, Elf *elf, bool *ret_interpreter_found, StackContext *c) {
371 bool package_metadata_found = false, interpreter_found = false;
372 size_t n_program_headers;
373 int r;
374
375 assert(name);
376 assert(elf);
377 assert(c);
378
379 /* When iterating over PT_LOAD we will visit modules more than once */
380 if (set_contains(*c->modules, name))
381 return 0;
382
383 r = sym_elf_getphdrnum(elf, &n_program_headers);
384 if (r < 0) /* Not the handle we are looking for - that's ok, skip it */
385 return 0;
386
387 /* Iterate over all program headers in that ELF object. These will have been copied by
388 * the kernel verbatim when the core file is generated. */
389 for (size_t i = 0; i < n_program_headers; ++i) {
390 GElf_Phdr mem, *program_header;
391 GElf_Nhdr note_header;
392 Elf_Data *data;
393
394 /* Package metadata is in PT_NOTE headers. */
395 program_header = sym_gelf_getphdr(elf, i, &mem);
396 if (!program_header || !IN_SET(program_header->p_type, PT_NOTE, PT_INTERP))
397 continue;
398
399 if (program_header->p_type == PT_INTERP) {
400 interpreter_found = true;
401 continue;
402 }
403
404 /* Fortunately there is an iterator we can use to walk over the
405 * elements of a PT_NOTE program header. We are interested in the
406 * note with type. */
407 data = sym_elf_getdata_rawchunk(elf,
408 program_header->p_offset,
409 program_header->p_filesz,
410 ELF_T_NHDR);
411 if (!data)
412 continue;
413
414 for (size_t note_offset = 0, name_offset, desc_offset;
415 note_offset < data->d_size &&
416 (note_offset = sym_gelf_getnote(data, note_offset, &note_header, &name_offset, &desc_offset)) > 0;) {
417
418 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *w = NULL;
419 const char *payload = (const char *)data->d_buf + desc_offset;
420
421 if (note_header.n_namesz == 0 || note_header.n_descsz == 0)
422 continue;
423
424 /* Package metadata might have different owners, but the
425 * magic ID is always the same. */
426 if (!IN_SET(note_header.n_type, ELF_PACKAGE_METADATA_ID, SD_ELF_NOTE_DLOPEN_TYPE))
427 continue;
428
429 _cleanup_free_ char *payload_0suffixed = NULL;
430 assert(note_offset > desc_offset);
431 size_t payload_len = note_offset - desc_offset;
432
433 /* If we are lucky and the payload is NUL-padded, we don't need to copy the string.
434 * But if happens to go all the way until the end of the buffer, make a copy. */
435 if (payload[payload_len-1] != '\0') {
436 payload_0suffixed = memdup_suffix0(payload, payload_len);
437 if (!payload_0suffixed)
438 return log_oom();
439 payload = payload_0suffixed;
440 }
441
442 r = sd_json_parse(payload, 0, &v, NULL, NULL);
443 if (r < 0) {
444 _cleanup_free_ char *esc = cescape(payload);
445 return log_error_errno(r, "json_parse on \"%s\" failed: %m", strnull(esc));
446 }
447
448 if (note_header.n_type == ELF_PACKAGE_METADATA_ID) {
449 /* If we have a build-id, merge it in the same JSON object so that it appears all
450 * nicely together in the logs/metadata. */
451 if (id_json) {
452 r = sd_json_variant_merge_object(&v, id_json);
453 if (r < 0)
454 return log_error_errno(r, "sd_json_variant_merge of package meta with buildId failed: %m");
455 }
456
457 /* Pretty-print to the buffer, so that the metadata goes as plaintext in the
458 * journal. */
459 report_module_metadata(c, name, v);
460
461 /* Then we build a new object using the module name as the key, and merge it
462 * with the previous parses, so that in the end it all fits together in a single
463 * JSON blob. */
464 r = sd_json_buildo(&w, SD_JSON_BUILD_PAIR_VARIANT(name, v));
465 if (r < 0)
466 return log_error_errno(r, "Failed to build JSON object: %m");
467
468 r = sd_json_variant_merge_object(c->package_metadata, w);
469 if (r < 0)
470 return log_error_errno(r, "sd_json_variant_merge of package meta with buildId failed: %m");
471
472 package_metadata_found = true;
473 } else if (c->dlopen_metadata) {
474 sd_json_variant *z;
475
476 JSON_VARIANT_ARRAY_FOREACH(z, v) {
477 r = sd_json_variant_append_array(c->dlopen_metadata, z);
478 if (r < 0)
479 return log_error_errno(r, "Failed to append entry to dlopen metadata: %m");
480 }
481 }
482
483 /* Finally stash the name, so we avoid double visits. */
484 r = set_put_strdup(c->modules, name);
485 if (r < 0)
486 return log_error_errno(r, "set_put_strdup failed: %m");
487
488 if (!c->dlopen_metadata) {
489 if (ret_interpreter_found)
490 *ret_interpreter_found = interpreter_found;
491
492 return 1;
493 }
494 }
495 }
496
497 if (ret_interpreter_found)
498 *ret_interpreter_found = interpreter_found;
499
500 return c->dlopen_metadata ? 0 : package_metadata_found;
501 }
502
503 /* Get the build-id out of an ELF object or a dwarf core module. */
504 static int parse_buildid(Dwfl_Module *mod, Elf *elf, const char *name, StackContext *c, sd_json_variant **ret_id_json) {
505 _cleanup_(sd_json_variant_unrefp) sd_json_variant *id_json = NULL;
506 const unsigned char *id;
507 GElf_Addr id_vaddr;
508 ssize_t id_len;
509 int r;
510
511 assert(mod || elf);
512 assert(name);
513 assert(c);
514
515 if (mod)
516 id_len = sym_dwfl_module_build_id(mod, &id, &id_vaddr);
517 else
518 id_len = sym_dwelf_elf_gnu_build_id(elf, (const void **)&id);
519 if (id_len <= 0) {
520 /* If we don't find a build-id, note it in the journal message, and try
521 * anyway to find the package metadata. It's unlikely to have the latter
522 * without the former, but there's no hard rule. */
523 if (c->m.f)
524 fprintf(c->m.f, "Module %s without build-id.\n", name);
525 } else {
526 /* We will later parse package metadata json and pass it to our caller. Prepare the
527 * build-id in json format too, so that it can be appended and parsed cleanly. It
528 * will then be added as metadata to the journal message with the stack trace. */
529 r = sd_json_buildo(&id_json, SD_JSON_BUILD_PAIR_HEX("buildId", id, id_len));
530 if (r < 0)
531 return log_error_errno(r, "json_build on buildId failed: %m");
532 }
533
534 if (ret_id_json)
535 *ret_id_json = TAKE_PTR(id_json);
536
537 return 0;
538 }
539
540 static int module_callback(Dwfl_Module *mod, void **userdata, const char *name, Dwarf_Addr start, void *arg) {
541 _cleanup_(sd_json_variant_unrefp) sd_json_variant *id_json = NULL;
542 StackContext *c = ASSERT_PTR(arg);
543 size_t n_program_headers;
544 GElf_Addr bias;
545 int r;
546 Elf *elf;
547
548 assert(mod);
549
550 if (!name)
551 name = "(unnamed)"; /* For logging purposes */
552
553 /* We are iterating on each "module", which is what dwfl calls ELF objects contained in the
554 * core file, and extracting the build-id first and then the package metadata.
555 * We proceed in a best-effort fashion - not all ELF objects might contain both or either.
556 * The build-id is easy, as libdwfl parses it during the sym_dwfl_core_file_report() call and
557 * stores it separately in an internal library struct. */
558 r = parse_buildid(mod, NULL, name, c, &id_json);
559 if (r < 0)
560 return DWARF_CB_ABORT;
561
562 /* The .note.package metadata is more difficult. From the module, we need to get a reference
563 * to the ELF object first. We might be lucky and just get it from elfutils. */
564 elf = sym_dwfl_module_getelf(mod, &bias);
565 if (elf) {
566 r = parse_metadata(name, id_json, elf, NULL, c);
567 if (r < 0)
568 return DWARF_CB_ABORT;
569 if (r > 0)
570 return DWARF_CB_OK;
571 } else
572 elf = c->elf;
573
574 /* We did not get the ELF object, or it's just a reference to the core. That is likely
575 * because we didn't get direct access to the executable, and the version of elfutils does
576 * not yet support parsing it out of the core file directly.
577 * So fallback to manual extraction - get the PT_LOAD section from the core,
578 * and if it's the right one we can interpret it as an Elf object, and parse
579 * its notes manually. */
580
581 r = sym_elf_getphdrnum(elf, &n_program_headers);
582 if (r < 0) {
583 log_warning("Could not parse number of program headers from core file: %s",
584 sym_elf_errmsg(-1)); /* -1 retrieves the most recent error */
585 report_module_metadata(c, name, id_json);
586
587 return DWARF_CB_OK;
588 }
589
590 for (size_t i = 0; i < n_program_headers; ++i) {
591 GElf_Phdr mem, *program_header;
592 Elf_Data *data;
593 GElf_Addr end_of_segment;
594
595 /* The core file stores the ELF files in the PT_LOAD segment. */
596 program_header = sym_gelf_getphdr(elf, i, &mem);
597 if (!program_header || program_header->p_type != PT_LOAD)
598 continue;
599
600 /* Check that the end of segment is a valid address. */
601 if (!ADD_SAFE(&end_of_segment, program_header->p_vaddr, program_header->p_memsz)) {
602 log_error("Abort due to corrupted core dump, end of segment address %#zx + %#zx overflows", (size_t)program_header->p_vaddr, (size_t)program_header->p_memsz);
603 return DWARF_CB_ABORT;
604 }
605
606 /* This PT_LOAD segment doesn't contain the start address, so it can't be the module we are looking for. */
607 if (start < program_header->p_vaddr || start >= end_of_segment)
608 continue;
609
610 /* Now get a usable Elf reference, and parse the notes from it. */
611 data = sym_elf_getdata_rawchunk(elf,
612 program_header->p_offset,
613 program_header->p_filesz,
614 ELF_T_NHDR);
615 if (!data)
616 continue;
617
618 _cleanup_(elf_endp) Elf *memelf = sym_elf_memory(data->d_buf, data->d_size);
619 if (!memelf)
620 continue;
621
622 r = parse_metadata(name, id_json, memelf, NULL, c);
623 if (r < 0)
624 return DWARF_CB_ABORT;
625 if (r > 0)
626 break;
627 }
628
629 return DWARF_CB_OK;
630 }
631
632 static int parse_core(
633 int fd,
634 const char *executable,
635 const char *root,
636 char **ret,
637 sd_json_variant **ret_package_metadata,
638 sd_json_variant **ret_dlopen_metadata) {
639
640 const Dwfl_Callbacks callbacks = {
641 .find_elf = sym_dwfl_build_id_find_elf,
642 .section_address = sym_dwfl_offline_section_address,
643 .find_debuginfo = sym_dwfl_standard_find_debuginfo,
644 };
645
646 _cleanup_(sd_json_variant_unrefp) sd_json_variant *package_metadata = NULL, *dlopen_metadata = NULL;
647 _cleanup_set_free_ Set *modules = NULL;
648 _cleanup_(stack_context_done) StackContext c = {
649 .package_metadata = &package_metadata,
650 .dlopen_metadata = ret_dlopen_metadata ? &dlopen_metadata : NULL,
651 .modules = &modules,
652 };
653 int r;
654
655 assert(fd >= 0);
656
657 if (lseek(fd, 0, SEEK_SET) < 0)
658 return log_warning_errno(errno, "Failed to seek to beginning of the core file: %m");
659
660 if (ret && !memstream_init(&c.m))
661 return log_oom();
662
663 sym_elf_version(EV_CURRENT);
664
665 c.elf = sym_elf_begin(fd, ELF_C_READ_MMAP, NULL);
666 if (!c.elf)
667 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, elf_begin() failed: %s", sym_elf_errmsg(sym_elf_errno()));
668
669 c.dwfl = sym_dwfl_begin(&callbacks);
670 if (!c.dwfl)
671 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, dwfl_begin() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
672
673 if (empty_or_root(root))
674 root = NULL;
675 if (root) {
676 if (sym_dwfl_set_sysroot) {
677 if (sym_dwfl_set_sysroot(c.dwfl, root) < 0)
678 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not set root directory, dwfl_set_sysroot() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
679 } else
680 log_warning("Loaded libdw does not support dwfl_set_sysroot(), ignoring provided root directory.");
681 }
682
683 if (sym_dwfl_core_file_report(c.dwfl, c.elf, executable) < 0)
684 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, dwfl_core_file_report() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
685
686 if (sym_dwfl_report_end(c.dwfl, NULL, NULL) != 0)
687 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, dwfl_report_end() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
688
689 if (sym_dwfl_getmodules(c.dwfl, &module_callback, &c, 0) < 0)
690 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, dwfl_getmodules() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
691
692 if (sym_dwfl_core_file_attach(c.dwfl, c.elf) < 0)
693 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, dwfl_core_file_attach() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
694
695 if (sym_dwfl_getthreads(c.dwfl, thread_callback, &c) < 0)
696 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse core file, dwfl_getthreads() failed: %s", sym_dwfl_errmsg(sym_dwfl_errno()));
697
698 if (ret) {
699 r = memstream_finalize(&c.m, ret, NULL);
700 if (r < 0)
701 return log_warning_errno(r, "Could not parse core file, flushing file buffer failed: %m");
702 }
703
704 if (ret_package_metadata)
705 *ret_package_metadata = TAKE_PTR(package_metadata);
706 if (ret_dlopen_metadata)
707 *ret_dlopen_metadata = TAKE_PTR(dlopen_metadata);
708
709 return 0;
710 }
711
712 static int parse_elf(
713 int fd,
714 const char *executable,
715 const char *root,
716 char **ret,
717 sd_json_variant **ret_package_metadata,
718 sd_json_variant **ret_dlopen_metadata) {
719 _cleanup_(sd_json_variant_unrefp) sd_json_variant *package_metadata = NULL, *dlopen_metadata = NULL, *elf_metadata = NULL;
720 _cleanup_set_free_ Set *modules = NULL;
721 _cleanup_(stack_context_done) StackContext c = {
722 .package_metadata = &package_metadata,
723 .dlopen_metadata = ret_dlopen_metadata ? &dlopen_metadata : NULL,
724 .modules = &modules,
725 };
726 const char *elf_type;
727 GElf_Ehdr elf_header;
728 int r;
729
730 assert(fd >= 0);
731
732 if (lseek(fd, 0, SEEK_SET) < 0)
733 return log_warning_errno(errno, "Failed to seek to beginning of the ELF file: %m");
734
735 if (ret && !memstream_init(&c.m))
736 return log_oom();
737
738 sym_elf_version(EV_CURRENT);
739
740 c.elf = sym_elf_begin(fd, ELF_C_READ_MMAP, NULL);
741 if (!c.elf)
742 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse ELF file, elf_begin() failed: %s", sym_elf_errmsg(sym_elf_errno()));
743
744 if (!sym_gelf_getehdr(c.elf, &elf_header))
745 return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "Could not parse ELF file, gelf_getehdr() failed: %s", sym_elf_errmsg(sym_elf_errno()));
746
747 if (elf_header.e_type == ET_CORE) {
748 _cleanup_free_ char *out = NULL;
749
750 r = parse_core(fd, executable, root, ret ? &out : NULL, &package_metadata, &dlopen_metadata);
751 if (r < 0)
752 return log_warning_errno(r, "Failed to inspect core file: %m");
753
754 if (out)
755 fprintf(c.m.f, "%s", out);
756
757 elf_type = "coredump";
758 } else {
759 _cleanup_(sd_json_variant_unrefp) sd_json_variant *id_json = NULL;
760 const char *e = executable ?: "(unnamed)";
761 bool interpreter_found = false;
762
763 r = parse_buildid(NULL, c.elf, e, &c, &id_json);
764 if (r < 0)
765 return log_warning_errno(r, "Failed to parse build-id of ELF file: %m");
766
767 r = parse_metadata(e, id_json, c.elf, &interpreter_found, &c);
768 if (r < 0)
769 return log_warning_errno(r, "Failed to parse package metadata of ELF file: %m");
770
771 /* If we found a build-id and nothing else, return at least that. */
772 if (!package_metadata && id_json) {
773 r = sd_json_buildo(&package_metadata, SD_JSON_BUILD_PAIR_VARIANT(e, id_json));
774 if (r < 0)
775 return log_warning_errno(r, "Failed to build JSON object: %m");
776 }
777
778 if (interpreter_found)
779 elf_type = "executable";
780 else
781 elf_type = "library";
782 }
783
784 /* Note that e_type is always DYN for both executables and libraries, so we can't tell them apart from the header,
785 * but we will search for the PT_INTERP section when parsing the metadata. */
786 r = sd_json_buildo(&elf_metadata, SD_JSON_BUILD_PAIR_STRING("elfType", elf_type));
787 if (r < 0)
788 return log_warning_errno(r, "Failed to build JSON object: %m");
789
790 const char *elf_architecture = sym_dwelf_elf_e_machine_string(elf_header.e_machine);
791 if (elf_architecture) {
792 r = sd_json_variant_merge_objectbo(
793 &elf_metadata,
794 SD_JSON_BUILD_PAIR_STRING("elfArchitecture", elf_architecture));
795 if (r < 0)
796 return log_warning_errno(r, "Failed to add elfArchitecture field: %m");
797
798 if (ret)
799 fprintf(c.m.f, "ELF object binary architecture: %s\n", elf_architecture);
800 }
801
802 /* We always at least have the ELF type, so merge that (and possibly the arch). */
803 r = sd_json_variant_merge_object(&elf_metadata, package_metadata);
804 if (r < 0)
805 return log_warning_errno(r, "Failed to merge JSON objects: %m");
806
807 if (ret) {
808 r = memstream_finalize(&c.m, ret, NULL);
809 if (r < 0)
810 return log_warning_errno(r, "Could not parse ELF file, flushing file buffer failed: %m");
811 }
812
813 if (ret_package_metadata)
814 *ret_package_metadata = TAKE_PTR(elf_metadata);
815 if (ret_dlopen_metadata)
816 *ret_dlopen_metadata = TAKE_PTR(dlopen_metadata);
817
818 return 0;
819 }
820
821 #endif
822
823 int parse_elf_object(
824 int fd,
825 const char *executable,
826 const char *root,
827 bool fork_disable_dump,
828 char **ret,
829 sd_json_variant **ret_package_metadata,
830 sd_json_variant **ret_dlopen_metadata) {
831 #if HAVE_ELFUTILS
832 _cleanup_close_pair_ int error_pipe[2] = EBADF_PAIR,
833 return_pipe[2] = EBADF_PAIR,
834 package_metadata_pipe[2] = EBADF_PAIR,
835 dlopen_metadata_pipe[2] = EBADF_PAIR;
836 _cleanup_(sd_json_variant_unrefp) sd_json_variant *package_metadata = NULL, *dlopen_metadata = NULL;
837 _cleanup_free_ char *buf = NULL;
838 int r;
839
840 assert(fd >= 0);
841
842 r = dlopen_dw(LOG_DEBUG);
843 if (r < 0)
844 return r;
845
846 r = dlopen_elf(LOG_DEBUG);
847 if (r < 0)
848 return r;
849
850 r = RET_NERRNO(pipe2(error_pipe, O_CLOEXEC|O_NONBLOCK));
851 if (r < 0)
852 return r;
853
854 if (ret) {
855 r = RET_NERRNO(pipe2(return_pipe, O_CLOEXEC|O_NONBLOCK));
856 if (r < 0)
857 return r;
858 }
859
860 if (ret_package_metadata) {
861 r = RET_NERRNO(pipe2(package_metadata_pipe, O_CLOEXEC|O_NONBLOCK));
862 if (r < 0)
863 return r;
864 }
865
866 if (ret_dlopen_metadata) {
867 r = RET_NERRNO(pipe2(dlopen_metadata_pipe, O_CLOEXEC|O_NONBLOCK));
868 if (r < 0)
869 return r;
870 }
871
872 /* Parsing possibly malformed data is crash-happy, so fork. In case we crash,
873 * the core file will not be lost, and the messages will still be attached to
874 * the journal. Reading the elf object might be slow, but it still has an upper
875 * bound since the core files have an upper size limit. It's also not doing any
876 * system call or interacting with the system in any way, besides reading from
877 * the file descriptor and writing into these four pipes. */
878 r = pidref_safe_fork_full(
879 "(sd-parse-elf)",
880 /* stdio_fds= */ NULL,
881 (int[]) { fd, error_pipe[1], return_pipe[1], package_metadata_pipe[1], dlopen_metadata_pipe[1] },
882 5,
883 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_USERNS|FORK_WAIT|FORK_REOPEN_LOG,
884 /* ret= */ NULL);
885 if (r < 0) {
886 if (r == -EPROTO) { /* We should have the errno from the child, but don't clobber original error */
887 ssize_t k;
888 int e;
889
890 k = read(error_pipe[0], &e, sizeof(e));
891 if (k < 0 && errno != EAGAIN) /* Pipe is non-blocking, EAGAIN means there's nothing */
892 return -errno;
893 if (k == sizeof(e))
894 return e; /* propagate error sent to us from child */
895 if (k != 0)
896 return -EIO;
897 }
898
899 return r;
900 }
901 if (r == 0) {
902 /* We want to avoid loops, given this can be called from systemd-coredump */
903 if (fork_disable_dump) {
904 r = set_dumpable(SUID_DUMP_DISABLE);
905 if (r < 0)
906 report_errno_and_exit(error_pipe[1], r);
907 }
908
909 r = parse_elf(
910 fd,
911 executable,
912 root,
913 ret ? &buf : NULL,
914 ret_package_metadata ? &package_metadata : NULL,
915 ret_dlopen_metadata ? &dlopen_metadata : NULL);
916 if (r < 0)
917 report_errno_and_exit(error_pipe[1], r);
918
919 if (buf) {
920 size_t len = strlen(buf);
921
922 if (len > COREDUMP_PIPE_MAX) {
923 /* This is iffy. A backtrace can be a few hundred kilobytes, but too much is
924 * too much. Let's log a warning and ignore the rest. */
925 log_warning("Generated backtrace is %zu bytes (more than the limit of %u bytes), backtrace will be truncated.",
926 len, COREDUMP_PIPE_MAX);
927 len = COREDUMP_PIPE_MAX;
928 }
929
930 /* Bump the space for the returned string.
931 * Failure is ignored, because partial output is still useful. */
932 (void) fcntl(return_pipe[1], F_SETPIPE_SZ, len);
933
934 r = loop_write(return_pipe[1], buf, len);
935 if (r == -EAGAIN)
936 log_warning("Write failed, backtrace will be truncated.");
937 else if (r < 0)
938 report_errno_and_exit(error_pipe[1], r);
939
940 return_pipe[1] = safe_close(return_pipe[1]);
941 }
942
943 if (package_metadata) {
944 _cleanup_fclose_ FILE *json_out = NULL;
945
946 /* Bump the space for the returned string. We don't know how much space we'll need in
947 * advance, so we'll just try to write as much as possible and maybe fail later. */
948 (void) fcntl(package_metadata_pipe[1], F_SETPIPE_SZ, COREDUMP_PIPE_MAX);
949
950 json_out = take_fdopen(&package_metadata_pipe[1], "w");
951 if (!json_out)
952 report_errno_and_exit(error_pipe[1], -errno);
953
954 r = sd_json_variant_dump(package_metadata, SD_JSON_FORMAT_FLUSH, json_out, NULL);
955 if (r < 0)
956 log_warning_errno(r, "Failed to write JSON package metadata, ignoring: %m");
957 }
958
959 if (dlopen_metadata) {
960 _cleanup_fclose_ FILE *json_out = NULL;
961
962 /* Bump the space for the returned string. We don't know how much space we'll need in
963 * advance, so we'll just try to write as much as possible and maybe fail later. */
964 (void) fcntl(dlopen_metadata_pipe[1], F_SETPIPE_SZ, COREDUMP_PIPE_MAX);
965
966 json_out = take_fdopen(&dlopen_metadata_pipe[1], "w");
967 if (!json_out)
968 report_errno_and_exit(error_pipe[1], -errno);
969
970 r = sd_json_variant_dump(dlopen_metadata, SD_JSON_FORMAT_FLUSH, json_out, NULL);
971 if (r < 0)
972 log_warning_errno(r, "Failed to write JSON package metadata, ignoring: %m");
973 }
974
975 _exit(EXIT_SUCCESS);
976 }
977
978 error_pipe[1] = safe_close(error_pipe[1]);
979 return_pipe[1] = safe_close(return_pipe[1]);
980 package_metadata_pipe[1] = safe_close(package_metadata_pipe[1]);
981 dlopen_metadata_pipe[1] = safe_close(dlopen_metadata_pipe[1]);
982
983 if (ret) {
984 _cleanup_fclose_ FILE *in = NULL;
985
986 in = take_fdopen(&return_pipe[0], "r");
987 if (!in)
988 return -errno;
989
990 r = read_full_stream(in, &buf, NULL);
991 if (r < 0)
992 return r;
993 }
994
995 if (ret_package_metadata) {
996 r = sd_json_parse_fd(
997 /* path= */ NULL,
998 TAKE_FD(package_metadata_pipe[0]),
999 SD_JSON_PARSE_DONATE_FD,
1000 &package_metadata,
1001 /* reterr_line= */ NULL,
1002 /* reterr_column= */ NULL);
1003 if (r < 0 && r != -ENODATA) /* ENODATA: json was empty, so we got nothing, but that's ok */
1004 log_warning_errno(r, "Failed to read or parse package metadata, ignoring: %m");
1005 }
1006
1007 if (ret_dlopen_metadata) {
1008 r = sd_json_parse_fd(
1009 /* path= */ NULL,
1010 TAKE_FD(dlopen_metadata_pipe[0]),
1011 SD_JSON_PARSE_DONATE_FD,
1012 &dlopen_metadata,
1013 /* reterr_line= */ NULL,
1014 /* reterr_column= */ NULL);
1015 if (r < 0 && r != -ENODATA) /* ENODATA: json was empty, so we got nothing, but that's ok */
1016 log_warning_errno(r, "Failed to read or parse dlopen metadata, ignoring: %m");
1017 }
1018
1019 if (ret)
1020 *ret = TAKE_PTR(buf);
1021 if (ret_package_metadata)
1022 *ret_package_metadata = TAKE_PTR(package_metadata);
1023 if (ret_dlopen_metadata)
1024 *ret_dlopen_metadata = TAKE_PTR(dlopen_metadata);
1025
1026 return 0;
1027 #else
1028 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "elfutils disabled, parsing ELF objects not supported");
1029 #endif
1030 }