193dccbeeb51760a3db8578ccdd4d4d5be3723d3
[binutils-gdb.git] / gdb / corelow.c
1 /* Core dump and executable file functions below target vector, for GDB.
2
3 Copyright (C) 1986-2020 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <signal.h>
23 #include <fcntl.h>
24 #include "frame.h" /* required by inferior.h */
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "symtab.h"
28 #include "command.h"
29 #include "bfd.h"
30 #include "target.h"
31 #include "process-stratum-target.h"
32 #include "gdbcore.h"
33 #include "gdbthread.h"
34 #include "regcache.h"
35 #include "regset.h"
36 #include "symfile.h"
37 #include "exec.h"
38 #include "readline/tilde.h"
39 #include "solib.h"
40 #include "solist.h"
41 #include "filenames.h"
42 #include "progspace.h"
43 #include "objfiles.h"
44 #include "gdb_bfd.h"
45 #include "completer.h"
46 #include "gdbsupport/filestuff.h"
47 #include "build-id.h"
48 #include "gdbsupport/pathstuff.h"
49 #include <unordered_map>
50 #include <unordered_set>
51 #include "gdbcmd.h"
52
53 #ifndef O_LARGEFILE
54 #define O_LARGEFILE 0
55 #endif
56
57 /* The core file target. */
58
59 static const target_info core_target_info = {
60 "core",
61 N_("Local core dump file"),
62 N_("Use a core file as a target.\n\
63 Specify the filename of the core file.")
64 };
65
66 class core_target final : public process_stratum_target
67 {
68 public:
69 core_target ();
70
71 const target_info &info () const override
72 { return core_target_info; }
73
74 void close () override;
75 void detach (inferior *, int) override;
76 void fetch_registers (struct regcache *, int) override;
77
78 enum target_xfer_status xfer_partial (enum target_object object,
79 const char *annex,
80 gdb_byte *readbuf,
81 const gdb_byte *writebuf,
82 ULONGEST offset, ULONGEST len,
83 ULONGEST *xfered_len) override;
84 void files_info () override;
85
86 bool thread_alive (ptid_t ptid) override;
87 const struct target_desc *read_description () override;
88
89 std::string pid_to_str (ptid_t) override;
90
91 const char *thread_name (struct thread_info *) override;
92
93 bool has_all_memory () override { return true; }
94 bool has_memory () override;
95 bool has_stack () override;
96 bool has_registers () override;
97 bool has_execution (inferior *inf) override { return false; }
98
99 bool info_proc (const char *, enum info_proc_what) override;
100
101 /* A few helpers. */
102
103 /* Getter, see variable definition. */
104 struct gdbarch *core_gdbarch ()
105 {
106 return m_core_gdbarch;
107 }
108
109 /* See definition. */
110 void get_core_register_section (struct regcache *regcache,
111 const struct regset *regset,
112 const char *name,
113 int section_min_size,
114 const char *human_name,
115 bool required);
116
117 /* See definition. */
118 void info_proc_mappings (struct gdbarch *gdbarch);
119
120 private: /* per-core data */
121
122 /* The core's section table. Note that these target sections are
123 *not* mapped in the current address spaces' set of target
124 sections --- those should come only from pure executable or
125 shared library bfds. The core bfd sections are an implementation
126 detail of the core target, just like ptrace is for unix child
127 targets. */
128 target_section_table m_core_section_table;
129
130 /* File-backed address space mappings: some core files include
131 information about memory mapped files. */
132 target_section_table m_core_file_mappings;
133
134 /* Unavailable mappings. These correspond to pathnames which either
135 weren't found or could not be opened. Knowing these addresses can
136 still be useful. */
137 std::vector<mem_range> m_core_unavailable_mappings;
138
139 /* Build m_core_file_mappings. Called from the constructor. */
140 void build_file_mappings ();
141
142 /* Helper method for xfer_partial. */
143 enum target_xfer_status xfer_memory_via_mappings (gdb_byte *readbuf,
144 const gdb_byte *writebuf,
145 ULONGEST offset,
146 ULONGEST len,
147 ULONGEST *xfered_len);
148
149 /* FIXME: kettenis/20031023: Eventually this field should
150 disappear. */
151 struct gdbarch *m_core_gdbarch = NULL;
152 };
153
154 core_target::core_target ()
155 {
156 m_core_gdbarch = gdbarch_from_bfd (core_bfd);
157
158 if (!m_core_gdbarch
159 || !gdbarch_iterate_over_regset_sections_p (m_core_gdbarch))
160 error (_("\"%s\": Core file format not supported"),
161 bfd_get_filename (core_bfd));
162
163 /* Find the data section */
164 m_core_section_table = build_section_table (core_bfd);
165
166 build_file_mappings ();
167 }
168
169 /* Construct the target_section_table for file-backed mappings if
170 they exist.
171
172 For each unique path in the note, we'll open a BFD with a bfd
173 target of "binary". This is an unstructured bfd target upon which
174 we'll impose a structure from the mappings in the architecture-specific
175 mappings note. A BFD section is allocated and initialized for each
176 file-backed mapping.
177
178 We take care to not share already open bfds with other parts of
179 GDB; in particular, we don't want to add new sections to existing
180 BFDs. We do, however, ensure that the BFDs that we allocate here
181 will go away (be deallocated) when the core target is detached. */
182
183 void
184 core_target::build_file_mappings ()
185 {
186 std::unordered_map<std::string, struct bfd *> bfd_map;
187 std::unordered_set<std::string> unavailable_paths;
188
189 /* See linux_read_core_file_mappings() in linux-tdep.c for an example
190 read_core_file_mappings method. */
191 gdbarch_read_core_file_mappings (m_core_gdbarch, core_bfd,
192
193 /* After determining the number of mappings, read_core_file_mappings
194 will invoke this lambda. */
195 [&] (ULONGEST)
196 {
197 },
198
199 /* read_core_file_mappings will invoke this lambda for each mapping
200 that it finds. */
201 [&] (int num, ULONGEST start, ULONGEST end, ULONGEST file_ofs,
202 const char *filename, const void *other)
203 {
204 /* Architecture-specific read_core_mapping methods are expected to
205 weed out non-file-backed mappings. */
206 gdb_assert (filename != nullptr);
207
208 struct bfd *bfd = bfd_map[filename];
209 if (bfd == nullptr)
210 {
211 /* Use exec_file_find() to do sysroot expansion. It'll
212 also strip the potential sysroot "target:" prefix. If
213 there is no sysroot, an equivalent (possibly more
214 canonical) pathname will be provided. */
215 gdb::unique_xmalloc_ptr<char> expanded_fname
216 = exec_file_find (filename, NULL);
217 if (expanded_fname == nullptr)
218 {
219 m_core_unavailable_mappings.emplace_back (start, end - start);
220 /* Print just one warning per path. */
221 if (unavailable_paths.insert (filename).second)
222 warning (_("Can't open file %s during file-backed mapping "
223 "note processing"),
224 filename);
225 return;
226 }
227
228 bfd = bfd_map[filename] = bfd_openr (expanded_fname.get (),
229 "binary");
230
231 if (bfd == nullptr || !bfd_check_format (bfd, bfd_object))
232 {
233 m_core_unavailable_mappings.emplace_back (start, end - start);
234 /* If we get here, there's a good chance that it's due to
235 an internal error. We issue a warning instead of an
236 internal error because of the possibility that the
237 file was removed in between checking for its
238 existence during the expansion in exec_file_find()
239 and the calls to bfd_openr() / bfd_check_format().
240 Output both the path from the core file note along
241 with its expansion to make debugging this problem
242 easier. */
243 warning (_("Can't open file %s which was expanded to %s "
244 "during file-backed mapping note processing"),
245 filename, expanded_fname.get ());
246 if (bfd != nullptr)
247 bfd_close (bfd);
248 return;
249 }
250 /* Ensure that the bfd will be closed when core_bfd is closed.
251 This can be checked before/after a core file detach via
252 "maint info bfds". */
253 gdb_bfd_record_inclusion (core_bfd, bfd);
254 }
255
256 /* Make new BFD section. All sections have the same name,
257 which is permitted by bfd_make_section_anyway(). */
258 asection *sec = bfd_make_section_anyway (bfd, "load");
259 if (sec == nullptr)
260 error (_("Can't make section"));
261 sec->filepos = file_ofs;
262 bfd_set_section_flags (sec, SEC_READONLY | SEC_HAS_CONTENTS);
263 bfd_set_section_size (sec, end - start);
264 bfd_set_section_vma (sec, start);
265 bfd_set_section_lma (sec, start);
266 bfd_set_section_alignment (sec, 2);
267
268 /* Set target_section fields. */
269 m_core_file_mappings.sections.emplace_back ();
270 target_section &ts = m_core_file_mappings.sections.back ();
271 ts.addr = start;
272 ts.endaddr = end;
273 ts.owner = nullptr;
274 ts.the_bfd_section = sec;
275 });
276
277 normalize_mem_ranges (&m_core_unavailable_mappings);
278 }
279
280 /* An arbitrary identifier for the core inferior. */
281 #define CORELOW_PID 1
282
283 /* Close the core target. */
284
285 void
286 core_target::close ()
287 {
288 if (core_bfd)
289 {
290 switch_to_no_thread (); /* Avoid confusion from thread
291 stuff. */
292 exit_inferior_silent (current_inferior ());
293
294 /* Clear out solib state while the bfd is still open. See
295 comments in clear_solib in solib.c. */
296 clear_solib ();
297
298 current_program_space->cbfd.reset (nullptr);
299 }
300
301 /* Core targets are heap-allocated (see core_target_open), so here
302 we delete ourselves. */
303 delete this;
304 }
305
306 /* Look for sections whose names start with `.reg/' so that we can
307 extract the list of threads in a core file. */
308
309 static void
310 add_to_thread_list (asection *asect, asection *reg_sect)
311 {
312 int core_tid;
313 int pid, lwpid;
314 bool fake_pid_p = false;
315 struct inferior *inf;
316
317 if (!startswith (bfd_section_name (asect), ".reg/"))
318 return;
319
320 core_tid = atoi (bfd_section_name (asect) + 5);
321
322 pid = bfd_core_file_pid (core_bfd);
323 if (pid == 0)
324 {
325 fake_pid_p = true;
326 pid = CORELOW_PID;
327 }
328
329 lwpid = core_tid;
330
331 inf = current_inferior ();
332 if (inf->pid == 0)
333 {
334 inferior_appeared (inf, pid);
335 inf->fake_pid_p = fake_pid_p;
336 }
337
338 ptid_t ptid (pid, lwpid);
339
340 thread_info *thr = add_thread (inf->process_target (), ptid);
341
342 /* Warning, Will Robinson, looking at BFD private data! */
343
344 if (reg_sect != NULL
345 && asect->filepos == reg_sect->filepos) /* Did we find .reg? */
346 switch_to_thread (thr); /* Yes, make it current. */
347 }
348
349 /* Issue a message saying we have no core to debug, if FROM_TTY. */
350
351 static void
352 maybe_say_no_core_file_now (int from_tty)
353 {
354 if (from_tty)
355 printf_filtered (_("No core file now.\n"));
356 }
357
358 /* Backward compatibility with old way of specifying core files. */
359
360 void
361 core_file_command (const char *filename, int from_tty)
362 {
363 dont_repeat (); /* Either way, seems bogus. */
364
365 if (filename == NULL)
366 {
367 if (core_bfd != NULL)
368 {
369 target_detach (current_inferior (), from_tty);
370 gdb_assert (core_bfd == NULL);
371 }
372 else
373 maybe_say_no_core_file_now (from_tty);
374 }
375 else
376 core_target_open (filename, from_tty);
377 }
378
379 /* Locate (and load) an executable file (and symbols) given the core file
380 BFD ABFD. */
381
382 static void
383 locate_exec_from_corefile_build_id (bfd *abfd, int from_tty)
384 {
385 const bfd_build_id *build_id = build_id_bfd_get (abfd);
386 if (build_id == nullptr)
387 return;
388
389 gdb_bfd_ref_ptr execbfd
390 = build_id_to_exec_bfd (build_id->size, build_id->data);
391
392 if (execbfd != nullptr)
393 {
394 exec_file_attach (bfd_get_filename (execbfd.get ()), from_tty);
395 symbol_file_add_main (bfd_get_filename (execbfd.get ()),
396 symfile_add_flag (from_tty ? SYMFILE_VERBOSE : 0));
397 }
398 }
399
400 /* See gdbcore.h. */
401
402 void
403 core_target_open (const char *arg, int from_tty)
404 {
405 const char *p;
406 int siggy;
407 int scratch_chan;
408 int flags;
409
410 target_preopen (from_tty);
411 if (!arg)
412 {
413 if (core_bfd)
414 error (_("No core file specified. (Use `detach' "
415 "to stop debugging a core file.)"));
416 else
417 error (_("No core file specified."));
418 }
419
420 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (arg));
421 if (!IS_ABSOLUTE_PATH (filename.get ()))
422 filename = gdb_abspath (filename.get ());
423
424 flags = O_BINARY | O_LARGEFILE;
425 if (write_files)
426 flags |= O_RDWR;
427 else
428 flags |= O_RDONLY;
429 scratch_chan = gdb_open_cloexec (filename.get (), flags, 0);
430 if (scratch_chan < 0)
431 perror_with_name (filename.get ());
432
433 gdb_bfd_ref_ptr temp_bfd (gdb_bfd_fopen (filename.get (), gnutarget,
434 write_files ? FOPEN_RUB : FOPEN_RB,
435 scratch_chan));
436 if (temp_bfd == NULL)
437 perror_with_name (filename.get ());
438
439 if (!bfd_check_format (temp_bfd.get (), bfd_core))
440 {
441 /* Do it after the err msg */
442 /* FIXME: should be checking for errors from bfd_close (for one
443 thing, on error it does not free all the storage associated
444 with the bfd). */
445 error (_("\"%s\" is not a core dump: %s"),
446 filename.get (), bfd_errmsg (bfd_get_error ()));
447 }
448
449 current_program_space->cbfd = std::move (temp_bfd);
450
451 core_target *target = new core_target ();
452
453 /* Own the target until it is successfully pushed. */
454 target_ops_up target_holder (target);
455
456 validate_files ();
457
458 /* If we have no exec file, try to set the architecture from the
459 core file. We don't do this unconditionally since an exec file
460 typically contains more information that helps us determine the
461 architecture than a core file. */
462 if (!exec_bfd)
463 set_gdbarch_from_file (core_bfd);
464
465 push_target (std::move (target_holder));
466
467 switch_to_no_thread ();
468
469 /* Need to flush the register cache (and the frame cache) from a
470 previous debug session. If inferior_ptid ends up the same as the
471 last debug session --- e.g., b foo; run; gcore core1; step; gcore
472 core2; core core1; core core2 --- then there's potential for
473 get_current_regcache to return the cached regcache of the
474 previous session, and the frame cache being stale. */
475 registers_changed ();
476
477 /* Build up thread list from BFD sections, and possibly set the
478 current thread to the .reg/NN section matching the .reg
479 section. */
480 asection *reg_sect = bfd_get_section_by_name (core_bfd, ".reg");
481 for (asection *sect : gdb_bfd_sections (core_bfd))
482 add_to_thread_list (sect, reg_sect);
483
484 if (inferior_ptid == null_ptid)
485 {
486 /* Either we found no .reg/NN section, and hence we have a
487 non-threaded core (single-threaded, from gdb's perspective),
488 or for some reason add_to_thread_list couldn't determine
489 which was the "main" thread. The latter case shouldn't
490 usually happen, but we're dealing with input here, which can
491 always be broken in different ways. */
492 thread_info *thread = first_thread_of_inferior (current_inferior ());
493
494 if (thread == NULL)
495 {
496 inferior_appeared (current_inferior (), CORELOW_PID);
497 thread = add_thread_silent (target, ptid_t (CORELOW_PID));
498 }
499
500 switch_to_thread (thread);
501 }
502
503 if (exec_bfd == nullptr)
504 locate_exec_from_corefile_build_id (core_bfd, from_tty);
505
506 post_create_inferior (from_tty);
507
508 /* Now go through the target stack looking for threads since there
509 may be a thread_stratum target loaded on top of target core by
510 now. The layer above should claim threads found in the BFD
511 sections. */
512 try
513 {
514 target_update_thread_list ();
515 }
516
517 catch (const gdb_exception_error &except)
518 {
519 exception_print (gdb_stderr, except);
520 }
521
522 p = bfd_core_file_failing_command (core_bfd);
523 if (p)
524 printf_filtered (_("Core was generated by `%s'.\n"), p);
525
526 /* Clearing any previous state of convenience variables. */
527 clear_exit_convenience_vars ();
528
529 siggy = bfd_core_file_failing_signal (core_bfd);
530 if (siggy > 0)
531 {
532 gdbarch *core_gdbarch = target->core_gdbarch ();
533
534 /* If we don't have a CORE_GDBARCH to work with, assume a native
535 core (map gdb_signal from host signals). If we do have
536 CORE_GDBARCH to work with, but no gdb_signal_from_target
537 implementation for that gdbarch, as a fallback measure,
538 assume the host signal mapping. It'll be correct for native
539 cores, but most likely incorrect for cross-cores. */
540 enum gdb_signal sig = (core_gdbarch != NULL
541 && gdbarch_gdb_signal_from_target_p (core_gdbarch)
542 ? gdbarch_gdb_signal_from_target (core_gdbarch,
543 siggy)
544 : gdb_signal_from_host (siggy));
545
546 printf_filtered (_("Program terminated with signal %s, %s"),
547 gdb_signal_to_name (sig), gdb_signal_to_string (sig));
548 if (gdbarch_report_signal_info_p (core_gdbarch))
549 gdbarch_report_signal_info (core_gdbarch, current_uiout, sig);
550 printf_filtered (_(".\n"));
551
552 /* Set the value of the internal variable $_exitsignal,
553 which holds the signal uncaught by the inferior. */
554 set_internalvar_integer (lookup_internalvar ("_exitsignal"),
555 siggy);
556 }
557
558 /* Fetch all registers from core file. */
559 target_fetch_registers (get_current_regcache (), -1);
560
561 /* Now, set up the frame cache, and print the top of stack. */
562 reinit_frame_cache ();
563 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
564
565 /* Current thread should be NUM 1 but the user does not know that.
566 If a program is single threaded gdb in general does not mention
567 anything about threads. That is why the test is >= 2. */
568 if (thread_count (target) >= 2)
569 {
570 try
571 {
572 thread_command (NULL, from_tty);
573 }
574 catch (const gdb_exception_error &except)
575 {
576 exception_print (gdb_stderr, except);
577 }
578 }
579 }
580
581 void
582 core_target::detach (inferior *inf, int from_tty)
583 {
584 /* Note that 'this' is dangling after this call. unpush_target
585 closes the target, and our close implementation deletes
586 'this'. */
587 unpush_target (this);
588
589 /* Clear the register cache and the frame cache. */
590 registers_changed ();
591 reinit_frame_cache ();
592 maybe_say_no_core_file_now (from_tty);
593 }
594
595 /* Try to retrieve registers from a section in core_bfd, and supply
596 them to REGSET.
597
598 If ptid's lwp member is zero, do the single-threaded
599 thing: look for a section named NAME. If ptid's lwp
600 member is non-zero, do the multi-threaded thing: look for a section
601 named "NAME/LWP", where LWP is the shortest ASCII decimal
602 representation of ptid's lwp member.
603
604 HUMAN_NAME is a human-readable name for the kind of registers the
605 NAME section contains, for use in error messages.
606
607 If REQUIRED is true, print an error if the core file doesn't have a
608 section by the appropriate name. Otherwise, just do nothing. */
609
610 void
611 core_target::get_core_register_section (struct regcache *regcache,
612 const struct regset *regset,
613 const char *name,
614 int section_min_size,
615 const char *human_name,
616 bool required)
617 {
618 gdb_assert (regset != nullptr);
619
620 struct bfd_section *section;
621 bfd_size_type size;
622 bool variable_size_section = (regset->flags & REGSET_VARIABLE_SIZE);
623
624 thread_section_name section_name (name, regcache->ptid ());
625
626 section = bfd_get_section_by_name (core_bfd, section_name.c_str ());
627 if (! section)
628 {
629 if (required)
630 warning (_("Couldn't find %s registers in core file."),
631 human_name);
632 return;
633 }
634
635 size = bfd_section_size (section);
636 if (size < section_min_size)
637 {
638 warning (_("Section `%s' in core file too small."),
639 section_name.c_str ());
640 return;
641 }
642 if (size != section_min_size && !variable_size_section)
643 {
644 warning (_("Unexpected size of section `%s' in core file."),
645 section_name.c_str ());
646 }
647
648 gdb::byte_vector contents (size);
649 if (!bfd_get_section_contents (core_bfd, section, contents.data (),
650 (file_ptr) 0, size))
651 {
652 warning (_("Couldn't read %s registers from `%s' section in core file."),
653 human_name, section_name.c_str ());
654 return;
655 }
656
657 regset->supply_regset (regset, regcache, -1, contents.data (), size);
658 }
659
660 /* Data passed to gdbarch_iterate_over_regset_sections's callback. */
661 struct get_core_registers_cb_data
662 {
663 core_target *target;
664 struct regcache *regcache;
665 };
666
667 /* Callback for get_core_registers that handles a single core file
668 register note section. */
669
670 static void
671 get_core_registers_cb (const char *sect_name, int supply_size, int collect_size,
672 const struct regset *regset,
673 const char *human_name, void *cb_data)
674 {
675 gdb_assert (regset != nullptr);
676
677 auto *data = (get_core_registers_cb_data *) cb_data;
678 bool required = false;
679 bool variable_size_section = (regset->flags & REGSET_VARIABLE_SIZE);
680
681 if (!variable_size_section)
682 gdb_assert (supply_size == collect_size);
683
684 if (strcmp (sect_name, ".reg") == 0)
685 {
686 required = true;
687 if (human_name == NULL)
688 human_name = "general-purpose";
689 }
690 else if (strcmp (sect_name, ".reg2") == 0)
691 {
692 if (human_name == NULL)
693 human_name = "floating-point";
694 }
695
696 data->target->get_core_register_section (data->regcache, regset, sect_name,
697 supply_size, human_name, required);
698 }
699
700 /* Get the registers out of a core file. This is the machine-
701 independent part. Fetch_core_registers is the machine-dependent
702 part, typically implemented in the xm-file for each
703 architecture. */
704
705 /* We just get all the registers, so we don't use regno. */
706
707 void
708 core_target::fetch_registers (struct regcache *regcache, int regno)
709 {
710 if (!(m_core_gdbarch != nullptr
711 && gdbarch_iterate_over_regset_sections_p (m_core_gdbarch)))
712 {
713 fprintf_filtered (gdb_stderr,
714 "Can't fetch registers from this type of core file\n");
715 return;
716 }
717
718 struct gdbarch *gdbarch = regcache->arch ();
719 get_core_registers_cb_data data = { this, regcache };
720 gdbarch_iterate_over_regset_sections (gdbarch,
721 get_core_registers_cb,
722 (void *) &data, NULL);
723
724 /* Mark all registers not found in the core as unavailable. */
725 for (int i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
726 if (regcache->get_register_status (i) == REG_UNKNOWN)
727 regcache->raw_supply (i, NULL);
728 }
729
730 void
731 core_target::files_info ()
732 {
733 print_section_info (&m_core_section_table, core_bfd);
734 }
735 \f
736 /* Helper method for core_target::xfer_partial. */
737
738 enum target_xfer_status
739 core_target::xfer_memory_via_mappings (gdb_byte *readbuf,
740 const gdb_byte *writebuf,
741 ULONGEST offset, ULONGEST len,
742 ULONGEST *xfered_len)
743 {
744 enum target_xfer_status xfer_status;
745
746 xfer_status = (section_table_xfer_memory_partial
747 (readbuf, writebuf,
748 offset, len, xfered_len,
749 m_core_file_mappings));
750
751 if (xfer_status == TARGET_XFER_OK || m_core_unavailable_mappings.empty ())
752 return xfer_status;
753
754 /* There are instances - e.g. when debugging within a docker
755 container using the AUFS storage driver - where the pathnames
756 obtained from the note section are incorrect. Despite the path
757 being wrong, just knowing the start and end addresses of the
758 mappings is still useful; we can attempt an access of the file
759 stratum constrained to the address ranges corresponding to the
760 unavailable mappings. */
761
762 ULONGEST memaddr = offset;
763 ULONGEST memend = offset + len;
764
765 for (const auto &mr : m_core_unavailable_mappings)
766 {
767 if (address_in_mem_range (memaddr, &mr))
768 {
769 if (!address_in_mem_range (memend, &mr))
770 len = mr.start + mr.length - memaddr;
771
772 xfer_status = this->beneath ()->xfer_partial (TARGET_OBJECT_MEMORY,
773 NULL,
774 readbuf,
775 writebuf,
776 offset,
777 len,
778 xfered_len);
779 break;
780 }
781 }
782
783 return xfer_status;
784 }
785
786 enum target_xfer_status
787 core_target::xfer_partial (enum target_object object, const char *annex,
788 gdb_byte *readbuf, const gdb_byte *writebuf,
789 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
790 {
791 switch (object)
792 {
793 case TARGET_OBJECT_MEMORY:
794 {
795 enum target_xfer_status xfer_status;
796
797 /* Try accessing memory contents from core file data,
798 restricting consideration to those sections for which
799 the BFD section flag SEC_HAS_CONTENTS is set. */
800 auto has_contents_cb = [] (const struct target_section *s)
801 {
802 return ((s->the_bfd_section->flags & SEC_HAS_CONTENTS) != 0);
803 };
804 xfer_status = section_table_xfer_memory_partial
805 (readbuf, writebuf,
806 offset, len, xfered_len,
807 m_core_section_table,
808 has_contents_cb);
809 if (xfer_status == TARGET_XFER_OK)
810 return TARGET_XFER_OK;
811
812 /* Check file backed mappings. If they're available, use
813 core file provided mappings (e.g. from .note.linuxcore.file
814 or the like) as this should provide a more accurate
815 result. If not, check the stratum beneath us, which should
816 be the file stratum. */
817 if (!m_core_file_mappings.sections.empty ())
818 xfer_status = xfer_memory_via_mappings (readbuf, writebuf, offset,
819 len, xfered_len);
820 else
821 xfer_status = this->beneath ()->xfer_partial (object, annex, readbuf,
822 writebuf, offset, len,
823 xfered_len);
824 if (xfer_status == TARGET_XFER_OK)
825 return TARGET_XFER_OK;
826
827 /* Finally, attempt to access data in core file sections with
828 no contents. These will typically read as all zero. */
829 auto no_contents_cb = [&] (const struct target_section *s)
830 {
831 return !has_contents_cb (s);
832 };
833 xfer_status = section_table_xfer_memory_partial
834 (readbuf, writebuf,
835 offset, len, xfered_len,
836 m_core_section_table,
837 no_contents_cb);
838
839 return xfer_status;
840 }
841 case TARGET_OBJECT_AUXV:
842 if (readbuf)
843 {
844 /* When the aux vector is stored in core file, BFD
845 represents this with a fake section called ".auxv". */
846
847 struct bfd_section *section;
848 bfd_size_type size;
849
850 section = bfd_get_section_by_name (core_bfd, ".auxv");
851 if (section == NULL)
852 return TARGET_XFER_E_IO;
853
854 size = bfd_section_size (section);
855 if (offset >= size)
856 return TARGET_XFER_EOF;
857 size -= offset;
858 if (size > len)
859 size = len;
860
861 if (size == 0)
862 return TARGET_XFER_EOF;
863 if (!bfd_get_section_contents (core_bfd, section, readbuf,
864 (file_ptr) offset, size))
865 {
866 warning (_("Couldn't read NT_AUXV note in core file."));
867 return TARGET_XFER_E_IO;
868 }
869
870 *xfered_len = (ULONGEST) size;
871 return TARGET_XFER_OK;
872 }
873 return TARGET_XFER_E_IO;
874
875 case TARGET_OBJECT_WCOOKIE:
876 if (readbuf)
877 {
878 /* When the StackGhost cookie is stored in core file, BFD
879 represents this with a fake section called
880 ".wcookie". */
881
882 struct bfd_section *section;
883 bfd_size_type size;
884
885 section = bfd_get_section_by_name (core_bfd, ".wcookie");
886 if (section == NULL)
887 return TARGET_XFER_E_IO;
888
889 size = bfd_section_size (section);
890 if (offset >= size)
891 return TARGET_XFER_EOF;
892 size -= offset;
893 if (size > len)
894 size = len;
895
896 if (size == 0)
897 return TARGET_XFER_EOF;
898 if (!bfd_get_section_contents (core_bfd, section, readbuf,
899 (file_ptr) offset, size))
900 {
901 warning (_("Couldn't read StackGhost cookie in core file."));
902 return TARGET_XFER_E_IO;
903 }
904
905 *xfered_len = (ULONGEST) size;
906 return TARGET_XFER_OK;
907
908 }
909 return TARGET_XFER_E_IO;
910
911 case TARGET_OBJECT_LIBRARIES:
912 if (m_core_gdbarch != nullptr
913 && gdbarch_core_xfer_shared_libraries_p (m_core_gdbarch))
914 {
915 if (writebuf)
916 return TARGET_XFER_E_IO;
917 else
918 {
919 *xfered_len = gdbarch_core_xfer_shared_libraries (m_core_gdbarch,
920 readbuf,
921 offset, len);
922
923 if (*xfered_len == 0)
924 return TARGET_XFER_EOF;
925 else
926 return TARGET_XFER_OK;
927 }
928 }
929 /* FALL THROUGH */
930
931 case TARGET_OBJECT_LIBRARIES_AIX:
932 if (m_core_gdbarch != nullptr
933 && gdbarch_core_xfer_shared_libraries_aix_p (m_core_gdbarch))
934 {
935 if (writebuf)
936 return TARGET_XFER_E_IO;
937 else
938 {
939 *xfered_len
940 = gdbarch_core_xfer_shared_libraries_aix (m_core_gdbarch,
941 readbuf, offset,
942 len);
943
944 if (*xfered_len == 0)
945 return TARGET_XFER_EOF;
946 else
947 return TARGET_XFER_OK;
948 }
949 }
950 /* FALL THROUGH */
951
952 case TARGET_OBJECT_SIGNAL_INFO:
953 if (readbuf)
954 {
955 if (m_core_gdbarch != nullptr
956 && gdbarch_core_xfer_siginfo_p (m_core_gdbarch))
957 {
958 LONGEST l = gdbarch_core_xfer_siginfo (m_core_gdbarch, readbuf,
959 offset, len);
960
961 if (l >= 0)
962 {
963 *xfered_len = l;
964 if (l == 0)
965 return TARGET_XFER_EOF;
966 else
967 return TARGET_XFER_OK;
968 }
969 }
970 }
971 return TARGET_XFER_E_IO;
972
973 default:
974 return this->beneath ()->xfer_partial (object, annex, readbuf,
975 writebuf, offset, len,
976 xfered_len);
977 }
978 }
979
980 \f
981
982 /* Okay, let's be honest: threads gleaned from a core file aren't
983 exactly lively, are they? On the other hand, if we don't claim
984 that each & every one is alive, then we don't get any of them
985 to appear in an "info thread" command, which is quite a useful
986 behaviour.
987 */
988 bool
989 core_target::thread_alive (ptid_t ptid)
990 {
991 return true;
992 }
993
994 /* Ask the current architecture what it knows about this core file.
995 That will be used, in turn, to pick a better architecture. This
996 wrapper could be avoided if targets got a chance to specialize
997 core_target. */
998
999 const struct target_desc *
1000 core_target::read_description ()
1001 {
1002 if (m_core_gdbarch && gdbarch_core_read_description_p (m_core_gdbarch))
1003 {
1004 const struct target_desc *result;
1005
1006 result = gdbarch_core_read_description (m_core_gdbarch, this, core_bfd);
1007 if (result != NULL)
1008 return result;
1009 }
1010
1011 return this->beneath ()->read_description ();
1012 }
1013
1014 std::string
1015 core_target::pid_to_str (ptid_t ptid)
1016 {
1017 struct inferior *inf;
1018 int pid;
1019
1020 /* The preferred way is to have a gdbarch/OS specific
1021 implementation. */
1022 if (m_core_gdbarch != nullptr
1023 && gdbarch_core_pid_to_str_p (m_core_gdbarch))
1024 return gdbarch_core_pid_to_str (m_core_gdbarch, ptid);
1025
1026 /* Otherwise, if we don't have one, we'll just fallback to
1027 "process", with normal_pid_to_str. */
1028
1029 /* Try the LWPID field first. */
1030 pid = ptid.lwp ();
1031 if (pid != 0)
1032 return normal_pid_to_str (ptid_t (pid));
1033
1034 /* Otherwise, this isn't a "threaded" core -- use the PID field, but
1035 only if it isn't a fake PID. */
1036 inf = find_inferior_ptid (this, ptid);
1037 if (inf != NULL && !inf->fake_pid_p)
1038 return normal_pid_to_str (ptid);
1039
1040 /* No luck. We simply don't have a valid PID to print. */
1041 return "<main task>";
1042 }
1043
1044 const char *
1045 core_target::thread_name (struct thread_info *thr)
1046 {
1047 if (m_core_gdbarch != nullptr
1048 && gdbarch_core_thread_name_p (m_core_gdbarch))
1049 return gdbarch_core_thread_name (m_core_gdbarch, thr);
1050 return NULL;
1051 }
1052
1053 bool
1054 core_target::has_memory ()
1055 {
1056 return (core_bfd != NULL);
1057 }
1058
1059 bool
1060 core_target::has_stack ()
1061 {
1062 return (core_bfd != NULL);
1063 }
1064
1065 bool
1066 core_target::has_registers ()
1067 {
1068 return (core_bfd != NULL);
1069 }
1070
1071 /* Implement the to_info_proc method. */
1072
1073 bool
1074 core_target::info_proc (const char *args, enum info_proc_what request)
1075 {
1076 struct gdbarch *gdbarch = get_current_arch ();
1077
1078 /* Since this is the core file target, call the 'core_info_proc'
1079 method on gdbarch, not 'info_proc'. */
1080 if (gdbarch_core_info_proc_p (gdbarch))
1081 gdbarch_core_info_proc (gdbarch, args, request);
1082
1083 return true;
1084 }
1085
1086 /* Get a pointer to the current core target. If not connected to a
1087 core target, return NULL. */
1088
1089 static core_target *
1090 get_current_core_target ()
1091 {
1092 target_ops *proc_target = current_inferior ()->process_target ();
1093 return dynamic_cast<core_target *> (proc_target);
1094 }
1095
1096 /* Display file backed mappings from core file. */
1097
1098 void
1099 core_target::info_proc_mappings (struct gdbarch *gdbarch)
1100 {
1101 if (!m_core_file_mappings.sections.empty ())
1102 {
1103 printf_filtered (_("Mapped address spaces:\n\n"));
1104 if (gdbarch_addr_bit (gdbarch) == 32)
1105 {
1106 printf_filtered ("\t%10s %10s %10s %10s %s\n",
1107 "Start Addr",
1108 " End Addr",
1109 " Size", " Offset", "objfile");
1110 }
1111 else
1112 {
1113 printf_filtered (" %18s %18s %10s %10s %s\n",
1114 "Start Addr",
1115 " End Addr",
1116 " Size", " Offset", "objfile");
1117 }
1118 }
1119
1120 for (const target_section &tsp : m_core_file_mappings.sections)
1121 {
1122 ULONGEST start = tsp.addr;
1123 ULONGEST end = tsp.endaddr;
1124 ULONGEST file_ofs = tsp.the_bfd_section->filepos;
1125 const char *filename = bfd_get_filename (tsp.the_bfd_section->owner);
1126
1127 if (gdbarch_addr_bit (gdbarch) == 32)
1128 printf_filtered ("\t%10s %10s %10s %10s %s\n",
1129 paddress (gdbarch, start),
1130 paddress (gdbarch, end),
1131 hex_string (end - start),
1132 hex_string (file_ofs),
1133 filename);
1134 else
1135 printf_filtered (" %18s %18s %10s %10s %s\n",
1136 paddress (gdbarch, start),
1137 paddress (gdbarch, end),
1138 hex_string (end - start),
1139 hex_string (file_ofs),
1140 filename);
1141 }
1142 }
1143
1144 /* Implement "maintenance print core-file-backed-mappings" command.
1145
1146 If mappings are loaded, the results should be similar to the
1147 mappings shown by "info proc mappings". This command is mainly a
1148 debugging tool for GDB developers to make sure that the expected
1149 mappings are present after loading a core file. For Linux, the
1150 output provided by this command will be very similar (if not
1151 identical) to that provided by "info proc mappings". This is not
1152 necessarily the case for other OSes which might provide
1153 more/different information in the "info proc mappings" output. */
1154
1155 static void
1156 maintenance_print_core_file_backed_mappings (const char *args, int from_tty)
1157 {
1158 core_target *targ = get_current_core_target ();
1159 if (targ != nullptr)
1160 targ->info_proc_mappings (targ->core_gdbarch ());
1161 }
1162
1163 void _initialize_corelow ();
1164 void
1165 _initialize_corelow ()
1166 {
1167 add_target (core_target_info, core_target_open, filename_completer);
1168 add_cmd ("core-file-backed-mappings", class_maintenance,
1169 maintenance_print_core_file_backed_mappings,
1170 _("Print core file's file-backed mappings."),
1171 &maintenanceprintlist);
1172 }