Automatic date update in version.in
[binutils-gdb.git] / gdb / corelow.c
blobbdda742ef59578155a5c5ef8941eacd04f427f94
1 /* Core dump and executable file functions below target vector, for GDB.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "arch-utils.h"
21 #include <signal.h>
22 #include <fcntl.h>
23 #include "frame.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "symtab.h"
27 #include "command.h"
28 #include "bfd.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcore.h"
32 #include "gdbthread.h"
33 #include "regcache.h"
34 #include "regset.h"
35 #include "symfile.h"
36 #include "exec.h"
37 #include "readline/tilde.h"
38 #include "solib.h"
39 #include "solist.h"
40 #include "filenames.h"
41 #include "progspace.h"
42 #include "objfiles.h"
43 #include "gdb_bfd.h"
44 #include "completer.h"
45 #include "gdbsupport/filestuff.h"
46 #include "build-id.h"
47 #include "gdbsupport/pathstuff.h"
48 #include "gdbsupport/scoped_fd.h"
49 #include "gdbsupport/x86-xstate.h"
50 #include "debuginfod-support.h"
51 #include <unordered_map>
52 #include <unordered_set>
53 #include "gdbcmd.h"
54 #include "xml-tdesc.h"
55 #include "memtag.h"
57 #ifndef O_LARGEFILE
58 #define O_LARGEFILE 0
59 #endif
61 /* The core file target. */
63 static const target_info core_target_info = {
64 "core",
65 N_("Local core dump file"),
66 N_("Use a core file as a target.\n\
67 Specify the filename of the core file.")
70 class core_target final : public process_stratum_target
72 public:
73 core_target ();
75 const target_info &info () const override
76 { return core_target_info; }
78 void close () override;
79 void detach (inferior *, int) override;
80 void fetch_registers (struct regcache *, int) override;
82 enum target_xfer_status xfer_partial (enum target_object object,
83 const char *annex,
84 gdb_byte *readbuf,
85 const gdb_byte *writebuf,
86 ULONGEST offset, ULONGEST len,
87 ULONGEST *xfered_len) override;
88 void files_info () override;
90 bool thread_alive (ptid_t ptid) override;
91 const struct target_desc *read_description () override;
93 std::string pid_to_str (ptid_t) override;
95 const char *thread_name (struct thread_info *) override;
97 bool has_all_memory () override { return true; }
98 bool has_memory () override;
99 bool has_stack () override;
100 bool has_registers () override;
101 bool has_execution (inferior *inf) override { return false; }
103 bool info_proc (const char *, enum info_proc_what) override;
105 bool supports_memory_tagging () override;
107 /* Core file implementation of fetch_memtags. Fetch the memory tags from
108 core file notes. */
109 bool fetch_memtags (CORE_ADDR address, size_t len,
110 gdb::byte_vector &tags, int type) override;
112 /* If the architecture supports it, check if ADDRESS is within a memory range
113 mapped with tags. For example, MTE tags for AArch64. */
114 bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
116 x86_xsave_layout fetch_x86_xsave_layout () override;
118 /* A few helpers. */
120 /* Getter, see variable definition. */
121 struct gdbarch *core_gdbarch ()
123 return m_core_gdbarch;
126 /* See definition. */
127 void get_core_register_section (struct regcache *regcache,
128 const struct regset *regset,
129 const char *name,
130 int section_min_size,
131 const char *human_name,
132 bool required);
134 /* See definition. */
135 void info_proc_mappings (struct gdbarch *gdbarch);
137 private: /* per-core data */
139 /* Get rid of the core inferior. */
140 void clear_core ();
142 /* The core's section table. Note that these target sections are
143 *not* mapped in the current address spaces' set of target
144 sections --- those should come only from pure executable or
145 shared library bfds. The core bfd sections are an implementation
146 detail of the core target, just like ptrace is for unix child
147 targets. */
148 std::vector<target_section> m_core_section_table;
150 /* File-backed address space mappings: some core files include
151 information about memory mapped files. */
152 std::vector<target_section> m_core_file_mappings;
154 /* Unavailable mappings. These correspond to pathnames which either
155 weren't found or could not be opened. Knowing these addresses can
156 still be useful. */
157 std::vector<mem_range> m_core_unavailable_mappings;
159 /* Build m_core_file_mappings. Called from the constructor. */
160 void build_file_mappings ();
162 /* Helper method for xfer_partial. */
163 enum target_xfer_status xfer_memory_via_mappings (gdb_byte *readbuf,
164 const gdb_byte *writebuf,
165 ULONGEST offset,
166 ULONGEST len,
167 ULONGEST *xfered_len);
169 /* FIXME: kettenis/20031023: Eventually this field should
170 disappear. */
171 struct gdbarch *m_core_gdbarch = NULL;
174 core_target::core_target ()
176 /* Find a first arch based on the BFD. We need the initial gdbarch so
177 we can setup the hooks to find a target description. */
178 m_core_gdbarch = gdbarch_from_bfd (current_program_space->core_bfd ());
180 /* If the arch is able to read a target description from the core, it
181 could yield a more specific gdbarch. */
182 const struct target_desc *tdesc = read_description ();
184 if (tdesc != nullptr)
186 struct gdbarch_info info;
187 info.abfd = current_program_space->core_bfd ();
188 info.target_desc = tdesc;
189 m_core_gdbarch = gdbarch_find_by_info (info);
192 if (!m_core_gdbarch
193 || !gdbarch_iterate_over_regset_sections_p (m_core_gdbarch))
194 error (_("\"%s\": Core file format not supported"),
195 bfd_get_filename (current_program_space->core_bfd ()));
197 /* Find the data section */
198 m_core_section_table = build_section_table (current_program_space->core_bfd ());
200 build_file_mappings ();
203 /* Construct the table for file-backed mappings if they exist.
205 For each unique path in the note, we'll open a BFD with a bfd
206 target of "binary". This is an unstructured bfd target upon which
207 we'll impose a structure from the mappings in the architecture-specific
208 mappings note. A BFD section is allocated and initialized for each
209 file-backed mapping.
211 We take care to not share already open bfds with other parts of
212 GDB; in particular, we don't want to add new sections to existing
213 BFDs. We do, however, ensure that the BFDs that we allocate here
214 will go away (be deallocated) when the core target is detached. */
216 void
217 core_target::build_file_mappings ()
219 std::unordered_map<std::string, struct bfd *> bfd_map;
220 std::unordered_set<std::string> unavailable_paths;
222 /* See linux_read_core_file_mappings() in linux-tdep.c for an example
223 read_core_file_mappings method. */
224 gdbarch_read_core_file_mappings (m_core_gdbarch,
225 current_program_space->core_bfd (),
227 /* After determining the number of mappings, read_core_file_mappings
228 will invoke this lambda. */
229 [&] (ULONGEST)
233 /* read_core_file_mappings will invoke this lambda for each mapping
234 that it finds. */
235 [&] (int num, ULONGEST start, ULONGEST end, ULONGEST file_ofs,
236 const char *filename, const bfd_build_id *build_id)
238 /* Architecture-specific read_core_mapping methods are expected to
239 weed out non-file-backed mappings. */
240 gdb_assert (filename != nullptr);
242 if (unavailable_paths.find (filename) != unavailable_paths.end ())
244 /* We have already seen some mapping for FILENAME but failed to
245 find/open the file. There is no point in trying the same
246 thing again so just record that the range [start, end) is
247 unavailable. */
248 m_core_unavailable_mappings.emplace_back (start, end - start);
249 return;
252 struct bfd *bfd = bfd_map[filename];
253 if (bfd == nullptr)
255 /* Use exec_file_find() to do sysroot expansion. It'll
256 also strip the potential sysroot "target:" prefix. If
257 there is no sysroot, an equivalent (possibly more
258 canonical) pathname will be provided. */
259 gdb::unique_xmalloc_ptr<char> expanded_fname
260 = exec_file_find (filename, NULL);
262 if (expanded_fname == nullptr && build_id != nullptr)
263 debuginfod_exec_query (build_id->data, build_id->size,
264 filename, &expanded_fname);
266 if (expanded_fname == nullptr)
268 m_core_unavailable_mappings.emplace_back (start, end - start);
269 unavailable_paths.insert (filename);
270 warning (_("Can't open file %s during file-backed mapping "
271 "note processing"),
272 filename);
273 return;
276 bfd = bfd_openr (expanded_fname.get (), "binary");
278 if (bfd == nullptr || !bfd_check_format (bfd, bfd_object))
280 m_core_unavailable_mappings.emplace_back (start, end - start);
281 unavailable_paths.insert (filename);
282 warning (_("Can't open file %s which was expanded to %s "
283 "during file-backed mapping note processing"),
284 filename, expanded_fname.get ());
286 if (bfd != nullptr)
287 bfd_close (bfd);
288 return;
290 /* Ensure that the bfd will be closed when core_bfd is closed.
291 This can be checked before/after a core file detach via
292 "maint info bfds". */
293 gdb_bfd_record_inclusion (current_program_space->core_bfd (), bfd);
294 bfd_map[filename] = bfd;
297 /* Make new BFD section. All sections have the same name,
298 which is permitted by bfd_make_section_anyway(). */
299 asection *sec = bfd_make_section_anyway (bfd, "load");
300 if (sec == nullptr)
301 error (_("Can't make section"));
302 sec->filepos = file_ofs;
303 bfd_set_section_flags (sec, SEC_READONLY | SEC_HAS_CONTENTS);
304 bfd_set_section_size (sec, end - start);
305 bfd_set_section_vma (sec, start);
306 bfd_set_section_lma (sec, start);
307 bfd_set_section_alignment (sec, 2);
309 /* Set target_section fields. */
310 m_core_file_mappings.emplace_back (start, end, sec);
312 /* If this is a bfd of a shared library, record its soname
313 and build id. */
314 if (build_id != nullptr)
316 gdb::unique_xmalloc_ptr<char> soname
317 = gdb_bfd_read_elf_soname (bfd->filename);
318 if (soname != nullptr)
319 set_cbfd_soname_build_id (current_program_space->cbfd,
320 soname.get (), build_id);
324 normalize_mem_ranges (&m_core_unavailable_mappings);
327 /* An arbitrary identifier for the core inferior. */
328 #define CORELOW_PID 1
330 void
331 core_target::clear_core ()
333 if (current_program_space->core_bfd () != nullptr)
335 switch_to_no_thread (); /* Avoid confusion from thread
336 stuff. */
337 exit_inferior (current_inferior ());
339 /* Clear out solib state while the bfd is still open. See
340 comments in clear_solib in solib.c. */
341 clear_solib (current_program_space);
343 current_program_space->cbfd.reset (nullptr);
347 /* Close the core target. */
349 void
350 core_target::close ()
352 clear_core ();
354 /* Core targets are heap-allocated (see core_target_open), so here
355 we delete ourselves. */
356 delete this;
359 /* Look for sections whose names start with `.reg/' so that we can
360 extract the list of threads in a core file. */
362 /* If ASECT is a section whose name begins with '.reg/' then extract the
363 lwpid after the '/' and create a new thread in INF.
365 If REG_SECT is not nullptr, and the both ASECT and REG_SECT point at the
366 same position in the parent bfd object then switch to the newly created
367 thread, otherwise, the selected thread is left unchanged. */
369 static void
370 add_to_thread_list (asection *asect, asection *reg_sect, inferior *inf)
372 if (!startswith (bfd_section_name (asect), ".reg/"))
373 return;
375 int lwpid = atoi (bfd_section_name (asect) + 5);
376 ptid_t ptid (inf->pid, lwpid);
377 thread_info *thr = add_thread (inf->process_target (), ptid);
379 /* Warning, Will Robinson, looking at BFD private data! */
381 if (reg_sect != NULL
382 && asect->filepos == reg_sect->filepos) /* Did we find .reg? */
383 switch_to_thread (thr); /* Yes, make it current. */
386 /* Issue a message saying we have no core to debug, if FROM_TTY. */
388 static void
389 maybe_say_no_core_file_now (int from_tty)
391 if (from_tty)
392 gdb_printf (_("No core file now.\n"));
395 /* Backward compatibility with old way of specifying core files. */
397 void
398 core_file_command (const char *filename, int from_tty)
400 dont_repeat (); /* Either way, seems bogus. */
402 if (filename == NULL)
404 if (current_program_space->core_bfd () != nullptr)
406 target_detach (current_inferior (), from_tty);
407 gdb_assert (current_program_space->core_bfd () == nullptr);
409 else
410 maybe_say_no_core_file_now (from_tty);
412 else
413 core_target_open (filename, from_tty);
416 /* A vmcore file is a core file created by the Linux kernel at the point of
417 a crash. Each thread in the core file represents a real CPU core, and
418 the lwpid for each thread is the pid of the process that was running on
419 that core at the moment of the crash.
421 However, not every CPU core will have been running a process, some cores
422 will be idle. For these idle cores the CPU writes an lwpid of 0. And
423 of course, multiple cores might be idle, so there could be multiple
424 threads with an lwpid of 0.
426 The problem is GDB doesn't really like threads with an lwpid of 0; GDB
427 presents such a thread as a process rather than a thread. And GDB
428 certainly doesn't like multiple threads having the same lwpid, each time
429 a new thread is seen with the same lwpid the earlier thread (with the
430 same lwpid) will be deleted.
432 This function addresses both of these problems by assigning a fake lwpid
433 to any thread with an lwpid of 0.
435 GDB finds the lwpid information by looking at the bfd section names
436 which include the lwpid, e.g. .reg/NN where NN is the lwpid. This
437 function looks though all the section names looking for sections named
438 .reg/NN. If any sections are found where NN == 0, then we assign a new
439 unique value of NN. Then, in a second pass, any sections ending /0 are
440 assigned their new number.
442 Remember, a core file may contain multiple register sections for
443 different register sets, but the sets are always grouped by thread, so
444 we can figure out which registers should be assigned the same new
445 lwpid. For example, consider a core file containing:
447 .reg/0, .reg2/0, .reg/0, .reg2/0
449 This represents two threads, each thread contains a .reg and .reg2
450 register set. The .reg represents the start of each thread. After
451 renaming the sections will now look like this:
453 .reg/1, .reg2/1, .reg/2, .reg2/2
455 After calling this function the rest of the core file handling code can
456 treat this core file just like any other core file. */
458 static void
459 rename_vmcore_idle_reg_sections (bfd *abfd, inferior *inf)
461 /* Map from the bfd section to its lwpid (the /NN number). */
462 std::vector<std::pair<asection *, int>> sections_and_lwpids;
464 /* The set of all /NN numbers found. Needed so we can easily find unused
465 numbers in the case that we need to rename some sections. */
466 std::unordered_set<int> all_lwpids;
468 /* A count of how many sections called .reg/0 we have found. */
469 unsigned zero_lwpid_count = 0;
471 /* Look for all the .reg sections. Record the section object and the
472 lwpid which is extracted from the section name. Spot if any have an
473 lwpid of zero. */
474 for (asection *sect : gdb_bfd_sections (current_program_space->core_bfd ()))
476 if (startswith (bfd_section_name (sect), ".reg/"))
478 int lwpid = atoi (bfd_section_name (sect) + 5);
479 sections_and_lwpids.emplace_back (sect, lwpid);
480 all_lwpids.insert (lwpid);
481 if (lwpid == 0)
482 zero_lwpid_count++;
486 /* If every ".reg/NN" section has a non-zero lwpid then we don't need to
487 do any renaming. */
488 if (zero_lwpid_count == 0)
489 return;
491 /* Assign a new number to any .reg sections with an lwpid of 0. */
492 int new_lwpid = 1;
493 for (auto &sect_and_lwpid : sections_and_lwpids)
494 if (sect_and_lwpid.second == 0)
496 while (all_lwpids.find (new_lwpid) != all_lwpids.end ())
497 new_lwpid++;
498 sect_and_lwpid.second = new_lwpid;
499 new_lwpid++;
502 /* Now update the names of any sections with an lwpid of 0. This is
503 more than just the .reg sections we originally found. */
504 std::string replacement_lwpid_str;
505 auto iter = sections_and_lwpids.begin ();
506 int replacement_lwpid = 0;
507 for (asection *sect : gdb_bfd_sections (current_program_space->core_bfd ()))
509 if (iter != sections_and_lwpids.end () && sect == iter->first)
511 gdb_assert (startswith (bfd_section_name (sect), ".reg/"));
513 int lwpid = atoi (bfd_section_name (sect) + 5);
514 if (lwpid == iter->second)
516 /* This section was not given a new number. */
517 gdb_assert (lwpid != 0);
518 replacement_lwpid = 0;
520 else
522 replacement_lwpid = iter->second;
523 ptid_t ptid (inf->pid, replacement_lwpid);
524 if (!replacement_lwpid_str.empty ())
525 replacement_lwpid_str += ", ";
526 replacement_lwpid_str += target_pid_to_str (ptid);
529 iter++;
532 if (replacement_lwpid != 0)
534 const char *name = bfd_section_name (sect);
535 size_t len = strlen (name);
537 if (strncmp (name + len - 2, "/0", 2) == 0)
539 /* This section needs a new name. */
540 std::string name_str
541 = string_printf ("%.*s/%d",
542 static_cast<int> (len - 2),
543 name, replacement_lwpid);
544 char *name_buf
545 = static_cast<char *> (bfd_alloc (abfd, name_str.size () + 1));
546 if (name_buf == nullptr)
547 error (_("failed to allocate space for section name '%s'"),
548 name_str.c_str ());
549 memcpy (name_buf, name_str.c_str(), name_str.size () + 1);
550 bfd_rename_section (sect, name_buf);
555 if (zero_lwpid_count == 1)
556 warning (_("found thread with pid 0, assigned replacement Target Id: %s"),
557 replacement_lwpid_str.c_str ());
558 else
559 warning (_("found threads with pid 0, assigned replacement Target Ids: %s"),
560 replacement_lwpid_str.c_str ());
563 /* Locate (and load) an executable file (and symbols) given the core file
564 BFD ABFD. */
566 static void
567 locate_exec_from_corefile_build_id (bfd *abfd, int from_tty)
569 const bfd_build_id *build_id = build_id_bfd_get (abfd);
570 if (build_id == nullptr)
571 return;
573 gdb_bfd_ref_ptr execbfd
574 = build_id_to_exec_bfd (build_id->size, build_id->data);
576 if (execbfd == nullptr)
578 /* Attempt to query debuginfod for the executable. */
579 gdb::unique_xmalloc_ptr<char> execpath;
580 scoped_fd fd = debuginfod_exec_query (build_id->data, build_id->size,
581 abfd->filename, &execpath);
583 if (fd.get () >= 0)
585 execbfd = gdb_bfd_open (execpath.get (), gnutarget);
587 if (execbfd == nullptr)
588 warning (_("\"%s\" from debuginfod cannot be opened as bfd: %s"),
589 execpath.get (),
590 gdb_bfd_errmsg (bfd_get_error (), nullptr).c_str ());
591 else if (!build_id_verify (execbfd.get (), build_id->size,
592 build_id->data))
593 execbfd.reset (nullptr);
597 if (execbfd != nullptr)
599 exec_file_attach (bfd_get_filename (execbfd.get ()), from_tty);
600 symbol_file_add_main (bfd_get_filename (execbfd.get ()),
601 symfile_add_flag (from_tty ? SYMFILE_VERBOSE : 0));
605 /* See gdbcore.h. */
607 void
608 core_target_open (const char *arg, int from_tty)
610 const char *p;
611 int siggy;
612 int scratch_chan;
613 int flags;
615 target_preopen (from_tty);
616 if (!arg)
618 if (current_program_space->core_bfd ())
619 error (_("No core file specified. (Use `detach' "
620 "to stop debugging a core file.)"));
621 else
622 error (_("No core file specified."));
625 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (arg));
626 if (strlen (filename.get ()) != 0
627 && !IS_ABSOLUTE_PATH (filename.get ()))
628 filename = make_unique_xstrdup (gdb_abspath (filename.get ()).c_str ());
630 flags = O_BINARY | O_LARGEFILE;
631 if (write_files)
632 flags |= O_RDWR;
633 else
634 flags |= O_RDONLY;
635 scratch_chan = gdb_open_cloexec (filename.get (), flags, 0).release ();
636 if (scratch_chan < 0)
637 perror_with_name (filename.get ());
639 gdb_bfd_ref_ptr temp_bfd (gdb_bfd_fopen (filename.get (), gnutarget,
640 write_files ? FOPEN_RUB : FOPEN_RB,
641 scratch_chan));
642 if (temp_bfd == NULL)
643 perror_with_name (filename.get ());
645 if (!bfd_check_format (temp_bfd.get (), bfd_core))
647 /* Do it after the err msg */
648 /* FIXME: should be checking for errors from bfd_close (for one
649 thing, on error it does not free all the storage associated
650 with the bfd). */
651 error (_("\"%s\" is not a core dump: %s"),
652 filename.get (), bfd_errmsg (bfd_get_error ()));
655 current_program_space->cbfd = std::move (temp_bfd);
657 core_target *target = new core_target ();
659 /* Own the target until it is successfully pushed. */
660 target_ops_up target_holder (target);
662 validate_files ();
664 /* If we have no exec file, try to set the architecture from the
665 core file. We don't do this unconditionally since an exec file
666 typically contains more information that helps us determine the
667 architecture than a core file. */
668 if (!current_program_space->exec_bfd ())
669 set_gdbarch_from_file (current_program_space->core_bfd ());
671 current_inferior ()->push_target (std::move (target_holder));
673 switch_to_no_thread ();
675 /* Need to flush the register cache (and the frame cache) from a
676 previous debug session. If inferior_ptid ends up the same as the
677 last debug session --- e.g., b foo; run; gcore core1; step; gcore
678 core2; core core1; core core2 --- then there's potential for
679 get_current_regcache to return the cached regcache of the
680 previous session, and the frame cache being stale. */
681 registers_changed ();
683 /* Find (or fake) the pid for the process in this core file, and
684 initialise the current inferior with that pid. */
685 bool fake_pid_p = false;
686 int pid = bfd_core_file_pid (current_program_space->core_bfd ());
687 if (pid == 0)
689 fake_pid_p = true;
690 pid = CORELOW_PID;
693 inferior *inf = current_inferior ();
694 gdb_assert (inf->pid == 0);
695 inferior_appeared (inf, pid);
696 inf->fake_pid_p = fake_pid_p;
698 /* Rename any .reg/0 sections, giving them each a fake lwpid. */
699 rename_vmcore_idle_reg_sections (current_program_space->core_bfd (), inf);
701 /* Build up thread list from BFD sections, and possibly set the
702 current thread to the .reg/NN section matching the .reg
703 section. */
704 asection *reg_sect
705 = bfd_get_section_by_name (current_program_space->core_bfd (), ".reg");
706 for (asection *sect : gdb_bfd_sections (current_program_space->core_bfd ()))
707 add_to_thread_list (sect, reg_sect, inf);
709 if (inferior_ptid == null_ptid)
711 /* Either we found no .reg/NN section, and hence we have a
712 non-threaded core (single-threaded, from gdb's perspective),
713 or for some reason add_to_thread_list couldn't determine
714 which was the "main" thread. The latter case shouldn't
715 usually happen, but we're dealing with input here, which can
716 always be broken in different ways. */
717 thread_info *thread = first_thread_of_inferior (inf);
719 if (thread == NULL)
720 thread = add_thread_silent (target, ptid_t (CORELOW_PID));
722 switch_to_thread (thread);
725 if (current_program_space->exec_bfd () == nullptr)
726 locate_exec_from_corefile_build_id (current_program_space->core_bfd (),
727 from_tty);
729 post_create_inferior (from_tty);
731 /* Now go through the target stack looking for threads since there
732 may be a thread_stratum target loaded on top of target core by
733 now. The layer above should claim threads found in the BFD
734 sections. */
737 target_update_thread_list ();
740 catch (const gdb_exception_error &except)
742 exception_print (gdb_stderr, except);
745 p = bfd_core_file_failing_command (current_program_space->core_bfd ());
746 if (p)
747 gdb_printf (_("Core was generated by `%s'.\n"), p);
749 /* Clearing any previous state of convenience variables. */
750 clear_exit_convenience_vars ();
752 siggy = bfd_core_file_failing_signal (current_program_space->core_bfd ());
753 if (siggy > 0)
755 gdbarch *core_gdbarch = target->core_gdbarch ();
757 /* If we don't have a CORE_GDBARCH to work with, assume a native
758 core (map gdb_signal from host signals). If we do have
759 CORE_GDBARCH to work with, but no gdb_signal_from_target
760 implementation for that gdbarch, as a fallback measure,
761 assume the host signal mapping. It'll be correct for native
762 cores, but most likely incorrect for cross-cores. */
763 enum gdb_signal sig = (core_gdbarch != NULL
764 && gdbarch_gdb_signal_from_target_p (core_gdbarch)
765 ? gdbarch_gdb_signal_from_target (core_gdbarch,
766 siggy)
767 : gdb_signal_from_host (siggy));
769 gdb_printf (_("Program terminated with signal %s, %s"),
770 gdb_signal_to_name (sig), gdb_signal_to_string (sig));
771 if (gdbarch_report_signal_info_p (core_gdbarch))
772 gdbarch_report_signal_info (core_gdbarch, current_uiout, sig);
773 gdb_printf (_(".\n"));
775 /* Set the value of the internal variable $_exitsignal,
776 which holds the signal uncaught by the inferior. */
777 set_internalvar_integer (lookup_internalvar ("_exitsignal"),
778 siggy);
781 /* Fetch all registers from core file. */
782 target_fetch_registers (get_thread_regcache (inferior_thread ()), -1);
784 /* Now, set up the frame cache, and print the top of stack. */
785 reinit_frame_cache ();
786 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
788 /* Current thread should be NUM 1 but the user does not know that.
789 If a program is single threaded gdb in general does not mention
790 anything about threads. That is why the test is >= 2. */
791 if (thread_count (target) >= 2)
795 thread_command (NULL, from_tty);
797 catch (const gdb_exception_error &except)
799 exception_print (gdb_stderr, except);
804 void
805 core_target::detach (inferior *inf, int from_tty)
807 /* Get rid of the core. Don't rely on core_target::close doing it,
808 because target_detach may be called with core_target's refcount > 1,
809 meaning core_target::close may not be called yet by the
810 unpush_target call below. */
811 clear_core ();
813 /* Note that 'this' may be dangling after this call. unpush_target
814 closes the target if the refcount reaches 0, and our close
815 implementation deletes 'this'. */
816 inf->unpush_target (this);
818 /* Clear the register cache and the frame cache. */
819 registers_changed ();
820 reinit_frame_cache ();
821 maybe_say_no_core_file_now (from_tty);
824 /* Try to retrieve registers from a section in core_bfd, and supply
825 them to REGSET.
827 If ptid's lwp member is zero, do the single-threaded
828 thing: look for a section named NAME. If ptid's lwp
829 member is non-zero, do the multi-threaded thing: look for a section
830 named "NAME/LWP", where LWP is the shortest ASCII decimal
831 representation of ptid's lwp member.
833 HUMAN_NAME is a human-readable name for the kind of registers the
834 NAME section contains, for use in error messages.
836 If REQUIRED is true, print an error if the core file doesn't have a
837 section by the appropriate name. Otherwise, just do nothing. */
839 void
840 core_target::get_core_register_section (struct regcache *regcache,
841 const struct regset *regset,
842 const char *name,
843 int section_min_size,
844 const char *human_name,
845 bool required)
847 gdb_assert (regset != nullptr);
849 struct bfd_section *section;
850 bfd_size_type size;
851 bool variable_size_section = (regset->flags & REGSET_VARIABLE_SIZE);
853 thread_section_name section_name (name, regcache->ptid ());
855 section = bfd_get_section_by_name (current_program_space->core_bfd (),
856 section_name.c_str ());
857 if (! section)
859 if (required)
860 warning (_("Couldn't find %s registers in core file."),
861 human_name);
862 return;
865 size = bfd_section_size (section);
866 if (size < section_min_size)
868 warning (_("Section `%s' in core file too small."),
869 section_name.c_str ());
870 return;
872 if (size != section_min_size && !variable_size_section)
874 warning (_("Unexpected size of section `%s' in core file."),
875 section_name.c_str ());
878 gdb::byte_vector contents (size);
879 if (!bfd_get_section_contents (current_program_space->core_bfd (), section,
880 contents.data (), (file_ptr) 0, size))
882 warning (_("Couldn't read %s registers from `%s' section in core file."),
883 human_name, section_name.c_str ());
884 return;
887 regset->supply_regset (regset, regcache, -1, contents.data (), size);
890 /* Data passed to gdbarch_iterate_over_regset_sections's callback. */
891 struct get_core_registers_cb_data
893 core_target *target;
894 struct regcache *regcache;
897 /* Callback for get_core_registers that handles a single core file
898 register note section. */
900 static void
901 get_core_registers_cb (const char *sect_name, int supply_size, int collect_size,
902 const struct regset *regset,
903 const char *human_name, void *cb_data)
905 gdb_assert (regset != nullptr);
907 auto *data = (get_core_registers_cb_data *) cb_data;
908 bool required = false;
909 bool variable_size_section = (regset->flags & REGSET_VARIABLE_SIZE);
911 if (!variable_size_section)
912 gdb_assert (supply_size == collect_size);
914 if (strcmp (sect_name, ".reg") == 0)
916 required = true;
917 if (human_name == NULL)
918 human_name = "general-purpose";
920 else if (strcmp (sect_name, ".reg2") == 0)
922 if (human_name == NULL)
923 human_name = "floating-point";
926 data->target->get_core_register_section (data->regcache, regset, sect_name,
927 supply_size, human_name, required);
930 /* Get the registers out of a core file. This is the machine-
931 independent part. Fetch_core_registers is the machine-dependent
932 part, typically implemented in the xm-file for each
933 architecture. */
935 /* We just get all the registers, so we don't use regno. */
937 void
938 core_target::fetch_registers (struct regcache *regcache, int regno)
940 if (!(m_core_gdbarch != nullptr
941 && gdbarch_iterate_over_regset_sections_p (m_core_gdbarch)))
943 gdb_printf (gdb_stderr,
944 "Can't fetch registers from this type of core file\n");
945 return;
948 struct gdbarch *gdbarch = regcache->arch ();
949 get_core_registers_cb_data data = { this, regcache };
950 gdbarch_iterate_over_regset_sections (gdbarch,
951 get_core_registers_cb,
952 (void *) &data, NULL);
954 /* Mark all registers not found in the core as unavailable. */
955 for (int i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
956 if (regcache->get_register_status (i) == REG_UNKNOWN)
957 regcache->raw_supply (i, NULL);
960 void
961 core_target::files_info ()
963 print_section_info (&m_core_section_table, current_program_space->core_bfd ());
966 /* Helper method for core_target::xfer_partial. */
968 enum target_xfer_status
969 core_target::xfer_memory_via_mappings (gdb_byte *readbuf,
970 const gdb_byte *writebuf,
971 ULONGEST offset, ULONGEST len,
972 ULONGEST *xfered_len)
974 enum target_xfer_status xfer_status;
976 xfer_status = (section_table_xfer_memory_partial
977 (readbuf, writebuf,
978 offset, len, xfered_len,
979 m_core_file_mappings));
981 if (xfer_status == TARGET_XFER_OK || m_core_unavailable_mappings.empty ())
982 return xfer_status;
984 /* There are instances - e.g. when debugging within a docker
985 container using the AUFS storage driver - where the pathnames
986 obtained from the note section are incorrect. Despite the path
987 being wrong, just knowing the start and end addresses of the
988 mappings is still useful; we can attempt an access of the file
989 stratum constrained to the address ranges corresponding to the
990 unavailable mappings. */
992 ULONGEST memaddr = offset;
993 ULONGEST memend = offset + len;
995 for (const auto &mr : m_core_unavailable_mappings)
997 if (address_in_mem_range (memaddr, &mr))
999 if (!address_in_mem_range (memend, &mr))
1000 len = mr.start + mr.length - memaddr;
1002 xfer_status = this->beneath ()->xfer_partial (TARGET_OBJECT_MEMORY,
1003 NULL,
1004 readbuf,
1005 writebuf,
1006 offset,
1007 len,
1008 xfered_len);
1009 break;
1013 return xfer_status;
1016 enum target_xfer_status
1017 core_target::xfer_partial (enum target_object object, const char *annex,
1018 gdb_byte *readbuf, const gdb_byte *writebuf,
1019 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
1021 switch (object)
1023 case TARGET_OBJECT_MEMORY:
1025 enum target_xfer_status xfer_status;
1027 /* Try accessing memory contents from core file data,
1028 restricting consideration to those sections for which
1029 the BFD section flag SEC_HAS_CONTENTS is set. */
1030 auto has_contents_cb = [] (const struct target_section *s)
1032 return ((s->the_bfd_section->flags & SEC_HAS_CONTENTS) != 0);
1034 xfer_status = section_table_xfer_memory_partial
1035 (readbuf, writebuf,
1036 offset, len, xfered_len,
1037 m_core_section_table,
1038 has_contents_cb);
1039 if (xfer_status == TARGET_XFER_OK)
1040 return TARGET_XFER_OK;
1042 /* Check file backed mappings. If they're available, use
1043 core file provided mappings (e.g. from .note.linuxcore.file
1044 or the like) as this should provide a more accurate
1045 result. If not, check the stratum beneath us, which should
1046 be the file stratum.
1048 We also check unavailable mappings due to Docker/AUFS driver
1049 issues. */
1050 if (!m_core_file_mappings.empty ()
1051 || !m_core_unavailable_mappings.empty ())
1053 xfer_status = xfer_memory_via_mappings (readbuf, writebuf, offset,
1054 len, xfered_len);
1056 else
1057 xfer_status = this->beneath ()->xfer_partial (object, annex, readbuf,
1058 writebuf, offset, len,
1059 xfered_len);
1060 if (xfer_status == TARGET_XFER_OK)
1061 return TARGET_XFER_OK;
1063 /* Finally, attempt to access data in core file sections with
1064 no contents. These will typically read as all zero. */
1065 auto no_contents_cb = [&] (const struct target_section *s)
1067 return !has_contents_cb (s);
1069 xfer_status = section_table_xfer_memory_partial
1070 (readbuf, writebuf,
1071 offset, len, xfered_len,
1072 m_core_section_table,
1073 no_contents_cb);
1075 return xfer_status;
1077 case TARGET_OBJECT_AUXV:
1078 if (readbuf)
1080 /* When the aux vector is stored in core file, BFD
1081 represents this with a fake section called ".auxv". */
1083 struct bfd_section *section;
1084 bfd_size_type size;
1086 section = bfd_get_section_by_name (current_program_space->core_bfd (),
1087 ".auxv");
1088 if (section == NULL)
1089 return TARGET_XFER_E_IO;
1091 size = bfd_section_size (section);
1092 if (offset >= size)
1093 return TARGET_XFER_EOF;
1094 size -= offset;
1095 if (size > len)
1096 size = len;
1098 if (size == 0)
1099 return TARGET_XFER_EOF;
1100 if (!bfd_get_section_contents (current_program_space->core_bfd (),
1101 section, readbuf, (file_ptr) offset,
1102 size))
1104 warning (_("Couldn't read NT_AUXV note in core file."));
1105 return TARGET_XFER_E_IO;
1108 *xfered_len = (ULONGEST) size;
1109 return TARGET_XFER_OK;
1111 return TARGET_XFER_E_IO;
1113 case TARGET_OBJECT_WCOOKIE:
1114 if (readbuf)
1116 /* When the StackGhost cookie is stored in core file, BFD
1117 represents this with a fake section called
1118 ".wcookie". */
1120 struct bfd_section *section;
1121 bfd_size_type size;
1123 section = bfd_get_section_by_name (current_program_space->core_bfd (),
1124 ".wcookie");
1125 if (section == NULL)
1126 return TARGET_XFER_E_IO;
1128 size = bfd_section_size (section);
1129 if (offset >= size)
1130 return TARGET_XFER_EOF;
1131 size -= offset;
1132 if (size > len)
1133 size = len;
1135 if (size == 0)
1136 return TARGET_XFER_EOF;
1137 if (!bfd_get_section_contents (current_program_space->core_bfd (),
1138 section, readbuf, (file_ptr) offset,
1139 size))
1141 warning (_("Couldn't read StackGhost cookie in core file."));
1142 return TARGET_XFER_E_IO;
1145 *xfered_len = (ULONGEST) size;
1146 return TARGET_XFER_OK;
1149 return TARGET_XFER_E_IO;
1151 case TARGET_OBJECT_LIBRARIES:
1152 if (m_core_gdbarch != nullptr
1153 && gdbarch_core_xfer_shared_libraries_p (m_core_gdbarch))
1155 if (writebuf)
1156 return TARGET_XFER_E_IO;
1157 else
1159 *xfered_len = gdbarch_core_xfer_shared_libraries (m_core_gdbarch,
1160 readbuf,
1161 offset, len);
1163 if (*xfered_len == 0)
1164 return TARGET_XFER_EOF;
1165 else
1166 return TARGET_XFER_OK;
1169 return TARGET_XFER_E_IO;
1171 case TARGET_OBJECT_LIBRARIES_AIX:
1172 if (m_core_gdbarch != nullptr
1173 && gdbarch_core_xfer_shared_libraries_aix_p (m_core_gdbarch))
1175 if (writebuf)
1176 return TARGET_XFER_E_IO;
1177 else
1179 *xfered_len
1180 = gdbarch_core_xfer_shared_libraries_aix (m_core_gdbarch,
1181 readbuf, offset,
1182 len);
1184 if (*xfered_len == 0)
1185 return TARGET_XFER_EOF;
1186 else
1187 return TARGET_XFER_OK;
1190 return TARGET_XFER_E_IO;
1192 case TARGET_OBJECT_SIGNAL_INFO:
1193 if (readbuf)
1195 if (m_core_gdbarch != nullptr
1196 && gdbarch_core_xfer_siginfo_p (m_core_gdbarch))
1198 LONGEST l = gdbarch_core_xfer_siginfo (m_core_gdbarch, readbuf,
1199 offset, len);
1201 if (l >= 0)
1203 *xfered_len = l;
1204 if (l == 0)
1205 return TARGET_XFER_EOF;
1206 else
1207 return TARGET_XFER_OK;
1211 return TARGET_XFER_E_IO;
1213 default:
1214 return this->beneath ()->xfer_partial (object, annex, readbuf,
1215 writebuf, offset, len,
1216 xfered_len);
1222 /* Okay, let's be honest: threads gleaned from a core file aren't
1223 exactly lively, are they? On the other hand, if we don't claim
1224 that each & every one is alive, then we don't get any of them
1225 to appear in an "info thread" command, which is quite a useful
1226 behaviour.
1228 bool
1229 core_target::thread_alive (ptid_t ptid)
1231 return true;
1234 /* Ask the current architecture what it knows about this core file.
1235 That will be used, in turn, to pick a better architecture. This
1236 wrapper could be avoided if targets got a chance to specialize
1237 core_target. */
1239 const struct target_desc *
1240 core_target::read_description ()
1242 /* First check whether the target wants us to use the corefile target
1243 description notes. */
1244 if (gdbarch_use_target_description_from_corefile_notes
1245 (m_core_gdbarch, current_program_space->core_bfd ()))
1247 /* If the core file contains a target description note then go ahead and
1248 use that. */
1249 bfd_size_type tdesc_note_size = 0;
1250 struct bfd_section *tdesc_note_section
1251 = bfd_get_section_by_name (current_program_space->core_bfd (), ".gdb-tdesc");
1252 if (tdesc_note_section != nullptr)
1253 tdesc_note_size = bfd_section_size (tdesc_note_section);
1254 if (tdesc_note_size > 0)
1256 gdb::char_vector contents (tdesc_note_size + 1);
1257 if (bfd_get_section_contents (current_program_space->core_bfd (),
1258 tdesc_note_section, contents.data (),
1259 (file_ptr) 0, tdesc_note_size))
1261 /* Ensure we have a null terminator. */
1262 contents[tdesc_note_size] = '\0';
1263 const struct target_desc *result
1264 = string_read_description_xml (contents.data ());
1265 if (result != nullptr)
1266 return result;
1271 /* If the architecture provides a corefile target description hook, use
1272 it now. Even if the core file contains a target description in a note
1273 section, it is not useful for targets that can potentially have distinct
1274 descriptions for each thread. One example is AArch64's SVE/SME
1275 extensions that allow per-thread vector length changes, resulting in
1276 registers with different sizes. */
1277 if (m_core_gdbarch && gdbarch_core_read_description_p (m_core_gdbarch))
1279 const struct target_desc *result;
1281 result = gdbarch_core_read_description
1282 (m_core_gdbarch, this, current_program_space->core_bfd ());
1283 if (result != nullptr)
1284 return result;
1287 return this->beneath ()->read_description ();
1290 std::string
1291 core_target::pid_to_str (ptid_t ptid)
1293 struct inferior *inf;
1294 int pid;
1296 /* The preferred way is to have a gdbarch/OS specific
1297 implementation. */
1298 if (m_core_gdbarch != nullptr
1299 && gdbarch_core_pid_to_str_p (m_core_gdbarch))
1300 return gdbarch_core_pid_to_str (m_core_gdbarch, ptid);
1302 /* Otherwise, if we don't have one, we'll just fallback to
1303 "process", with normal_pid_to_str. */
1305 /* Try the LWPID field first. */
1306 pid = ptid.lwp ();
1307 if (pid != 0)
1308 return normal_pid_to_str (ptid_t (pid));
1310 /* Otherwise, this isn't a "threaded" core -- use the PID field, but
1311 only if it isn't a fake PID. */
1312 inf = find_inferior_ptid (this, ptid);
1313 if (inf != NULL && !inf->fake_pid_p)
1314 return normal_pid_to_str (ptid);
1316 /* No luck. We simply don't have a valid PID to print. */
1317 return "<main task>";
1320 const char *
1321 core_target::thread_name (struct thread_info *thr)
1323 if (m_core_gdbarch != nullptr
1324 && gdbarch_core_thread_name_p (m_core_gdbarch))
1325 return gdbarch_core_thread_name (m_core_gdbarch, thr);
1326 return NULL;
1329 bool
1330 core_target::has_memory ()
1332 return current_program_space->core_bfd () != nullptr;
1335 bool
1336 core_target::has_stack ()
1338 return current_program_space->core_bfd () != nullptr;
1341 bool
1342 core_target::has_registers ()
1344 return current_program_space->core_bfd () != nullptr;
1347 /* Implement the to_info_proc method. */
1349 bool
1350 core_target::info_proc (const char *args, enum info_proc_what request)
1352 struct gdbarch *gdbarch = get_current_arch ();
1354 /* Since this is the core file target, call the 'core_info_proc'
1355 method on gdbarch, not 'info_proc'. */
1356 if (gdbarch_core_info_proc_p (gdbarch))
1357 gdbarch_core_info_proc (gdbarch, args, request);
1359 return true;
1362 /* Implementation of the "supports_memory_tagging" target_ops method. */
1364 bool
1365 core_target::supports_memory_tagging ()
1367 /* Look for memory tag sections. If they exist, that means this core file
1368 supports memory tagging. */
1370 return (bfd_get_section_by_name (current_program_space->core_bfd (), "memtag")
1371 != nullptr);
1374 /* Implementation of the "fetch_memtags" target_ops method. */
1376 bool
1377 core_target::fetch_memtags (CORE_ADDR address, size_t len,
1378 gdb::byte_vector &tags, int type)
1380 gdbarch *gdbarch = current_inferior ()->arch ();
1382 /* Make sure we have a way to decode the memory tag notes. */
1383 if (!gdbarch_decode_memtag_section_p (gdbarch))
1384 error (_("gdbarch_decode_memtag_section not implemented for this "
1385 "architecture."));
1387 memtag_section_info info;
1388 info.memtag_section = nullptr;
1390 while (get_next_core_memtag_section (current_program_space->core_bfd (),
1391 info.memtag_section, address, info))
1393 size_t adjusted_length
1394 = (address + len < info.end_address) ? len : (info.end_address - address);
1396 /* Decode the memory tag note and return the tags. */
1397 gdb::byte_vector tags_read
1398 = gdbarch_decode_memtag_section (gdbarch, info.memtag_section, type,
1399 address, adjusted_length);
1401 /* Transfer over the tags that have been read. */
1402 tags.insert (tags.end (), tags_read.begin (), tags_read.end ());
1404 /* ADDRESS + LEN may cross the boundaries of a particular memory tag
1405 segment. Check if we need to fetch tags from a different section. */
1406 if (!tags_read.empty () && (address + len) < info.end_address)
1407 return true;
1409 /* There are more tags to fetch. Update ADDRESS and LEN. */
1410 len -= (info.end_address - address);
1411 address = info.end_address;
1414 return false;
1417 bool
1418 core_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
1420 return gdbarch_tagged_address_p (gdbarch, address);
1423 /* Implementation of the "fetch_x86_xsave_layout" target_ops method. */
1425 x86_xsave_layout
1426 core_target::fetch_x86_xsave_layout ()
1428 if (m_core_gdbarch != nullptr &&
1429 gdbarch_core_read_x86_xsave_layout_p (m_core_gdbarch))
1431 x86_xsave_layout layout;
1432 if (!gdbarch_core_read_x86_xsave_layout (m_core_gdbarch, layout))
1433 return {};
1435 return layout;
1438 return {};
1441 /* Get a pointer to the current core target. If not connected to a
1442 core target, return NULL. */
1444 static core_target *
1445 get_current_core_target ()
1447 target_ops *proc_target = current_inferior ()->process_target ();
1448 return dynamic_cast<core_target *> (proc_target);
1451 /* Display file backed mappings from core file. */
1453 void
1454 core_target::info_proc_mappings (struct gdbarch *gdbarch)
1456 if (!m_core_file_mappings.empty ())
1458 gdb_printf (_("Mapped address spaces:\n\n"));
1459 if (gdbarch_addr_bit (gdbarch) == 32)
1461 gdb_printf ("\t%10s %10s %10s %10s %s\n",
1462 "Start Addr",
1463 " End Addr",
1464 " Size", " Offset", "objfile");
1466 else
1468 gdb_printf (" %18s %18s %10s %10s %s\n",
1469 "Start Addr",
1470 " End Addr",
1471 " Size", " Offset", "objfile");
1475 for (const target_section &tsp : m_core_file_mappings)
1477 ULONGEST start = tsp.addr;
1478 ULONGEST end = tsp.endaddr;
1479 ULONGEST file_ofs = tsp.the_bfd_section->filepos;
1480 const char *filename = bfd_get_filename (tsp.the_bfd_section->owner);
1482 if (gdbarch_addr_bit (gdbarch) == 32)
1483 gdb_printf ("\t%10s %10s %10s %10s %s\n",
1484 paddress (gdbarch, start),
1485 paddress (gdbarch, end),
1486 hex_string (end - start),
1487 hex_string (file_ofs),
1488 filename);
1489 else
1490 gdb_printf (" %18s %18s %10s %10s %s\n",
1491 paddress (gdbarch, start),
1492 paddress (gdbarch, end),
1493 hex_string (end - start),
1494 hex_string (file_ofs),
1495 filename);
1499 /* Implement "maintenance print core-file-backed-mappings" command.
1501 If mappings are loaded, the results should be similar to the
1502 mappings shown by "info proc mappings". This command is mainly a
1503 debugging tool for GDB developers to make sure that the expected
1504 mappings are present after loading a core file. For Linux, the
1505 output provided by this command will be very similar (if not
1506 identical) to that provided by "info proc mappings". This is not
1507 necessarily the case for other OSes which might provide
1508 more/different information in the "info proc mappings" output. */
1510 static void
1511 maintenance_print_core_file_backed_mappings (const char *args, int from_tty)
1513 core_target *targ = get_current_core_target ();
1514 if (targ != nullptr)
1515 targ->info_proc_mappings (targ->core_gdbarch ());
1518 void _initialize_corelow ();
1519 void
1520 _initialize_corelow ()
1522 add_target (core_target_info, core_target_open, filename_completer);
1523 add_cmd ("core-file-backed-mappings", class_maintenance,
1524 maintenance_print_core_file_backed_mappings,
1525 _("Print core file's file-backed mappings."),
1526 &maintenanceprintlist);