Home | History | Annotate | Line # | Download | only in gdb
symfile.c revision 1.6.4.1
      1 /* Generic symbol file reading for the GNU debugger, GDB.
      2 
      3    Copyright (C) 1990-2017 Free Software Foundation, Inc.
      4 
      5    Contributed by Cygnus Support, using pieces from other GDB modules.
      6 
      7    This file is part of GDB.
      8 
      9    This program is free software; you can redistribute it and/or modify
     10    it under the terms of the GNU General Public License as published by
     11    the Free Software Foundation; either version 3 of the License, or
     12    (at your option) any later version.
     13 
     14    This program is distributed in the hope that it will be useful,
     15    but WITHOUT ANY WARRANTY; without even the implied warranty of
     16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     17    GNU General Public License for more details.
     18 
     19    You should have received a copy of the GNU General Public License
     20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     21 
     22 #include "defs.h"
     23 #include "arch-utils.h"
     24 #include "bfdlink.h"
     25 #include "symtab.h"
     26 #include "gdbtypes.h"
     27 #include "gdbcore.h"
     28 #include "frame.h"
     29 #include "target.h"
     30 #include "value.h"
     31 #include "symfile.h"
     32 #include "objfiles.h"
     33 #include "source.h"
     34 #include "gdbcmd.h"
     35 #include "breakpoint.h"
     36 #include "language.h"
     37 #include "complaints.h"
     38 #include "demangle.h"
     39 #include "inferior.h"
     40 #include "regcache.h"
     41 #include "filenames.h"		/* for DOSish file names */
     42 #include "gdb-stabs.h"
     43 #include "gdb_obstack.h"
     44 #include "completer.h"
     45 #include "bcache.h"
     46 #include "hashtab.h"
     47 #include "readline/readline.h"
     48 #include "block.h"
     49 #include "observer.h"
     50 #include "exec.h"
     51 #include "parser-defs.h"
     52 #include "varobj.h"
     53 #include "elf-bfd.h"
     54 #include "solib.h"
     55 #include "remote.h"
     56 #include "stack.h"
     57 #include "gdb_bfd.h"
     58 #include "cli/cli-utils.h"
     59 
     60 #include <sys/types.h>
     61 #include <fcntl.h>
     62 #include <sys/stat.h>
     63 #include <ctype.h>
     64 #include <chrono>
     65 
     66 #include "psymtab.h"
     67 
     68 int (*deprecated_ui_load_progress_hook) (const char *section,
     69 					 unsigned long num);
     70 void (*deprecated_show_load_progress) (const char *section,
     71 			    unsigned long section_sent,
     72 			    unsigned long section_size,
     73 			    unsigned long total_sent,
     74 			    unsigned long total_size);
     75 void (*deprecated_pre_add_symbol_hook) (const char *);
     76 void (*deprecated_post_add_symbol_hook) (void);
     77 
     78 static void clear_symtab_users_cleanup (void *ignore);
     79 
     80 /* Global variables owned by this file.  */
     81 int readnow_symbol_files;	/* Read full symbols immediately.  */
     82 
     83 /* Functions this file defines.  */
     84 
     85 static void load_command (char *, int);
     86 
     87 static void symbol_file_add_main_1 (const char *args, symfile_add_flags add_flags,
     88 				    objfile_flags flags);
     89 
     90 static void add_symbol_file_command (char *, int);
     91 
     92 static const struct sym_fns *find_sym_fns (bfd *);
     93 
     94 static void overlay_invalidate_all (void);
     95 
     96 static void overlay_auto_command (char *, int);
     97 
     98 static void overlay_manual_command (char *, int);
     99 
    100 static void overlay_off_command (char *, int);
    101 
    102 static void overlay_load_command (char *, int);
    103 
    104 static void overlay_command (char *, int);
    105 
    106 static void simple_free_overlay_table (void);
    107 
    108 static void read_target_long_array (CORE_ADDR, unsigned int *, int, int,
    109 				    enum bfd_endian);
    110 
    111 static int simple_read_overlay_table (void);
    112 
    113 static int simple_overlay_update_1 (struct obj_section *);
    114 
    115 static void info_ext_lang_command (char *args, int from_tty);
    116 
    117 static void symfile_find_segment_sections (struct objfile *objfile);
    118 
    119 void _initialize_symfile (void);
    120 
    121 /* List of all available sym_fns.  On gdb startup, each object file reader
    122    calls add_symtab_fns() to register information on each format it is
    123    prepared to read.  */
    124 
    125 typedef struct
    126 {
    127   /* BFD flavour that we handle.  */
    128   enum bfd_flavour sym_flavour;
    129 
    130   /* The "vtable" of symbol functions.  */
    131   const struct sym_fns *sym_fns;
    132 } registered_sym_fns;
    133 
    134 DEF_VEC_O (registered_sym_fns);
    135 
    136 static VEC (registered_sym_fns) *symtab_fns = NULL;
    137 
    138 /* Values for "set print symbol-loading".  */
    139 
    140 const char print_symbol_loading_off[] = "off";
    141 const char print_symbol_loading_brief[] = "brief";
    142 const char print_symbol_loading_full[] = "full";
    143 static const char *print_symbol_loading_enums[] =
    144 {
    145   print_symbol_loading_off,
    146   print_symbol_loading_brief,
    147   print_symbol_loading_full,
    148   NULL
    149 };
    150 static const char *print_symbol_loading = print_symbol_loading_full;
    151 
    152 /* If non-zero, shared library symbols will be added automatically
    153    when the inferior is created, new libraries are loaded, or when
    154    attaching to the inferior.  This is almost always what users will
    155    want to have happen; but for very large programs, the startup time
    156    will be excessive, and so if this is a problem, the user can clear
    157    this flag and then add the shared library symbols as needed.  Note
    158    that there is a potential for confusion, since if the shared
    159    library symbols are not loaded, commands like "info fun" will *not*
    160    report all the functions that are actually present.  */
    161 
    162 int auto_solib_add = 1;
    163 
    164 
    166 /* Return non-zero if symbol-loading messages should be printed.
    167    FROM_TTY is the standard from_tty argument to gdb commands.
    168    If EXEC is non-zero the messages are for the executable.
    169    Otherwise, messages are for shared libraries.
    170    If FULL is non-zero then the caller is printing a detailed message.
    171    E.g., the message includes the shared library name.
    172    Otherwise, the caller is printing a brief "summary" message.  */
    173 
    174 int
    175 print_symbol_loading_p (int from_tty, int exec, int full)
    176 {
    177   if (!from_tty && !info_verbose)
    178     return 0;
    179 
    180   if (exec)
    181     {
    182       /* We don't check FULL for executables, there are few such
    183 	 messages, therefore brief == full.  */
    184       return print_symbol_loading != print_symbol_loading_off;
    185     }
    186   if (full)
    187     return print_symbol_loading == print_symbol_loading_full;
    188   return print_symbol_loading == print_symbol_loading_brief;
    189 }
    190 
    191 /* True if we are reading a symbol table.  */
    192 
    193 int currently_reading_symtab = 0;
    194 
    195 /* Increment currently_reading_symtab and return a cleanup that can be
    196    used to decrement it.  */
    197 
    198 scoped_restore_tmpl<int>
    199 increment_reading_symtab (void)
    200 {
    201   gdb_assert (currently_reading_symtab >= 0);
    202   return make_scoped_restore (&currently_reading_symtab,
    203 			      currently_reading_symtab + 1);
    204 }
    205 
    206 /* Remember the lowest-addressed loadable section we've seen.
    207    This function is called via bfd_map_over_sections.
    208 
    209    In case of equal vmas, the section with the largest size becomes the
    210    lowest-addressed loadable section.
    211 
    212    If the vmas and sizes are equal, the last section is considered the
    213    lowest-addressed loadable section.  */
    214 
    215 void
    216 find_lowest_section (bfd *abfd, asection *sect, void *obj)
    217 {
    218   asection **lowest = (asection **) obj;
    219 
    220   if (0 == (bfd_get_section_flags (abfd, sect) & (SEC_ALLOC | SEC_LOAD)))
    221     return;
    222   if (!*lowest)
    223     *lowest = sect;		/* First loadable section */
    224   else if (bfd_section_vma (abfd, *lowest) > bfd_section_vma (abfd, sect))
    225     *lowest = sect;		/* A lower loadable section */
    226   else if (bfd_section_vma (abfd, *lowest) == bfd_section_vma (abfd, sect)
    227 	   && (bfd_section_size (abfd, (*lowest))
    228 	       <= bfd_section_size (abfd, sect)))
    229     *lowest = sect;
    230 }
    231 
    232 /* Create a new section_addr_info, with room for NUM_SECTIONS.  The
    233    new object's 'num_sections' field is set to 0; it must be updated
    234    by the caller.  */
    235 
    236 struct section_addr_info *
    237 alloc_section_addr_info (size_t num_sections)
    238 {
    239   struct section_addr_info *sap;
    240   size_t size;
    241 
    242   size = (sizeof (struct section_addr_info)
    243 	  +  sizeof (struct other_sections) * (num_sections - 1));
    244   sap = (struct section_addr_info *) xmalloc (size);
    245   memset (sap, 0, size);
    246 
    247   return sap;
    248 }
    249 
    250 /* Build (allocate and populate) a section_addr_info struct from
    251    an existing section table.  */
    252 
    253 extern struct section_addr_info *
    254 build_section_addr_info_from_section_table (const struct target_section *start,
    255                                             const struct target_section *end)
    256 {
    257   struct section_addr_info *sap;
    258   const struct target_section *stp;
    259   int oidx;
    260 
    261   sap = alloc_section_addr_info (end - start);
    262 
    263   for (stp = start, oidx = 0; stp != end; stp++)
    264     {
    265       struct bfd_section *asect = stp->the_bfd_section;
    266       bfd *abfd = asect->owner;
    267 
    268       if (bfd_get_section_flags (abfd, asect) & (SEC_ALLOC | SEC_LOAD)
    269 	  && oidx < end - start)
    270 	{
    271 	  sap->other[oidx].addr = stp->addr;
    272 	  sap->other[oidx].name = xstrdup (bfd_section_name (abfd, asect));
    273 	  sap->other[oidx].sectindex = gdb_bfd_section_index (abfd, asect);
    274 	  oidx++;
    275 	}
    276     }
    277 
    278   sap->num_sections = oidx;
    279 
    280   return sap;
    281 }
    282 
    283 /* Create a section_addr_info from section offsets in ABFD.  */
    284 
    285 static struct section_addr_info *
    286 build_section_addr_info_from_bfd (bfd *abfd)
    287 {
    288   struct section_addr_info *sap;
    289   int i;
    290   struct bfd_section *sec;
    291 
    292   sap = alloc_section_addr_info (bfd_count_sections (abfd));
    293   for (i = 0, sec = abfd->sections; sec != NULL; sec = sec->next)
    294     if (bfd_get_section_flags (abfd, sec) & (SEC_ALLOC | SEC_LOAD))
    295       {
    296 	sap->other[i].addr = bfd_get_section_vma (abfd, sec);
    297 	sap->other[i].name = xstrdup (bfd_get_section_name (abfd, sec));
    298 	sap->other[i].sectindex = gdb_bfd_section_index (abfd, sec);
    299 	i++;
    300       }
    301 
    302   sap->num_sections = i;
    303 
    304   return sap;
    305 }
    306 
    307 /* Create a section_addr_info from section offsets in OBJFILE.  */
    308 
    309 struct section_addr_info *
    310 build_section_addr_info_from_objfile (const struct objfile *objfile)
    311 {
    312   struct section_addr_info *sap;
    313   int i;
    314 
    315   /* Before reread_symbols gets rewritten it is not safe to call:
    316      gdb_assert (objfile->num_sections == bfd_count_sections (objfile->obfd));
    317      */
    318   sap = build_section_addr_info_from_bfd (objfile->obfd);
    319   for (i = 0; i < sap->num_sections; i++)
    320     {
    321       int sectindex = sap->other[i].sectindex;
    322 
    323       sap->other[i].addr += objfile->section_offsets->offsets[sectindex];
    324     }
    325   return sap;
    326 }
    327 
    328 /* Free all memory allocated by build_section_addr_info_from_section_table.  */
    329 
    330 extern void
    331 free_section_addr_info (struct section_addr_info *sap)
    332 {
    333   int idx;
    334 
    335   for (idx = 0; idx < sap->num_sections; idx++)
    336     xfree (sap->other[idx].name);
    337   xfree (sap);
    338 }
    339 
    340 /* Initialize OBJFILE's sect_index_* members.  */
    341 
    342 static void
    343 init_objfile_sect_indices (struct objfile *objfile)
    344 {
    345   asection *sect;
    346   int i;
    347 
    348   sect = bfd_get_section_by_name (objfile->obfd, ".text");
    349   if (sect)
    350     objfile->sect_index_text = sect->index;
    351 
    352   sect = bfd_get_section_by_name (objfile->obfd, ".data");
    353   if (sect)
    354     objfile->sect_index_data = sect->index;
    355 
    356   sect = bfd_get_section_by_name (objfile->obfd, ".bss");
    357   if (sect)
    358     objfile->sect_index_bss = sect->index;
    359 
    360   sect = bfd_get_section_by_name (objfile->obfd, ".rodata");
    361   if (sect)
    362     objfile->sect_index_rodata = sect->index;
    363 
    364   /* This is where things get really weird...  We MUST have valid
    365      indices for the various sect_index_* members or gdb will abort.
    366      So if for example, there is no ".text" section, we have to
    367      accomodate that.  First, check for a file with the standard
    368      one or two segments.  */
    369 
    370   symfile_find_segment_sections (objfile);
    371 
    372   /* Except when explicitly adding symbol files at some address,
    373      section_offsets contains nothing but zeros, so it doesn't matter
    374      which slot in section_offsets the individual sect_index_* members
    375      index into.  So if they are all zero, it is safe to just point
    376      all the currently uninitialized indices to the first slot.  But
    377      beware: if this is the main executable, it may be relocated
    378      later, e.g. by the remote qOffsets packet, and then this will
    379      be wrong!  That's why we try segments first.  */
    380 
    381   for (i = 0; i < objfile->num_sections; i++)
    382     {
    383       if (ANOFFSET (objfile->section_offsets, i) != 0)
    384 	{
    385 	  break;
    386 	}
    387     }
    388   if (i == objfile->num_sections)
    389     {
    390       if (objfile->sect_index_text == -1)
    391 	objfile->sect_index_text = 0;
    392       if (objfile->sect_index_data == -1)
    393 	objfile->sect_index_data = 0;
    394       if (objfile->sect_index_bss == -1)
    395 	objfile->sect_index_bss = 0;
    396       if (objfile->sect_index_rodata == -1)
    397 	objfile->sect_index_rodata = 0;
    398     }
    399 }
    400 
    401 /* The arguments to place_section.  */
    402 
    403 struct place_section_arg
    404 {
    405   struct section_offsets *offsets;
    406   CORE_ADDR lowest;
    407 };
    408 
    409 /* Find a unique offset to use for loadable section SECT if
    410    the user did not provide an offset.  */
    411 
    412 static void
    413 place_section (bfd *abfd, asection *sect, void *obj)
    414 {
    415   struct place_section_arg *arg = (struct place_section_arg *) obj;
    416   CORE_ADDR *offsets = arg->offsets->offsets, start_addr;
    417   int done;
    418   ULONGEST align = ((ULONGEST) 1) << bfd_get_section_alignment (abfd, sect);
    419 
    420   /* We are only interested in allocated sections.  */
    421   if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
    422     return;
    423 
    424   /* If the user specified an offset, honor it.  */
    425   if (offsets[gdb_bfd_section_index (abfd, sect)] != 0)
    426     return;
    427 
    428   /* Otherwise, let's try to find a place for the section.  */
    429   start_addr = (arg->lowest + align - 1) & -align;
    430 
    431   do {
    432     asection *cur_sec;
    433 
    434     done = 1;
    435 
    436     for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
    437       {
    438 	int indx = cur_sec->index;
    439 
    440 	/* We don't need to compare against ourself.  */
    441 	if (cur_sec == sect)
    442 	  continue;
    443 
    444 	/* We can only conflict with allocated sections.  */
    445 	if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0)
    446 	  continue;
    447 
    448 	/* If the section offset is 0, either the section has not been placed
    449 	   yet, or it was the lowest section placed (in which case LOWEST
    450 	   will be past its end).  */
    451 	if (offsets[indx] == 0)
    452 	  continue;
    453 
    454 	/* If this section would overlap us, then we must move up.  */
    455 	if (start_addr + bfd_get_section_size (sect) > offsets[indx]
    456 	    && start_addr < offsets[indx] + bfd_get_section_size (cur_sec))
    457 	  {
    458 	    start_addr = offsets[indx] + bfd_get_section_size (cur_sec);
    459 	    start_addr = (start_addr + align - 1) & -align;
    460 	    done = 0;
    461 	    break;
    462 	  }
    463 
    464 	/* Otherwise, we appear to be OK.  So far.  */
    465       }
    466     }
    467   while (!done);
    468 
    469   offsets[gdb_bfd_section_index (abfd, sect)] = start_addr;
    470   arg->lowest = start_addr + bfd_get_section_size (sect);
    471 }
    472 
    473 /* Store struct section_addr_info as prepared (made relative and with SECTINDEX
    474    filled-in) by addr_info_make_relative into SECTION_OFFSETS of NUM_SECTIONS
    475    entries.  */
    476 
    477 void
    478 relative_addr_info_to_section_offsets (struct section_offsets *section_offsets,
    479 				       int num_sections,
    480 				       const struct section_addr_info *addrs)
    481 {
    482   int i;
    483 
    484   memset (section_offsets, 0, SIZEOF_N_SECTION_OFFSETS (num_sections));
    485 
    486   /* Now calculate offsets for section that were specified by the caller.  */
    487   for (i = 0; i < addrs->num_sections; i++)
    488     {
    489       const struct other_sections *osp;
    490 
    491       osp = &addrs->other[i];
    492       if (osp->sectindex == -1)
    493   	continue;
    494 
    495       /* Record all sections in offsets.  */
    496       /* The section_offsets in the objfile are here filled in using
    497          the BFD index.  */
    498       section_offsets->offsets[osp->sectindex] = osp->addr;
    499     }
    500 }
    501 
    502 /* Transform section name S for a name comparison.  prelink can split section
    503    `.bss' into two sections `.dynbss' and `.bss' (in this order).  Similarly
    504    prelink can split `.sbss' into `.sdynbss' and `.sbss'.  Use virtual address
    505    of the new `.dynbss' (`.sdynbss') section as the adjacent new `.bss'
    506    (`.sbss') section has invalid (increased) virtual address.  */
    507 
    508 static const char *
    509 addr_section_name (const char *s)
    510 {
    511   if (strcmp (s, ".dynbss") == 0)
    512     return ".bss";
    513   if (strcmp (s, ".sdynbss") == 0)
    514     return ".sbss";
    515 
    516   return s;
    517 }
    518 
    519 /* qsort comparator for addrs_section_sort.  Sort entries in ascending order by
    520    their (name, sectindex) pair.  sectindex makes the sort by name stable.  */
    521 
    522 static int
    523 addrs_section_compar (const void *ap, const void *bp)
    524 {
    525   const struct other_sections *a = *((struct other_sections **) ap);
    526   const struct other_sections *b = *((struct other_sections **) bp);
    527   int retval;
    528 
    529   retval = strcmp (addr_section_name (a->name), addr_section_name (b->name));
    530   if (retval)
    531     return retval;
    532 
    533   return a->sectindex - b->sectindex;
    534 }
    535 
    536 /* Provide sorted array of pointers to sections of ADDRS.  The array is
    537    terminated by NULL.  Caller is responsible to call xfree for it.  */
    538 
    539 static struct other_sections **
    540 addrs_section_sort (struct section_addr_info *addrs)
    541 {
    542   struct other_sections **array;
    543   int i;
    544 
    545   /* `+ 1' for the NULL terminator.  */
    546   array = XNEWVEC (struct other_sections *, addrs->num_sections + 1);
    547   for (i = 0; i < addrs->num_sections; i++)
    548     array[i] = &addrs->other[i];
    549   array[i] = NULL;
    550 
    551   qsort (array, i, sizeof (*array), addrs_section_compar);
    552 
    553   return array;
    554 }
    555 
    556 /* Relativize absolute addresses in ADDRS into offsets based on ABFD.  Fill-in
    557    also SECTINDEXes specific to ABFD there.  This function can be used to
    558    rebase ADDRS to start referencing different BFD than before.  */
    559 
    560 void
    561 addr_info_make_relative (struct section_addr_info *addrs, bfd *abfd)
    562 {
    563   asection *lower_sect;
    564   CORE_ADDR lower_offset;
    565   int i;
    566   struct cleanup *my_cleanup;
    567   struct section_addr_info *abfd_addrs;
    568   struct other_sections **addrs_sorted, **abfd_addrs_sorted;
    569   struct other_sections **addrs_to_abfd_addrs;
    570 
    571   /* Find lowest loadable section to be used as starting point for
    572      continguous sections.  */
    573   lower_sect = NULL;
    574   bfd_map_over_sections (abfd, find_lowest_section, &lower_sect);
    575   if (lower_sect == NULL)
    576     {
    577       warning (_("no loadable sections found in added symbol-file %s"),
    578 	       bfd_get_filename (abfd));
    579       lower_offset = 0;
    580     }
    581   else
    582     lower_offset = bfd_section_vma (bfd_get_filename (abfd), lower_sect);
    583 
    584   /* Create ADDRS_TO_ABFD_ADDRS array to map the sections in ADDRS to sections
    585      in ABFD.  Section names are not unique - there can be multiple sections of
    586      the same name.  Also the sections of the same name do not have to be
    587      adjacent to each other.  Some sections may be present only in one of the
    588      files.  Even sections present in both files do not have to be in the same
    589      order.
    590 
    591      Use stable sort by name for the sections in both files.  Then linearly
    592      scan both lists matching as most of the entries as possible.  */
    593 
    594   addrs_sorted = addrs_section_sort (addrs);
    595   my_cleanup = make_cleanup (xfree, addrs_sorted);
    596 
    597   abfd_addrs = build_section_addr_info_from_bfd (abfd);
    598   make_cleanup_free_section_addr_info (abfd_addrs);
    599   abfd_addrs_sorted = addrs_section_sort (abfd_addrs);
    600   make_cleanup (xfree, abfd_addrs_sorted);
    601 
    602   /* Now create ADDRS_TO_ABFD_ADDRS from ADDRS_SORTED and
    603      ABFD_ADDRS_SORTED.  */
    604 
    605   addrs_to_abfd_addrs = XCNEWVEC (struct other_sections *, addrs->num_sections);
    606   make_cleanup (xfree, addrs_to_abfd_addrs);
    607 
    608   while (*addrs_sorted)
    609     {
    610       const char *sect_name = addr_section_name ((*addrs_sorted)->name);
    611 
    612       while (*abfd_addrs_sorted
    613 	     && strcmp (addr_section_name ((*abfd_addrs_sorted)->name),
    614 			sect_name) < 0)
    615 	abfd_addrs_sorted++;
    616 
    617       if (*abfd_addrs_sorted
    618 	  && strcmp (addr_section_name ((*abfd_addrs_sorted)->name),
    619 		     sect_name) == 0)
    620 	{
    621 	  int index_in_addrs;
    622 
    623 	  /* Make the found item directly addressable from ADDRS.  */
    624 	  index_in_addrs = *addrs_sorted - addrs->other;
    625 	  gdb_assert (addrs_to_abfd_addrs[index_in_addrs] == NULL);
    626 	  addrs_to_abfd_addrs[index_in_addrs] = *abfd_addrs_sorted;
    627 
    628 	  /* Never use the same ABFD entry twice.  */
    629 	  abfd_addrs_sorted++;
    630 	}
    631 
    632       addrs_sorted++;
    633     }
    634 
    635   /* Calculate offsets for the loadable sections.
    636      FIXME! Sections must be in order of increasing loadable section
    637      so that contiguous sections can use the lower-offset!!!
    638 
    639      Adjust offsets if the segments are not contiguous.
    640      If the section is contiguous, its offset should be set to
    641      the offset of the highest loadable section lower than it
    642      (the loadable section directly below it in memory).
    643      this_offset = lower_offset = lower_addr - lower_orig_addr */
    644 
    645   for (i = 0; i < addrs->num_sections; i++)
    646     {
    647       struct other_sections *sect = addrs_to_abfd_addrs[i];
    648 
    649       if (sect)
    650 	{
    651 	  /* This is the index used by BFD.  */
    652 	  addrs->other[i].sectindex = sect->sectindex;
    653 
    654 	  if (addrs->other[i].addr != 0)
    655 	    {
    656 	      addrs->other[i].addr -= sect->addr;
    657 	      lower_offset = addrs->other[i].addr;
    658 	    }
    659 	  else
    660 	    addrs->other[i].addr = lower_offset;
    661 	}
    662       else
    663 	{
    664 	  /* addr_section_name transformation is not used for SECT_NAME.  */
    665 	  const char *sect_name = addrs->other[i].name;
    666 
    667 	  /* This section does not exist in ABFD, which is normally
    668 	     unexpected and we want to issue a warning.
    669 
    670 	     However, the ELF prelinker does create a few sections which are
    671 	     marked in the main executable as loadable (they are loaded in
    672 	     memory from the DYNAMIC segment) and yet are not present in
    673 	     separate debug info files.  This is fine, and should not cause
    674 	     a warning.  Shared libraries contain just the section
    675 	     ".gnu.liblist" but it is not marked as loadable there.  There is
    676 	     no other way to identify them than by their name as the sections
    677 	     created by prelink have no special flags.
    678 
    679 	     For the sections `.bss' and `.sbss' see addr_section_name.  */
    680 
    681 	  if (!(strcmp (sect_name, ".gnu.liblist") == 0
    682 		|| strcmp (sect_name, ".gnu.conflict") == 0
    683 		|| (strcmp (sect_name, ".bss") == 0
    684 		    && i > 0
    685 		    && strcmp (addrs->other[i - 1].name, ".dynbss") == 0
    686 		    && addrs_to_abfd_addrs[i - 1] != NULL)
    687 		|| (strcmp (sect_name, ".sbss") == 0
    688 		    && i > 0
    689 		    && strcmp (addrs->other[i - 1].name, ".sdynbss") == 0
    690 		    && addrs_to_abfd_addrs[i - 1] != NULL)))
    691 	    warning (_("section %s not found in %s"), sect_name,
    692 		     bfd_get_filename (abfd));
    693 
    694 	  addrs->other[i].addr = 0;
    695 	  addrs->other[i].sectindex = -1;
    696 	}
    697     }
    698 
    699   do_cleanups (my_cleanup);
    700 }
    701 
    702 /* Parse the user's idea of an offset for dynamic linking, into our idea
    703    of how to represent it for fast symbol reading.  This is the default
    704    version of the sym_fns.sym_offsets function for symbol readers that
    705    don't need to do anything special.  It allocates a section_offsets table
    706    for the objectfile OBJFILE and stuffs ADDR into all of the offsets.  */
    707 
    708 void
    709 default_symfile_offsets (struct objfile *objfile,
    710 			 const struct section_addr_info *addrs)
    711 {
    712   objfile->num_sections = gdb_bfd_count_sections (objfile->obfd);
    713   objfile->section_offsets = (struct section_offsets *)
    714     obstack_alloc (&objfile->objfile_obstack,
    715 		   SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
    716   relative_addr_info_to_section_offsets (objfile->section_offsets,
    717 					 objfile->num_sections, addrs);
    718 
    719   /* For relocatable files, all loadable sections will start at zero.
    720      The zero is meaningless, so try to pick arbitrary addresses such
    721      that no loadable sections overlap.  This algorithm is quadratic,
    722      but the number of sections in a single object file is generally
    723      small.  */
    724   if ((bfd_get_file_flags (objfile->obfd) & (EXEC_P | DYNAMIC)) == 0)
    725     {
    726       struct place_section_arg arg;
    727       bfd *abfd = objfile->obfd;
    728       asection *cur_sec;
    729 
    730       for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
    731 	/* We do not expect this to happen; just skip this step if the
    732 	   relocatable file has a section with an assigned VMA.  */
    733 	if (bfd_section_vma (abfd, cur_sec) != 0)
    734 	  break;
    735 
    736       if (cur_sec == NULL)
    737 	{
    738 	  CORE_ADDR *offsets = objfile->section_offsets->offsets;
    739 
    740 	  /* Pick non-overlapping offsets for sections the user did not
    741 	     place explicitly.  */
    742 	  arg.offsets = objfile->section_offsets;
    743 	  arg.lowest = 0;
    744 	  bfd_map_over_sections (objfile->obfd, place_section, &arg);
    745 
    746 	  /* Correctly filling in the section offsets is not quite
    747 	     enough.  Relocatable files have two properties that
    748 	     (most) shared objects do not:
    749 
    750 	     - Their debug information will contain relocations.  Some
    751 	     shared libraries do also, but many do not, so this can not
    752 	     be assumed.
    753 
    754 	     - If there are multiple code sections they will be loaded
    755 	     at different relative addresses in memory than they are
    756 	     in the objfile, since all sections in the file will start
    757 	     at address zero.
    758 
    759 	     Because GDB has very limited ability to map from an
    760 	     address in debug info to the correct code section,
    761 	     it relies on adding SECT_OFF_TEXT to things which might be
    762 	     code.  If we clear all the section offsets, and set the
    763 	     section VMAs instead, then symfile_relocate_debug_section
    764 	     will return meaningful debug information pointing at the
    765 	     correct sections.
    766 
    767 	     GDB has too many different data structures for section
    768 	     addresses - a bfd, objfile, and so_list all have section
    769 	     tables, as does exec_ops.  Some of these could probably
    770 	     be eliminated.  */
    771 
    772 	  for (cur_sec = abfd->sections; cur_sec != NULL;
    773 	       cur_sec = cur_sec->next)
    774 	    {
    775 	      if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0)
    776 		continue;
    777 
    778 	      bfd_set_section_vma (abfd, cur_sec, offsets[cur_sec->index]);
    779 	      exec_set_section_address (bfd_get_filename (abfd),
    780 					cur_sec->index,
    781 					offsets[cur_sec->index]);
    782 	      offsets[cur_sec->index] = 0;
    783 	    }
    784 	}
    785     }
    786 
    787   /* Remember the bfd indexes for the .text, .data, .bss and
    788      .rodata sections.  */
    789   init_objfile_sect_indices (objfile);
    790 }
    791 
    792 /* Divide the file into segments, which are individual relocatable units.
    793    This is the default version of the sym_fns.sym_segments function for
    794    symbol readers that do not have an explicit representation of segments.
    795    It assumes that object files do not have segments, and fully linked
    796    files have a single segment.  */
    797 
    798 struct symfile_segment_data *
    799 default_symfile_segments (bfd *abfd)
    800 {
    801   int num_sections, i;
    802   asection *sect;
    803   struct symfile_segment_data *data;
    804   CORE_ADDR low, high;
    805 
    806   /* Relocatable files contain enough information to position each
    807      loadable section independently; they should not be relocated
    808      in segments.  */
    809   if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC)) == 0)
    810     return NULL;
    811 
    812   /* Make sure there is at least one loadable section in the file.  */
    813   for (sect = abfd->sections; sect != NULL; sect = sect->next)
    814     {
    815       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
    816 	continue;
    817 
    818       break;
    819     }
    820   if (sect == NULL)
    821     return NULL;
    822 
    823   low = bfd_get_section_vma (abfd, sect);
    824   high = low + bfd_get_section_size (sect);
    825 
    826   data = XCNEW (struct symfile_segment_data);
    827   data->num_segments = 1;
    828   data->segment_bases = XCNEW (CORE_ADDR);
    829   data->segment_sizes = XCNEW (CORE_ADDR);
    830 
    831   num_sections = bfd_count_sections (abfd);
    832   data->segment_info = XCNEWVEC (int, num_sections);
    833 
    834   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
    835     {
    836       CORE_ADDR vma;
    837 
    838       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
    839 	continue;
    840 
    841       vma = bfd_get_section_vma (abfd, sect);
    842       if (vma < low)
    843 	low = vma;
    844       if (vma + bfd_get_section_size (sect) > high)
    845 	high = vma + bfd_get_section_size (sect);
    846 
    847       data->segment_info[i] = 1;
    848     }
    849 
    850   data->segment_bases[0] = low;
    851   data->segment_sizes[0] = high - low;
    852 
    853   return data;
    854 }
    855 
    856 /* This is a convenience function to call sym_read for OBJFILE and
    857    possibly force the partial symbols to be read.  */
    858 
    859 static void
    860 read_symbols (struct objfile *objfile, symfile_add_flags add_flags)
    861 {
    862   (*objfile->sf->sym_read) (objfile, add_flags);
    863   objfile->per_bfd->minsyms_read = 1;
    864 
    865   /* find_separate_debug_file_in_section should be called only if there is
    866      single binary with no existing separate debug info file.  */
    867   if (!objfile_has_partial_symbols (objfile)
    868       && objfile->separate_debug_objfile == NULL
    869       && objfile->separate_debug_objfile_backlink == NULL)
    870     {
    871       gdb_bfd_ref_ptr abfd (find_separate_debug_file_in_section (objfile));
    872 
    873       if (abfd != NULL)
    874 	{
    875 	  /* find_separate_debug_file_in_section uses the same filename for the
    876 	     virtual section-as-bfd like the bfd filename containing the
    877 	     section.  Therefore use also non-canonical name form for the same
    878 	     file containing the section.  */
    879 	  symbol_file_add_separate (abfd.get (), objfile->original_name,
    880 				    add_flags, objfile);
    881 	}
    882     }
    883   if ((add_flags & SYMFILE_NO_READ) == 0)
    884     require_partial_symbols (objfile, 0);
    885 }
    886 
    887 /* Initialize entry point information for this objfile.  */
    888 
    889 static void
    890 init_entry_point_info (struct objfile *objfile)
    891 {
    892   struct entry_info *ei = &objfile->per_bfd->ei;
    893 
    894   if (ei->initialized)
    895     return;
    896   ei->initialized = 1;
    897 
    898   /* Save startup file's range of PC addresses to help blockframe.c
    899      decide where the bottom of the stack is.  */
    900 
    901   if (bfd_get_file_flags (objfile->obfd) & EXEC_P)
    902     {
    903       /* Executable file -- record its entry point so we'll recognize
    904          the startup file because it contains the entry point.  */
    905       ei->entry_point = bfd_get_start_address (objfile->obfd);
    906       ei->entry_point_p = 1;
    907     }
    908   else if (bfd_get_file_flags (objfile->obfd) & DYNAMIC
    909 	   && bfd_get_start_address (objfile->obfd) != 0)
    910     {
    911       /* Some shared libraries may have entry points set and be
    912 	 runnable.  There's no clear way to indicate this, so just check
    913 	 for values other than zero.  */
    914       ei->entry_point = bfd_get_start_address (objfile->obfd);
    915       ei->entry_point_p = 1;
    916     }
    917   else
    918     {
    919       /* Examination of non-executable.o files.  Short-circuit this stuff.  */
    920       ei->entry_point_p = 0;
    921     }
    922 
    923   if (ei->entry_point_p)
    924     {
    925       struct obj_section *osect;
    926       CORE_ADDR entry_point =  ei->entry_point;
    927       int found;
    928 
    929       /* Make certain that the address points at real code, and not a
    930 	 function descriptor.  */
    931       entry_point
    932 	= gdbarch_convert_from_func_ptr_addr (get_objfile_arch (objfile),
    933 					      entry_point,
    934 					      &current_target);
    935 
    936       /* Remove any ISA markers, so that this matches entries in the
    937 	 symbol table.  */
    938       ei->entry_point
    939 	= gdbarch_addr_bits_remove (get_objfile_arch (objfile), entry_point);
    940 
    941       found = 0;
    942       ALL_OBJFILE_OSECTIONS (objfile, osect)
    943 	{
    944 	  struct bfd_section *sect = osect->the_bfd_section;
    945 
    946 	  if (entry_point >= bfd_get_section_vma (objfile->obfd, sect)
    947 	      && entry_point < (bfd_get_section_vma (objfile->obfd, sect)
    948 				+ bfd_get_section_size (sect)))
    949 	    {
    950 	      ei->the_bfd_section_index
    951 		= gdb_bfd_section_index (objfile->obfd, sect);
    952 	      found = 1;
    953 	      break;
    954 	    }
    955 	}
    956 
    957       if (!found)
    958 	ei->the_bfd_section_index = SECT_OFF_TEXT (objfile);
    959     }
    960 }
    961 
    962 /* Process a symbol file, as either the main file or as a dynamically
    963    loaded file.
    964 
    965    This function does not set the OBJFILE's entry-point info.
    966 
    967    OBJFILE is where the symbols are to be read from.
    968 
    969    ADDRS is the list of section load addresses.  If the user has given
    970    an 'add-symbol-file' command, then this is the list of offsets and
    971    addresses he or she provided as arguments to the command; or, if
    972    we're handling a shared library, these are the actual addresses the
    973    sections are loaded at, according to the inferior's dynamic linker
    974    (as gleaned by GDB's shared library code).  We convert each address
    975    into an offset from the section VMA's as it appears in the object
    976    file, and then call the file's sym_offsets function to convert this
    977    into a format-specific offset table --- a `struct section_offsets'.
    978 
    979    ADD_FLAGS encodes verbosity level, whether this is main symbol or
    980    an extra symbol file such as dynamically loaded code, and wether
    981    breakpoint reset should be deferred.  */
    982 
    983 static void
    984 syms_from_objfile_1 (struct objfile *objfile,
    985 		     struct section_addr_info *addrs,
    986 		     symfile_add_flags add_flags)
    987 {
    988   struct section_addr_info *local_addr = NULL;
    989   struct cleanup *old_chain;
    990   const int mainline = add_flags & SYMFILE_MAINLINE;
    991 
    992   objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd));
    993 
    994   if (objfile->sf == NULL)
    995     {
    996       /* No symbols to load, but we still need to make sure
    997 	 that the section_offsets table is allocated.  */
    998       int num_sections = gdb_bfd_count_sections (objfile->obfd);
    999       size_t size = SIZEOF_N_SECTION_OFFSETS (num_sections);
   1000 
   1001       objfile->num_sections = num_sections;
   1002       objfile->section_offsets
   1003 	= (struct section_offsets *) obstack_alloc (&objfile->objfile_obstack,
   1004 						    size);
   1005       memset (objfile->section_offsets, 0, size);
   1006       return;
   1007     }
   1008 
   1009   /* Make sure that partially constructed symbol tables will be cleaned up
   1010      if an error occurs during symbol reading.  */
   1011   old_chain = make_cleanup_free_objfile (objfile);
   1012 
   1013   /* If ADDRS is NULL, put together a dummy address list.
   1014      We now establish the convention that an addr of zero means
   1015      no load address was specified.  */
   1016   if (! addrs)
   1017     {
   1018       local_addr = alloc_section_addr_info (1);
   1019       make_cleanup (xfree, local_addr);
   1020       addrs = local_addr;
   1021     }
   1022 
   1023   if (mainline)
   1024     {
   1025       /* We will modify the main symbol table, make sure that all its users
   1026          will be cleaned up if an error occurs during symbol reading.  */
   1027       make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/);
   1028 
   1029       /* Since no error yet, throw away the old symbol table.  */
   1030 
   1031       if (symfile_objfile != NULL)
   1032 	{
   1033 	  free_objfile (symfile_objfile);
   1034 	  gdb_assert (symfile_objfile == NULL);
   1035 	}
   1036 
   1037       /* Currently we keep symbols from the add-symbol-file command.
   1038          If the user wants to get rid of them, they should do "symbol-file"
   1039          without arguments first.  Not sure this is the best behavior
   1040          (PR 2207).  */
   1041 
   1042       (*objfile->sf->sym_new_init) (objfile);
   1043     }
   1044 
   1045   /* Convert addr into an offset rather than an absolute address.
   1046      We find the lowest address of a loaded segment in the objfile,
   1047      and assume that <addr> is where that got loaded.
   1048 
   1049      We no longer warn if the lowest section is not a text segment (as
   1050      happens for the PA64 port.  */
   1051   if (addrs->num_sections > 0)
   1052     addr_info_make_relative (addrs, objfile->obfd);
   1053 
   1054   /* Initialize symbol reading routines for this objfile, allow complaints to
   1055      appear for this new file, and record how verbose to be, then do the
   1056      initial symbol reading for this file.  */
   1057 
   1058   (*objfile->sf->sym_init) (objfile);
   1059   clear_complaints (&symfile_complaints, 1, add_flags & SYMFILE_VERBOSE);
   1060 
   1061   (*objfile->sf->sym_offsets) (objfile, addrs);
   1062 
   1063   read_symbols (objfile, add_flags);
   1064 
   1065   /* Discard cleanups as symbol reading was successful.  */
   1066 
   1067   discard_cleanups (old_chain);
   1068   xfree (local_addr);
   1069 }
   1070 
   1071 /* Same as syms_from_objfile_1, but also initializes the objfile
   1072    entry-point info.  */
   1073 
   1074 static void
   1075 syms_from_objfile (struct objfile *objfile,
   1076 		   struct section_addr_info *addrs,
   1077 		   symfile_add_flags add_flags)
   1078 {
   1079   syms_from_objfile_1 (objfile, addrs, add_flags);
   1080   init_entry_point_info (objfile);
   1081 }
   1082 
   1083 /* Perform required actions after either reading in the initial
   1084    symbols for a new objfile, or mapping in the symbols from a reusable
   1085    objfile.  ADD_FLAGS is a bitmask of enum symfile_add_flags.  */
   1086 
   1087 static void
   1088 finish_new_objfile (struct objfile *objfile, symfile_add_flags add_flags)
   1089 {
   1090   /* If this is the main symbol file we have to clean up all users of the
   1091      old main symbol file.  Otherwise it is sufficient to fixup all the
   1092      breakpoints that may have been redefined by this symbol file.  */
   1093   if (add_flags & SYMFILE_MAINLINE)
   1094     {
   1095       /* OK, make it the "real" symbol file.  */
   1096       symfile_objfile = objfile;
   1097 
   1098       clear_symtab_users (add_flags);
   1099     }
   1100   else if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
   1101     {
   1102       breakpoint_re_set ();
   1103     }
   1104 
   1105   /* We're done reading the symbol file; finish off complaints.  */
   1106   clear_complaints (&symfile_complaints, 0, add_flags & SYMFILE_VERBOSE);
   1107 }
   1108 
   1109 /* Process a symbol file, as either the main file or as a dynamically
   1110    loaded file.
   1111 
   1112    ABFD is a BFD already open on the file, as from symfile_bfd_open.
   1113    A new reference is acquired by this function.
   1114 
   1115    For NAME description see allocate_objfile's definition.
   1116 
   1117    ADD_FLAGS encodes verbosity, whether this is main symbol file or
   1118    extra, such as dynamically loaded code, and what to do with breakpoins.
   1119 
   1120    ADDRS is as described for syms_from_objfile_1, above.
   1121    ADDRS is ignored when SYMFILE_MAINLINE bit is set in ADD_FLAGS.
   1122 
   1123    PARENT is the original objfile if ABFD is a separate debug info file.
   1124    Otherwise PARENT is NULL.
   1125 
   1126    Upon success, returns a pointer to the objfile that was added.
   1127    Upon failure, jumps back to command level (never returns).  */
   1128 
   1129 static struct objfile *
   1130 symbol_file_add_with_addrs (bfd *abfd, const char *name,
   1131 			    symfile_add_flags add_flags,
   1132 			    struct section_addr_info *addrs,
   1133 			    objfile_flags flags, struct objfile *parent)
   1134 {
   1135   struct objfile *objfile;
   1136   const int from_tty = add_flags & SYMFILE_VERBOSE;
   1137   const int mainline = add_flags & SYMFILE_MAINLINE;
   1138   const int should_print = (print_symbol_loading_p (from_tty, mainline, 1)
   1139 			    && (readnow_symbol_files
   1140 				|| (add_flags & SYMFILE_NO_READ) == 0));
   1141 
   1142   if (readnow_symbol_files)
   1143     {
   1144       flags |= OBJF_READNOW;
   1145       add_flags &= ~SYMFILE_NO_READ;
   1146     }
   1147 
   1148   /* Give user a chance to burp if we'd be
   1149      interactively wiping out any existing symbols.  */
   1150 
   1151   if ((have_full_symbols () || have_partial_symbols ())
   1152       && mainline
   1153       && from_tty
   1154       && !query (_("Load new symbol table from \"%s\"? "), name))
   1155     error (_("Not confirmed."));
   1156 
   1157   if (mainline)
   1158     flags |= OBJF_MAINLINE;
   1159   objfile = allocate_objfile (abfd, name, flags);
   1160 
   1161   if (parent)
   1162     add_separate_debug_objfile (objfile, parent);
   1163 
   1164   /* We either created a new mapped symbol table, mapped an existing
   1165      symbol table file which has not had initial symbol reading
   1166      performed, or need to read an unmapped symbol table.  */
   1167   if (should_print)
   1168     {
   1169       if (deprecated_pre_add_symbol_hook)
   1170 	deprecated_pre_add_symbol_hook (name);
   1171       else
   1172 	{
   1173 	  printf_unfiltered (_("Reading symbols from %s..."), name);
   1174 	  wrap_here ("");
   1175 	  gdb_flush (gdb_stdout);
   1176 	}
   1177     }
   1178   syms_from_objfile (objfile, addrs, add_flags);
   1179 
   1180   /* We now have at least a partial symbol table.  Check to see if the
   1181      user requested that all symbols be read on initial access via either
   1182      the gdb startup command line or on a per symbol file basis.  Expand
   1183      all partial symbol tables for this objfile if so.  */
   1184 
   1185   if ((flags & OBJF_READNOW))
   1186     {
   1187       if (should_print)
   1188 	{
   1189 	  printf_unfiltered (_("expanding to full symbols..."));
   1190 	  wrap_here ("");
   1191 	  gdb_flush (gdb_stdout);
   1192 	}
   1193 
   1194       if (objfile->sf)
   1195 	objfile->sf->qf->expand_all_symtabs (objfile);
   1196     }
   1197 
   1198   if (should_print && !objfile_has_symbols (objfile))
   1199     {
   1200       wrap_here ("");
   1201       printf_unfiltered (_("(no debugging symbols found)..."));
   1202       wrap_here ("");
   1203     }
   1204 
   1205   if (should_print)
   1206     {
   1207       if (deprecated_post_add_symbol_hook)
   1208 	deprecated_post_add_symbol_hook ();
   1209       else
   1210 	printf_unfiltered (_("done.\n"));
   1211     }
   1212 
   1213   /* We print some messages regardless of whether 'from_tty ||
   1214      info_verbose' is true, so make sure they go out at the right
   1215      time.  */
   1216   gdb_flush (gdb_stdout);
   1217 
   1218   if (objfile->sf == NULL)
   1219     {
   1220       observer_notify_new_objfile (objfile);
   1221       return objfile;	/* No symbols.  */
   1222     }
   1223 
   1224   finish_new_objfile (objfile, add_flags);
   1225 
   1226   observer_notify_new_objfile (objfile);
   1227 
   1228   bfd_cache_close_all ();
   1229   return (objfile);
   1230 }
   1231 
   1232 /* Add BFD as a separate debug file for OBJFILE.  For NAME description
   1233    see allocate_objfile's definition.  */
   1234 
   1235 void
   1236 symbol_file_add_separate (bfd *bfd, const char *name,
   1237 			  symfile_add_flags symfile_flags,
   1238 			  struct objfile *objfile)
   1239 {
   1240   struct section_addr_info *sap;
   1241   struct cleanup *my_cleanup;
   1242 
   1243   /* Create section_addr_info.  We can't directly use offsets from OBJFILE
   1244      because sections of BFD may not match sections of OBJFILE and because
   1245      vma may have been modified by tools such as prelink.  */
   1246   sap = build_section_addr_info_from_objfile (objfile);
   1247   my_cleanup = make_cleanup_free_section_addr_info (sap);
   1248 
   1249   symbol_file_add_with_addrs
   1250     (bfd, name, symfile_flags, sap,
   1251      objfile->flags & (OBJF_REORDERED | OBJF_SHARED | OBJF_READNOW
   1252 		       | OBJF_USERLOADED),
   1253      objfile);
   1254 
   1255   do_cleanups (my_cleanup);
   1256 }
   1257 
   1258 /* Process the symbol file ABFD, as either the main file or as a
   1259    dynamically loaded file.
   1260    See symbol_file_add_with_addrs's comments for details.  */
   1261 
   1262 struct objfile *
   1263 symbol_file_add_from_bfd (bfd *abfd, const char *name,
   1264 			  symfile_add_flags add_flags,
   1265                           struct section_addr_info *addrs,
   1266                           objfile_flags flags, struct objfile *parent)
   1267 {
   1268   return symbol_file_add_with_addrs (abfd, name, add_flags, addrs, flags,
   1269 				     parent);
   1270 }
   1271 
   1272 /* Process a symbol file, as either the main file or as a dynamically
   1273    loaded file.  See symbol_file_add_with_addrs's comments for details.  */
   1274 
   1275 struct objfile *
   1276 symbol_file_add (const char *name, symfile_add_flags add_flags,
   1277 		 struct section_addr_info *addrs, objfile_flags flags)
   1278 {
   1279   gdb_bfd_ref_ptr bfd (symfile_bfd_open (name));
   1280 
   1281   return symbol_file_add_from_bfd (bfd.get (), name, add_flags, addrs,
   1282 				   flags, NULL);
   1283 }
   1284 
   1285 /* Call symbol_file_add() with default values and update whatever is
   1286    affected by the loading of a new main().
   1287    Used when the file is supplied in the gdb command line
   1288    and by some targets with special loading requirements.
   1289    The auxiliary function, symbol_file_add_main_1(), has the flags
   1290    argument for the switches that can only be specified in the symbol_file
   1291    command itself.  */
   1292 
   1293 void
   1294 symbol_file_add_main (const char *args, symfile_add_flags add_flags)
   1295 {
   1296   symbol_file_add_main_1 (args, add_flags, 0);
   1297 }
   1298 
   1299 static void
   1300 symbol_file_add_main_1 (const char *args, symfile_add_flags add_flags,
   1301 			objfile_flags flags)
   1302 {
   1303   add_flags |= current_inferior ()->symfile_flags | SYMFILE_MAINLINE;
   1304 
   1305   symbol_file_add (args, add_flags, NULL, flags);
   1306 
   1307   /* Getting new symbols may change our opinion about
   1308      what is frameless.  */
   1309   reinit_frame_cache ();
   1310 
   1311   if ((add_flags & SYMFILE_NO_READ) == 0)
   1312     set_initial_language ();
   1313 }
   1314 
   1315 void
   1316 symbol_file_clear (int from_tty)
   1317 {
   1318   if ((have_full_symbols () || have_partial_symbols ())
   1319       && from_tty
   1320       && (symfile_objfile
   1321 	  ? !query (_("Discard symbol table from `%s'? "),
   1322 		    objfile_name (symfile_objfile))
   1323 	  : !query (_("Discard symbol table? "))))
   1324     error (_("Not confirmed."));
   1325 
   1326   /* solib descriptors may have handles to objfiles.  Wipe them before their
   1327      objfiles get stale by free_all_objfiles.  */
   1328   no_shared_libraries (NULL, from_tty);
   1329 
   1330   free_all_objfiles ();
   1331 
   1332   gdb_assert (symfile_objfile == NULL);
   1333   if (from_tty)
   1334     printf_unfiltered (_("No symbol file now.\n"));
   1335 }
   1336 
   1337 static int
   1338 separate_debug_file_exists (const char *name, unsigned long crc,
   1339 			    struct objfile *parent_objfile)
   1340 {
   1341   unsigned long file_crc;
   1342   int file_crc_p;
   1343   struct stat parent_stat, abfd_stat;
   1344   int verified_as_different;
   1345 
   1346   /* Find a separate debug info file as if symbols would be present in
   1347      PARENT_OBJFILE itself this function would not be called.  .gnu_debuglink
   1348      section can contain just the basename of PARENT_OBJFILE without any
   1349      ".debug" suffix as "/usr/lib/debug/path/to/file" is a separate tree where
   1350      the separate debug infos with the same basename can exist.  */
   1351 
   1352   if (filename_cmp (name, objfile_name (parent_objfile)) == 0)
   1353     return 0;
   1354 
   1355   gdb_bfd_ref_ptr abfd (gdb_bfd_open (name, gnutarget, -1));
   1356 
   1357   if (abfd == NULL)
   1358     return 0;
   1359 
   1360   /* Verify symlinks were not the cause of filename_cmp name difference above.
   1361 
   1362      Some operating systems, e.g. Windows, do not provide a meaningful
   1363      st_ino; they always set it to zero.  (Windows does provide a
   1364      meaningful st_dev.)  Files accessed from gdbservers that do not
   1365      support the vFile:fstat packet will also have st_ino set to zero.
   1366      Do not indicate a duplicate library in either case.  While there
   1367      is no guarantee that a system that provides meaningful inode
   1368      numbers will never set st_ino to zero, this is merely an
   1369      optimization, so we do not need to worry about false negatives.  */
   1370 
   1371   if (bfd_stat (abfd.get (), &abfd_stat) == 0
   1372       && abfd_stat.st_ino != 0
   1373       && bfd_stat (parent_objfile->obfd, &parent_stat) == 0)
   1374     {
   1375       if (abfd_stat.st_dev == parent_stat.st_dev
   1376 	  && abfd_stat.st_ino == parent_stat.st_ino)
   1377 	return 0;
   1378       verified_as_different = 1;
   1379     }
   1380   else
   1381     verified_as_different = 0;
   1382 
   1383   file_crc_p = gdb_bfd_crc (abfd.get (), &file_crc);
   1384 
   1385   if (!file_crc_p)
   1386     return 0;
   1387 
   1388   if (crc != file_crc)
   1389     {
   1390       unsigned long parent_crc;
   1391 
   1392       /* If the files could not be verified as different with
   1393 	 bfd_stat then we need to calculate the parent's CRC
   1394 	 to verify whether the files are different or not.  */
   1395 
   1396       if (!verified_as_different)
   1397 	{
   1398 	  if (!gdb_bfd_crc (parent_objfile->obfd, &parent_crc))
   1399 	    return 0;
   1400 	}
   1401 
   1402       if (verified_as_different || parent_crc != file_crc)
   1403 	warning (_("the debug information found in \"%s\""
   1404 		   " does not match \"%s\" (CRC mismatch).\n"),
   1405 		 name, objfile_name (parent_objfile));
   1406 
   1407       return 0;
   1408     }
   1409 
   1410   return 1;
   1411 }
   1412 
   1413 char *debug_file_directory = NULL;
   1414 static void
   1415 show_debug_file_directory (struct ui_file *file, int from_tty,
   1416 			   struct cmd_list_element *c, const char *value)
   1417 {
   1418   fprintf_filtered (file,
   1419 		    _("The directory where separate debug "
   1420 		      "symbols are searched for is \"%s\".\n"),
   1421 		    value);
   1422 }
   1423 
   1424 #if ! defined (DEBUG_SUBDIRECTORY)
   1425 #define DEBUG_SUBDIRECTORY ".debug"
   1426 #endif
   1427 
   1428 /* Find a separate debuginfo file for OBJFILE, using DIR as the directory
   1429    where the original file resides (may not be the same as
   1430    dirname(objfile->name) due to symlinks), and DEBUGLINK as the file we are
   1431    looking for.  CANON_DIR is the "realpath" form of DIR.
   1432    DIR must contain a trailing '/'.
   1433    Returns the path of the file with separate debug info, of NULL.  */
   1434 
   1435 static char *
   1436 find_separate_debug_file (const char *dir,
   1437 			  const char *canon_dir,
   1438 			  const char *debuglink,
   1439 			  unsigned long crc32, struct objfile *objfile)
   1440 {
   1441   char *debugdir;
   1442   char *debugfile;
   1443   int i;
   1444   VEC (char_ptr) *debugdir_vec;
   1445   struct cleanup *back_to;
   1446   int ix;
   1447 
   1448   /* Set I to std::max (strlen (canon_dir), strlen (dir)).  */
   1449   i = strlen (dir);
   1450   if (canon_dir != NULL && strlen (canon_dir) > i)
   1451     i = strlen (canon_dir);
   1452 
   1453   debugfile
   1454     = (char *) xmalloc (strlen (debug_file_directory) + 1
   1455 			+ i
   1456 			+ strlen (DEBUG_SUBDIRECTORY)
   1457 			+ strlen ("/")
   1458 			+ strlen (debuglink)
   1459 			+ 1);
   1460 
   1461   /* First try in the same directory as the original file.  */
   1462   strcpy (debugfile, dir);
   1463   strcat (debugfile, debuglink);
   1464 
   1465   if (separate_debug_file_exists (debugfile, crc32, objfile))
   1466     return debugfile;
   1467 
   1468   /* Then try in the subdirectory named DEBUG_SUBDIRECTORY.  */
   1469   strcpy (debugfile, dir);
   1470   strcat (debugfile, DEBUG_SUBDIRECTORY);
   1471   strcat (debugfile, "/");
   1472   strcat (debugfile, debuglink);
   1473 
   1474   if (separate_debug_file_exists (debugfile, crc32, objfile))
   1475     return debugfile;
   1476 
   1477   /* Then try in the global debugfile directories.
   1478 
   1479      Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will
   1480      cause "/..." lookups.  */
   1481 
   1482   debugdir_vec = dirnames_to_char_ptr_vec (debug_file_directory);
   1483   back_to = make_cleanup_free_char_ptr_vec (debugdir_vec);
   1484 
   1485   for (ix = 0; VEC_iterate (char_ptr, debugdir_vec, ix, debugdir); ++ix)
   1486     {
   1487       strcpy (debugfile, debugdir);
   1488       strcat (debugfile, "/");
   1489       strcat (debugfile, dir);
   1490       strcat (debugfile, debuglink);
   1491 
   1492       if (separate_debug_file_exists (debugfile, crc32, objfile))
   1493 	{
   1494 	  do_cleanups (back_to);
   1495 	  return debugfile;
   1496 	}
   1497 
   1498       /* If the file is in the sysroot, try using its base path in the
   1499 	 global debugfile directory.  */
   1500       if (canon_dir != NULL
   1501 	  && filename_ncmp (canon_dir, gdb_sysroot,
   1502 			    strlen (gdb_sysroot)) == 0
   1503 	  && IS_DIR_SEPARATOR (canon_dir[strlen (gdb_sysroot)]))
   1504 	{
   1505 	  strcpy (debugfile, debugdir);
   1506 	  strcat (debugfile, canon_dir + strlen (gdb_sysroot));
   1507 	  strcat (debugfile, "/");
   1508 	  strcat (debugfile, debuglink);
   1509 
   1510 	  if (separate_debug_file_exists (debugfile, crc32, objfile))
   1511 	    {
   1512 	      do_cleanups (back_to);
   1513 	      return debugfile;
   1514 	    }
   1515 	}
   1516     }
   1517 
   1518   do_cleanups (back_to);
   1519   xfree (debugfile);
   1520   return NULL;
   1521 }
   1522 
   1523 /* Modify PATH to contain only "[/]directory/" part of PATH.
   1524    If there were no directory separators in PATH, PATH will be empty
   1525    string on return.  */
   1526 
   1527 static void
   1528 terminate_after_last_dir_separator (char *path)
   1529 {
   1530   int i;
   1531 
   1532   /* Strip off the final filename part, leaving the directory name,
   1533      followed by a slash.  The directory can be relative or absolute.  */
   1534   for (i = strlen(path) - 1; i >= 0; i--)
   1535     if (IS_DIR_SEPARATOR (path[i]))
   1536       break;
   1537 
   1538   /* If I is -1 then no directory is present there and DIR will be "".  */
   1539   path[i + 1] = '\0';
   1540 }
   1541 
   1542 /* Find separate debuginfo for OBJFILE (using .gnu_debuglink section).
   1543    Returns pathname, or NULL.  */
   1544 
   1545 char *
   1546 find_separate_debug_file_by_debuglink (struct objfile *objfile)
   1547 {
   1548   char *debuglink;
   1549   char *dir, *canon_dir;
   1550   char *debugfile;
   1551   unsigned long crc32;
   1552   struct cleanup *cleanups;
   1553 
   1554   debuglink = bfd_get_debug_link_info (objfile->obfd, &crc32);
   1555 
   1556   if (debuglink == NULL)
   1557     {
   1558       /* There's no separate debug info, hence there's no way we could
   1559 	 load it => no warning.  */
   1560       return NULL;
   1561     }
   1562 
   1563   cleanups = make_cleanup (xfree, debuglink);
   1564   dir = xstrdup (objfile_name (objfile));
   1565   make_cleanup (xfree, dir);
   1566   terminate_after_last_dir_separator (dir);
   1567   canon_dir = lrealpath (dir);
   1568 
   1569   debugfile = find_separate_debug_file (dir, canon_dir, debuglink,
   1570 					crc32, objfile);
   1571   xfree (canon_dir);
   1572 
   1573   if (debugfile == NULL)
   1574     {
   1575       /* For PR gdb/9538, try again with realpath (if different from the
   1576 	 original).  */
   1577 
   1578       struct stat st_buf;
   1579 
   1580       if (lstat (objfile_name (objfile), &st_buf) == 0
   1581 	  && S_ISLNK (st_buf.st_mode))
   1582 	{
   1583 	  char *symlink_dir;
   1584 
   1585 	  symlink_dir = lrealpath (objfile_name (objfile));
   1586 	  if (symlink_dir != NULL)
   1587 	    {
   1588 	      make_cleanup (xfree, symlink_dir);
   1589 	      terminate_after_last_dir_separator (symlink_dir);
   1590 	      if (strcmp (dir, symlink_dir) != 0)
   1591 		{
   1592 		  /* Different directory, so try using it.  */
   1593 		  debugfile = find_separate_debug_file (symlink_dir,
   1594 							symlink_dir,
   1595 							debuglink,
   1596 							crc32,
   1597 							objfile);
   1598 		}
   1599 	    }
   1600 	}
   1601     }
   1602 
   1603   do_cleanups (cleanups);
   1604   return debugfile;
   1605 }
   1606 
   1607 /* This is the symbol-file command.  Read the file, analyze its
   1608    symbols, and add a struct symtab to a symtab list.  The syntax of
   1609    the command is rather bizarre:
   1610 
   1611    1. The function buildargv implements various quoting conventions
   1612    which are undocumented and have little or nothing in common with
   1613    the way things are quoted (or not quoted) elsewhere in GDB.
   1614 
   1615    2. Options are used, which are not generally used in GDB (perhaps
   1616    "set mapped on", "set readnow on" would be better)
   1617 
   1618    3. The order of options matters, which is contrary to GNU
   1619    conventions (because it is confusing and inconvenient).  */
   1620 
   1621 void
   1622 symbol_file_command (char *args, int from_tty)
   1623 {
   1624   dont_repeat ();
   1625 
   1626   if (args == NULL)
   1627     {
   1628       symbol_file_clear (from_tty);
   1629     }
   1630   else
   1631     {
   1632       char **argv = gdb_buildargv (args);
   1633       objfile_flags flags = OBJF_USERLOADED;
   1634       symfile_add_flags add_flags = 0;
   1635       struct cleanup *cleanups;
   1636       char *name = NULL;
   1637 
   1638       if (from_tty)
   1639 	add_flags |= SYMFILE_VERBOSE;
   1640 
   1641       cleanups = make_cleanup_freeargv (argv);
   1642       while (*argv != NULL)
   1643 	{
   1644 	  if (strcmp (*argv, "-readnow") == 0)
   1645 	    flags |= OBJF_READNOW;
   1646 	  else if (**argv == '-')
   1647 	    error (_("unknown option `%s'"), *argv);
   1648 	  else
   1649 	    {
   1650 	      symbol_file_add_main_1 (*argv, add_flags, flags);
   1651 	      name = *argv;
   1652 	    }
   1653 
   1654 	  argv++;
   1655 	}
   1656 
   1657       if (name == NULL)
   1658 	error (_("no symbol file name was specified"));
   1659 
   1660       do_cleanups (cleanups);
   1661     }
   1662 }
   1663 
   1664 /* Set the initial language.
   1665 
   1666    FIXME: A better solution would be to record the language in the
   1667    psymtab when reading partial symbols, and then use it (if known) to
   1668    set the language.  This would be a win for formats that encode the
   1669    language in an easily discoverable place, such as DWARF.  For
   1670    stabs, we can jump through hoops looking for specially named
   1671    symbols or try to intuit the language from the specific type of
   1672    stabs we find, but we can't do that until later when we read in
   1673    full symbols.  */
   1674 
   1675 void
   1676 set_initial_language (void)
   1677 {
   1678   enum language lang = main_language ();
   1679 
   1680   if (lang == language_unknown)
   1681     {
   1682       char *name = main_name ();
   1683       struct symbol *sym = lookup_symbol (name, NULL, VAR_DOMAIN, NULL).symbol;
   1684 
   1685       if (sym != NULL)
   1686 	lang = SYMBOL_LANGUAGE (sym);
   1687     }
   1688 
   1689   if (lang == language_unknown)
   1690     {
   1691       /* Make C the default language */
   1692       lang = language_c;
   1693     }
   1694 
   1695   set_language (lang);
   1696   expected_language = current_language; /* Don't warn the user.  */
   1697 }
   1698 
   1699 /* Open the file specified by NAME and hand it off to BFD for
   1700    preliminary analysis.  Return a newly initialized bfd *, which
   1701    includes a newly malloc'd` copy of NAME (tilde-expanded and made
   1702    absolute).  In case of trouble, error() is called.  */
   1703 
   1704 gdb_bfd_ref_ptr
   1705 symfile_bfd_open (const char *name)
   1706 {
   1707   int desc = -1;
   1708   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
   1709 
   1710   if (!is_target_filename (name))
   1711     {
   1712       char *expanded_name, *absolute_name;
   1713 
   1714       expanded_name = tilde_expand (name); /* Returns 1st new malloc'd copy.  */
   1715 
   1716       /* Look down path for it, allocate 2nd new malloc'd copy.  */
   1717       desc = openp (getenv ("PATH"),
   1718 		    OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
   1719 		    expanded_name, O_RDONLY | O_BINARY, &absolute_name);
   1720 #if defined(__GO32__) || defined(_WIN32) || defined (__CYGWIN__)
   1721       if (desc < 0)
   1722 	{
   1723 	  char *exename = (char *) alloca (strlen (expanded_name) + 5);
   1724 
   1725 	  strcat (strcpy (exename, expanded_name), ".exe");
   1726 	  desc = openp (getenv ("PATH"),
   1727 			OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
   1728 			exename, O_RDONLY | O_BINARY, &absolute_name);
   1729 	}
   1730 #endif
   1731       if (desc < 0)
   1732 	{
   1733 	  make_cleanup (xfree, expanded_name);
   1734 	  perror_with_name (expanded_name);
   1735 	}
   1736 
   1737       xfree (expanded_name);
   1738       make_cleanup (xfree, absolute_name);
   1739       name = absolute_name;
   1740     }
   1741 
   1742   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (name, gnutarget, desc));
   1743   if (sym_bfd == NULL)
   1744     error (_("`%s': can't open to read symbols: %s."), name,
   1745 	   bfd_errmsg (bfd_get_error ()));
   1746 
   1747   if (!gdb_bfd_has_target_filename (sym_bfd.get ()))
   1748     bfd_set_cacheable (sym_bfd.get (), 1);
   1749 
   1750   if (!bfd_check_format (sym_bfd.get (), bfd_object))
   1751     error (_("`%s': can't read symbols: %s."), name,
   1752 	   bfd_errmsg (bfd_get_error ()));
   1753 
   1754   do_cleanups (back_to);
   1755 
   1756   return sym_bfd;
   1757 }
   1758 
   1759 /* Return the section index for SECTION_NAME on OBJFILE.  Return -1 if
   1760    the section was not found.  */
   1761 
   1762 int
   1763 get_section_index (struct objfile *objfile, const char *section_name)
   1764 {
   1765   asection *sect = bfd_get_section_by_name (objfile->obfd, section_name);
   1766 
   1767   if (sect)
   1768     return sect->index;
   1769   else
   1770     return -1;
   1771 }
   1772 
   1773 /* Link SF into the global symtab_fns list.
   1774    FLAVOUR is the file format that SF handles.
   1775    Called on startup by the _initialize routine in each object file format
   1776    reader, to register information about each format the reader is prepared
   1777    to handle.  */
   1778 
   1779 void
   1780 add_symtab_fns (enum bfd_flavour flavour, const struct sym_fns *sf)
   1781 {
   1782   registered_sym_fns fns = { flavour, sf };
   1783 
   1784   VEC_safe_push (registered_sym_fns, symtab_fns, &fns);
   1785 }
   1786 
   1787 /* Initialize OBJFILE to read symbols from its associated BFD.  It
   1788    either returns or calls error().  The result is an initialized
   1789    struct sym_fns in the objfile structure, that contains cached
   1790    information about the symbol file.  */
   1791 
   1792 static const struct sym_fns *
   1793 find_sym_fns (bfd *abfd)
   1794 {
   1795   registered_sym_fns *rsf;
   1796   enum bfd_flavour our_flavour = bfd_get_flavour (abfd);
   1797   int i;
   1798 
   1799   if (our_flavour == bfd_target_srec_flavour
   1800       || our_flavour == bfd_target_ihex_flavour
   1801       || our_flavour == bfd_target_tekhex_flavour)
   1802     return NULL;	/* No symbols.  */
   1803 
   1804   for (i = 0; VEC_iterate (registered_sym_fns, symtab_fns, i, rsf); ++i)
   1805     if (our_flavour == rsf->sym_flavour)
   1806       return rsf->sym_fns;
   1807 
   1808   error (_("I'm sorry, Dave, I can't do that.  Symbol format `%s' unknown."),
   1809 	 bfd_get_target (abfd));
   1810 }
   1811 
   1812 
   1814 /* This function runs the load command of our current target.  */
   1815 
   1816 static void
   1817 load_command (char *arg, int from_tty)
   1818 {
   1819   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
   1820 
   1821   dont_repeat ();
   1822 
   1823   /* The user might be reloading because the binary has changed.  Take
   1824      this opportunity to check.  */
   1825   reopen_exec_file ();
   1826   reread_symbols ();
   1827 
   1828   if (arg == NULL)
   1829     {
   1830       char *parg;
   1831       int count = 0;
   1832 
   1833       parg = arg = get_exec_file (1);
   1834 
   1835       /* Count how many \ " ' tab space there are in the name.  */
   1836       while ((parg = strpbrk (parg, "\\\"'\t ")))
   1837 	{
   1838 	  parg++;
   1839 	  count++;
   1840 	}
   1841 
   1842       if (count)
   1843 	{
   1844 	  /* We need to quote this string so buildargv can pull it apart.  */
   1845 	  char *temp = (char *) xmalloc (strlen (arg) + count + 1 );
   1846 	  char *ptemp = temp;
   1847 	  char *prev;
   1848 
   1849 	  make_cleanup (xfree, temp);
   1850 
   1851 	  prev = parg = arg;
   1852 	  while ((parg = strpbrk (parg, "\\\"'\t ")))
   1853 	    {
   1854 	      strncpy (ptemp, prev, parg - prev);
   1855 	      ptemp += parg - prev;
   1856 	      prev = parg++;
   1857 	      *ptemp++ = '\\';
   1858 	    }
   1859 	  strcpy (ptemp, prev);
   1860 
   1861 	  arg = temp;
   1862 	}
   1863     }
   1864 
   1865   target_load (arg, from_tty);
   1866 
   1867   /* After re-loading the executable, we don't really know which
   1868      overlays are mapped any more.  */
   1869   overlay_cache_invalid = 1;
   1870 
   1871   do_cleanups (cleanup);
   1872 }
   1873 
   1874 /* This version of "load" should be usable for any target.  Currently
   1875    it is just used for remote targets, not inftarg.c or core files,
   1876    on the theory that only in that case is it useful.
   1877 
   1878    Avoiding xmodem and the like seems like a win (a) because we don't have
   1879    to worry about finding it, and (b) On VMS, fork() is very slow and so
   1880    we don't want to run a subprocess.  On the other hand, I'm not sure how
   1881    performance compares.  */
   1882 
   1883 static int validate_download = 0;
   1884 
   1885 /* Callback service function for generic_load (bfd_map_over_sections).  */
   1886 
   1887 static void
   1888 add_section_size_callback (bfd *abfd, asection *asec, void *data)
   1889 {
   1890   bfd_size_type *sum = (bfd_size_type *) data;
   1891 
   1892   *sum += bfd_get_section_size (asec);
   1893 }
   1894 
   1895 /* Opaque data for load_section_callback.  */
   1896 struct load_section_data {
   1897   CORE_ADDR load_offset;
   1898   struct load_progress_data *progress_data;
   1899   VEC(memory_write_request_s) *requests;
   1900 };
   1901 
   1902 /* Opaque data for load_progress.  */
   1903 struct load_progress_data {
   1904   /* Cumulative data.  */
   1905   unsigned long write_count;
   1906   unsigned long data_count;
   1907   bfd_size_type total_size;
   1908 };
   1909 
   1910 /* Opaque data for load_progress for a single section.  */
   1911 struct load_progress_section_data {
   1912   struct load_progress_data *cumulative;
   1913 
   1914   /* Per-section data.  */
   1915   const char *section_name;
   1916   ULONGEST section_sent;
   1917   ULONGEST section_size;
   1918   CORE_ADDR lma;
   1919   gdb_byte *buffer;
   1920 };
   1921 
   1922 /* Target write callback routine for progress reporting.  */
   1923 
   1924 static void
   1925 load_progress (ULONGEST bytes, void *untyped_arg)
   1926 {
   1927   struct load_progress_section_data *args
   1928     = (struct load_progress_section_data *) untyped_arg;
   1929   struct load_progress_data *totals;
   1930 
   1931   if (args == NULL)
   1932     /* Writing padding data.  No easy way to get at the cumulative
   1933        stats, so just ignore this.  */
   1934     return;
   1935 
   1936   totals = args->cumulative;
   1937 
   1938   if (bytes == 0 && args->section_sent == 0)
   1939     {
   1940       /* The write is just starting.  Let the user know we've started
   1941 	 this section.  */
   1942       current_uiout->message ("Loading section %s, size %s lma %s\n",
   1943 			      args->section_name,
   1944 			      hex_string (args->section_size),
   1945 			      paddress (target_gdbarch (), args->lma));
   1946       return;
   1947     }
   1948 
   1949   if (validate_download)
   1950     {
   1951       /* Broken memories and broken monitors manifest themselves here
   1952 	 when bring new computers to life.  This doubles already slow
   1953 	 downloads.  */
   1954       /* NOTE: cagney/1999-10-18: A more efficient implementation
   1955 	 might add a verify_memory() method to the target vector and
   1956 	 then use that.  remote.c could implement that method using
   1957 	 the ``qCRC'' packet.  */
   1958       gdb_byte *check = (gdb_byte *) xmalloc (bytes);
   1959       struct cleanup *verify_cleanups = make_cleanup (xfree, check);
   1960 
   1961       if (target_read_memory (args->lma, check, bytes) != 0)
   1962 	error (_("Download verify read failed at %s"),
   1963 	       paddress (target_gdbarch (), args->lma));
   1964       if (memcmp (args->buffer, check, bytes) != 0)
   1965 	error (_("Download verify compare failed at %s"),
   1966 	       paddress (target_gdbarch (), args->lma));
   1967       do_cleanups (verify_cleanups);
   1968     }
   1969   totals->data_count += bytes;
   1970   args->lma += bytes;
   1971   args->buffer += bytes;
   1972   totals->write_count += 1;
   1973   args->section_sent += bytes;
   1974   if (check_quit_flag ()
   1975       || (deprecated_ui_load_progress_hook != NULL
   1976 	  && deprecated_ui_load_progress_hook (args->section_name,
   1977 					       args->section_sent)))
   1978     error (_("Canceled the download"));
   1979 
   1980   if (deprecated_show_load_progress != NULL)
   1981     deprecated_show_load_progress (args->section_name,
   1982 				   args->section_sent,
   1983 				   args->section_size,
   1984 				   totals->data_count,
   1985 				   totals->total_size);
   1986 }
   1987 
   1988 /* Callback service function for generic_load (bfd_map_over_sections).  */
   1989 
   1990 static void
   1991 load_section_callback (bfd *abfd, asection *asec, void *data)
   1992 {
   1993   struct memory_write_request *new_request;
   1994   struct load_section_data *args = (struct load_section_data *) data;
   1995   struct load_progress_section_data *section_data;
   1996   bfd_size_type size = bfd_get_section_size (asec);
   1997   gdb_byte *buffer;
   1998   const char *sect_name = bfd_get_section_name (abfd, asec);
   1999 
   2000   if ((bfd_get_section_flags (abfd, asec) & SEC_LOAD) == 0)
   2001     return;
   2002 
   2003   if (size == 0)
   2004     return;
   2005 
   2006   new_request = VEC_safe_push (memory_write_request_s,
   2007 			       args->requests, NULL);
   2008   memset (new_request, 0, sizeof (struct memory_write_request));
   2009   section_data = XCNEW (struct load_progress_section_data);
   2010   new_request->begin = bfd_section_lma (abfd, asec) + args->load_offset;
   2011   new_request->end = new_request->begin + size; /* FIXME Should size
   2012 						   be in instead?  */
   2013   new_request->data = (gdb_byte *) xmalloc (size);
   2014   new_request->baton = section_data;
   2015 
   2016   buffer = new_request->data;
   2017 
   2018   section_data->cumulative = args->progress_data;
   2019   section_data->section_name = sect_name;
   2020   section_data->section_size = size;
   2021   section_data->lma = new_request->begin;
   2022   section_data->buffer = buffer;
   2023 
   2024   bfd_get_section_contents (abfd, asec, buffer, 0, size);
   2025 }
   2026 
   2027 /* Clean up an entire memory request vector, including load
   2028    data and progress records.  */
   2029 
   2030 static void
   2031 clear_memory_write_data (void *arg)
   2032 {
   2033   VEC(memory_write_request_s) **vec_p = (VEC(memory_write_request_s) **) arg;
   2034   VEC(memory_write_request_s) *vec = *vec_p;
   2035   int i;
   2036   struct memory_write_request *mr;
   2037 
   2038   for (i = 0; VEC_iterate (memory_write_request_s, vec, i, mr); ++i)
   2039     {
   2040       xfree (mr->data);
   2041       xfree (mr->baton);
   2042     }
   2043   VEC_free (memory_write_request_s, vec);
   2044 }
   2045 
   2046 static void print_transfer_performance (struct ui_file *stream,
   2047 					unsigned long data_count,
   2048 					unsigned long write_count,
   2049 				        std::chrono::steady_clock::duration d);
   2050 
   2051 void
   2052 generic_load (const char *args, int from_tty)
   2053 {
   2054   char *filename;
   2055   struct cleanup *old_cleanups = make_cleanup (null_cleanup, 0);
   2056   struct load_section_data cbdata;
   2057   struct load_progress_data total_progress;
   2058   struct ui_out *uiout = current_uiout;
   2059 
   2060   CORE_ADDR entry;
   2061   char **argv;
   2062 
   2063   memset (&cbdata, 0, sizeof (cbdata));
   2064   memset (&total_progress, 0, sizeof (total_progress));
   2065   cbdata.progress_data = &total_progress;
   2066 
   2067   make_cleanup (clear_memory_write_data, &cbdata.requests);
   2068 
   2069   if (args == NULL)
   2070     error_no_arg (_("file to load"));
   2071 
   2072   argv = gdb_buildargv (args);
   2073   make_cleanup_freeargv (argv);
   2074 
   2075   filename = tilde_expand (argv[0]);
   2076   make_cleanup (xfree, filename);
   2077 
   2078   if (argv[1] != NULL)
   2079     {
   2080       const char *endptr;
   2081 
   2082       cbdata.load_offset = strtoulst (argv[1], &endptr, 0);
   2083 
   2084       /* If the last word was not a valid number then
   2085          treat it as a file name with spaces in.  */
   2086       if (argv[1] == endptr)
   2087         error (_("Invalid download offset:%s."), argv[1]);
   2088 
   2089       if (argv[2] != NULL)
   2090 	error (_("Too many parameters."));
   2091     }
   2092 
   2093   /* Open the file for loading.  */
   2094   gdb_bfd_ref_ptr loadfile_bfd (gdb_bfd_open (filename, gnutarget, -1));
   2095   if (loadfile_bfd == NULL)
   2096     {
   2097       perror_with_name (filename);
   2098       return;
   2099     }
   2100 
   2101   if (!bfd_check_format (loadfile_bfd.get (), bfd_object))
   2102     {
   2103       error (_("\"%s\" is not an object file: %s"), filename,
   2104 	     bfd_errmsg (bfd_get_error ()));
   2105     }
   2106 
   2107   bfd_map_over_sections (loadfile_bfd.get (), add_section_size_callback,
   2108 			 (void *) &total_progress.total_size);
   2109 
   2110   bfd_map_over_sections (loadfile_bfd.get (), load_section_callback, &cbdata);
   2111 
   2112   using namespace std::chrono;
   2113 
   2114   steady_clock::time_point start_time = steady_clock::now ();
   2115 
   2116   if (target_write_memory_blocks (cbdata.requests, flash_discard,
   2117 				  load_progress) != 0)
   2118     error (_("Load failed"));
   2119 
   2120   steady_clock::time_point end_time = steady_clock::now ();
   2121 
   2122   entry = bfd_get_start_address (loadfile_bfd.get ());
   2123   entry = gdbarch_addr_bits_remove (target_gdbarch (), entry);
   2124   uiout->text ("Start address ");
   2125   uiout->field_fmt ("address", "%s", paddress (target_gdbarch (), entry));
   2126   uiout->text (", load size ");
   2127   uiout->field_fmt ("load-size", "%lu", total_progress.data_count);
   2128   uiout->text ("\n");
   2129   regcache_write_pc (get_current_regcache (), entry);
   2130 
   2131   /* Reset breakpoints, now that we have changed the load image.  For
   2132      instance, breakpoints may have been set (or reset, by
   2133      post_create_inferior) while connected to the target but before we
   2134      loaded the program.  In that case, the prologue analyzer could
   2135      have read instructions from the target to find the right
   2136      breakpoint locations.  Loading has changed the contents of that
   2137      memory.  */
   2138 
   2139   breakpoint_re_set ();
   2140 
   2141   print_transfer_performance (gdb_stdout, total_progress.data_count,
   2142 			      total_progress.write_count,
   2143 			      end_time - start_time);
   2144 
   2145   do_cleanups (old_cleanups);
   2146 }
   2147 
   2148 /* Report on STREAM the performance of a memory transfer operation,
   2149    such as 'load'.  DATA_COUNT is the number of bytes transferred.
   2150    WRITE_COUNT is the number of separate write operations, or 0, if
   2151    that information is not available.  TIME is how long the operation
   2152    lasted.  */
   2153 
   2154 static void
   2155 print_transfer_performance (struct ui_file *stream,
   2156 			    unsigned long data_count,
   2157 			    unsigned long write_count,
   2158 			    std::chrono::steady_clock::duration time)
   2159 {
   2160   using namespace std::chrono;
   2161   struct ui_out *uiout = current_uiout;
   2162 
   2163   milliseconds ms = duration_cast<milliseconds> (time);
   2164 
   2165   uiout->text ("Transfer rate: ");
   2166   if (ms.count () > 0)
   2167     {
   2168       unsigned long rate = ((ULONGEST) data_count * 1000) / ms.count ();
   2169 
   2170       if (uiout->is_mi_like_p ())
   2171 	{
   2172 	  uiout->field_fmt ("transfer-rate", "%lu", rate * 8);
   2173 	  uiout->text (" bits/sec");
   2174 	}
   2175       else if (rate < 1024)
   2176 	{
   2177 	  uiout->field_fmt ("transfer-rate", "%lu", rate);
   2178 	  uiout->text (" bytes/sec");
   2179 	}
   2180       else
   2181 	{
   2182 	  uiout->field_fmt ("transfer-rate", "%lu", rate / 1024);
   2183 	  uiout->text (" KB/sec");
   2184 	}
   2185     }
   2186   else
   2187     {
   2188       uiout->field_fmt ("transferred-bits", "%lu", (data_count * 8));
   2189       uiout->text (" bits in <1 sec");
   2190     }
   2191   if (write_count > 0)
   2192     {
   2193       uiout->text (", ");
   2194       uiout->field_fmt ("write-rate", "%lu", data_count / write_count);
   2195       uiout->text (" bytes/write");
   2196     }
   2197   uiout->text (".\n");
   2198 }
   2199 
   2200 /* This function allows the addition of incrementally linked object files.
   2201    It does not modify any state in the target, only in the debugger.  */
   2202 /* Note: ezannoni 2000-04-13 This function/command used to have a
   2203    special case syntax for the rombug target (Rombug is the boot
   2204    monitor for Microware's OS-9 / OS-9000, see remote-os9k.c). In the
   2205    rombug case, the user doesn't need to supply a text address,
   2206    instead a call to target_link() (in target.c) would supply the
   2207    value to use.  We are now discontinuing this type of ad hoc syntax.  */
   2208 
   2209 static void
   2210 add_symbol_file_command (char *args, int from_tty)
   2211 {
   2212   struct gdbarch *gdbarch = get_current_arch ();
   2213   char *filename = NULL;
   2214   char *arg;
   2215   int section_index = 0;
   2216   int argcnt = 0;
   2217   int sec_num = 0;
   2218   int i;
   2219   int expecting_sec_name = 0;
   2220   int expecting_sec_addr = 0;
   2221   char **argv;
   2222   struct objfile *objf;
   2223   objfile_flags flags = OBJF_USERLOADED | OBJF_SHARED;
   2224   symfile_add_flags add_flags = 0;
   2225 
   2226   if (from_tty)
   2227     add_flags |= SYMFILE_VERBOSE;
   2228 
   2229   struct sect_opt
   2230   {
   2231     const char *name;
   2232     const char *value;
   2233   };
   2234 
   2235   struct section_addr_info *section_addrs;
   2236   struct sect_opt *sect_opts = NULL;
   2237   size_t num_sect_opts = 0;
   2238   struct cleanup *my_cleanups = make_cleanup (null_cleanup, NULL);
   2239 
   2240   num_sect_opts = 16;
   2241   sect_opts = XNEWVEC (struct sect_opt, num_sect_opts);
   2242 
   2243   dont_repeat ();
   2244 
   2245   if (args == NULL)
   2246     error (_("add-symbol-file takes a file name and an address"));
   2247 
   2248   argv = gdb_buildargv (args);
   2249   make_cleanup_freeargv (argv);
   2250 
   2251   for (arg = argv[0], argcnt = 0; arg != NULL; arg = argv[++argcnt])
   2252     {
   2253       /* Process the argument.  */
   2254       if (argcnt == 0)
   2255 	{
   2256 	  /* The first argument is the file name.  */
   2257 	  filename = tilde_expand (arg);
   2258 	  make_cleanup (xfree, filename);
   2259 	}
   2260       else if (argcnt == 1)
   2261 	{
   2262 	  /* The second argument is always the text address at which
   2263 	     to load the program.  */
   2264 	  sect_opts[section_index].name = ".text";
   2265 	  sect_opts[section_index].value = arg;
   2266 	  if (++section_index >= num_sect_opts)
   2267 	    {
   2268 	      num_sect_opts *= 2;
   2269 	      sect_opts = ((struct sect_opt *)
   2270 			   xrealloc (sect_opts,
   2271 				     num_sect_opts
   2272 				     * sizeof (struct sect_opt)));
   2273 	    }
   2274 	}
   2275       else
   2276 	{
   2277 	  /* It's an option (starting with '-') or it's an argument
   2278 	     to an option.  */
   2279 	  if (expecting_sec_name)
   2280 	    {
   2281 	      sect_opts[section_index].name = arg;
   2282 	      expecting_sec_name = 0;
   2283 	    }
   2284 	  else if (expecting_sec_addr)
   2285 	    {
   2286 	      sect_opts[section_index].value = arg;
   2287 	      expecting_sec_addr = 0;
   2288 	      if (++section_index >= num_sect_opts)
   2289 		{
   2290 		  num_sect_opts *= 2;
   2291 		  sect_opts = ((struct sect_opt *)
   2292 			       xrealloc (sect_opts,
   2293 					 num_sect_opts
   2294 					 * sizeof (struct sect_opt)));
   2295 		}
   2296 	    }
   2297 	  else if (strcmp (arg, "-readnow") == 0)
   2298 	    flags |= OBJF_READNOW;
   2299 	  else if (strcmp (arg, "-s") == 0)
   2300 	    {
   2301 	      expecting_sec_name = 1;
   2302 	      expecting_sec_addr = 1;
   2303 	    }
   2304 	  else
   2305 	    error (_("USAGE: add-symbol-file <filename> <textaddress>"
   2306 		     " [-readnow] [-s <secname> <addr>]*"));
   2307 	}
   2308     }
   2309 
   2310   /* This command takes at least two arguments.  The first one is a
   2311      filename, and the second is the address where this file has been
   2312      loaded.  Abort now if this address hasn't been provided by the
   2313      user.  */
   2314   if (section_index < 1)
   2315     error (_("The address where %s has been loaded is missing"), filename);
   2316 
   2317   /* Print the prompt for the query below.  And save the arguments into
   2318      a sect_addr_info structure to be passed around to other
   2319      functions.  We have to split this up into separate print
   2320      statements because hex_string returns a local static
   2321      string.  */
   2322 
   2323   printf_unfiltered (_("add symbol table from file \"%s\" at\n"), filename);
   2324   section_addrs = alloc_section_addr_info (section_index);
   2325   make_cleanup (xfree, section_addrs);
   2326   for (i = 0; i < section_index; i++)
   2327     {
   2328       CORE_ADDR addr;
   2329       const char *val = sect_opts[i].value;
   2330       const char *sec = sect_opts[i].name;
   2331 
   2332       addr = parse_and_eval_address (val);
   2333 
   2334       /* Here we store the section offsets in the order they were
   2335          entered on the command line.  */
   2336       section_addrs->other[sec_num].name = (char *) sec;
   2337       section_addrs->other[sec_num].addr = addr;
   2338       printf_unfiltered ("\t%s_addr = %s\n", sec,
   2339 			 paddress (gdbarch, addr));
   2340       sec_num++;
   2341 
   2342       /* The object's sections are initialized when a
   2343 	 call is made to build_objfile_section_table (objfile).
   2344 	 This happens in reread_symbols.
   2345 	 At this point, we don't know what file type this is,
   2346 	 so we can't determine what section names are valid.  */
   2347     }
   2348   section_addrs->num_sections = sec_num;
   2349 
   2350   if (from_tty && (!query ("%s", "")))
   2351     error (_("Not confirmed."));
   2352 
   2353   objf = symbol_file_add (filename, add_flags, section_addrs, flags);
   2354 
   2355   add_target_sections_of_objfile (objf);
   2356 
   2357   /* Getting new symbols may change our opinion about what is
   2358      frameless.  */
   2359   reinit_frame_cache ();
   2360   do_cleanups (my_cleanups);
   2361 }
   2362 
   2363 
   2365 /* This function removes a symbol file that was added via add-symbol-file.  */
   2366 
   2367 static void
   2368 remove_symbol_file_command (char *args, int from_tty)
   2369 {
   2370   char **argv;
   2371   struct objfile *objf = NULL;
   2372   struct cleanup *my_cleanups;
   2373   struct program_space *pspace = current_program_space;
   2374 
   2375   dont_repeat ();
   2376 
   2377   if (args == NULL)
   2378     error (_("remove-symbol-file: no symbol file provided"));
   2379 
   2380   my_cleanups = make_cleanup (null_cleanup, NULL);
   2381 
   2382   argv = gdb_buildargv (args);
   2383 
   2384   if (strcmp (argv[0], "-a") == 0)
   2385     {
   2386       /* Interpret the next argument as an address.  */
   2387       CORE_ADDR addr;
   2388 
   2389       if (argv[1] == NULL)
   2390 	error (_("Missing address argument"));
   2391 
   2392       if (argv[2] != NULL)
   2393 	error (_("Junk after %s"), argv[1]);
   2394 
   2395       addr = parse_and_eval_address (argv[1]);
   2396 
   2397       ALL_OBJFILES (objf)
   2398 	{
   2399 	  if ((objf->flags & OBJF_USERLOADED) != 0
   2400 	      && (objf->flags & OBJF_SHARED) != 0
   2401 	      && objf->pspace == pspace && is_addr_in_objfile (addr, objf))
   2402 	    break;
   2403 	}
   2404     }
   2405   else if (argv[0] != NULL)
   2406     {
   2407       /* Interpret the current argument as a file name.  */
   2408       char *filename;
   2409 
   2410       if (argv[1] != NULL)
   2411 	error (_("Junk after %s"), argv[0]);
   2412 
   2413       filename = tilde_expand (argv[0]);
   2414       make_cleanup (xfree, filename);
   2415 
   2416       ALL_OBJFILES (objf)
   2417 	{
   2418 	  if ((objf->flags & OBJF_USERLOADED) != 0
   2419 	      && (objf->flags & OBJF_SHARED) != 0
   2420 	      && objf->pspace == pspace
   2421 	      && filename_cmp (filename, objfile_name (objf)) == 0)
   2422 	    break;
   2423 	}
   2424     }
   2425 
   2426   if (objf == NULL)
   2427     error (_("No symbol file found"));
   2428 
   2429   if (from_tty
   2430       && !query (_("Remove symbol table from file \"%s\"? "),
   2431 		 objfile_name (objf)))
   2432     error (_("Not confirmed."));
   2433 
   2434   free_objfile (objf);
   2435   clear_symtab_users (0);
   2436 
   2437   do_cleanups (my_cleanups);
   2438 }
   2439 
   2440 /* Re-read symbols if a symbol-file has changed.  */
   2441 
   2442 void
   2443 reread_symbols (void)
   2444 {
   2445   struct objfile *objfile;
   2446   long new_modtime;
   2447   struct stat new_statbuf;
   2448   int res;
   2449   std::vector<struct objfile *> new_objfiles;
   2450 
   2451   /* With the addition of shared libraries, this should be modified,
   2452      the load time should be saved in the partial symbol tables, since
   2453      different tables may come from different source files.  FIXME.
   2454      This routine should then walk down each partial symbol table
   2455      and see if the symbol table that it originates from has been changed.  */
   2456 
   2457   for (objfile = object_files; objfile; objfile = objfile->next)
   2458     {
   2459       if (objfile->obfd == NULL)
   2460 	continue;
   2461 
   2462       /* Separate debug objfiles are handled in the main objfile.  */
   2463       if (objfile->separate_debug_objfile_backlink)
   2464 	continue;
   2465 
   2466       /* If this object is from an archive (what you usually create with
   2467 	 `ar', often called a `static library' on most systems, though
   2468 	 a `shared library' on AIX is also an archive), then you should
   2469 	 stat on the archive name, not member name.  */
   2470       if (objfile->obfd->my_archive)
   2471 	res = stat (objfile->obfd->my_archive->filename, &new_statbuf);
   2472       else
   2473 	res = stat (objfile_name (objfile), &new_statbuf);
   2474       if (res != 0)
   2475 	{
   2476 	  /* FIXME, should use print_sys_errmsg but it's not filtered.  */
   2477 	  printf_unfiltered (_("`%s' has disappeared; keeping its symbols.\n"),
   2478 			     objfile_name (objfile));
   2479 	  continue;
   2480 	}
   2481       new_modtime = new_statbuf.st_mtime;
   2482       if (new_modtime != objfile->mtime)
   2483 	{
   2484 	  struct cleanup *old_cleanups;
   2485 	  struct section_offsets *offsets;
   2486 	  int num_offsets;
   2487 	  char *original_name;
   2488 
   2489 	  printf_unfiltered (_("`%s' has changed; re-reading symbols.\n"),
   2490 			     objfile_name (objfile));
   2491 
   2492 	  /* There are various functions like symbol_file_add,
   2493 	     symfile_bfd_open, syms_from_objfile, etc., which might
   2494 	     appear to do what we want.  But they have various other
   2495 	     effects which we *don't* want.  So we just do stuff
   2496 	     ourselves.  We don't worry about mapped files (for one thing,
   2497 	     any mapped file will be out of date).  */
   2498 
   2499 	  /* If we get an error, blow away this objfile (not sure if
   2500 	     that is the correct response for things like shared
   2501 	     libraries).  */
   2502 	  old_cleanups = make_cleanup_free_objfile (objfile);
   2503 	  /* We need to do this whenever any symbols go away.  */
   2504 	  make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/);
   2505 
   2506 	  if (exec_bfd != NULL
   2507 	      && filename_cmp (bfd_get_filename (objfile->obfd),
   2508 			       bfd_get_filename (exec_bfd)) == 0)
   2509 	    {
   2510 	      /* Reload EXEC_BFD without asking anything.  */
   2511 
   2512 	      exec_file_attach (bfd_get_filename (objfile->obfd), 0);
   2513 	    }
   2514 
   2515 	  /* Keep the calls order approx. the same as in free_objfile.  */
   2516 
   2517 	  /* Free the separate debug objfiles.  It will be
   2518 	     automatically recreated by sym_read.  */
   2519 	  free_objfile_separate_debug (objfile);
   2520 
   2521 	  /* Remove any references to this objfile in the global
   2522 	     value lists.  */
   2523 	  preserve_values (objfile);
   2524 
   2525 	  /* Nuke all the state that we will re-read.  Much of the following
   2526 	     code which sets things to NULL really is necessary to tell
   2527 	     other parts of GDB that there is nothing currently there.
   2528 
   2529 	     Try to keep the freeing order compatible with free_objfile.  */
   2530 
   2531 	  if (objfile->sf != NULL)
   2532 	    {
   2533 	      (*objfile->sf->sym_finish) (objfile);
   2534 	    }
   2535 
   2536 	  clear_objfile_data (objfile);
   2537 
   2538 	  /* Clean up any state BFD has sitting around.  */
   2539 	  {
   2540 	    gdb_bfd_ref_ptr obfd (objfile->obfd);
   2541 	    char *obfd_filename;
   2542 
   2543 	    obfd_filename = bfd_get_filename (objfile->obfd);
   2544 	    /* Open the new BFD before freeing the old one, so that
   2545 	       the filename remains live.  */
   2546 	    gdb_bfd_ref_ptr temp (gdb_bfd_open (obfd_filename, gnutarget, -1));
   2547 	    objfile->obfd = temp.release ();
   2548 	    if (objfile->obfd == NULL)
   2549 	      error (_("Can't open %s to read symbols."), obfd_filename);
   2550 	  }
   2551 
   2552 	  original_name = xstrdup (objfile->original_name);
   2553 	  make_cleanup (xfree, original_name);
   2554 
   2555 	  /* bfd_openr sets cacheable to true, which is what we want.  */
   2556 	  if (!bfd_check_format (objfile->obfd, bfd_object))
   2557 	    error (_("Can't read symbols from %s: %s."), objfile_name (objfile),
   2558 		   bfd_errmsg (bfd_get_error ()));
   2559 
   2560 	  /* Save the offsets, we will nuke them with the rest of the
   2561 	     objfile_obstack.  */
   2562 	  num_offsets = objfile->num_sections;
   2563 	  offsets = ((struct section_offsets *)
   2564 		     alloca (SIZEOF_N_SECTION_OFFSETS (num_offsets)));
   2565 	  memcpy (offsets, objfile->section_offsets,
   2566 		  SIZEOF_N_SECTION_OFFSETS (num_offsets));
   2567 
   2568 	  /* FIXME: Do we have to free a whole linked list, or is this
   2569 	     enough?  */
   2570 	  if (objfile->global_psymbols.list)
   2571 	    xfree (objfile->global_psymbols.list);
   2572 	  memset (&objfile->global_psymbols, 0,
   2573 		  sizeof (objfile->global_psymbols));
   2574 	  if (objfile->static_psymbols.list)
   2575 	    xfree (objfile->static_psymbols.list);
   2576 	  memset (&objfile->static_psymbols, 0,
   2577 		  sizeof (objfile->static_psymbols));
   2578 
   2579 	  /* Free the obstacks for non-reusable objfiles.  */
   2580 	  psymbol_bcache_free (objfile->psymbol_cache);
   2581 	  objfile->psymbol_cache = psymbol_bcache_init ();
   2582 	  obstack_free (&objfile->objfile_obstack, 0);
   2583 	  objfile->sections = NULL;
   2584 	  objfile->compunit_symtabs = NULL;
   2585 	  objfile->psymtabs = NULL;
   2586 	  objfile->psymtabs_addrmap = NULL;
   2587 	  objfile->free_psymtabs = NULL;
   2588 	  objfile->template_symbols = NULL;
   2589 
   2590 	  /* obstack_init also initializes the obstack so it is
   2591 	     empty.  We could use obstack_specify_allocation but
   2592 	     gdb_obstack.h specifies the alloc/dealloc functions.  */
   2593 	  obstack_init (&objfile->objfile_obstack);
   2594 
   2595 	  /* set_objfile_per_bfd potentially allocates the per-bfd
   2596 	     data on the objfile's obstack (if sharing data across
   2597 	     multiple users is not possible), so it's important to
   2598 	     do it *after* the obstack has been initialized.  */
   2599 	  set_objfile_per_bfd (objfile);
   2600 
   2601 	  objfile->original_name
   2602 	    = (char *) obstack_copy0 (&objfile->objfile_obstack, original_name,
   2603 				      strlen (original_name));
   2604 
   2605 	  /* Reset the sym_fns pointer.  The ELF reader can change it
   2606 	     based on whether .gdb_index is present, and we need it to
   2607 	     start over.  PR symtab/15885  */
   2608 	  objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd));
   2609 
   2610 	  build_objfile_section_table (objfile);
   2611 	  terminate_minimal_symbol_table (objfile);
   2612 
   2613 	  /* We use the same section offsets as from last time.  I'm not
   2614 	     sure whether that is always correct for shared libraries.  */
   2615 	  objfile->section_offsets = (struct section_offsets *)
   2616 	    obstack_alloc (&objfile->objfile_obstack,
   2617 			   SIZEOF_N_SECTION_OFFSETS (num_offsets));
   2618 	  memcpy (objfile->section_offsets, offsets,
   2619 		  SIZEOF_N_SECTION_OFFSETS (num_offsets));
   2620 	  objfile->num_sections = num_offsets;
   2621 
   2622 	  /* What the hell is sym_new_init for, anyway?  The concept of
   2623 	     distinguishing between the main file and additional files
   2624 	     in this way seems rather dubious.  */
   2625 	  if (objfile == symfile_objfile)
   2626 	    {
   2627 	      (*objfile->sf->sym_new_init) (objfile);
   2628 	    }
   2629 
   2630 	  (*objfile->sf->sym_init) (objfile);
   2631 	  clear_complaints (&symfile_complaints, 1, 1);
   2632 
   2633 	  objfile->flags &= ~OBJF_PSYMTABS_READ;
   2634 	  read_symbols (objfile, 0);
   2635 
   2636 	  if (!objfile_has_symbols (objfile))
   2637 	    {
   2638 	      wrap_here ("");
   2639 	      printf_unfiltered (_("(no debugging symbols found)\n"));
   2640 	      wrap_here ("");
   2641 	    }
   2642 
   2643 	  /* We're done reading the symbol file; finish off complaints.  */
   2644 	  clear_complaints (&symfile_complaints, 0, 1);
   2645 
   2646 	  /* Getting new symbols may change our opinion about what is
   2647 	     frameless.  */
   2648 
   2649 	  reinit_frame_cache ();
   2650 
   2651 	  /* Discard cleanups as symbol reading was successful.  */
   2652 	  discard_cleanups (old_cleanups);
   2653 
   2654 	  /* If the mtime has changed between the time we set new_modtime
   2655 	     and now, we *want* this to be out of date, so don't call stat
   2656 	     again now.  */
   2657 	  objfile->mtime = new_modtime;
   2658 	  init_entry_point_info (objfile);
   2659 
   2660 	  new_objfiles.push_back (objfile);
   2661 	}
   2662     }
   2663 
   2664   if (!new_objfiles.empty ())
   2665     {
   2666       /* Notify objfiles that we've modified objfile sections.  */
   2667       objfiles_changed ();
   2668 
   2669       clear_symtab_users (0);
   2670 
   2671       /* clear_objfile_data for each objfile was called before freeing it and
   2672 	 observer_notify_new_objfile (NULL) has been called by
   2673 	 clear_symtab_users above.  Notify the new files now.  */
   2674       for (auto iter : new_objfiles)
   2675 	observer_notify_new_objfile (iter);
   2676 
   2677       /* At least one objfile has changed, so we can consider that
   2678          the executable we're debugging has changed too.  */
   2679       observer_notify_executable_changed ();
   2680     }
   2681 }
   2682 
   2683 
   2685 typedef struct
   2686 {
   2687   char *ext;
   2688   enum language lang;
   2689 } filename_language;
   2690 
   2691 DEF_VEC_O (filename_language);
   2692 
   2693 static VEC (filename_language) *filename_language_table;
   2694 
   2695 /* See symfile.h.  */
   2696 
   2697 void
   2698 add_filename_language (const char *ext, enum language lang)
   2699 {
   2700   filename_language entry;
   2701 
   2702   entry.ext = xstrdup (ext);
   2703   entry.lang = lang;
   2704 
   2705   VEC_safe_push (filename_language, filename_language_table, &entry);
   2706 }
   2707 
   2708 static char *ext_args;
   2709 static void
   2710 show_ext_args (struct ui_file *file, int from_tty,
   2711 	       struct cmd_list_element *c, const char *value)
   2712 {
   2713   fprintf_filtered (file,
   2714 		    _("Mapping between filename extension "
   2715 		      "and source language is \"%s\".\n"),
   2716 		    value);
   2717 }
   2718 
   2719 static void
   2720 set_ext_lang_command (char *args, int from_tty, struct cmd_list_element *e)
   2721 {
   2722   int i;
   2723   char *cp = ext_args;
   2724   enum language lang;
   2725   filename_language *entry;
   2726 
   2727   /* First arg is filename extension, starting with '.'  */
   2728   if (*cp != '.')
   2729     error (_("'%s': Filename extension must begin with '.'"), ext_args);
   2730 
   2731   /* Find end of first arg.  */
   2732   while (*cp && !isspace (*cp))
   2733     cp++;
   2734 
   2735   if (*cp == '\0')
   2736     error (_("'%s': two arguments required -- "
   2737 	     "filename extension and language"),
   2738 	   ext_args);
   2739 
   2740   /* Null-terminate first arg.  */
   2741   *cp++ = '\0';
   2742 
   2743   /* Find beginning of second arg, which should be a source language.  */
   2744   cp = skip_spaces (cp);
   2745 
   2746   if (*cp == '\0')
   2747     error (_("'%s': two arguments required -- "
   2748 	     "filename extension and language"),
   2749 	   ext_args);
   2750 
   2751   /* Lookup the language from among those we know.  */
   2752   lang = language_enum (cp);
   2753 
   2754   /* Now lookup the filename extension: do we already know it?  */
   2755   for (i = 0;
   2756        VEC_iterate (filename_language, filename_language_table, i, entry);
   2757        ++i)
   2758     {
   2759       if (0 == strcmp (ext_args, entry->ext))
   2760 	break;
   2761     }
   2762 
   2763   if (entry == NULL)
   2764     {
   2765       /* New file extension.  */
   2766       add_filename_language (ext_args, lang);
   2767     }
   2768   else
   2769     {
   2770       /* Redefining a previously known filename extension.  */
   2771 
   2772       /* if (from_tty) */
   2773       /*   query ("Really make files of type %s '%s'?", */
   2774       /*          ext_args, language_str (lang));           */
   2775 
   2776       xfree (entry->ext);
   2777       entry->ext = xstrdup (ext_args);
   2778       entry->lang = lang;
   2779     }
   2780 }
   2781 
   2782 static void
   2783 info_ext_lang_command (char *args, int from_tty)
   2784 {
   2785   int i;
   2786   filename_language *entry;
   2787 
   2788   printf_filtered (_("Filename extensions and the languages they represent:"));
   2789   printf_filtered ("\n\n");
   2790   for (i = 0;
   2791        VEC_iterate (filename_language, filename_language_table, i, entry);
   2792        ++i)
   2793     printf_filtered ("\t%s\t- %s\n", entry->ext, language_str (entry->lang));
   2794 }
   2795 
   2796 enum language
   2797 deduce_language_from_filename (const char *filename)
   2798 {
   2799   int i;
   2800   const char *cp;
   2801 
   2802   if (filename != NULL)
   2803     if ((cp = strrchr (filename, '.')) != NULL)
   2804       {
   2805 	filename_language *entry;
   2806 
   2807 	for (i = 0;
   2808 	     VEC_iterate (filename_language, filename_language_table, i, entry);
   2809 	     ++i)
   2810 	  if (strcmp (cp, entry->ext) == 0)
   2811 	    return entry->lang;
   2812       }
   2813 
   2814   return language_unknown;
   2815 }
   2816 
   2817 /* Allocate and initialize a new symbol table.
   2819    CUST is from the result of allocate_compunit_symtab.  */
   2820 
   2821 struct symtab *
   2822 allocate_symtab (struct compunit_symtab *cust, const char *filename)
   2823 {
   2824   struct objfile *objfile = cust->objfile;
   2825   struct symtab *symtab
   2826     = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symtab);
   2827 
   2828   symtab->filename
   2829     = (const char *) bcache (filename, strlen (filename) + 1,
   2830 			     objfile->per_bfd->filename_cache);
   2831   symtab->fullname = NULL;
   2832   symtab->language = deduce_language_from_filename (filename);
   2833 
   2834   /* This can be very verbose with lots of headers.
   2835      Only print at higher debug levels.  */
   2836   if (symtab_create_debug >= 2)
   2837     {
   2838       /* Be a bit clever with debugging messages, and don't print objfile
   2839 	 every time, only when it changes.  */
   2840       static char *last_objfile_name = NULL;
   2841 
   2842       if (last_objfile_name == NULL
   2843 	  || strcmp (last_objfile_name, objfile_name (objfile)) != 0)
   2844 	{
   2845 	  xfree (last_objfile_name);
   2846 	  last_objfile_name = xstrdup (objfile_name (objfile));
   2847 	  fprintf_unfiltered (gdb_stdlog,
   2848 			      "Creating one or more symtabs for objfile %s ...\n",
   2849 			      last_objfile_name);
   2850 	}
   2851       fprintf_unfiltered (gdb_stdlog,
   2852 			  "Created symtab %s for module %s.\n",
   2853 			  host_address_to_string (symtab), filename);
   2854     }
   2855 
   2856   /* Add it to CUST's list of symtabs.  */
   2857   if (cust->filetabs == NULL)
   2858     {
   2859       cust->filetabs = symtab;
   2860       cust->last_filetab = symtab;
   2861     }
   2862   else
   2863     {
   2864       cust->last_filetab->next = symtab;
   2865       cust->last_filetab = symtab;
   2866     }
   2867 
   2868   /* Backlink to the containing compunit symtab.  */
   2869   symtab->compunit_symtab = cust;
   2870 
   2871   return symtab;
   2872 }
   2873 
   2874 /* Allocate and initialize a new compunit.
   2875    NAME is the name of the main source file, if there is one, or some
   2876    descriptive text if there are no source files.  */
   2877 
   2878 struct compunit_symtab *
   2879 allocate_compunit_symtab (struct objfile *objfile, const char *name)
   2880 {
   2881   struct compunit_symtab *cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
   2882 					       struct compunit_symtab);
   2883   const char *saved_name;
   2884 
   2885   cu->objfile = objfile;
   2886 
   2887   /* The name we record here is only for display/debugging purposes.
   2888      Just save the basename to avoid path issues (too long for display,
   2889      relative vs absolute, etc.).  */
   2890   saved_name = lbasename (name);
   2891   cu->name
   2892     = (const char *) obstack_copy0 (&objfile->objfile_obstack, saved_name,
   2893 				    strlen (saved_name));
   2894 
   2895   COMPUNIT_DEBUGFORMAT (cu) = "unknown";
   2896 
   2897   if (symtab_create_debug)
   2898     {
   2899       fprintf_unfiltered (gdb_stdlog,
   2900 			  "Created compunit symtab %s for %s.\n",
   2901 			  host_address_to_string (cu),
   2902 			  cu->name);
   2903     }
   2904 
   2905   return cu;
   2906 }
   2907 
   2908 /* Hook CU to the objfile it comes from.  */
   2909 
   2910 void
   2911 add_compunit_symtab_to_objfile (struct compunit_symtab *cu)
   2912 {
   2913   cu->next = cu->objfile->compunit_symtabs;
   2914   cu->objfile->compunit_symtabs = cu;
   2915 }
   2916 
   2917 
   2919 /* Reset all data structures in gdb which may contain references to
   2920    symbol table data.  */
   2921 
   2922 void
   2923 clear_symtab_users (symfile_add_flags add_flags)
   2924 {
   2925   /* Someday, we should do better than this, by only blowing away
   2926      the things that really need to be blown.  */
   2927 
   2928   /* Clear the "current" symtab first, because it is no longer valid.
   2929      breakpoint_re_set may try to access the current symtab.  */
   2930   clear_current_source_symtab_and_line ();
   2931 
   2932   clear_displays ();
   2933   clear_last_displayed_sal ();
   2934   clear_pc_function_cache ();
   2935   observer_notify_new_objfile (NULL);
   2936 
   2937   /* Clear globals which might have pointed into a removed objfile.
   2938      FIXME: It's not clear which of these are supposed to persist
   2939      between expressions and which ought to be reset each time.  */
   2940   expression_context_block = NULL;
   2941   innermost_block = NULL;
   2942 
   2943   /* Varobj may refer to old symbols, perform a cleanup.  */
   2944   varobj_invalidate ();
   2945 
   2946   /* Now that the various caches have been cleared, we can re_set
   2947      our breakpoints without risking it using stale data.  */
   2948   if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
   2949     breakpoint_re_set ();
   2950 }
   2951 
   2952 static void
   2953 clear_symtab_users_cleanup (void *ignore)
   2954 {
   2955   clear_symtab_users (0);
   2956 }
   2957 
   2958 /* OVERLAYS:
   2960    The following code implements an abstraction for debugging overlay sections.
   2961 
   2962    The target model is as follows:
   2963    1) The gnu linker will permit multiple sections to be mapped into the
   2964    same VMA, each with its own unique LMA (or load address).
   2965    2) It is assumed that some runtime mechanism exists for mapping the
   2966    sections, one by one, from the load address into the VMA address.
   2967    3) This code provides a mechanism for gdb to keep track of which
   2968    sections should be considered to be mapped from the VMA to the LMA.
   2969    This information is used for symbol lookup, and memory read/write.
   2970    For instance, if a section has been mapped then its contents
   2971    should be read from the VMA, otherwise from the LMA.
   2972 
   2973    Two levels of debugger support for overlays are available.  One is
   2974    "manual", in which the debugger relies on the user to tell it which
   2975    overlays are currently mapped.  This level of support is
   2976    implemented entirely in the core debugger, and the information about
   2977    whether a section is mapped is kept in the objfile->obj_section table.
   2978 
   2979    The second level of support is "automatic", and is only available if
   2980    the target-specific code provides functionality to read the target's
   2981    overlay mapping table, and translate its contents for the debugger
   2982    (by updating the mapped state information in the obj_section tables).
   2983 
   2984    The interface is as follows:
   2985    User commands:
   2986    overlay map <name>   -- tell gdb to consider this section mapped
   2987    overlay unmap <name> -- tell gdb to consider this section unmapped
   2988    overlay list         -- list the sections that GDB thinks are mapped
   2989    overlay read-target  -- get the target's state of what's mapped
   2990    overlay off/manual/auto -- set overlay debugging state
   2991    Functional interface:
   2992    find_pc_mapped_section(pc):    if the pc is in the range of a mapped
   2993    section, return that section.
   2994    find_pc_overlay(pc):       find any overlay section that contains
   2995    the pc, either in its VMA or its LMA
   2996    section_is_mapped(sect):       true if overlay is marked as mapped
   2997    section_is_overlay(sect):      true if section's VMA != LMA
   2998    pc_in_mapped_range(pc,sec):    true if pc belongs to section's VMA
   2999    pc_in_unmapped_range(...):     true if pc belongs to section's LMA
   3000    sections_overlap(sec1, sec2):  true if mapped sec1 and sec2 ranges overlap
   3001    overlay_mapped_address(...):   map an address from section's LMA to VMA
   3002    overlay_unmapped_address(...): map an address from section's VMA to LMA
   3003    symbol_overlayed_address(...): Return a "current" address for symbol:
   3004    either in VMA or LMA depending on whether
   3005    the symbol's section is currently mapped.  */
   3006 
   3007 /* Overlay debugging state: */
   3008 
   3009 enum overlay_debugging_state overlay_debugging = ovly_off;
   3010 int overlay_cache_invalid = 0;	/* True if need to refresh mapped state.  */
   3011 
   3012 /* Function: section_is_overlay (SECTION)
   3013    Returns true if SECTION has VMA not equal to LMA, ie.
   3014    SECTION is loaded at an address different from where it will "run".  */
   3015 
   3016 int
   3017 section_is_overlay (struct obj_section *section)
   3018 {
   3019   if (overlay_debugging && section)
   3020     {
   3021       bfd *abfd = section->objfile->obfd;
   3022       asection *bfd_section = section->the_bfd_section;
   3023 
   3024       if (bfd_section_lma (abfd, bfd_section) != 0
   3025 	  && bfd_section_lma (abfd, bfd_section)
   3026 	     != bfd_section_vma (abfd, bfd_section))
   3027 	return 1;
   3028     }
   3029 
   3030   return 0;
   3031 }
   3032 
   3033 /* Function: overlay_invalidate_all (void)
   3034    Invalidate the mapped state of all overlay sections (mark it as stale).  */
   3035 
   3036 static void
   3037 overlay_invalidate_all (void)
   3038 {
   3039   struct objfile *objfile;
   3040   struct obj_section *sect;
   3041 
   3042   ALL_OBJSECTIONS (objfile, sect)
   3043     if (section_is_overlay (sect))
   3044       sect->ovly_mapped = -1;
   3045 }
   3046 
   3047 /* Function: section_is_mapped (SECTION)
   3048    Returns true if section is an overlay, and is currently mapped.
   3049 
   3050    Access to the ovly_mapped flag is restricted to this function, so
   3051    that we can do automatic update.  If the global flag
   3052    OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call
   3053    overlay_invalidate_all.  If the mapped state of the particular
   3054    section is stale, then call TARGET_OVERLAY_UPDATE to refresh it.  */
   3055 
   3056 int
   3057 section_is_mapped (struct obj_section *osect)
   3058 {
   3059   struct gdbarch *gdbarch;
   3060 
   3061   if (osect == 0 || !section_is_overlay (osect))
   3062     return 0;
   3063 
   3064   switch (overlay_debugging)
   3065     {
   3066     default:
   3067     case ovly_off:
   3068       return 0;			/* overlay debugging off */
   3069     case ovly_auto:		/* overlay debugging automatic */
   3070       /* Unles there is a gdbarch_overlay_update function,
   3071          there's really nothing useful to do here (can't really go auto).  */
   3072       gdbarch = get_objfile_arch (osect->objfile);
   3073       if (gdbarch_overlay_update_p (gdbarch))
   3074 	{
   3075 	  if (overlay_cache_invalid)
   3076 	    {
   3077 	      overlay_invalidate_all ();
   3078 	      overlay_cache_invalid = 0;
   3079 	    }
   3080 	  if (osect->ovly_mapped == -1)
   3081 	    gdbarch_overlay_update (gdbarch, osect);
   3082 	}
   3083       /* fall thru to manual case */
   3084     case ovly_on:		/* overlay debugging manual */
   3085       return osect->ovly_mapped == 1;
   3086     }
   3087 }
   3088 
   3089 /* Function: pc_in_unmapped_range
   3090    If PC falls into the lma range of SECTION, return true, else false.  */
   3091 
   3092 CORE_ADDR
   3093 pc_in_unmapped_range (CORE_ADDR pc, struct obj_section *section)
   3094 {
   3095   if (section_is_overlay (section))
   3096     {
   3097       bfd *abfd = section->objfile->obfd;
   3098       asection *bfd_section = section->the_bfd_section;
   3099 
   3100       /* We assume the LMA is relocated by the same offset as the VMA.  */
   3101       bfd_vma size = bfd_get_section_size (bfd_section);
   3102       CORE_ADDR offset = obj_section_offset (section);
   3103 
   3104       if (bfd_get_section_lma (abfd, bfd_section) + offset <= pc
   3105 	  && pc < bfd_get_section_lma (abfd, bfd_section) + offset + size)
   3106 	return 1;
   3107     }
   3108 
   3109   return 0;
   3110 }
   3111 
   3112 /* Function: pc_in_mapped_range
   3113    If PC falls into the vma range of SECTION, return true, else false.  */
   3114 
   3115 CORE_ADDR
   3116 pc_in_mapped_range (CORE_ADDR pc, struct obj_section *section)
   3117 {
   3118   if (section_is_overlay (section))
   3119     {
   3120       if (obj_section_addr (section) <= pc
   3121 	  && pc < obj_section_endaddr (section))
   3122 	return 1;
   3123     }
   3124 
   3125   return 0;
   3126 }
   3127 
   3128 /* Return true if the mapped ranges of sections A and B overlap, false
   3129    otherwise.  */
   3130 
   3131 static int
   3132 sections_overlap (struct obj_section *a, struct obj_section *b)
   3133 {
   3134   CORE_ADDR a_start = obj_section_addr (a);
   3135   CORE_ADDR a_end = obj_section_endaddr (a);
   3136   CORE_ADDR b_start = obj_section_addr (b);
   3137   CORE_ADDR b_end = obj_section_endaddr (b);
   3138 
   3139   return (a_start < b_end && b_start < a_end);
   3140 }
   3141 
   3142 /* Function: overlay_unmapped_address (PC, SECTION)
   3143    Returns the address corresponding to PC in the unmapped (load) range.
   3144    May be the same as PC.  */
   3145 
   3146 CORE_ADDR
   3147 overlay_unmapped_address (CORE_ADDR pc, struct obj_section *section)
   3148 {
   3149   if (section_is_overlay (section) && pc_in_mapped_range (pc, section))
   3150     {
   3151       bfd *abfd = section->objfile->obfd;
   3152       asection *bfd_section = section->the_bfd_section;
   3153 
   3154       return pc + bfd_section_lma (abfd, bfd_section)
   3155 		- bfd_section_vma (abfd, bfd_section);
   3156     }
   3157 
   3158   return pc;
   3159 }
   3160 
   3161 /* Function: overlay_mapped_address (PC, SECTION)
   3162    Returns the address corresponding to PC in the mapped (runtime) range.
   3163    May be the same as PC.  */
   3164 
   3165 CORE_ADDR
   3166 overlay_mapped_address (CORE_ADDR pc, struct obj_section *section)
   3167 {
   3168   if (section_is_overlay (section) && pc_in_unmapped_range (pc, section))
   3169     {
   3170       bfd *abfd = section->objfile->obfd;
   3171       asection *bfd_section = section->the_bfd_section;
   3172 
   3173       return pc + bfd_section_vma (abfd, bfd_section)
   3174 		- bfd_section_lma (abfd, bfd_section);
   3175     }
   3176 
   3177   return pc;
   3178 }
   3179 
   3180 /* Function: symbol_overlayed_address
   3181    Return one of two addresses (relative to the VMA or to the LMA),
   3182    depending on whether the section is mapped or not.  */
   3183 
   3184 CORE_ADDR
   3185 symbol_overlayed_address (CORE_ADDR address, struct obj_section *section)
   3186 {
   3187   if (overlay_debugging)
   3188     {
   3189       /* If the symbol has no section, just return its regular address.  */
   3190       if (section == 0)
   3191 	return address;
   3192       /* If the symbol's section is not an overlay, just return its
   3193 	 address.  */
   3194       if (!section_is_overlay (section))
   3195 	return address;
   3196       /* If the symbol's section is mapped, just return its address.  */
   3197       if (section_is_mapped (section))
   3198 	return address;
   3199       /*
   3200        * HOWEVER: if the symbol is in an overlay section which is NOT mapped,
   3201        * then return its LOADED address rather than its vma address!!
   3202        */
   3203       return overlay_unmapped_address (address, section);
   3204     }
   3205   return address;
   3206 }
   3207 
   3208 /* Function: find_pc_overlay (PC)
   3209    Return the best-match overlay section for PC:
   3210    If PC matches a mapped overlay section's VMA, return that section.
   3211    Else if PC matches an unmapped section's VMA, return that section.
   3212    Else if PC matches an unmapped section's LMA, return that section.  */
   3213 
   3214 struct obj_section *
   3215 find_pc_overlay (CORE_ADDR pc)
   3216 {
   3217   struct objfile *objfile;
   3218   struct obj_section *osect, *best_match = NULL;
   3219 
   3220   if (overlay_debugging)
   3221     {
   3222       ALL_OBJSECTIONS (objfile, osect)
   3223 	if (section_is_overlay (osect))
   3224 	  {
   3225 	    if (pc_in_mapped_range (pc, osect))
   3226 	      {
   3227 		if (section_is_mapped (osect))
   3228 		  return osect;
   3229 		else
   3230 		  best_match = osect;
   3231 	      }
   3232 	    else if (pc_in_unmapped_range (pc, osect))
   3233 	      best_match = osect;
   3234 	  }
   3235     }
   3236   return best_match;
   3237 }
   3238 
   3239 /* Function: find_pc_mapped_section (PC)
   3240    If PC falls into the VMA address range of an overlay section that is
   3241    currently marked as MAPPED, return that section.  Else return NULL.  */
   3242 
   3243 struct obj_section *
   3244 find_pc_mapped_section (CORE_ADDR pc)
   3245 {
   3246   struct objfile *objfile;
   3247   struct obj_section *osect;
   3248 
   3249   if (overlay_debugging)
   3250     {
   3251       ALL_OBJSECTIONS (objfile, osect)
   3252 	if (pc_in_mapped_range (pc, osect) && section_is_mapped (osect))
   3253 	  return osect;
   3254     }
   3255 
   3256   return NULL;
   3257 }
   3258 
   3259 /* Function: list_overlays_command
   3260    Print a list of mapped sections and their PC ranges.  */
   3261 
   3262 static void
   3263 list_overlays_command (char *args, int from_tty)
   3264 {
   3265   int nmapped = 0;
   3266   struct objfile *objfile;
   3267   struct obj_section *osect;
   3268 
   3269   if (overlay_debugging)
   3270     {
   3271       ALL_OBJSECTIONS (objfile, osect)
   3272       if (section_is_mapped (osect))
   3273 	{
   3274 	  struct gdbarch *gdbarch = get_objfile_arch (objfile);
   3275 	  const char *name;
   3276 	  bfd_vma lma, vma;
   3277 	  int size;
   3278 
   3279 	  vma = bfd_section_vma (objfile->obfd, osect->the_bfd_section);
   3280 	  lma = bfd_section_lma (objfile->obfd, osect->the_bfd_section);
   3281 	  size = bfd_get_section_size (osect->the_bfd_section);
   3282 	  name = bfd_section_name (objfile->obfd, osect->the_bfd_section);
   3283 
   3284 	  printf_filtered ("Section %s, loaded at ", name);
   3285 	  fputs_filtered (paddress (gdbarch, lma), gdb_stdout);
   3286 	  puts_filtered (" - ");
   3287 	  fputs_filtered (paddress (gdbarch, lma + size), gdb_stdout);
   3288 	  printf_filtered (", mapped at ");
   3289 	  fputs_filtered (paddress (gdbarch, vma), gdb_stdout);
   3290 	  puts_filtered (" - ");
   3291 	  fputs_filtered (paddress (gdbarch, vma + size), gdb_stdout);
   3292 	  puts_filtered ("\n");
   3293 
   3294 	  nmapped++;
   3295 	}
   3296     }
   3297   if (nmapped == 0)
   3298     printf_filtered (_("No sections are mapped.\n"));
   3299 }
   3300 
   3301 /* Function: map_overlay_command
   3302    Mark the named section as mapped (ie. residing at its VMA address).  */
   3303 
   3304 static void
   3305 map_overlay_command (char *args, int from_tty)
   3306 {
   3307   struct objfile *objfile, *objfile2;
   3308   struct obj_section *sec, *sec2;
   3309 
   3310   if (!overlay_debugging)
   3311     error (_("Overlay debugging not enabled.  Use "
   3312 	     "either the 'overlay auto' or\n"
   3313 	     "the 'overlay manual' command."));
   3314 
   3315   if (args == 0 || *args == 0)
   3316     error (_("Argument required: name of an overlay section"));
   3317 
   3318   /* First, find a section matching the user supplied argument.  */
   3319   ALL_OBJSECTIONS (objfile, sec)
   3320     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
   3321     {
   3322       /* Now, check to see if the section is an overlay.  */
   3323       if (!section_is_overlay (sec))
   3324 	continue;		/* not an overlay section */
   3325 
   3326       /* Mark the overlay as "mapped".  */
   3327       sec->ovly_mapped = 1;
   3328 
   3329       /* Next, make a pass and unmap any sections that are
   3330          overlapped by this new section: */
   3331       ALL_OBJSECTIONS (objfile2, sec2)
   3332 	if (sec2->ovly_mapped && sec != sec2 && sections_overlap (sec, sec2))
   3333 	{
   3334 	  if (info_verbose)
   3335 	    printf_unfiltered (_("Note: section %s unmapped by overlap\n"),
   3336 			     bfd_section_name (objfile->obfd,
   3337 					       sec2->the_bfd_section));
   3338 	  sec2->ovly_mapped = 0;	/* sec2 overlaps sec: unmap sec2.  */
   3339 	}
   3340       return;
   3341     }
   3342   error (_("No overlay section called %s"), args);
   3343 }
   3344 
   3345 /* Function: unmap_overlay_command
   3346    Mark the overlay section as unmapped
   3347    (ie. resident in its LMA address range, rather than the VMA range).  */
   3348 
   3349 static void
   3350 unmap_overlay_command (char *args, int from_tty)
   3351 {
   3352   struct objfile *objfile;
   3353   struct obj_section *sec = NULL;
   3354 
   3355   if (!overlay_debugging)
   3356     error (_("Overlay debugging not enabled.  "
   3357 	     "Use either the 'overlay auto' or\n"
   3358 	     "the 'overlay manual' command."));
   3359 
   3360   if (args == 0 || *args == 0)
   3361     error (_("Argument required: name of an overlay section"));
   3362 
   3363   /* First, find a section matching the user supplied argument.  */
   3364   ALL_OBJSECTIONS (objfile, sec)
   3365     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
   3366     {
   3367       if (!sec->ovly_mapped)
   3368 	error (_("Section %s is not mapped"), args);
   3369       sec->ovly_mapped = 0;
   3370       return;
   3371     }
   3372   error (_("No overlay section called %s"), args);
   3373 }
   3374 
   3375 /* Function: overlay_auto_command
   3376    A utility command to turn on overlay debugging.
   3377    Possibly this should be done via a set/show command.  */
   3378 
   3379 static void
   3380 overlay_auto_command (char *args, int from_tty)
   3381 {
   3382   overlay_debugging = ovly_auto;
   3383   enable_overlay_breakpoints ();
   3384   if (info_verbose)
   3385     printf_unfiltered (_("Automatic overlay debugging enabled."));
   3386 }
   3387 
   3388 /* Function: overlay_manual_command
   3389    A utility command to turn on overlay debugging.
   3390    Possibly this should be done via a set/show command.  */
   3391 
   3392 static void
   3393 overlay_manual_command (char *args, int from_tty)
   3394 {
   3395   overlay_debugging = ovly_on;
   3396   disable_overlay_breakpoints ();
   3397   if (info_verbose)
   3398     printf_unfiltered (_("Overlay debugging enabled."));
   3399 }
   3400 
   3401 /* Function: overlay_off_command
   3402    A utility command to turn on overlay debugging.
   3403    Possibly this should be done via a set/show command.  */
   3404 
   3405 static void
   3406 overlay_off_command (char *args, int from_tty)
   3407 {
   3408   overlay_debugging = ovly_off;
   3409   disable_overlay_breakpoints ();
   3410   if (info_verbose)
   3411     printf_unfiltered (_("Overlay debugging disabled."));
   3412 }
   3413 
   3414 static void
   3415 overlay_load_command (char *args, int from_tty)
   3416 {
   3417   struct gdbarch *gdbarch = get_current_arch ();
   3418 
   3419   if (gdbarch_overlay_update_p (gdbarch))
   3420     gdbarch_overlay_update (gdbarch, NULL);
   3421   else
   3422     error (_("This target does not know how to read its overlay state."));
   3423 }
   3424 
   3425 /* Function: overlay_command
   3426    A place-holder for a mis-typed command.  */
   3427 
   3428 /* Command list chain containing all defined "overlay" subcommands.  */
   3429 static struct cmd_list_element *overlaylist;
   3430 
   3431 static void
   3432 overlay_command (char *args, int from_tty)
   3433 {
   3434   printf_unfiltered
   3435     ("\"overlay\" must be followed by the name of an overlay command.\n");
   3436   help_list (overlaylist, "overlay ", all_commands, gdb_stdout);
   3437 }
   3438 
   3439 /* Target Overlays for the "Simplest" overlay manager:
   3440 
   3441    This is GDB's default target overlay layer.  It works with the
   3442    minimal overlay manager supplied as an example by Cygnus.  The
   3443    entry point is via a function pointer "gdbarch_overlay_update",
   3444    so targets that use a different runtime overlay manager can
   3445    substitute their own overlay_update function and take over the
   3446    function pointer.
   3447 
   3448    The overlay_update function pokes around in the target's data structures
   3449    to see what overlays are mapped, and updates GDB's overlay mapping with
   3450    this information.
   3451 
   3452    In this simple implementation, the target data structures are as follows:
   3453    unsigned _novlys;            /# number of overlay sections #/
   3454    unsigned _ovly_table[_novlys][4] = {
   3455    {VMA, OSIZE, LMA, MAPPED},    /# one entry per overlay section #/
   3456    {..., ...,  ..., ...},
   3457    }
   3458    unsigned _novly_regions;     /# number of overlay regions #/
   3459    unsigned _ovly_region_table[_novly_regions][3] = {
   3460    {VMA, OSIZE, MAPPED_TO_LMA},  /# one entry per overlay region #/
   3461    {..., ...,  ...},
   3462    }
   3463    These functions will attempt to update GDB's mappedness state in the
   3464    symbol section table, based on the target's mappedness state.
   3465 
   3466    To do this, we keep a cached copy of the target's _ovly_table, and
   3467    attempt to detect when the cached copy is invalidated.  The main
   3468    entry point is "simple_overlay_update(SECT), which looks up SECT in
   3469    the cached table and re-reads only the entry for that section from
   3470    the target (whenever possible).  */
   3471 
   3472 /* Cached, dynamically allocated copies of the target data structures: */
   3473 static unsigned (*cache_ovly_table)[4] = 0;
   3474 static unsigned cache_novlys = 0;
   3475 static CORE_ADDR cache_ovly_table_base = 0;
   3476 enum ovly_index
   3477   {
   3478     VMA, OSIZE, LMA, MAPPED
   3479   };
   3480 
   3481 /* Throw away the cached copy of _ovly_table.  */
   3482 
   3483 static void
   3484 simple_free_overlay_table (void)
   3485 {
   3486   if (cache_ovly_table)
   3487     xfree (cache_ovly_table);
   3488   cache_novlys = 0;
   3489   cache_ovly_table = NULL;
   3490   cache_ovly_table_base = 0;
   3491 }
   3492 
   3493 /* Read an array of ints of size SIZE from the target into a local buffer.
   3494    Convert to host order.  int LEN is number of ints.  */
   3495 
   3496 static void
   3497 read_target_long_array (CORE_ADDR memaddr, unsigned int *myaddr,
   3498 			int len, int size, enum bfd_endian byte_order)
   3499 {
   3500   /* FIXME (alloca): Not safe if array is very large.  */
   3501   gdb_byte *buf = (gdb_byte *) alloca (len * size);
   3502   int i;
   3503 
   3504   read_memory (memaddr, buf, len * size);
   3505   for (i = 0; i < len; i++)
   3506     myaddr[i] = extract_unsigned_integer (size * i + buf, size, byte_order);
   3507 }
   3508 
   3509 /* Find and grab a copy of the target _ovly_table
   3510    (and _novlys, which is needed for the table's size).  */
   3511 
   3512 static int
   3513 simple_read_overlay_table (void)
   3514 {
   3515   struct bound_minimal_symbol novlys_msym;
   3516   struct bound_minimal_symbol ovly_table_msym;
   3517   struct gdbarch *gdbarch;
   3518   int word_size;
   3519   enum bfd_endian byte_order;
   3520 
   3521   simple_free_overlay_table ();
   3522   novlys_msym = lookup_minimal_symbol ("_novlys", NULL, NULL);
   3523   if (! novlys_msym.minsym)
   3524     {
   3525       error (_("Error reading inferior's overlay table: "
   3526              "couldn't find `_novlys' variable\n"
   3527              "in inferior.  Use `overlay manual' mode."));
   3528       return 0;
   3529     }
   3530 
   3531   ovly_table_msym = lookup_bound_minimal_symbol ("_ovly_table");
   3532   if (! ovly_table_msym.minsym)
   3533     {
   3534       error (_("Error reading inferior's overlay table: couldn't find "
   3535              "`_ovly_table' array\n"
   3536              "in inferior.  Use `overlay manual' mode."));
   3537       return 0;
   3538     }
   3539 
   3540   gdbarch = get_objfile_arch (ovly_table_msym.objfile);
   3541   word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
   3542   byte_order = gdbarch_byte_order (gdbarch);
   3543 
   3544   cache_novlys = read_memory_integer (BMSYMBOL_VALUE_ADDRESS (novlys_msym),
   3545 				      4, byte_order);
   3546   cache_ovly_table
   3547     = (unsigned int (*)[4]) xmalloc (cache_novlys * sizeof (*cache_ovly_table));
   3548   cache_ovly_table_base = BMSYMBOL_VALUE_ADDRESS (ovly_table_msym);
   3549   read_target_long_array (cache_ovly_table_base,
   3550                           (unsigned int *) cache_ovly_table,
   3551                           cache_novlys * 4, word_size, byte_order);
   3552 
   3553   return 1;			/* SUCCESS */
   3554 }
   3555 
   3556 /* Function: simple_overlay_update_1
   3557    A helper function for simple_overlay_update.  Assuming a cached copy
   3558    of _ovly_table exists, look through it to find an entry whose vma,
   3559    lma and size match those of OSECT.  Re-read the entry and make sure
   3560    it still matches OSECT (else the table may no longer be valid).
   3561    Set OSECT's mapped state to match the entry.  Return: 1 for
   3562    success, 0 for failure.  */
   3563 
   3564 static int
   3565 simple_overlay_update_1 (struct obj_section *osect)
   3566 {
   3567   int i;
   3568   bfd *obfd = osect->objfile->obfd;
   3569   asection *bsect = osect->the_bfd_section;
   3570   struct gdbarch *gdbarch = get_objfile_arch (osect->objfile);
   3571   int word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
   3572   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
   3573 
   3574   for (i = 0; i < cache_novlys; i++)
   3575     if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
   3576 	&& cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect))
   3577       {
   3578 	read_target_long_array (cache_ovly_table_base + i * word_size,
   3579 				(unsigned int *) cache_ovly_table[i],
   3580 				4, word_size, byte_order);
   3581 	if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
   3582 	    && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect))
   3583 	  {
   3584 	    osect->ovly_mapped = cache_ovly_table[i][MAPPED];
   3585 	    return 1;
   3586 	  }
   3587 	else	/* Warning!  Warning!  Target's ovly table has changed!  */
   3588 	  return 0;
   3589       }
   3590   return 0;
   3591 }
   3592 
   3593 /* Function: simple_overlay_update
   3594    If OSECT is NULL, then update all sections' mapped state
   3595    (after re-reading the entire target _ovly_table).
   3596    If OSECT is non-NULL, then try to find a matching entry in the
   3597    cached ovly_table and update only OSECT's mapped state.
   3598    If a cached entry can't be found or the cache isn't valid, then
   3599    re-read the entire cache, and go ahead and update all sections.  */
   3600 
   3601 void
   3602 simple_overlay_update (struct obj_section *osect)
   3603 {
   3604   struct objfile *objfile;
   3605 
   3606   /* Were we given an osect to look up?  NULL means do all of them.  */
   3607   if (osect)
   3608     /* Have we got a cached copy of the target's overlay table?  */
   3609     if (cache_ovly_table != NULL)
   3610       {
   3611 	/* Does its cached location match what's currently in the
   3612 	   symtab?  */
   3613 	struct bound_minimal_symbol minsym
   3614 	  = lookup_minimal_symbol ("_ovly_table", NULL, NULL);
   3615 
   3616 	if (minsym.minsym == NULL)
   3617 	  error (_("Error reading inferior's overlay table: couldn't "
   3618 		   "find `_ovly_table' array\n"
   3619 		   "in inferior.  Use `overlay manual' mode."));
   3620 
   3621 	if (cache_ovly_table_base == BMSYMBOL_VALUE_ADDRESS (minsym))
   3622 	  /* Then go ahead and try to look up this single section in
   3623 	     the cache.  */
   3624 	  if (simple_overlay_update_1 (osect))
   3625 	    /* Found it!  We're done.  */
   3626 	    return;
   3627       }
   3628 
   3629   /* Cached table no good: need to read the entire table anew.
   3630      Or else we want all the sections, in which case it's actually
   3631      more efficient to read the whole table in one block anyway.  */
   3632 
   3633   if (! simple_read_overlay_table ())
   3634     return;
   3635 
   3636   /* Now may as well update all sections, even if only one was requested.  */
   3637   ALL_OBJSECTIONS (objfile, osect)
   3638     if (section_is_overlay (osect))
   3639     {
   3640       int i;
   3641       bfd *obfd = osect->objfile->obfd;
   3642       asection *bsect = osect->the_bfd_section;
   3643 
   3644       for (i = 0; i < cache_novlys; i++)
   3645 	if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
   3646 	    && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect))
   3647 	  { /* obj_section matches i'th entry in ovly_table.  */
   3648 	    osect->ovly_mapped = cache_ovly_table[i][MAPPED];
   3649 	    break;		/* finished with inner for loop: break out.  */
   3650 	  }
   3651     }
   3652 }
   3653 
   3654 /* Set the output sections and output offsets for section SECTP in
   3655    ABFD.  The relocation code in BFD will read these offsets, so we
   3656    need to be sure they're initialized.  We map each section to itself,
   3657    with no offset; this means that SECTP->vma will be honored.  */
   3658 
   3659 static void
   3660 symfile_dummy_outputs (bfd *abfd, asection *sectp, void *dummy)
   3661 {
   3662   sectp->output_section = sectp;
   3663   sectp->output_offset = 0;
   3664 }
   3665 
   3666 /* Default implementation for sym_relocate.  */
   3667 
   3668 bfd_byte *
   3669 default_symfile_relocate (struct objfile *objfile, asection *sectp,
   3670                           bfd_byte *buf)
   3671 {
   3672   /* Use sectp->owner instead of objfile->obfd.  sectp may point to a
   3673      DWO file.  */
   3674   bfd *abfd = sectp->owner;
   3675 
   3676   /* We're only interested in sections with relocation
   3677      information.  */
   3678   if ((sectp->flags & SEC_RELOC) == 0)
   3679     return NULL;
   3680 
   3681   /* We will handle section offsets properly elsewhere, so relocate as if
   3682      all sections begin at 0.  */
   3683   bfd_map_over_sections (abfd, symfile_dummy_outputs, NULL);
   3684 
   3685   return bfd_simple_get_relocated_section_contents (abfd, sectp, buf, NULL);
   3686 }
   3687 
   3688 /* Relocate the contents of a debug section SECTP in ABFD.  The
   3689    contents are stored in BUF if it is non-NULL, or returned in a
   3690    malloc'd buffer otherwise.
   3691 
   3692    For some platforms and debug info formats, shared libraries contain
   3693    relocations against the debug sections (particularly for DWARF-2;
   3694    one affected platform is PowerPC GNU/Linux, although it depends on
   3695    the version of the linker in use).  Also, ELF object files naturally
   3696    have unresolved relocations for their debug sections.  We need to apply
   3697    the relocations in order to get the locations of symbols correct.
   3698    Another example that may require relocation processing, is the
   3699    DWARF-2 .eh_frame section in .o files, although it isn't strictly a
   3700    debug section.  */
   3701 
   3702 bfd_byte *
   3703 symfile_relocate_debug_section (struct objfile *objfile,
   3704                                 asection *sectp, bfd_byte *buf)
   3705 {
   3706   gdb_assert (objfile->sf->sym_relocate);
   3707 
   3708   return (*objfile->sf->sym_relocate) (objfile, sectp, buf);
   3709 }
   3710 
   3711 struct symfile_segment_data *
   3712 get_symfile_segment_data (bfd *abfd)
   3713 {
   3714   const struct sym_fns *sf = find_sym_fns (abfd);
   3715 
   3716   if (sf == NULL)
   3717     return NULL;
   3718 
   3719   return sf->sym_segments (abfd);
   3720 }
   3721 
   3722 void
   3723 free_symfile_segment_data (struct symfile_segment_data *data)
   3724 {
   3725   xfree (data->segment_bases);
   3726   xfree (data->segment_sizes);
   3727   xfree (data->segment_info);
   3728   xfree (data);
   3729 }
   3730 
   3731 /* Given:
   3732    - DATA, containing segment addresses from the object file ABFD, and
   3733      the mapping from ABFD's sections onto the segments that own them,
   3734      and
   3735    - SEGMENT_BASES[0 .. NUM_SEGMENT_BASES - 1], holding the actual
   3736      segment addresses reported by the target,
   3737    store the appropriate offsets for each section in OFFSETS.
   3738 
   3739    If there are fewer entries in SEGMENT_BASES than there are segments
   3740    in DATA, then apply SEGMENT_BASES' last entry to all the segments.
   3741 
   3742    If there are more entries, then ignore the extra.  The target may
   3743    not be able to distinguish between an empty data segment and a
   3744    missing data segment; a missing text segment is less plausible.  */
   3745 
   3746 int
   3747 symfile_map_offsets_to_segments (bfd *abfd,
   3748 				 const struct symfile_segment_data *data,
   3749 				 struct section_offsets *offsets,
   3750 				 int num_segment_bases,
   3751 				 const CORE_ADDR *segment_bases)
   3752 {
   3753   int i;
   3754   asection *sect;
   3755 
   3756   /* It doesn't make sense to call this function unless you have some
   3757      segment base addresses.  */
   3758   gdb_assert (num_segment_bases > 0);
   3759 
   3760   /* If we do not have segment mappings for the object file, we
   3761      can not relocate it by segments.  */
   3762   gdb_assert (data != NULL);
   3763   gdb_assert (data->num_segments > 0);
   3764 
   3765   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
   3766     {
   3767       int which = data->segment_info[i];
   3768 
   3769       gdb_assert (0 <= which && which <= data->num_segments);
   3770 
   3771       /* Don't bother computing offsets for sections that aren't
   3772          loaded as part of any segment.  */
   3773       if (! which)
   3774         continue;
   3775 
   3776       /* Use the last SEGMENT_BASES entry as the address of any extra
   3777          segments mentioned in DATA->segment_info.  */
   3778       if (which > num_segment_bases)
   3779         which = num_segment_bases;
   3780 
   3781       offsets->offsets[i] = (segment_bases[which - 1]
   3782                              - data->segment_bases[which - 1]);
   3783     }
   3784 
   3785   return 1;
   3786 }
   3787 
   3788 static void
   3789 symfile_find_segment_sections (struct objfile *objfile)
   3790 {
   3791   bfd *abfd = objfile->obfd;
   3792   int i;
   3793   asection *sect;
   3794   struct symfile_segment_data *data;
   3795 
   3796   data = get_symfile_segment_data (objfile->obfd);
   3797   if (data == NULL)
   3798     return;
   3799 
   3800   if (data->num_segments != 1 && data->num_segments != 2)
   3801     {
   3802       free_symfile_segment_data (data);
   3803       return;
   3804     }
   3805 
   3806   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
   3807     {
   3808       int which = data->segment_info[i];
   3809 
   3810       if (which == 1)
   3811 	{
   3812 	  if (objfile->sect_index_text == -1)
   3813 	    objfile->sect_index_text = sect->index;
   3814 
   3815 	  if (objfile->sect_index_rodata == -1)
   3816 	    objfile->sect_index_rodata = sect->index;
   3817 	}
   3818       else if (which == 2)
   3819 	{
   3820 	  if (objfile->sect_index_data == -1)
   3821 	    objfile->sect_index_data = sect->index;
   3822 
   3823 	  if (objfile->sect_index_bss == -1)
   3824 	    objfile->sect_index_bss = sect->index;
   3825 	}
   3826     }
   3827 
   3828   free_symfile_segment_data (data);
   3829 }
   3830 
   3831 /* Listen for free_objfile events.  */
   3832 
   3833 static void
   3834 symfile_free_objfile (struct objfile *objfile)
   3835 {
   3836   /* Remove the target sections owned by this objfile.  */
   3837   if (objfile != NULL)
   3838     remove_target_sections ((void *) objfile);
   3839 }
   3840 
   3841 /* Wrapper around the quick_symbol_functions expand_symtabs_matching "method".
   3842    Expand all symtabs that match the specified criteria.
   3843    See quick_symbol_functions.expand_symtabs_matching for details.  */
   3844 
   3845 void
   3846 expand_symtabs_matching
   3847   (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
   3848    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
   3849    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
   3850    enum search_domain kind)
   3851 {
   3852   struct objfile *objfile;
   3853 
   3854   ALL_OBJFILES (objfile)
   3855   {
   3856     if (objfile->sf)
   3857       objfile->sf->qf->expand_symtabs_matching (objfile, file_matcher,
   3858 						symbol_matcher,
   3859 						expansion_notify, kind);
   3860   }
   3861 }
   3862 
   3863 /* Wrapper around the quick_symbol_functions map_symbol_filenames "method".
   3864    Map function FUN over every file.
   3865    See quick_symbol_functions.map_symbol_filenames for details.  */
   3866 
   3867 void
   3868 map_symbol_filenames (symbol_filename_ftype *fun, void *data,
   3869 		      int need_fullname)
   3870 {
   3871   struct objfile *objfile;
   3872 
   3873   ALL_OBJFILES (objfile)
   3874   {
   3875     if (objfile->sf)
   3876       objfile->sf->qf->map_symbol_filenames (objfile, fun, data,
   3877 					     need_fullname);
   3878   }
   3879 }
   3880 
   3881 void
   3882 _initialize_symfile (void)
   3883 {
   3884   struct cmd_list_element *c;
   3885 
   3886   observer_attach_free_objfile (symfile_free_objfile);
   3887 
   3888   c = add_cmd ("symbol-file", class_files, symbol_file_command, _("\
   3889 Load symbol table from executable file FILE.\n\
   3890 The `file' command can also load symbol tables, as well as setting the file\n\
   3891 to execute."), &cmdlist);
   3892   set_cmd_completer (c, filename_completer);
   3893 
   3894   c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command, _("\
   3895 Load symbols from FILE, assuming FILE has been dynamically loaded.\n\
   3896 Usage: add-symbol-file FILE ADDR [-s <SECT> <SECT_ADDR> -s <SECT> <SECT_ADDR>\
   3897  ...]\nADDR is the starting address of the file's text.\n\
   3898 The optional arguments are section-name section-address pairs and\n\
   3899 should be specified if the data and bss segments are not contiguous\n\
   3900 with the text.  SECT is a section name to be loaded at SECT_ADDR."),
   3901 	       &cmdlist);
   3902   set_cmd_completer (c, filename_completer);
   3903 
   3904   c = add_cmd ("remove-symbol-file", class_files,
   3905 	       remove_symbol_file_command, _("\
   3906 Remove a symbol file added via the add-symbol-file command.\n\
   3907 Usage: remove-symbol-file FILENAME\n\
   3908        remove-symbol-file -a ADDRESS\n\
   3909 The file to remove can be identified by its filename or by an address\n\
   3910 that lies within the boundaries of this symbol file in memory."),
   3911 	       &cmdlist);
   3912 
   3913   c = add_cmd ("load", class_files, load_command, _("\
   3914 Dynamically load FILE into the running program, and record its symbols\n\
   3915 for access from GDB.\n\
   3916 An optional load OFFSET may also be given as a literal address.\n\
   3917 When OFFSET is provided, FILE must also be provided.  FILE can be provided\n\
   3918 on its own.\n\
   3919 Usage: load [FILE] [OFFSET]"), &cmdlist);
   3920   set_cmd_completer (c, filename_completer);
   3921 
   3922   add_prefix_cmd ("overlay", class_support, overlay_command,
   3923 		  _("Commands for debugging overlays."), &overlaylist,
   3924 		  "overlay ", 0, &cmdlist);
   3925 
   3926   add_com_alias ("ovly", "overlay", class_alias, 1);
   3927   add_com_alias ("ov", "overlay", class_alias, 1);
   3928 
   3929   add_cmd ("map-overlay", class_support, map_overlay_command,
   3930 	   _("Assert that an overlay section is mapped."), &overlaylist);
   3931 
   3932   add_cmd ("unmap-overlay", class_support, unmap_overlay_command,
   3933 	   _("Assert that an overlay section is unmapped."), &overlaylist);
   3934 
   3935   add_cmd ("list-overlays", class_support, list_overlays_command,
   3936 	   _("List mappings of overlay sections."), &overlaylist);
   3937 
   3938   add_cmd ("manual", class_support, overlay_manual_command,
   3939 	   _("Enable overlay debugging."), &overlaylist);
   3940   add_cmd ("off", class_support, overlay_off_command,
   3941 	   _("Disable overlay debugging."), &overlaylist);
   3942   add_cmd ("auto", class_support, overlay_auto_command,
   3943 	   _("Enable automatic overlay debugging."), &overlaylist);
   3944   add_cmd ("load-target", class_support, overlay_load_command,
   3945 	   _("Read the overlay mapping state from the target."), &overlaylist);
   3946 
   3947   /* Filename extension to source language lookup table: */
   3948   add_setshow_string_noescape_cmd ("extension-language", class_files,
   3949 				   &ext_args, _("\
   3950 Set mapping between filename extension and source language."), _("\
   3951 Show mapping between filename extension and source language."), _("\
   3952 Usage: set extension-language .foo bar"),
   3953 				   set_ext_lang_command,
   3954 				   show_ext_args,
   3955 				   &setlist, &showlist);
   3956 
   3957   add_info ("extensions", info_ext_lang_command,
   3958 	    _("All filename extensions associated with a source language."));
   3959 
   3960   add_setshow_optional_filename_cmd ("debug-file-directory", class_support,
   3961 				     &debug_file_directory, _("\
   3962 Set the directories where separate debug symbols are searched for."), _("\
   3963 Show the directories where separate debug symbols are searched for."), _("\
   3964 Separate debug symbols are first searched for in the same\n\
   3965 directory as the binary, then in the `" DEBUG_SUBDIRECTORY "' subdirectory,\n\
   3966 and lastly at the path of the directory of the binary with\n\
   3967 each global debug-file-directory component prepended."),
   3968 				     NULL,
   3969 				     show_debug_file_directory,
   3970 				     &setlist, &showlist);
   3971 
   3972   add_setshow_enum_cmd ("symbol-loading", no_class,
   3973 			print_symbol_loading_enums, &print_symbol_loading,
   3974 			_("\
   3975 Set printing of symbol loading messages."), _("\
   3976 Show printing of symbol loading messages."), _("\
   3977 off   == turn all messages off\n\
   3978 brief == print messages for the executable,\n\
   3979          and brief messages for shared libraries\n\
   3980 full  == print messages for the executable,\n\
   3981          and messages for each shared library."),
   3982 			NULL,
   3983 			NULL,
   3984 			&setprintlist, &showprintlist);
   3985 }
   3986