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