1 /* Core dump and executable file functions below target vector, for GDB.
3 Copyright (C) 1986-2025 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"
23 #include "exceptions.h"
31 #include "process-stratum-target.h"
33 #include "gdbthread.h"
38 #include "readline/tilde.h"
40 #include "filenames.h"
41 #include "progspace.h"
44 #include "completer.h"
45 #include "gdbsupport/filestuff.h"
47 #include "gdbsupport/pathstuff.h"
48 #include "gdbsupport/scoped_fd.h"
49 #include "gdbsupport/x86-xstate.h"
50 #include "gdbsupport/unordered_map.h"
51 #include "gdbsupport/unordered_set.h"
52 #include "cli/cli-cmds.h"
53 #include "xml-tdesc.h"
55 #include "cli/cli-style.h"
61 /* Forward declarations. */
63 static void core_target_open (const char *arg
, int from_tty
);
65 /* A mem_range and the build-id associated with the file mapped into the
68 struct mem_range_and_build_id
70 mem_range_and_build_id (mem_range
&&r
, const bfd_build_id
*id
)
75 /* A range of memory addresses. */
78 /* The build-id of the file mapped into RANGE. */
79 const bfd_build_id
*build_id
;
82 /* An instance of this class is created within the core_target and is used
83 to hold all the information that relating to mapped files, their address
84 ranges, and their corresponding build-ids. */
86 struct mapped_file_info
88 /* See comment on function definition. */
90 void add (const char *soname
, const char *expected_filename
,
91 const char *actual_filename
, std::vector
<mem_range
> &&ranges
,
92 const bfd_build_id
*build_id
);
94 /* See comment on function definition. */
96 std::optional
<core_target_mapped_file_info
>
97 lookup (const char *filename
, const std::optional
<CORE_ADDR
> &addr
);
101 /* Helper for ::lookup. BUILD_ID is a build-id that was found in
102 one of the data structures within this class. Lookup the
103 corresponding filename in m_build_id_to_filename_map and return a pair
104 containing the build-id and filename.
106 If no corresponding filename is found in m_build_id_to_filename_map
107 then the returned pair contains BUILD_ID and an empty string.
109 If BUILD_ID is nullptr then the returned pair contains nullptr and an
112 struct core_target_mapped_file_info
113 make_result (const bfd_build_id
*build_id
)
115 if (build_id
!= nullptr)
117 auto it
= m_build_id_to_filename_map
.find (build_id
);
118 if (it
!= m_build_id_to_filename_map
.end ())
119 return { build_id
, it
->second
};
122 return { build_id
, {} };
125 /* A type that maps a string to a build-id. */
126 using string_to_build_id_map
127 = gdb::unordered_map
<std::string
, const bfd_build_id
*>;
129 /* A type that maps a build-id to a string. */
130 using build_id_to_string_map
131 = gdb::unordered_map
<const bfd_build_id
*, std::string
>;
133 /* When loading a core file, the build-ids are extracted based on the
134 file backed mappings. This map associates the name of a file that was
135 mapped into the core file with the corresponding build-id. The
136 build-id pointers in this map will never be nullptr as we only record
137 files if they have a build-id. */
139 string_to_build_id_map m_filename_to_build_id_map
;
141 /* Map a build-id pointer back to the name of the file that was mapped
142 into the inferior's address space. If we lookup a matching build-id
143 using either a soname or an address then this map allows us to also
144 provide a full path to a file with a matching build-id. */
146 build_id_to_string_map m_build_id_to_filename_map
;
148 /* If the file that was mapped into the core file was a shared library
149 then it might have a DT_SONAME tag in its .dynamic section, this tag
150 contains the name of a shared object. When opening a shared library,
151 if it's basename appears in this map then we can use the corresponding
154 In the rare case that two different files have the same DT_SONAME
155 value then the build-id pointer in this map will be nullptr, this
156 indicates that it's not possible to find a build-id based on the given
159 string_to_build_id_map m_soname_to_build_id_map
;
161 /* This vector maps memory ranges onto an associated build-id. The
162 ranges are those of the files mapped into the core file.
164 Entries in this vector must not overlap, and are sorted be increasing
165 memory address. Within each entry the build-id pointer will not be
168 While building this vector the entries are not sorted, they are
169 sorted once after the table has finished being built. */
171 std::vector
<mem_range_and_build_id
> m_address_to_build_id_list
;
173 /* False if address_to_build_id_list is unsorted, otherwise true. */
175 bool m_address_to_build_id_list_sorted
= false;
178 /* The core file target. */
180 static const target_info core_target_info
= {
182 N_("Local core dump file"),
183 N_("Use a core file as a target.\n\
184 Specify the filename of the core file.")
187 class core_target final
: public process_stratum_target
192 const target_info
&info () const override
193 { return core_target_info
; }
195 void close () override
;
196 void detach (inferior
*, int) override
;
197 void fetch_registers (struct regcache
*, int) override
;
199 enum target_xfer_status
xfer_partial (enum target_object object
,
202 const gdb_byte
*writebuf
,
203 ULONGEST offset
, ULONGEST len
,
204 ULONGEST
*xfered_len
) override
;
205 void files_info () override
;
207 bool thread_alive (ptid_t ptid
) override
;
208 const struct target_desc
*read_description () override
;
210 std::string
pid_to_str (ptid_t
) override
;
212 const char *thread_name (struct thread_info
*) override
;
214 bool has_all_memory () override
{ return true; }
215 bool has_memory () override
;
216 bool has_stack () override
;
217 bool has_registers () override
;
218 bool has_execution (inferior
*inf
) override
{ return false; }
220 bool info_proc (const char *, enum info_proc_what
) override
;
222 bool supports_memory_tagging () override
;
224 /* Core file implementation of fetch_memtags. Fetch the memory tags from
226 bool fetch_memtags (CORE_ADDR address
, size_t len
,
227 gdb::byte_vector
&tags
, int type
) override
;
229 /* If the architecture supports it, check if ADDRESS is within a memory range
230 mapped with tags. For example, MTE tags for AArch64. */
231 bool is_address_tagged (gdbarch
*gdbarch
, CORE_ADDR address
) override
;
233 x86_xsave_layout
fetch_x86_xsave_layout () override
;
237 /* Getter, see variable definition. */
238 struct gdbarch
*core_gdbarch ()
240 return m_core_gdbarch
;
243 /* See definition. */
244 void get_core_register_section (struct regcache
*regcache
,
245 const struct regset
*regset
,
247 int section_min_size
,
248 const char *human_name
,
251 /* See definition. */
252 void info_proc_mappings (struct gdbarch
*gdbarch
);
254 std::optional
<core_target_mapped_file_info
>
255 lookup_mapped_file_info (const char *filename
,
256 const std::optional
<CORE_ADDR
> &addr
)
258 return m_mapped_file_info
.lookup (filename
, addr
);
261 /* Return a string containing the expected executable filename obtained
262 from the mapped file information within the core file. The filename
263 returned will be for the mapped file whose ELF headers are mapped at
264 the lowest address (i.e. which GDB encounters first).
266 If no suitable filename can be found then the returned string will be
269 If there are no build-ids embedded into the core file then the
270 returned string will be empty.
272 If a non-empty string is returned then there is no guarantee that the
273 named file exists on disk, or if it does exist on disk, then the
274 on-disk file might have a different build-id to the desired
277 expected_exec_filename () const
279 return m_expected_exec_filename
;
282 private: /* per-core data */
284 /* Get rid of the core inferior. */
287 /* The core's section table. Note that these target sections are
288 *not* mapped in the current address spaces' set of target
289 sections --- those should come only from pure executable or
290 shared library bfds. The core bfd sections are an implementation
291 detail of the core target, just like ptrace is for unix child
293 std::vector
<target_section
> m_core_section_table
;
295 /* File-backed address space mappings: some core files include
296 information about memory mapped files. */
297 std::vector
<target_section
> m_core_file_mappings
;
299 /* Unavailable mappings. These correspond to pathnames which either
300 weren't found or could not be opened. Knowing these addresses can
302 std::vector
<mem_range
> m_core_unavailable_mappings
;
304 /* Data structure that holds information mapping filenames and address
305 ranges to the corresponding build-ids as well as the reverse build-id
306 to filename mapping. */
307 mapped_file_info m_mapped_file_info
;
309 /* Build m_core_file_mappings and m_mapped_file_info. Called from the
311 void build_file_mappings ();
313 /* FIXME: kettenis/20031023: Eventually this field should
315 struct gdbarch
*m_core_gdbarch
= NULL
;
317 /* If not empty then this contains the name of the executable discovered
318 when processing the memory-mapped file information. This will only
319 be set if we find a mapped with a suitable build-id. */
320 std::string m_expected_exec_filename
;
323 core_target::core_target ()
325 /* Find a first arch based on the BFD. We need the initial gdbarch so
326 we can setup the hooks to find a target description. */
327 m_core_gdbarch
= gdbarch_from_bfd (current_program_space
->core_bfd ());
329 /* If the arch is able to read a target description from the core, it
330 could yield a more specific gdbarch. */
331 const struct target_desc
*tdesc
= read_description ();
333 if (tdesc
!= nullptr)
335 struct gdbarch_info info
;
336 info
.abfd
= current_program_space
->core_bfd ();
337 info
.target_desc
= tdesc
;
338 m_core_gdbarch
= gdbarch_find_by_info (info
);
342 || !gdbarch_iterate_over_regset_sections_p (m_core_gdbarch
))
343 error (_("\"%s\": Core file format not supported"),
344 bfd_get_filename (current_program_space
->core_bfd ()));
346 /* Find the data section */
347 m_core_section_table
= build_section_table (current_program_space
->core_bfd ());
349 build_file_mappings ();
352 /* Construct the table for file-backed mappings if they exist.
354 For each unique path in the note, we'll open a BFD with a bfd
355 target of "binary". This is an unstructured bfd target upon which
356 we'll impose a structure from the mappings in the architecture-specific
357 mappings note. A BFD section is allocated and initialized for each
360 We take care to not share already open bfds with other parts of
361 GDB; in particular, we don't want to add new sections to existing
362 BFDs. We do, however, ensure that the BFDs that we allocate here
363 will go away (be deallocated) when the core target is detached. */
366 core_target::build_file_mappings ()
368 /* Type holding information about a single file mapped into the inferior
369 at the point when the core file was created. Associates a build-id
370 with the list of regions the file is mapped into. */
373 /* Type for a region of a file that was mapped into the inferior when
374 the core file was generated. */
377 /* Constructor. See member variables for argument descriptions. */
378 region (CORE_ADDR start_
, CORE_ADDR end_
, CORE_ADDR file_ofs_
)
384 /* The inferior address for the start of the mapped region. */
387 /* The inferior address immediately after the mapped region. */
390 /* The offset within the mapped file for this content. */
394 /* If not nullptr, then this is the build-id associated with this
396 const bfd_build_id
*build_id
= nullptr;
398 /* If true then we have seen multiple different build-ids associated
399 with the same filename. The build_id field will have been set back
400 to nullptr, and we should not set build_id in future. */
401 bool ignore_build_id_p
= false;
403 /* All the mapped regions of this file. */
404 std::vector
<region
> regions
;
407 gdb::unordered_map
<std::string
, struct bfd
*> bfd_map
;
408 gdb::unordered_set
<std::string
> unavailable_paths
;
410 /* All files mapped into the core file. The key is the filename. */
411 gdb::unordered_map
<std::string
, mapped_file
> mapped_files
;
413 /* See linux_read_core_file_mappings() in linux-tdep.c for an example
414 read_core_file_mappings method. */
415 gdbarch_read_core_file_mappings (m_core_gdbarch
,
416 current_program_space
->core_bfd (),
418 /* After determining the number of mappings, read_core_file_mappings
419 will invoke this lambda. */
424 /* read_core_file_mappings will invoke this lambda for each mapping
426 [&] (int num
, ULONGEST start
, ULONGEST end
, ULONGEST file_ofs
,
427 const char *filename
, const bfd_build_id
*build_id
)
429 /* Architecture-specific read_core_mapping methods are expected to
430 weed out non-file-backed mappings. */
431 gdb_assert (filename
!= nullptr);
433 /* Add this mapped region to the data for FILENAME. */
434 mapped_file
&file_data
= mapped_files
[filename
];
435 file_data
.regions
.emplace_back (start
, end
, file_ofs
);
436 if (build_id
!= nullptr && !file_data
.ignore_build_id_p
)
438 if (file_data
.build_id
== nullptr)
439 file_data
.build_id
= build_id
;
440 else if (!build_id_equal (build_id
, file_data
.build_id
))
442 warning (_("Multiple build-ids found for %ps"),
443 styled_string (file_name_style
.style (), filename
));
444 file_data
.build_id
= nullptr;
445 file_data
.ignore_build_id_p
= true;
450 /* Get the build-id of the core file. */
451 const bfd_build_id
*core_build_id
452 = build_id_bfd_get (current_program_space
->core_bfd ());
454 for (const auto &iter
: mapped_files
)
456 const std::string
&filename
= iter
.first
;
457 const mapped_file
&file_data
= iter
.second
;
459 /* If this mapped file has the same build-id as was discovered for
460 the core-file itself, then we assume this is the main
461 executable. Record the filename as we can use this later. */
462 if (file_data
.build_id
!= nullptr
463 && m_expected_exec_filename
.empty ()
464 && build_id_equal (file_data
.build_id
, core_build_id
))
465 m_expected_exec_filename
= filename
;
467 /* Use exec_file_find() to do sysroot expansion. It'll
468 also strip the potential sysroot "target:" prefix. If
469 there is no sysroot, an equivalent (possibly more
470 canonical) pathname will be provided. */
471 gdb::unique_xmalloc_ptr
<char> expanded_fname
472 = exec_file_find (filename
.c_str (), nullptr);
474 bool build_id_mismatch
= false;
475 if (expanded_fname
!= nullptr && file_data
.build_id
!= nullptr)
477 /* We temporarily open the bfd as a structured target, this
478 allows us to read the build-id from the bfd if there is one.
479 For this task it's OK if we reuse an already open bfd object,
480 so we make this call through GDB's bfd cache. Once we've
481 checked the build-id (if there is one) we'll drop this
482 reference and re-open the bfd using the "binary" target. */
483 gdb_bfd_ref_ptr tmp_bfd
484 = gdb_bfd_open (expanded_fname
.get (), gnutarget
);
486 if (tmp_bfd
!= nullptr
487 && bfd_check_format (tmp_bfd
.get (), bfd_object
)
488 && build_id_bfd_get (tmp_bfd
.get ()) != nullptr)
490 /* The newly opened TMP_BFD has a build-id, and this mapped
491 file has a build-id extracted from the core-file. Check
492 the build-id's match, and if not, reject TMP_BFD. */
493 const struct bfd_build_id
*found
494 = build_id_bfd_get (tmp_bfd
.get ());
495 if (!build_id_equal (found
, file_data
.build_id
))
496 build_id_mismatch
= true;
500 gdb_bfd_ref_ptr abfd
;
501 if (expanded_fname
!= nullptr && !build_id_mismatch
)
503 struct bfd
*b
= bfd_openr (expanded_fname
.get (), "binary");
504 abfd
= gdb_bfd_ref_ptr::new_reference (b
);
507 if ((expanded_fname
== nullptr
509 || !bfd_check_format (abfd
.get (), bfd_object
))
510 && file_data
.build_id
!= nullptr)
512 abfd
= find_objfile_by_build_id (current_program_space
,
518 /* The find_objfile_by_build_id will have opened ABFD using
519 the GNUTARGET global bfd type, however, we need the bfd
520 opened as the binary type (see the function's header
521 comment), so now we reopen ABFD with the desired binary
524 = make_unique_xstrdup (bfd_get_filename (abfd
.get ()));
525 struct bfd
*b
= bfd_openr (expanded_fname
.get (), "binary");
526 gdb_assert (b
!= nullptr);
527 abfd
= gdb_bfd_ref_ptr::new_reference (b
);
531 std::vector
<mem_range
> ranges
;
532 for (const mapped_file::region
®ion
: file_data
.regions
)
533 ranges
.emplace_back (region
.start
, region
.end
- region
.start
);
535 if (expanded_fname
== nullptr
537 || !bfd_check_format (abfd
.get (), bfd_object
))
539 /* If ABFD was opened, but the wrong format, close it now. */
542 /* When true, this indicates that the mapped contents of this
543 file are available within the core file. When false, some of
544 the mapped contents are not available. If the contents are
545 entirely available within the core file, then we don't need to
546 warn the user if GDB cannot find the file. */
547 bool content_is_in_core_file_p
= true;
549 /* Record all regions for this file as unavailable. */
550 for (const mapped_file::region
®ion
: file_data
.regions
)
552 /* Check to see if the region is available within the core
554 bool found_region_in_core_file
= false;
555 for (const target_section
&ts
: m_core_section_table
)
557 if (ts
.addr
<= region
.start
&& ts
.endaddr
>= region
.end
558 && (ts
.the_bfd_section
->flags
& SEC_HAS_CONTENTS
) != 0)
560 found_region_in_core_file
= true;
565 /* This region is not available within the core file.
566 Without the file available to read from it is not possible
567 for GDB to read this mapping within the inferior. Warn
568 the user about this case. */
569 if (!found_region_in_core_file
)
570 content_is_in_core_file_p
= false;
572 /* Record the unavailable region. */
573 m_core_unavailable_mappings
.emplace_back (region
.start
,
578 /* And give the user an appropriate warning. */
579 if (build_id_mismatch
)
581 if (expanded_fname
== nullptr
582 || filename
== expanded_fname
.get ())
583 warning (_("File %ps doesn't match build-id from core-file "
584 "during file-backed mapping processing"),
585 styled_string (file_name_style
.style (),
588 warning (_("File %ps which was expanded to %ps, doesn't match "
589 "build-id from core-file during file-backed "
590 "mapping processing"),
591 styled_string (file_name_style
.style (),
593 styled_string (file_name_style
.style (),
594 expanded_fname
.get ()));
596 else if (!content_is_in_core_file_p
)
598 if (expanded_fname
== nullptr
599 || filename
== expanded_fname
.get ())
600 warning (_("Can't open file %ps during file-backed mapping "
602 styled_string (file_name_style
.style (),
605 warning (_("Can't open file %ps which was expanded to %ps "
606 "during file-backed mapping note processing"),
607 styled_string (file_name_style
.style (),
609 styled_string (file_name_style
.style (),
610 expanded_fname
.get ()));
615 /* Ensure that the bfd will be closed when core_bfd is closed.
616 This can be checked before/after a core file detach via "maint
618 gdb_bfd_record_inclusion (current_program_space
->core_bfd (),
621 /* Create sections for each mapped region. */
622 for (const mapped_file::region
®ion
: file_data
.regions
)
624 /* Make new BFD section. All sections have the same name,
625 which is permitted by bfd_make_section_anyway(). */
626 asection
*sec
= bfd_make_section_anyway (abfd
.get (), "load");
628 error (_("Can't make section"));
629 sec
->filepos
= region
.file_ofs
;
630 bfd_set_section_flags (sec
, SEC_READONLY
| SEC_HAS_CONTENTS
);
631 bfd_set_section_size (sec
, region
.end
- region
.start
);
632 bfd_set_section_vma (sec
, region
.start
);
633 bfd_set_section_lma (sec
, region
.start
);
634 bfd_set_section_alignment (sec
, 2);
636 /* Set target_section fields. */
637 m_core_file_mappings
.emplace_back (region
.start
, region
.end
, sec
);
641 /* If this is a bfd with a build-id then record the filename,
642 optional soname (DT_SONAME .dynamic attribute), and the range of
643 addresses at which this bfd is mapped. This information can be
644 used to perform build-id checking when loading the shared
646 if (file_data
.build_id
!= nullptr)
648 normalize_mem_ranges (&ranges
);
650 const char *actual_filename
= nullptr;
651 gdb::unique_xmalloc_ptr
<char> soname
;
654 actual_filename
= bfd_get_filename (abfd
.get ());
655 soname
= gdb_bfd_read_elf_soname (actual_filename
);
658 m_mapped_file_info
.add (soname
.get (), filename
.c_str (),
659 actual_filename
, std::move (ranges
),
664 normalize_mem_ranges (&m_core_unavailable_mappings
);
667 /* An arbitrary identifier for the core inferior. */
668 #define CORELOW_PID 1
671 core_target::clear_core ()
673 if (current_program_space
->core_bfd () != nullptr)
675 switch_to_no_thread (); /* Avoid confusion from thread
677 exit_inferior (current_inferior ());
679 /* Clear out solib state while the bfd is still open. See
680 comments in clear_solib in solib.c. */
681 clear_solib (current_program_space
);
683 current_program_space
->cbfd
.reset (nullptr);
687 /* Close the core target. */
690 core_target::close ()
694 /* Core targets are heap-allocated (see core_target_open), so here
695 we delete ourselves. */
699 /* Look for sections whose names start with `.reg/' so that we can
700 extract the list of threads in a core file. */
702 /* If ASECT is a section whose name begins with '.reg/' then extract the
703 lwpid after the '/' and create a new thread in INF.
705 If REG_SECT is not nullptr, and the both ASECT and REG_SECT point at the
706 same position in the parent bfd object then switch to the newly created
707 thread, otherwise, the selected thread is left unchanged. */
710 add_to_thread_list (asection
*asect
, asection
*reg_sect
, inferior
*inf
)
712 if (!startswith (bfd_section_name (asect
), ".reg/"))
715 int lwpid
= atoi (bfd_section_name (asect
) + 5);
716 ptid_t
ptid (inf
->pid
, lwpid
);
717 thread_info
*thr
= add_thread (inf
->process_target (), ptid
);
719 /* Warning, Will Robinson, looking at BFD private data! */
722 && asect
->filepos
== reg_sect
->filepos
) /* Did we find .reg? */
723 switch_to_thread (thr
); /* Yes, make it current. */
726 /* Issue a message saying we have no core to debug, if FROM_TTY. */
729 maybe_say_no_core_file_now (int from_tty
)
732 gdb_printf (_("No core file now.\n"));
735 /* Backward compatibility with old way of specifying core files. */
738 core_file_command (const char *filename
, int from_tty
)
740 dont_repeat (); /* Either way, seems bogus. */
742 if (filename
== NULL
)
744 if (current_program_space
->core_bfd () != nullptr)
746 target_detach (current_inferior (), from_tty
);
747 gdb_assert (current_program_space
->core_bfd () == nullptr);
750 maybe_say_no_core_file_now (from_tty
);
753 core_target_open (filename
, from_tty
);
756 /* A vmcore file is a core file created by the Linux kernel at the point of
757 a crash. Each thread in the core file represents a real CPU core, and
758 the lwpid for each thread is the pid of the process that was running on
759 that core at the moment of the crash.
761 However, not every CPU core will have been running a process, some cores
762 will be idle. For these idle cores the CPU writes an lwpid of 0. And
763 of course, multiple cores might be idle, so there could be multiple
764 threads with an lwpid of 0.
766 The problem is GDB doesn't really like threads with an lwpid of 0; GDB
767 presents such a thread as a process rather than a thread. And GDB
768 certainly doesn't like multiple threads having the same lwpid, each time
769 a new thread is seen with the same lwpid the earlier thread (with the
770 same lwpid) will be deleted.
772 This function addresses both of these problems by assigning a fake lwpid
773 to any thread with an lwpid of 0.
775 GDB finds the lwpid information by looking at the bfd section names
776 which include the lwpid, e.g. .reg/NN where NN is the lwpid. This
777 function looks though all the section names looking for sections named
778 .reg/NN. If any sections are found where NN == 0, then we assign a new
779 unique value of NN. Then, in a second pass, any sections ending /0 are
780 assigned their new number.
782 Remember, a core file may contain multiple register sections for
783 different register sets, but the sets are always grouped by thread, so
784 we can figure out which registers should be assigned the same new
785 lwpid. For example, consider a core file containing:
787 .reg/0, .reg2/0, .reg/0, .reg2/0
789 This represents two threads, each thread contains a .reg and .reg2
790 register set. The .reg represents the start of each thread. After
791 renaming the sections will now look like this:
793 .reg/1, .reg2/1, .reg/2, .reg2/2
795 After calling this function the rest of the core file handling code can
796 treat this core file just like any other core file. */
799 rename_vmcore_idle_reg_sections (bfd
*abfd
, inferior
*inf
)
801 /* Map from the bfd section to its lwpid (the /NN number). */
802 std::vector
<std::pair
<asection
*, int>> sections_and_lwpids
;
804 /* The set of all /NN numbers found. Needed so we can easily find unused
805 numbers in the case that we need to rename some sections. */
806 gdb::unordered_set
<int> all_lwpids
;
808 /* A count of how many sections called .reg/0 we have found. */
809 unsigned zero_lwpid_count
= 0;
811 /* Look for all the .reg sections. Record the section object and the
812 lwpid which is extracted from the section name. Spot if any have an
814 for (asection
*sect
: gdb_bfd_sections (current_program_space
->core_bfd ()))
816 if (startswith (bfd_section_name (sect
), ".reg/"))
818 int lwpid
= atoi (bfd_section_name (sect
) + 5);
819 sections_and_lwpids
.emplace_back (sect
, lwpid
);
820 all_lwpids
.insert (lwpid
);
826 /* If every ".reg/NN" section has a non-zero lwpid then we don't need to
828 if (zero_lwpid_count
== 0)
831 /* Assign a new number to any .reg sections with an lwpid of 0. */
833 for (auto §_and_lwpid
: sections_and_lwpids
)
834 if (sect_and_lwpid
.second
== 0)
836 while (all_lwpids
.find (new_lwpid
) != all_lwpids
.end ())
838 sect_and_lwpid
.second
= new_lwpid
;
842 /* Now update the names of any sections with an lwpid of 0. This is
843 more than just the .reg sections we originally found. */
844 std::string replacement_lwpid_str
;
845 auto iter
= sections_and_lwpids
.begin ();
846 int replacement_lwpid
= 0;
847 for (asection
*sect
: gdb_bfd_sections (current_program_space
->core_bfd ()))
849 if (iter
!= sections_and_lwpids
.end () && sect
== iter
->first
)
851 gdb_assert (startswith (bfd_section_name (sect
), ".reg/"));
853 int lwpid
= atoi (bfd_section_name (sect
) + 5);
854 if (lwpid
== iter
->second
)
856 /* This section was not given a new number. */
857 gdb_assert (lwpid
!= 0);
858 replacement_lwpid
= 0;
862 replacement_lwpid
= iter
->second
;
863 ptid_t
ptid (inf
->pid
, replacement_lwpid
);
864 if (!replacement_lwpid_str
.empty ())
865 replacement_lwpid_str
+= ", ";
866 replacement_lwpid_str
+= target_pid_to_str (ptid
);
872 if (replacement_lwpid
!= 0)
874 const char *name
= bfd_section_name (sect
);
875 size_t len
= strlen (name
);
877 if (strncmp (name
+ len
- 2, "/0", 2) == 0)
879 /* This section needs a new name. */
881 = string_printf ("%.*s/%d",
882 static_cast<int> (len
- 2),
883 name
, replacement_lwpid
);
885 = static_cast<char *> (bfd_alloc (abfd
, name_str
.size () + 1));
886 if (name_buf
== nullptr)
887 error (_("failed to allocate space for section name '%s'"),
889 memcpy (name_buf
, name_str
.c_str(), name_str
.size () + 1);
890 bfd_rename_section (sect
, name_buf
);
895 if (zero_lwpid_count
== 1)
896 warning (_("found thread with pid 0, assigned replacement Target Id: %s"),
897 replacement_lwpid_str
.c_str ());
899 warning (_("found threads with pid 0, assigned replacement Target Ids: %s"),
900 replacement_lwpid_str
.c_str ());
903 /* Use CTX to try and find (and open) the executable file for the core file
904 CBFD. BUILD_ID is the build-id for CBFD which was already extracted by
907 Will return the opened executable or nullptr if the executable couldn't
910 static gdb_bfd_ref_ptr
911 locate_exec_from_corefile_exec_context (bfd
*cbfd
,
912 const bfd_build_id
*build_id
,
913 const core_file_exec_context
&ctx
)
915 /* CTX must be valid, and a valid context has an execfn() string. */
916 gdb_assert (ctx
.valid ());
917 gdb_assert (ctx
.execfn () != nullptr);
919 /* EXEC_NAME will be the command used to start the inferior. This might
920 not be an absolute path (but could be). */
921 const char *exec_name
= ctx
.execfn ();
923 /* Function to open FILENAME and check if its build-id matches BUILD_ID
924 from this enclosing scope. Returns the open BFD for filename if the
925 FILENAME has a matching build-id, otherwise, returns nullptr. */
926 const auto open_and_check_build_id
927 = [&build_id
] (const char *filename
) -> gdb_bfd_ref_ptr
929 /* Try to open a file. If this succeeds then we still need to perform
931 gdb_bfd_ref_ptr execbfd
= gdb_bfd_open (filename
, gnutarget
);
933 /* We managed to open a file, but if it's build-id doesn't match
934 BUILD_ID then we just cannot trust it's the right file. */
935 if (execbfd
!= nullptr)
937 const bfd_build_id
*other_build_id
= build_id_bfd_get (execbfd
.get ());
939 if (other_build_id
== nullptr
940 || !build_id_equal (other_build_id
, build_id
))
947 gdb_bfd_ref_ptr execbfd
;
949 /* If EXEC_NAME is absolute then try to open it now. Otherwise, see if
950 EXEC_NAME is a relative path from the location of the core file. This
951 is just a guess, the executable might not be here, but we still rely
952 on a build-id match in order to accept any executable we find; we
953 don't accept something just because it happens to be in the right
955 if (IS_ABSOLUTE_PATH (exec_name
))
956 execbfd
= open_and_check_build_id (exec_name
);
959 std::string p
= (gdb_ldirname (bfd_get_filename (cbfd
))
962 execbfd
= open_and_check_build_id (p
.c_str ());
965 /* If we haven't found the executable yet, then try checking to see if
966 the executable is in the same directory as the core file. Again,
967 there's no reason why this should be the case, but it's worth a try,
968 and the build-id check should ensure we don't use an invalid file if
969 we happen to find one. */
970 if (execbfd
== nullptr)
972 const char *base_name
= lbasename (exec_name
);
973 std::string p
= (gdb_ldirname (bfd_get_filename (cbfd
))
976 execbfd
= open_and_check_build_id (p
.c_str ());
979 /* If the above didn't provide EXECBFD then try the exec_filename from
980 the context. This will be an absolute filename which the gdbarch code
981 figured out from the core file. In some cases the gdbarch code might
982 not be able to figure out a suitable absolute filename though. */
983 if (execbfd
== nullptr && ctx
.exec_filename () != nullptr)
985 gdb_assert (IS_ABSOLUTE_PATH (ctx
.exec_filename ()));
987 /* Try to open a file. If this succeeds then we still need to
988 perform a build-id check. */
989 execbfd
= open_and_check_build_id (ctx
.exec_filename ());
995 /* Locate (and load) an executable file (and symbols) given the core file
999 locate_exec_from_corefile_build_id (bfd
*abfd
,
1000 core_target
*target
,
1001 const core_file_exec_context
&ctx
,
1004 const bfd_build_id
*build_id
= build_id_bfd_get (abfd
);
1005 if (build_id
== nullptr)
1008 gdb_bfd_ref_ptr execbfd
;
1011 execbfd
= locate_exec_from_corefile_exec_context (abfd
, build_id
, ctx
);
1013 if (execbfd
== nullptr)
1015 /* The filename used for the find_objfile_by_build_id call. */
1016 std::string filename
;
1018 if (!target
->expected_exec_filename ().empty ())
1019 filename
= target
->expected_exec_filename ();
1022 /* We didn't find an executable name from the mapped file
1023 information, so as a stand-in build a string based on the
1025 std::string build_id_hex_str
1026 = bin2hex (build_id
->data
, build_id
->size
);
1028 = string_printf ("with build-id %s", build_id_hex_str
.c_str ());
1032 = find_objfile_by_build_id (current_program_space
, build_id
,
1036 if (execbfd
!= nullptr)
1038 exec_file_attach (bfd_get_filename (execbfd
.get ()), from_tty
);
1039 symbol_file_add_main (bfd_get_filename (execbfd
.get ()),
1040 symfile_add_flag (from_tty
? SYMFILE_VERBOSE
: 0));
1044 /* Open and set up the core file bfd. */
1047 core_target_open (const char *arg
, int from_tty
)
1053 target_preopen (from_tty
);
1055 std::string filename
= extract_single_filename_arg (arg
);
1057 if (filename
.empty ())
1059 if (current_program_space
->core_bfd ())
1060 error (_("No core file specified. (Use `detach' "
1061 "to stop debugging a core file.)"));
1063 error (_("No core file specified."));
1066 if (!IS_ABSOLUTE_PATH (filename
.c_str ()))
1067 filename
= gdb_abspath (filename
);
1069 flags
= O_BINARY
| O_LARGEFILE
;
1074 scratch_chan
= gdb_open_cloexec (filename
.c_str (), flags
, 0).release ();
1075 if (scratch_chan
< 0)
1076 perror_with_name (filename
.c_str ());
1078 gdb_bfd_ref_ptr
temp_bfd (gdb_bfd_fopen (filename
.c_str (), gnutarget
,
1079 write_files
? FOPEN_RUB
: FOPEN_RB
,
1081 if (temp_bfd
== NULL
)
1082 perror_with_name (filename
.c_str ());
1084 if (!bfd_check_format (temp_bfd
.get (), bfd_core
))
1086 /* Do it after the err msg */
1087 /* FIXME: should be checking for errors from bfd_close (for one
1088 thing, on error it does not free all the storage associated
1090 error (_("\"%s\" is not a core dump: %s"),
1091 filename
.c_str (), bfd_errmsg (bfd_get_error ()));
1094 current_program_space
->cbfd
= std::move (temp_bfd
);
1096 core_target
*target
= new core_target ();
1098 /* Own the target until it is successfully pushed. */
1099 target_ops_up
target_holder (target
);
1103 current_inferior ()->push_target (std::move (target_holder
));
1105 switch_to_no_thread ();
1107 /* Need to flush the register cache (and the frame cache) from a
1108 previous debug session. If inferior_ptid ends up the same as the
1109 last debug session --- e.g., b foo; run; gcore core1; step; gcore
1110 core2; core core1; core core2 --- then there's potential for
1111 get_current_regcache to return the cached regcache of the
1112 previous session, and the frame cache being stale. */
1113 registers_changed ();
1115 /* Find (or fake) the pid for the process in this core file, and
1116 initialise the current inferior with that pid. */
1117 bool fake_pid_p
= false;
1118 int pid
= bfd_core_file_pid (current_program_space
->core_bfd ());
1125 inferior
*inf
= current_inferior ();
1126 gdb_assert (inf
->pid
== 0);
1127 inferior_appeared (inf
, pid
);
1128 inf
->fake_pid_p
= fake_pid_p
;
1130 /* Rename any .reg/0 sections, giving them each a fake lwpid. */
1131 rename_vmcore_idle_reg_sections (current_program_space
->core_bfd (), inf
);
1133 /* Build up thread list from BFD sections, and possibly set the
1134 current thread to the .reg/NN section matching the .reg
1137 = bfd_get_section_by_name (current_program_space
->core_bfd (), ".reg");
1138 for (asection
*sect
: gdb_bfd_sections (current_program_space
->core_bfd ()))
1139 add_to_thread_list (sect
, reg_sect
, inf
);
1141 if (inferior_ptid
== null_ptid
)
1143 /* Either we found no .reg/NN section, and hence we have a
1144 non-threaded core (single-threaded, from gdb's perspective),
1145 or for some reason add_to_thread_list couldn't determine
1146 which was the "main" thread. The latter case shouldn't
1147 usually happen, but we're dealing with input here, which can
1148 always be broken in different ways. */
1149 thread_info
*thread
= first_thread_of_inferior (inf
);
1152 thread
= add_thread_silent (target
, ptid_t (CORELOW_PID
));
1154 switch_to_thread (thread
);
1157 /* In order to parse the exec context from the core file the current
1158 inferior needs to have a suitable gdbarch set. If an exec file is
1159 loaded then the gdbarch will have been set based on the exec file, but
1160 if not, ensure we have a suitable gdbarch in place now. */
1161 if (current_program_space
->exec_bfd () == nullptr)
1162 current_inferior ()->set_arch (target
->core_gdbarch ());
1164 /* See if the gdbarch can find the executable name and argument list from
1166 core_file_exec_context ctx
1167 = gdbarch_core_parse_exec_context (target
->core_gdbarch (),
1168 current_program_space
->core_bfd ());
1170 /* If we don't have an executable loaded then see if we can locate one
1171 based on the core file. */
1172 if (current_program_space
->exec_bfd () == nullptr)
1173 locate_exec_from_corefile_build_id (current_program_space
->core_bfd (),
1174 target
, ctx
, from_tty
);
1176 /* If we have no exec file, try to set the architecture from the
1177 core file. We don't do this unconditionally since an exec file
1178 typically contains more information that helps us determine the
1179 architecture than a core file. */
1180 if (current_program_space
->exec_bfd () == nullptr)
1181 set_gdbarch_from_file (current_program_space
->core_bfd ());
1183 post_create_inferior (from_tty
, true);
1185 /* Now go through the target stack looking for threads since there
1186 may be a thread_stratum target loaded on top of target core by
1187 now. The layer above should claim threads found in the BFD
1191 target_update_thread_list ();
1194 catch (const gdb_exception_error
&except
)
1196 exception_print (gdb_stderr
, except
);
1201 /* Copy the arguments into the inferior. */
1202 std::vector
<char *> argv
;
1203 for (const gdb::unique_xmalloc_ptr
<char> &a
: ctx
.args ())
1204 argv
.push_back (a
.get ());
1205 gdb::array_view
<char * const> view (argv
.data (), argv
.size ());
1206 current_inferior ()->set_args (view
, true);
1208 /* And now copy the environment. */
1209 current_inferior ()->environment
= ctx
.environment ();
1211 /* Inform the user of executable and arguments. */
1212 const std::string
&args
= current_inferior ()->args ();
1213 gdb_printf (_("Core was generated by `%ps%s%s'.\n"),
1214 styled_string (file_name_style
.style (),
1216 (args
.length () > 0 ? " " : ""), args
.c_str ());
1220 const char *failing_command
1221 = bfd_core_file_failing_command (current_program_space
->core_bfd ());
1222 if (failing_command
!= nullptr)
1223 gdb_printf (_("Core was generated by `%s'.\n"),
1227 /* Clearing any previous state of convenience variables. */
1228 clear_exit_convenience_vars ();
1230 siggy
= bfd_core_file_failing_signal (current_program_space
->core_bfd ());
1233 gdbarch
*core_gdbarch
= target
->core_gdbarch ();
1235 /* If we don't have a CORE_GDBARCH to work with, assume a native
1236 core (map gdb_signal from host signals). If we do have
1237 CORE_GDBARCH to work with, but no gdb_signal_from_target
1238 implementation for that gdbarch, as a fallback measure,
1239 assume the host signal mapping. It'll be correct for native
1240 cores, but most likely incorrect for cross-cores. */
1241 enum gdb_signal sig
= (core_gdbarch
!= NULL
1242 && gdbarch_gdb_signal_from_target_p (core_gdbarch
)
1243 ? gdbarch_gdb_signal_from_target (core_gdbarch
,
1245 : gdb_signal_from_host (siggy
));
1247 gdb_printf (_("Program terminated with signal %s, %s"),
1248 gdb_signal_to_name (sig
), gdb_signal_to_string (sig
));
1249 if (gdbarch_report_signal_info_p (core_gdbarch
))
1250 gdbarch_report_signal_info (core_gdbarch
, current_uiout
, sig
);
1251 gdb_printf (_(".\n"));
1253 /* Set the value of the internal variable $_exitsignal,
1254 which holds the signal uncaught by the inferior. */
1255 set_internalvar_integer (lookup_internalvar ("_exitsignal"),
1259 /* Fetch all registers from core file. */
1260 target_fetch_registers (get_thread_regcache (inferior_thread ()), -1);
1262 /* Now, set up the frame cache, and print the top of stack. */
1263 reinit_frame_cache ();
1264 print_stack_frame (get_selected_frame (NULL
), 1, SRC_AND_LOC
, 1);
1266 /* Current thread should be NUM 1 but the user does not know that.
1267 If a program is single threaded gdb in general does not mention
1268 anything about threads. That is why the test is >= 2. */
1269 if (thread_count (target
) >= 2)
1273 thread_command (NULL
, from_tty
);
1275 catch (const gdb_exception_error
&except
)
1277 exception_print (gdb_stderr
, except
);
1283 core_target::detach (inferior
*inf
, int from_tty
)
1285 /* Get rid of the core. Don't rely on core_target::close doing it,
1286 because target_detach may be called with core_target's refcount > 1,
1287 meaning core_target::close may not be called yet by the
1288 unpush_target call below. */
1291 /* Note that 'this' may be dangling after this call. unpush_target
1292 closes the target if the refcount reaches 0, and our close
1293 implementation deletes 'this'. */
1294 inf
->unpush_target (this);
1296 /* Clear the register cache and the frame cache. */
1297 registers_changed ();
1298 reinit_frame_cache ();
1299 maybe_say_no_core_file_now (from_tty
);
1302 /* Try to retrieve registers from a section in core_bfd, and supply
1305 If ptid's lwp member is zero, do the single-threaded
1306 thing: look for a section named NAME. If ptid's lwp
1307 member is non-zero, do the multi-threaded thing: look for a section
1308 named "NAME/LWP", where LWP is the shortest ASCII decimal
1309 representation of ptid's lwp member.
1311 HUMAN_NAME is a human-readable name for the kind of registers the
1312 NAME section contains, for use in error messages.
1314 If REQUIRED is true, print an error if the core file doesn't have a
1315 section by the appropriate name. Otherwise, just do nothing. */
1318 core_target::get_core_register_section (struct regcache
*regcache
,
1319 const struct regset
*regset
,
1321 int section_min_size
,
1322 const char *human_name
,
1325 gdb_assert (regset
!= nullptr);
1327 struct bfd_section
*section
;
1329 bool variable_size_section
= (regset
->flags
& REGSET_VARIABLE_SIZE
);
1331 thread_section_name
section_name (name
, regcache
->ptid ());
1333 section
= bfd_get_section_by_name (current_program_space
->core_bfd (),
1334 section_name
.c_str ());
1338 warning (_("Couldn't find %s registers in core file."),
1343 size
= bfd_section_size (section
);
1344 if (size
< section_min_size
)
1346 warning (_("Section `%s' in core file too small."),
1347 section_name
.c_str ());
1350 if (size
!= section_min_size
&& !variable_size_section
)
1352 warning (_("Unexpected size of section `%s' in core file."),
1353 section_name
.c_str ());
1356 gdb::byte_vector
contents (size
);
1357 if (!bfd_get_section_contents (current_program_space
->core_bfd (), section
,
1358 contents
.data (), (file_ptr
) 0, size
))
1360 warning (_("Couldn't read %s registers from `%s' section in core file."),
1361 human_name
, section_name
.c_str ());
1365 regset
->supply_regset (regset
, regcache
, -1, contents
.data (), size
);
1368 /* Data passed to gdbarch_iterate_over_regset_sections's callback. */
1369 struct get_core_registers_cb_data
1371 core_target
*target
;
1372 struct regcache
*regcache
;
1375 /* Callback for get_core_registers that handles a single core file
1376 register note section. */
1379 get_core_registers_cb (const char *sect_name
, int supply_size
, int collect_size
,
1380 const struct regset
*regset
,
1381 const char *human_name
, void *cb_data
)
1383 gdb_assert (regset
!= nullptr);
1385 auto *data
= (get_core_registers_cb_data
*) cb_data
;
1386 bool required
= false;
1387 bool variable_size_section
= (regset
->flags
& REGSET_VARIABLE_SIZE
);
1389 if (!variable_size_section
)
1390 gdb_assert (supply_size
== collect_size
);
1392 if (strcmp (sect_name
, ".reg") == 0)
1395 if (human_name
== NULL
)
1396 human_name
= "general-purpose";
1398 else if (strcmp (sect_name
, ".reg2") == 0)
1400 if (human_name
== NULL
)
1401 human_name
= "floating-point";
1404 data
->target
->get_core_register_section (data
->regcache
, regset
, sect_name
,
1405 supply_size
, human_name
, required
);
1408 /* Get the registers out of a core file. This is the machine-
1409 independent part. Fetch_core_registers is the machine-dependent
1410 part, typically implemented in the xm-file for each
1413 /* We just get all the registers, so we don't use regno. */
1416 core_target::fetch_registers (struct regcache
*regcache
, int regno
)
1418 if (!(m_core_gdbarch
!= nullptr
1419 && gdbarch_iterate_over_regset_sections_p (m_core_gdbarch
)))
1421 gdb_printf (gdb_stderr
,
1422 "Can't fetch registers from this type of core file\n");
1426 struct gdbarch
*gdbarch
= regcache
->arch ();
1427 get_core_registers_cb_data data
= { this, regcache
};
1428 gdbarch_iterate_over_regset_sections (gdbarch
,
1429 get_core_registers_cb
,
1430 (void *) &data
, NULL
);
1432 /* Mark all registers not found in the core as unavailable. */
1433 for (int i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
1434 if (regcache
->get_register_status (i
) == REG_UNKNOWN
)
1435 regcache
->raw_supply (i
, NULL
);
1439 core_target::files_info ()
1441 print_section_info (&m_core_section_table
, current_program_space
->core_bfd ());
1445 enum target_xfer_status
1446 core_target::xfer_partial (enum target_object object
, const char *annex
,
1447 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1448 ULONGEST offset
, ULONGEST len
, ULONGEST
*xfered_len
)
1452 case TARGET_OBJECT_MEMORY
:
1454 enum target_xfer_status xfer_status
;
1456 /* Try accessing memory contents from core file data,
1457 restricting consideration to those sections for which
1458 the BFD section flag SEC_HAS_CONTENTS is set. */
1459 auto has_contents_cb
= [] (const struct target_section
*s
)
1461 return ((s
->the_bfd_section
->flags
& SEC_HAS_CONTENTS
) != 0);
1463 xfer_status
= section_table_xfer_memory_partial
1465 offset
, len
, xfered_len
,
1466 m_core_section_table
,
1468 if (xfer_status
== TARGET_XFER_OK
)
1469 return TARGET_XFER_OK
;
1471 /* Check file backed mappings. If they're available, use core file
1472 provided mappings (e.g. from .note.linuxcore.file or the like)
1473 as this should provide a more accurate result. */
1474 if (!m_core_file_mappings
.empty ())
1476 xfer_status
= section_table_xfer_memory_partial
1477 (readbuf
, writebuf
, offset
, len
, xfered_len
,
1478 m_core_file_mappings
);
1479 if (xfer_status
== TARGET_XFER_OK
)
1483 /* If the access is within an unavailable file mapping then we try
1484 to check in the stratum below (the executable stratum). The
1485 thinking here is that if the mapping was read/write then the
1486 contents would have been written into the core file and the
1487 access would have been satisfied by m_core_section_table.
1489 But if the access has not yet been resolved then we can assume
1490 the access is read-only. If the executable was not found
1491 during the mapped file check then we'll have an unavailable
1492 mapping entry, however, if the user has provided the executable
1493 (maybe in a different location) then we might be able to
1494 resolve the access from there.
1496 If that fails, but the access is within an unavailable region,
1497 then the access itself should fail. */
1498 for (const auto &mr
: m_core_unavailable_mappings
)
1500 if (mr
.contains (offset
))
1502 if (!mr
.contains (offset
+ len
))
1503 len
= mr
.start
+ mr
.length
- offset
;
1506 = this->beneath ()->xfer_partial (TARGET_OBJECT_MEMORY
,
1510 if (xfer_status
== TARGET_XFER_OK
)
1511 return TARGET_XFER_OK
;
1513 return TARGET_XFER_E_IO
;
1517 /* The following is acting as a fallback in case we encounter a
1518 situation where the core file is lacking and mapped file
1519 information. Here we query the exec file stratum to see if it
1520 can resolve the access. Doing this when we are missing mapped
1521 file information might be the best we can do, but there are
1522 certainly cases this will get wrong, e.g. if an inferior created
1523 a zero initialised mapping over the top of some data that exists
1524 within the executable then this will return the executable data
1525 rather than the zero data. Maybe we should just drop this
1527 if (m_core_file_mappings
.empty ()
1528 && m_core_unavailable_mappings
.empty ())
1531 = this->beneath ()->xfer_partial (object
, annex
, readbuf
,
1532 writebuf
, offset
, len
,
1534 if (xfer_status
== TARGET_XFER_OK
)
1535 return TARGET_XFER_OK
;
1538 /* Finally, attempt to access data in core file sections with
1539 no contents. These will typically read as all zero. */
1540 auto no_contents_cb
= [&] (const struct target_section
*s
)
1542 return !has_contents_cb (s
);
1544 xfer_status
= section_table_xfer_memory_partial
1546 offset
, len
, xfered_len
,
1547 m_core_section_table
,
1552 case TARGET_OBJECT_AUXV
:
1555 /* When the aux vector is stored in core file, BFD
1556 represents this with a fake section called ".auxv". */
1558 struct bfd_section
*section
;
1561 section
= bfd_get_section_by_name (current_program_space
->core_bfd (),
1563 if (section
== NULL
)
1564 return TARGET_XFER_E_IO
;
1566 size
= bfd_section_size (section
);
1568 return TARGET_XFER_EOF
;
1574 return TARGET_XFER_EOF
;
1575 if (!bfd_get_section_contents (current_program_space
->core_bfd (),
1576 section
, readbuf
, (file_ptr
) offset
,
1579 warning (_("Couldn't read NT_AUXV note in core file."));
1580 return TARGET_XFER_E_IO
;
1583 *xfered_len
= (ULONGEST
) size
;
1584 return TARGET_XFER_OK
;
1586 return TARGET_XFER_E_IO
;
1588 case TARGET_OBJECT_WCOOKIE
:
1591 /* When the StackGhost cookie is stored in core file, BFD
1592 represents this with a fake section called
1595 struct bfd_section
*section
;
1598 section
= bfd_get_section_by_name (current_program_space
->core_bfd (),
1600 if (section
== NULL
)
1601 return TARGET_XFER_E_IO
;
1603 size
= bfd_section_size (section
);
1605 return TARGET_XFER_EOF
;
1611 return TARGET_XFER_EOF
;
1612 if (!bfd_get_section_contents (current_program_space
->core_bfd (),
1613 section
, readbuf
, (file_ptr
) offset
,
1616 warning (_("Couldn't read StackGhost cookie in core file."));
1617 return TARGET_XFER_E_IO
;
1620 *xfered_len
= (ULONGEST
) size
;
1621 return TARGET_XFER_OK
;
1624 return TARGET_XFER_E_IO
;
1626 case TARGET_OBJECT_LIBRARIES
:
1627 if (m_core_gdbarch
!= nullptr
1628 && gdbarch_core_xfer_shared_libraries_p (m_core_gdbarch
))
1631 return TARGET_XFER_E_IO
;
1634 *xfered_len
= gdbarch_core_xfer_shared_libraries (m_core_gdbarch
,
1638 if (*xfered_len
== 0)
1639 return TARGET_XFER_EOF
;
1641 return TARGET_XFER_OK
;
1644 return TARGET_XFER_E_IO
;
1646 case TARGET_OBJECT_LIBRARIES_AIX
:
1647 if (m_core_gdbarch
!= nullptr
1648 && gdbarch_core_xfer_shared_libraries_aix_p (m_core_gdbarch
))
1651 return TARGET_XFER_E_IO
;
1655 = gdbarch_core_xfer_shared_libraries_aix (m_core_gdbarch
,
1659 if (*xfered_len
== 0)
1660 return TARGET_XFER_EOF
;
1662 return TARGET_XFER_OK
;
1665 return TARGET_XFER_E_IO
;
1667 case TARGET_OBJECT_SIGNAL_INFO
:
1670 if (m_core_gdbarch
!= nullptr
1671 && gdbarch_core_xfer_siginfo_p (m_core_gdbarch
))
1673 LONGEST l
= gdbarch_core_xfer_siginfo (m_core_gdbarch
, readbuf
,
1680 return TARGET_XFER_EOF
;
1682 return TARGET_XFER_OK
;
1686 return TARGET_XFER_E_IO
;
1689 return this->beneath ()->xfer_partial (object
, annex
, readbuf
,
1690 writebuf
, offset
, len
,
1697 /* Okay, let's be honest: threads gleaned from a core file aren't
1698 exactly lively, are they? On the other hand, if we don't claim
1699 that each & every one is alive, then we don't get any of them
1700 to appear in an "info thread" command, which is quite a useful
1704 core_target::thread_alive (ptid_t ptid
)
1709 /* Ask the current architecture what it knows about this core file.
1710 That will be used, in turn, to pick a better architecture. This
1711 wrapper could be avoided if targets got a chance to specialize
1714 const struct target_desc
*
1715 core_target::read_description ()
1717 /* First check whether the target wants us to use the corefile target
1718 description notes. */
1719 if (gdbarch_use_target_description_from_corefile_notes
1720 (m_core_gdbarch
, current_program_space
->core_bfd ()))
1722 /* If the core file contains a target description note then go ahead and
1724 bfd_size_type tdesc_note_size
= 0;
1725 struct bfd_section
*tdesc_note_section
1726 = bfd_get_section_by_name (current_program_space
->core_bfd (), ".gdb-tdesc");
1727 if (tdesc_note_section
!= nullptr)
1728 tdesc_note_size
= bfd_section_size (tdesc_note_section
);
1729 if (tdesc_note_size
> 0)
1731 gdb::char_vector
contents (tdesc_note_size
+ 1);
1732 if (bfd_get_section_contents (current_program_space
->core_bfd (),
1733 tdesc_note_section
, contents
.data (),
1734 (file_ptr
) 0, tdesc_note_size
))
1736 /* Ensure we have a null terminator. */
1737 contents
[tdesc_note_size
] = '\0';
1738 const struct target_desc
*result
1739 = string_read_description_xml (contents
.data ());
1740 if (result
!= nullptr)
1746 /* If the architecture provides a corefile target description hook, use
1747 it now. Even if the core file contains a target description in a note
1748 section, it is not useful for targets that can potentially have distinct
1749 descriptions for each thread. One example is AArch64's SVE/SME
1750 extensions that allow per-thread vector length changes, resulting in
1751 registers with different sizes. */
1752 if (m_core_gdbarch
&& gdbarch_core_read_description_p (m_core_gdbarch
))
1754 const struct target_desc
*result
;
1756 result
= gdbarch_core_read_description
1757 (m_core_gdbarch
, this, current_program_space
->core_bfd ());
1758 if (result
!= nullptr)
1762 return this->beneath ()->read_description ();
1766 core_target::pid_to_str (ptid_t ptid
)
1768 struct inferior
*inf
;
1771 /* The preferred way is to have a gdbarch/OS specific
1773 if (m_core_gdbarch
!= nullptr
1774 && gdbarch_core_pid_to_str_p (m_core_gdbarch
))
1775 return gdbarch_core_pid_to_str (m_core_gdbarch
, ptid
);
1777 /* Otherwise, if we don't have one, we'll just fallback to
1778 "process", with normal_pid_to_str. */
1780 /* Try the LWPID field first. */
1783 return normal_pid_to_str (ptid_t (pid
));
1785 /* Otherwise, this isn't a "threaded" core -- use the PID field, but
1786 only if it isn't a fake PID. */
1787 inf
= find_inferior_ptid (this, ptid
);
1788 if (inf
!= NULL
&& !inf
->fake_pid_p
)
1789 return normal_pid_to_str (ptid
);
1791 /* No luck. We simply don't have a valid PID to print. */
1792 return "<main task>";
1796 core_target::thread_name (struct thread_info
*thr
)
1798 if (m_core_gdbarch
!= nullptr
1799 && gdbarch_core_thread_name_p (m_core_gdbarch
))
1800 return gdbarch_core_thread_name (m_core_gdbarch
, thr
);
1805 core_target::has_memory ()
1807 return current_program_space
->core_bfd () != nullptr;
1811 core_target::has_stack ()
1813 return current_program_space
->core_bfd () != nullptr;
1817 core_target::has_registers ()
1819 return current_program_space
->core_bfd () != nullptr;
1822 /* Implement the to_info_proc method. */
1825 core_target::info_proc (const char *args
, enum info_proc_what request
)
1827 struct gdbarch
*gdbarch
= get_current_arch ();
1829 /* Since this is the core file target, call the 'core_info_proc'
1830 method on gdbarch, not 'info_proc'. */
1831 if (gdbarch_core_info_proc_p (gdbarch
))
1832 gdbarch_core_info_proc (gdbarch
, args
, request
);
1837 /* Implementation of the "supports_memory_tagging" target_ops method. */
1840 core_target::supports_memory_tagging ()
1842 /* Look for memory tag sections. If they exist, that means this core file
1843 supports memory tagging. */
1845 return (bfd_get_section_by_name (current_program_space
->core_bfd (), "memtag")
1849 /* Implementation of the "fetch_memtags" target_ops method. */
1852 core_target::fetch_memtags (CORE_ADDR address
, size_t len
,
1853 gdb::byte_vector
&tags
, int type
)
1855 gdbarch
*gdbarch
= current_inferior ()->arch ();
1857 /* Make sure we have a way to decode the memory tag notes. */
1858 if (!gdbarch_decode_memtag_section_p (gdbarch
))
1859 error (_("gdbarch_decode_memtag_section not implemented for this "
1862 memtag_section_info info
;
1863 info
.memtag_section
= nullptr;
1865 while (get_next_core_memtag_section (current_program_space
->core_bfd (),
1866 info
.memtag_section
, address
, info
))
1868 size_t adjusted_length
1869 = (address
+ len
< info
.end_address
) ? len
: (info
.end_address
- address
);
1871 /* Decode the memory tag note and return the tags. */
1872 gdb::byte_vector tags_read
1873 = gdbarch_decode_memtag_section (gdbarch
, info
.memtag_section
, type
,
1874 address
, adjusted_length
);
1876 /* Transfer over the tags that have been read. */
1877 tags
.insert (tags
.end (), tags_read
.begin (), tags_read
.end ());
1879 /* ADDRESS + LEN may cross the boundaries of a particular memory tag
1880 segment. Check if we need to fetch tags from a different section. */
1881 if (!tags_read
.empty () && (address
+ len
) < info
.end_address
)
1884 /* There are more tags to fetch. Update ADDRESS and LEN. */
1885 len
-= (info
.end_address
- address
);
1886 address
= info
.end_address
;
1893 core_target::is_address_tagged (gdbarch
*gdbarch
, CORE_ADDR address
)
1895 return gdbarch_tagged_address_p (gdbarch
, address
);
1898 /* Implementation of the "fetch_x86_xsave_layout" target_ops method. */
1901 core_target::fetch_x86_xsave_layout ()
1903 if (m_core_gdbarch
!= nullptr &&
1904 gdbarch_core_read_x86_xsave_layout_p (m_core_gdbarch
))
1906 x86_xsave_layout layout
;
1907 if (!gdbarch_core_read_x86_xsave_layout (m_core_gdbarch
, layout
))
1916 /* Get a pointer to the current core target. If not connected to a
1917 core target, return NULL. */
1919 static core_target
*
1920 get_current_core_target ()
1922 target_ops
*proc_target
= current_inferior ()->process_target ();
1923 return dynamic_cast<core_target
*> (proc_target
);
1926 /* Display file backed mappings from core file. */
1929 core_target::info_proc_mappings (struct gdbarch
*gdbarch
)
1931 if (m_core_file_mappings
.empty ())
1934 gdb_printf (_("Mapped address spaces:\n\n"));
1935 ui_out_emit_table
emitter (current_uiout
, 5, -1, "ProcMappings");
1937 int width
= gdbarch_addr_bit (gdbarch
) == 32 ? 10 : 18;
1938 current_uiout
->table_header (width
, ui_left
, "start", "Start Addr");
1939 current_uiout
->table_header (width
, ui_left
, "end", "End Addr");
1940 current_uiout
->table_header (width
, ui_left
, "size", "Size");
1941 current_uiout
->table_header (width
, ui_left
, "offset", "Offset");
1942 current_uiout
->table_header (0, ui_left
, "objfile", "File");
1943 current_uiout
->table_body ();
1945 for (const target_section
&tsp
: m_core_file_mappings
)
1947 ULONGEST start
= tsp
.addr
;
1948 ULONGEST end
= tsp
.endaddr
;
1949 ULONGEST file_ofs
= tsp
.the_bfd_section
->filepos
;
1950 const char *filename
= bfd_get_filename (tsp
.the_bfd_section
->owner
);
1952 ui_out_emit_tuple
tuple_emitter (current_uiout
, nullptr);
1953 current_uiout
->field_core_addr ("start", gdbarch
, start
);
1954 current_uiout
->field_core_addr ("end", gdbarch
, end
);
1955 /* These next two aren't really addresses and so shouldn't be
1957 current_uiout
->field_string ("size", paddress (gdbarch
, end
- start
));
1958 current_uiout
->field_string ("offset", paddress (gdbarch
, file_ofs
));
1959 current_uiout
->field_string ("objfile", filename
,
1960 file_name_style
.style ());
1961 current_uiout
->text ("\n");
1965 /* Implement "maintenance print core-file-backed-mappings" command.
1967 If mappings are loaded, the results should be similar to the
1968 mappings shown by "info proc mappings". This command is mainly a
1969 debugging tool for GDB developers to make sure that the expected
1970 mappings are present after loading a core file. For Linux, the
1971 output provided by this command will be very similar (if not
1972 identical) to that provided by "info proc mappings". This is not
1973 necessarily the case for other OSes which might provide
1974 more/different information in the "info proc mappings" output. */
1977 maintenance_print_core_file_backed_mappings (const char *args
, int from_tty
)
1979 core_target
*targ
= get_current_core_target ();
1980 if (targ
!= nullptr)
1981 targ
->info_proc_mappings (targ
->core_gdbarch ());
1984 /* Add more details discovered while processing the core-file's mapped file
1985 information, we're building maps between filenames and the corresponding
1986 build-ids, between address ranges and the corresponding build-ids, and
1987 also a reverse map between build-id and the corresponding filename.
1989 SONAME is the DT_SONAME attribute extracted from the .dynamic section of
1990 a shared library that was mapped into the core file. This can be
1991 nullptr if the mapped files was not a shared library, or didn't have a
1992 DT_SONAME attribute.
1994 EXPECTED_FILENAME is the name of the file that was mapped into the
1995 inferior as extracted from the core file, this should never be nullptr.
1997 ACTUAL_FILENAME is the name of the actual file GDB found to provide the
1998 mapped file information, this can be nullptr if GDB failed to find a
1999 suitable file. This might be different to EXPECTED_FILENAME, e.g. GDB
2000 might have downloaded the file from debuginfod and so ACTUAL_FILENAME
2001 will be a file in the debuginfod client cache.
2003 RANGES is the list of memory ranges at which this file was mapped into
2006 BUILD_ID is the build-id for this mapped file, this will never be
2007 nullptr. Not every mapped file will have a build-id, but there's no
2008 point calling this function if we failed to find a build-id; this
2009 structure only exists so we can lookup files based on their build-id. */
2012 mapped_file_info::add (const char *soname
,
2013 const char *expected_filename
,
2014 const char *actual_filename
,
2015 std::vector
<mem_range
> &&ranges
,
2016 const bfd_build_id
*build_id
)
2018 gdb_assert (build_id
!= nullptr);
2019 gdb_assert (expected_filename
!= nullptr);
2021 if (soname
!= nullptr)
2023 /* If we already have an entry with this SONAME then this indicates
2024 that the inferior has two files mapped into memory with different
2025 file names (and most likely different build-ids), but with the
2026 same DT_SONAME attribute. In this case we can't use the
2027 DT_SONAME to figure out the expected build-id of a shared
2028 library, so poison the entry for this SONAME by setting the entry
2030 auto it
= m_soname_to_build_id_map
.find (soname
);
2031 if (it
!= m_soname_to_build_id_map
.end ()
2032 && it
->second
!= nullptr
2033 && !build_id_equal (it
->second
, build_id
))
2034 m_soname_to_build_id_map
[soname
] = nullptr;
2036 m_soname_to_build_id_map
[soname
] = build_id
;
2039 /* When the core file is initially opened and the mapped files are
2040 parsed, we group the build-id information based on the file name. As
2041 a consequence, we should see each EXPECTED_FILENAME value exactly
2042 once. This means that each insertion should always succeed. */
2044 = m_filename_to_build_id_map
.emplace (expected_filename
, build_id
).second
;
2045 gdb_assert (inserted
);
2047 /* Setup the reverse build-id to file name map. */
2048 if (actual_filename
!= nullptr)
2049 m_build_id_to_filename_map
.emplace (build_id
, actual_filename
);
2051 /* Setup the list of memory range to build-id objects. */
2052 for (mem_range
&r
: ranges
)
2053 m_address_to_build_id_list
.emplace_back (std::move (r
), build_id
);
2055 /* At this point the m_address_to_build_id_list is unsorted (we just
2056 added some entries to the end of the list). All entries should be
2057 added before any look-ups are performed, and the list is only sorted
2058 when the first look-up is performed. */
2059 gdb_assert (!m_address_to_build_id_list_sorted
);
2062 /* FILENAME is the name of a file GDB is trying to load, and ADDR is
2063 (optionally) an address within the file in the inferior's address space.
2065 Search through the information gathered from the core-file's mapped file
2066 information looking for a file named FILENAME, or for a file that covers
2067 ADDR. If a match is found then return the build-id for the file along
2068 with the location where GDB found the mapped file.
2070 The location of the mapped file might be the empty string if GDB was
2071 unable to find the mapped file.
2073 If no build-id can be found for FILENAME then GDB will return a pair
2074 containing nullptr (for the build-id) and an empty string for the file
2077 std::optional
<core_target_mapped_file_info
>
2078 mapped_file_info::lookup (const char *filename
,
2079 const std::optional
<CORE_ADDR
> &addr
)
2081 if (filename
!= nullptr)
2083 /* If there's a matching entry in m_filename_to_build_id_map then the
2084 associated build-id will not be nullptr, and can be used to
2085 validate that FILENAME is correct. */
2086 auto it
= m_filename_to_build_id_map
.find (filename
);
2087 if (it
!= m_filename_to_build_id_map
.end ())
2088 return make_result (it
->second
);
2091 if (addr
.has_value ())
2093 /* On the first lookup, sort the address_to_build_id_list. */
2094 if (!m_address_to_build_id_list_sorted
)
2096 std::sort (m_address_to_build_id_list
.begin (),
2097 m_address_to_build_id_list
.end (),
2098 [] (const mem_range_and_build_id
&a
,
2099 const mem_range_and_build_id
&b
) {
2100 return a
.range
< b
.range
;
2102 m_address_to_build_id_list_sorted
= true;
2105 /* Look for the first entry whose range's start address is not less
2106 than, or equal too, the address ADDR. If we find such an entry,
2107 then the previous entry's range might contain ADDR. If it does
2108 then that previous entry's build-id can be used. */
2109 auto it
= std::lower_bound
2110 (m_address_to_build_id_list
.begin (),
2111 m_address_to_build_id_list
.end (),
2113 [] (const mem_range_and_build_id
&a
,
2114 const CORE_ADDR
&b
) {
2115 return a
.range
.start
<= b
;
2118 if (it
!= m_address_to_build_id_list
.begin ())
2122 if (it
->range
.contains (*addr
))
2123 return make_result (it
->build_id
);
2127 if (filename
!= nullptr)
2129 /* If the basename of FILENAME appears in m_soname_to_build_id_map
2130 then when the mapped files were processed, we saw a file with a
2131 DT_SONAME attribute corresponding to FILENAME, use that build-id
2132 to validate FILENAME.
2134 However, the build-id in this map might be nullptr if we saw
2135 multiple mapped files with the same DT_SONAME attribute (though
2136 this should be pretty rare). */
2138 = m_soname_to_build_id_map
.find (lbasename (filename
));
2139 if (it
!= m_soname_to_build_id_map
.end ()
2140 && it
->second
!= nullptr)
2141 return make_result (it
->second
);
2147 /* See gdbcore.h. */
2149 std::optional
<core_target_mapped_file_info
>
2150 core_target_find_mapped_file (const char *filename
,
2151 std::optional
<CORE_ADDR
> addr
)
2153 core_target
*targ
= get_current_core_target ();
2154 if (targ
== nullptr || current_program_space
->cbfd
.get () == nullptr)
2157 return targ
->lookup_mapped_file_info (filename
, addr
);
2160 INIT_GDB_FILE (corelow
)
2162 add_target (core_target_info
, core_target_open
,
2163 filename_maybe_quoted_completer
);
2164 add_cmd ("core-file-backed-mappings", class_maintenance
,
2165 maintenance_print_core_file_backed_mappings
,
2166 _("Print core file's file-backed mappings."),
2167 &maintenanceprintlist
);