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