gdb/symfile.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Generic symbol file reading for the GNU debugger, GDB.

  2.    Copyright (C) 1990-2015 Free Software Foundation, Inc.

  3.    Contributed by Cygnus Support, using pieces from other GDB modules.

  4.    This file is part of GDB.

  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 3 of the License, or
  8.    (at your option) any later version.

  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.

  13.    You should have received a copy of the GNU General Public License
  14.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  15. #include "defs.h"
  16. #include "arch-utils.h"
  17. #include "bfdlink.h"
  18. #include "symtab.h"
  19. #include "gdbtypes.h"
  20. #include "gdbcore.h"
  21. #include "frame.h"
  22. #include "target.h"
  23. #include "value.h"
  24. #include "symfile.h"
  25. #include "objfiles.h"
  26. #include "source.h"
  27. #include "gdbcmd.h"
  28. #include "breakpoint.h"
  29. #include "language.h"
  30. #include "complaints.h"
  31. #include "demangle.h"
  32. #include "inferior.h"
  33. #include "regcache.h"
  34. #include "filenames.h"                /* for DOSish file names */
  35. #include "gdb-stabs.h"
  36. #include "gdb_obstack.h"
  37. #include "completer.h"
  38. #include "bcache.h"
  39. #include "hashtab.h"
  40. #include "readline/readline.h"
  41. #include "block.h"
  42. #include "observer.h"
  43. #include "exec.h"
  44. #include "parser-defs.h"
  45. #include "varobj.h"
  46. #include "elf-bfd.h"
  47. #include "solib.h"
  48. #include "remote.h"
  49. #include "stack.h"
  50. #include "gdb_bfd.h"
  51. #include "cli/cli-utils.h"

  52. #include <sys/types.h>
  53. #include <fcntl.h>
  54. #include <sys/stat.h>
  55. #include <ctype.h>
  56. #include <time.h>
  57. #include <sys/time.h>

  58. #include "psymtab.h"

  59. int (*deprecated_ui_load_progress_hook) (const char *section,
  60.                                          unsigned long num);
  61. void (*deprecated_show_load_progress) (const char *section,
  62.                             unsigned long section_sent,
  63.                             unsigned long section_size,
  64.                             unsigned long total_sent,
  65.                             unsigned long total_size);
  66. void (*deprecated_pre_add_symbol_hook) (const char *);
  67. void (*deprecated_post_add_symbol_hook) (void);

  68. static void clear_symtab_users_cleanup (void *ignore);

  69. /* Global variables owned by this file.  */
  70. int readnow_symbol_files;        /* Read full symbols immediately.  */

  71. /* Functions this file defines.  */

  72. static void load_command (char *, int);

  73. static void symbol_file_add_main_1 (const char *args, int from_tty, int flags);

  74. static void add_symbol_file_command (char *, int);

  75. static const struct sym_fns *find_sym_fns (bfd *);

  76. static void decrement_reading_symtab (void *);

  77. static void overlay_invalidate_all (void);

  78. static void overlay_auto_command (char *, int);

  79. static void overlay_manual_command (char *, int);

  80. static void overlay_off_command (char *, int);

  81. static void overlay_load_command (char *, int);

  82. static void overlay_command (char *, int);

  83. static void simple_free_overlay_table (void);

  84. static void read_target_long_array (CORE_ADDR, unsigned int *, int, int,
  85.                                     enum bfd_endian);

  86. static int simple_read_overlay_table (void);

  87. static int simple_overlay_update_1 (struct obj_section *);

  88. static void add_filename_language (char *ext, enum language lang);

  89. static void info_ext_lang_command (char *args, int from_tty);

  90. static void init_filename_language_table (void);

  91. static void symfile_find_segment_sections (struct objfile *objfile);

  92. void _initialize_symfile (void);

  93. /* List of all available sym_fns.  On gdb startup, each object file reader
  94.    calls add_symtab_fns() to register information on each format it is
  95.    prepared to read.  */

  96. typedef struct
  97. {
  98.   /* BFD flavour that we handle.  */
  99.   enum bfd_flavour sym_flavour;

  100.   /* The "vtable" of symbol functions.  */
  101.   const struct sym_fns *sym_fns;
  102. } registered_sym_fns;

  103. DEF_VEC_O (registered_sym_fns);

  104. static VEC (registered_sym_fns) *symtab_fns = NULL;

  105. /* Values for "set print symbol-loading".  */

  106. const char print_symbol_loading_off[] = "off";
  107. const char print_symbol_loading_brief[] = "brief";
  108. const char print_symbol_loading_full[] = "full";
  109. static const char *print_symbol_loading_enums[] =
  110. {
  111.   print_symbol_loading_off,
  112.   print_symbol_loading_brief,
  113.   print_symbol_loading_full,
  114.   NULL
  115. };
  116. static const char *print_symbol_loading = print_symbol_loading_full;

  117. /* If non-zero, shared library symbols will be added automatically
  118.    when the inferior is created, new libraries are loaded, or when
  119.    attaching to the inferior.  This is almost always what users will
  120.    want to have happen; but for very large programs, the startup time
  121.    will be excessive, and so if this is a problem, the user can clear
  122.    this flag and then add the shared library symbols as needed.  Note
  123.    that there is a potential for confusion, since if the shared
  124.    library symbols are not loaded, commands like "info fun" will *not*
  125.    report all the functions that are actually present.  */

  126. int auto_solib_add = 1;


  127. /* Return non-zero if symbol-loading messages should be printed.
  128.    FROM_TTY is the standard from_tty argument to gdb commands.
  129.    If EXEC is non-zero the messages are for the executable.
  130.    Otherwise, messages are for shared libraries.
  131.    If FULL is non-zero then the caller is printing a detailed message.
  132.    E.g., the message includes the shared library name.
  133.    Otherwise, the caller is printing a brief "summary" message.  */

  134. int
  135. print_symbol_loading_p (int from_tty, int exec, int full)
  136. {
  137.   if (!from_tty && !info_verbose)
  138.     return 0;

  139.   if (exec)
  140.     {
  141.       /* We don't check FULL for executables, there are few such
  142.          messages, therefore brief == full.  */
  143.       return print_symbol_loading != print_symbol_loading_off;
  144.     }
  145.   if (full)
  146.     return print_symbol_loading == print_symbol_loading_full;
  147.   return print_symbol_loading == print_symbol_loading_brief;
  148. }

  149. /* True if we are reading a symbol table.  */

  150. int currently_reading_symtab = 0;

  151. static void
  152. decrement_reading_symtab (void *dummy)
  153. {
  154.   currently_reading_symtab--;
  155.   gdb_assert (currently_reading_symtab >= 0);
  156. }

  157. /* Increment currently_reading_symtab and return a cleanup that can be
  158.    used to decrement it.  */

  159. struct cleanup *
  160. increment_reading_symtab (void)
  161. {
  162.   ++currently_reading_symtab;
  163.   gdb_assert (currently_reading_symtab > 0);
  164.   return make_cleanup (decrement_reading_symtab, NULL);
  165. }

  166. /* Remember the lowest-addressed loadable section we've seen.
  167.    This function is called via bfd_map_over_sections.

  168.    In case of equal vmas, the section with the largest size becomes the
  169.    lowest-addressed loadable section.

  170.    If the vmas and sizes are equal, the last section is considered the
  171.    lowest-addressed loadable section.  */

  172. void
  173. find_lowest_section (bfd *abfd, asection *sect, void *obj)
  174. {
  175.   asection **lowest = (asection **) obj;

  176.   if (0 == (bfd_get_section_flags (abfd, sect) & (SEC_ALLOC | SEC_LOAD)))
  177.     return;
  178.   if (!*lowest)
  179.     *lowest = sect;                /* First loadable section */
  180.   else if (bfd_section_vma (abfd, *lowest) > bfd_section_vma (abfd, sect))
  181.     *lowest = sect;                /* A lower loadable section */
  182.   else if (bfd_section_vma (abfd, *lowest) == bfd_section_vma (abfd, sect)
  183.            && (bfd_section_size (abfd, (*lowest))
  184.                <= bfd_section_size (abfd, sect)))
  185.     *lowest = sect;
  186. }

  187. /* Create a new section_addr_info, with room for NUM_SECTIONS.  The
  188.    new object's 'num_sections' field is set to 0; it must be updated
  189.    by the caller.  */

  190. struct section_addr_info *
  191. alloc_section_addr_info (size_t num_sections)
  192. {
  193.   struct section_addr_info *sap;
  194.   size_t size;

  195.   size = (sizeof (struct section_addr_info)
  196.           +  sizeof (struct other_sections) * (num_sections - 1));
  197.   sap = (struct section_addr_info *) xmalloc (size);
  198.   memset (sap, 0, size);

  199.   return sap;
  200. }

  201. /* Build (allocate and populate) a section_addr_info struct from
  202.    an existing section table.  */

  203. extern struct section_addr_info *
  204. build_section_addr_info_from_section_table (const struct target_section *start,
  205.                                             const struct target_section *end)
  206. {
  207.   struct section_addr_info *sap;
  208.   const struct target_section *stp;
  209.   int oidx;

  210.   sap = alloc_section_addr_info (end - start);

  211.   for (stp = start, oidx = 0; stp != end; stp++)
  212.     {
  213.       struct bfd_section *asect = stp->the_bfd_section;
  214.       bfd *abfd = asect->owner;

  215.       if (bfd_get_section_flags (abfd, asect) & (SEC_ALLOC | SEC_LOAD)
  216.           && oidx < end - start)
  217.         {
  218.           sap->other[oidx].addr = stp->addr;
  219.           sap->other[oidx].name = xstrdup (bfd_section_name (abfd, asect));
  220.           sap->other[oidx].sectindex = gdb_bfd_section_index (abfd, asect);
  221.           oidx++;
  222.         }
  223.     }

  224.   sap->num_sections = oidx;

  225.   return sap;
  226. }

  227. /* Create a section_addr_info from section offsets in ABFD.  */

  228. static struct section_addr_info *
  229. build_section_addr_info_from_bfd (bfd *abfd)
  230. {
  231.   struct section_addr_info *sap;
  232.   int i;
  233.   struct bfd_section *sec;

  234.   sap = alloc_section_addr_info (bfd_count_sections (abfd));
  235.   for (i = 0, sec = abfd->sections; sec != NULL; sec = sec->next)
  236.     if (bfd_get_section_flags (abfd, sec) & (SEC_ALLOC | SEC_LOAD))
  237.       {
  238.         sap->other[i].addr = bfd_get_section_vma (abfd, sec);
  239.         sap->other[i].name = xstrdup (bfd_get_section_name (abfd, sec));
  240.         sap->other[i].sectindex = gdb_bfd_section_index (abfd, sec);
  241.         i++;
  242.       }

  243.   sap->num_sections = i;

  244.   return sap;
  245. }

  246. /* Create a section_addr_info from section offsets in OBJFILE.  */

  247. struct section_addr_info *
  248. build_section_addr_info_from_objfile (const struct objfile *objfile)
  249. {
  250.   struct section_addr_info *sap;
  251.   int i;

  252.   /* Before reread_symbols gets rewritten it is not safe to call:
  253.      gdb_assert (objfile->num_sections == bfd_count_sections (objfile->obfd));
  254.      */
  255.   sap = build_section_addr_info_from_bfd (objfile->obfd);
  256.   for (i = 0; i < sap->num_sections; i++)
  257.     {
  258.       int sectindex = sap->other[i].sectindex;

  259.       sap->other[i].addr += objfile->section_offsets->offsets[sectindex];
  260.     }
  261.   return sap;
  262. }

  263. /* Free all memory allocated by build_section_addr_info_from_section_table.  */

  264. extern void
  265. free_section_addr_info (struct section_addr_info *sap)
  266. {
  267.   int idx;

  268.   for (idx = 0; idx < sap->num_sections; idx++)
  269.     xfree (sap->other[idx].name);
  270.   xfree (sap);
  271. }

  272. /* Initialize OBJFILE's sect_index_* members.  */

  273. static void
  274. init_objfile_sect_indices (struct objfile *objfile)
  275. {
  276.   asection *sect;
  277.   int i;

  278.   sect = bfd_get_section_by_name (objfile->obfd, ".text");
  279.   if (sect)
  280.     objfile->sect_index_text = sect->index;

  281.   sect = bfd_get_section_by_name (objfile->obfd, ".data");
  282.   if (sect)
  283.     objfile->sect_index_data = sect->index;

  284.   sect = bfd_get_section_by_name (objfile->obfd, ".bss");
  285.   if (sect)
  286.     objfile->sect_index_bss = sect->index;

  287.   sect = bfd_get_section_by_name (objfile->obfd, ".rodata");
  288.   if (sect)
  289.     objfile->sect_index_rodata = sect->index;

  290.   /* This is where things get really weird...  We MUST have valid
  291.      indices for the various sect_index_* members or gdb will abort.
  292.      So if for example, there is no ".text" section, we have to
  293.      accomodate that.  First, check for a file with the standard
  294.      one or two segments.  */

  295.   symfile_find_segment_sections (objfile);

  296.   /* Except when explicitly adding symbol files at some address,
  297.      section_offsets contains nothing but zeros, so it doesn't matter
  298.      which slot in section_offsets the individual sect_index_* members
  299.      index into.  So if they are all zero, it is safe to just point
  300.      all the currently uninitialized indices to the first slot.  But
  301.      beware: if this is the main executable, it may be relocated
  302.      later, e.g. by the remote qOffsets packet, and then this will
  303.      be wrong!  That's why we try segments first.  */

  304.   for (i = 0; i < objfile->num_sections; i++)
  305.     {
  306.       if (ANOFFSET (objfile->section_offsets, i) != 0)
  307.         {
  308.           break;
  309.         }
  310.     }
  311.   if (i == objfile->num_sections)
  312.     {
  313.       if (objfile->sect_index_text == -1)
  314.         objfile->sect_index_text = 0;
  315.       if (objfile->sect_index_data == -1)
  316.         objfile->sect_index_data = 0;
  317.       if (objfile->sect_index_bss == -1)
  318.         objfile->sect_index_bss = 0;
  319.       if (objfile->sect_index_rodata == -1)
  320.         objfile->sect_index_rodata = 0;
  321.     }
  322. }

  323. /* The arguments to place_section.  */

  324. struct place_section_arg
  325. {
  326.   struct section_offsets *offsets;
  327.   CORE_ADDR lowest;
  328. };

  329. /* Find a unique offset to use for loadable section SECT if
  330.    the user did not provide an offset.  */

  331. static void
  332. place_section (bfd *abfd, asection *sect, void *obj)
  333. {
  334.   struct place_section_arg *arg = obj;
  335.   CORE_ADDR *offsets = arg->offsets->offsets, start_addr;
  336.   int done;
  337.   ULONGEST align = ((ULONGEST) 1) << bfd_get_section_alignment (abfd, sect);

  338.   /* We are only interested in allocated sections.  */
  339.   if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
  340.     return;

  341.   /* If the user specified an offset, honor it.  */
  342.   if (offsets[gdb_bfd_section_index (abfd, sect)] != 0)
  343.     return;

  344.   /* Otherwise, let's try to find a place for the section.  */
  345.   start_addr = (arg->lowest + align - 1) & -align;

  346.   do {
  347.     asection *cur_sec;

  348.     done = 1;

  349.     for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
  350.       {
  351.         int indx = cur_sec->index;

  352.         /* We don't need to compare against ourself.  */
  353.         if (cur_sec == sect)
  354.           continue;

  355.         /* We can only conflict with allocated sections.  */
  356.         if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0)
  357.           continue;

  358.         /* If the section offset is 0, either the section has not been placed
  359.            yet, or it was the lowest section placed (in which case LOWEST
  360.            will be past its end).  */
  361.         if (offsets[indx] == 0)
  362.           continue;

  363.         /* If this section would overlap us, then we must move up.  */
  364.         if (start_addr + bfd_get_section_size (sect) > offsets[indx]
  365.             && start_addr < offsets[indx] + bfd_get_section_size (cur_sec))
  366.           {
  367.             start_addr = offsets[indx] + bfd_get_section_size (cur_sec);
  368.             start_addr = (start_addr + align - 1) & -align;
  369.             done = 0;
  370.             break;
  371.           }

  372.         /* Otherwise, we appear to be OK.  So far.  */
  373.       }
  374.     }
  375.   while (!done);

  376.   offsets[gdb_bfd_section_index (abfd, sect)] = start_addr;
  377.   arg->lowest = start_addr + bfd_get_section_size (sect);
  378. }

  379. /* Store struct section_addr_info as prepared (made relative and with SECTINDEX
  380.    filled-in) by addr_info_make_relative into SECTION_OFFSETS of NUM_SECTIONS
  381.    entries.  */

  382. void
  383. relative_addr_info_to_section_offsets (struct section_offsets *section_offsets,
  384.                                        int num_sections,
  385.                                        const struct section_addr_info *addrs)
  386. {
  387.   int i;

  388.   memset (section_offsets, 0, SIZEOF_N_SECTION_OFFSETS (num_sections));

  389.   /* Now calculate offsets for section that were specified by the caller.  */
  390.   for (i = 0; i < addrs->num_sections; i++)
  391.     {
  392.       const struct other_sections *osp;

  393.       osp = &addrs->other[i];
  394.       if (osp->sectindex == -1)
  395.           continue;

  396.       /* Record all sections in offsets.  */
  397.       /* The section_offsets in the objfile are here filled in using
  398.          the BFD index.  */
  399.       section_offsets->offsets[osp->sectindex] = osp->addr;
  400.     }
  401. }

  402. /* Transform section name S for a name comparison.  prelink can split section
  403.    `.bss' into two sections `.dynbss' and `.bss' (in this order).  Similarly
  404.    prelink can split `.sbss' into `.sdynbss' and `.sbss'.  Use virtual address
  405.    of the new `.dynbss' (`.sdynbss') section as the adjacent new `.bss'
  406.    (`.sbss') section has invalid (increased) virtual address.  */

  407. static const char *
  408. addr_section_name (const char *s)
  409. {
  410.   if (strcmp (s, ".dynbss") == 0)
  411.     return ".bss";
  412.   if (strcmp (s, ".sdynbss") == 0)
  413.     return ".sbss";

  414.   return s;
  415. }

  416. /* qsort comparator for addrs_section_sort.  Sort entries in ascending order by
  417.    their (name, sectindex) pair.  sectindex makes the sort by name stable.  */

  418. static int
  419. addrs_section_compar (const void *ap, const void *bp)
  420. {
  421.   const struct other_sections *a = *((struct other_sections **) ap);
  422.   const struct other_sections *b = *((struct other_sections **) bp);
  423.   int retval;

  424.   retval = strcmp (addr_section_name (a->name), addr_section_name (b->name));
  425.   if (retval)
  426.     return retval;

  427.   return a->sectindex - b->sectindex;
  428. }

  429. /* Provide sorted array of pointers to sections of ADDRS.  The array is
  430.    terminated by NULL.  Caller is responsible to call xfree for it.  */

  431. static struct other_sections **
  432. addrs_section_sort (struct section_addr_info *addrs)
  433. {
  434.   struct other_sections **array;
  435.   int i;

  436.   /* `+ 1' for the NULL terminator.  */
  437.   array = xmalloc (sizeof (*array) * (addrs->num_sections + 1));
  438.   for (i = 0; i < addrs->num_sections; i++)
  439.     array[i] = &addrs->other[i];
  440.   array[i] = NULL;

  441.   qsort (array, i, sizeof (*array), addrs_section_compar);

  442.   return array;
  443. }

  444. /* Relativize absolute addresses in ADDRS into offsets based on ABFD.  Fill-in
  445.    also SECTINDEXes specific to ABFD there.  This function can be used to
  446.    rebase ADDRS to start referencing different BFD than before.  */

  447. void
  448. addr_info_make_relative (struct section_addr_info *addrs, bfd *abfd)
  449. {
  450.   asection *lower_sect;
  451.   CORE_ADDR lower_offset;
  452.   int i;
  453.   struct cleanup *my_cleanup;
  454.   struct section_addr_info *abfd_addrs;
  455.   struct other_sections **addrs_sorted, **abfd_addrs_sorted;
  456.   struct other_sections **addrs_to_abfd_addrs;

  457.   /* Find lowest loadable section to be used as starting point for
  458.      continguous sections.  */
  459.   lower_sect = NULL;
  460.   bfd_map_over_sections (abfd, find_lowest_section, &lower_sect);
  461.   if (lower_sect == NULL)
  462.     {
  463.       warning (_("no loadable sections found in added symbol-file %s"),
  464.                bfd_get_filename (abfd));
  465.       lower_offset = 0;
  466.     }
  467.   else
  468.     lower_offset = bfd_section_vma (bfd_get_filename (abfd), lower_sect);

  469.   /* Create ADDRS_TO_ABFD_ADDRS array to map the sections in ADDRS to sections
  470.      in ABFD.  Section names are not unique - there can be multiple sections of
  471.      the same name.  Also the sections of the same name do not have to be
  472.      adjacent to each other.  Some sections may be present only in one of the
  473.      files.  Even sections present in both files do not have to be in the same
  474.      order.

  475.      Use stable sort by name for the sections in both files.  Then linearly
  476.      scan both lists matching as most of the entries as possible.  */

  477.   addrs_sorted = addrs_section_sort (addrs);
  478.   my_cleanup = make_cleanup (xfree, addrs_sorted);

  479.   abfd_addrs = build_section_addr_info_from_bfd (abfd);
  480.   make_cleanup_free_section_addr_info (abfd_addrs);
  481.   abfd_addrs_sorted = addrs_section_sort (abfd_addrs);
  482.   make_cleanup (xfree, abfd_addrs_sorted);

  483.   /* Now create ADDRS_TO_ABFD_ADDRS from ADDRS_SORTED and
  484.      ABFD_ADDRS_SORTED.  */

  485.   addrs_to_abfd_addrs = xzalloc (sizeof (*addrs_to_abfd_addrs)
  486.                                  * addrs->num_sections);
  487.   make_cleanup (xfree, addrs_to_abfd_addrs);

  488.   while (*addrs_sorted)
  489.     {
  490.       const char *sect_name = addr_section_name ((*addrs_sorted)->name);

  491.       while (*abfd_addrs_sorted
  492.              && strcmp (addr_section_name ((*abfd_addrs_sorted)->name),
  493.                         sect_name) < 0)
  494.         abfd_addrs_sorted++;

  495.       if (*abfd_addrs_sorted
  496.           && strcmp (addr_section_name ((*abfd_addrs_sorted)->name),
  497.                      sect_name) == 0)
  498.         {
  499.           int index_in_addrs;

  500.           /* Make the found item directly addressable from ADDRS.  */
  501.           index_in_addrs = *addrs_sorted - addrs->other;
  502.           gdb_assert (addrs_to_abfd_addrs[index_in_addrs] == NULL);
  503.           addrs_to_abfd_addrs[index_in_addrs] = *abfd_addrs_sorted;

  504.           /* Never use the same ABFD entry twice.  */
  505.           abfd_addrs_sorted++;
  506.         }

  507.       addrs_sorted++;
  508.     }

  509.   /* Calculate offsets for the loadable sections.
  510.      FIXME! Sections must be in order of increasing loadable section
  511.      so that contiguous sections can use the lower-offset!!!

  512.      Adjust offsets if the segments are not contiguous.
  513.      If the section is contiguous, its offset should be set to
  514.      the offset of the highest loadable section lower than it
  515.      (the loadable section directly below it in memory).
  516.      this_offset = lower_offset = lower_addr - lower_orig_addr */

  517.   for (i = 0; i < addrs->num_sections; i++)
  518.     {
  519.       struct other_sections *sect = addrs_to_abfd_addrs[i];

  520.       if (sect)
  521.         {
  522.           /* This is the index used by BFD.  */
  523.           addrs->other[i].sectindex = sect->sectindex;

  524.           if (addrs->other[i].addr != 0)
  525.             {
  526.               addrs->other[i].addr -= sect->addr;
  527.               lower_offset = addrs->other[i].addr;
  528.             }
  529.           else
  530.             addrs->other[i].addr = lower_offset;
  531.         }
  532.       else
  533.         {
  534.           /* addr_section_name transformation is not used for SECT_NAME.  */
  535.           const char *sect_name = addrs->other[i].name;

  536.           /* This section does not exist in ABFD, which is normally
  537.              unexpected and we want to issue a warning.

  538.              However, the ELF prelinker does create a few sections which are
  539.              marked in the main executable as loadable (they are loaded in
  540.              memory from the DYNAMIC segment) and yet are not present in
  541.              separate debug info files.  This is fine, and should not cause
  542.              a warning.  Shared libraries contain just the section
  543.              ".gnu.liblist" but it is not marked as loadable there.  There is
  544.              no other way to identify them than by their name as the sections
  545.              created by prelink have no special flags.

  546.              For the sections `.bss' and `.sbss' see addr_section_name.  */

  547.           if (!(strcmp (sect_name, ".gnu.liblist") == 0
  548.                 || strcmp (sect_name, ".gnu.conflict") == 0
  549.                 || (strcmp (sect_name, ".bss") == 0
  550.                     && i > 0
  551.                     && strcmp (addrs->other[i - 1].name, ".dynbss") == 0
  552.                     && addrs_to_abfd_addrs[i - 1] != NULL)
  553.                 || (strcmp (sect_name, ".sbss") == 0
  554.                     && i > 0
  555.                     && strcmp (addrs->other[i - 1].name, ".sdynbss") == 0
  556.                     && addrs_to_abfd_addrs[i - 1] != NULL)))
  557.             warning (_("section %s not found in %s"), sect_name,
  558.                      bfd_get_filename (abfd));

  559.           addrs->other[i].addr = 0;
  560.           addrs->other[i].sectindex = -1;
  561.         }
  562.     }

  563.   do_cleanups (my_cleanup);
  564. }

  565. /* Parse the user's idea of an offset for dynamic linking, into our idea
  566.    of how to represent it for fast symbol reading.  This is the default
  567.    version of the sym_fns.sym_offsets function for symbol readers that
  568.    don't need to do anything special.  It allocates a section_offsets table
  569.    for the objectfile OBJFILE and stuffs ADDR into all of the offsets.  */

  570. void
  571. default_symfile_offsets (struct objfile *objfile,
  572.                          const struct section_addr_info *addrs)
  573. {
  574.   objfile->num_sections = gdb_bfd_count_sections (objfile->obfd);
  575.   objfile->section_offsets = (struct section_offsets *)
  576.     obstack_alloc (&objfile->objfile_obstack,
  577.                    SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
  578.   relative_addr_info_to_section_offsets (objfile->section_offsets,
  579.                                          objfile->num_sections, addrs);

  580.   /* For relocatable files, all loadable sections will start at zero.
  581.      The zero is meaningless, so try to pick arbitrary addresses such
  582.      that no loadable sections overlap.  This algorithm is quadratic,
  583.      but the number of sections in a single object file is generally
  584.      small.  */
  585.   if ((bfd_get_file_flags (objfile->obfd) & (EXEC_P | DYNAMIC)) == 0)
  586.     {
  587.       struct place_section_arg arg;
  588.       bfd *abfd = objfile->obfd;
  589.       asection *cur_sec;

  590.       for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
  591.         /* We do not expect this to happen; just skip this step if the
  592.            relocatable file has a section with an assigned VMA.  */
  593.         if (bfd_section_vma (abfd, cur_sec) != 0)
  594.           break;

  595.       if (cur_sec == NULL)
  596.         {
  597.           CORE_ADDR *offsets = objfile->section_offsets->offsets;

  598.           /* Pick non-overlapping offsets for sections the user did not
  599.              place explicitly.  */
  600.           arg.offsets = objfile->section_offsets;
  601.           arg.lowest = 0;
  602.           bfd_map_over_sections (objfile->obfd, place_section, &arg);

  603.           /* Correctly filling in the section offsets is not quite
  604.              enough.  Relocatable files have two properties that
  605.              (most) shared objects do not:

  606.              - Their debug information will contain relocations.  Some
  607.              shared libraries do also, but many do not, so this can not
  608.              be assumed.

  609.              - If there are multiple code sections they will be loaded
  610.              at different relative addresses in memory than they are
  611.              in the objfile, since all sections in the file will start
  612.              at address zero.

  613.              Because GDB has very limited ability to map from an
  614.              address in debug info to the correct code section,
  615.              it relies on adding SECT_OFF_TEXT to things which might be
  616.              code.  If we clear all the section offsets, and set the
  617.              section VMAs instead, then symfile_relocate_debug_section
  618.              will return meaningful debug information pointing at the
  619.              correct sections.

  620.              GDB has too many different data structures for section
  621.              addresses - a bfd, objfile, and so_list all have section
  622.              tables, as does exec_ops.  Some of these could probably
  623.              be eliminated.  */

  624.           for (cur_sec = abfd->sections; cur_sec != NULL;
  625.                cur_sec = cur_sec->next)
  626.             {
  627.               if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0)
  628.                 continue;

  629.               bfd_set_section_vma (abfd, cur_sec, offsets[cur_sec->index]);
  630.               exec_set_section_address (bfd_get_filename (abfd),
  631.                                         cur_sec->index,
  632.                                         offsets[cur_sec->index]);
  633.               offsets[cur_sec->index] = 0;
  634.             }
  635.         }
  636.     }

  637.   /* Remember the bfd indexes for the .text, .data, .bss and
  638.      .rodata sections.  */
  639.   init_objfile_sect_indices (objfile);
  640. }

  641. /* Divide the file into segments, which are individual relocatable units.
  642.    This is the default version of the sym_fns.sym_segments function for
  643.    symbol readers that do not have an explicit representation of segments.
  644.    It assumes that object files do not have segments, and fully linked
  645.    files have a single segment.  */

  646. struct symfile_segment_data *
  647. default_symfile_segments (bfd *abfd)
  648. {
  649.   int num_sections, i;
  650.   asection *sect;
  651.   struct symfile_segment_data *data;
  652.   CORE_ADDR low, high;

  653.   /* Relocatable files contain enough information to position each
  654.      loadable section independently; they should not be relocated
  655.      in segments.  */
  656.   if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC)) == 0)
  657.     return NULL;

  658.   /* Make sure there is at least one loadable section in the file.  */
  659.   for (sect = abfd->sections; sect != NULL; sect = sect->next)
  660.     {
  661.       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
  662.         continue;

  663.       break;
  664.     }
  665.   if (sect == NULL)
  666.     return NULL;

  667.   low = bfd_get_section_vma (abfd, sect);
  668.   high = low + bfd_get_section_size (sect);

  669.   data = XCNEW (struct symfile_segment_data);
  670.   data->num_segments = 1;
  671.   data->segment_bases = XCNEW (CORE_ADDR);
  672.   data->segment_sizes = XCNEW (CORE_ADDR);

  673.   num_sections = bfd_count_sections (abfd);
  674.   data->segment_info = XCNEWVEC (int, num_sections);

  675.   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
  676.     {
  677.       CORE_ADDR vma;

  678.       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
  679.         continue;

  680.       vma = bfd_get_section_vma (abfd, sect);
  681.       if (vma < low)
  682.         low = vma;
  683.       if (vma + bfd_get_section_size (sect) > high)
  684.         high = vma + bfd_get_section_size (sect);

  685.       data->segment_info[i] = 1;
  686.     }

  687.   data->segment_bases[0] = low;
  688.   data->segment_sizes[0] = high - low;

  689.   return data;
  690. }

  691. /* This is a convenience function to call sym_read for OBJFILE and
  692.    possibly force the partial symbols to be read.  */

  693. static void
  694. read_symbols (struct objfile *objfile, int add_flags)
  695. {
  696.   (*objfile->sf->sym_read) (objfile, add_flags);
  697.   objfile->per_bfd->minsyms_read = 1;

  698.   /* find_separate_debug_file_in_section should be called only if there is
  699.      single binary with no existing separate debug info file.  */
  700.   if (!objfile_has_partial_symbols (objfile)
  701.       && objfile->separate_debug_objfile == NULL
  702.       && objfile->separate_debug_objfile_backlink == NULL)
  703.     {
  704.       bfd *abfd = find_separate_debug_file_in_section (objfile);
  705.       struct cleanup *cleanup = make_cleanup_bfd_unref (abfd);

  706.       if (abfd != NULL)
  707.         {
  708.           /* find_separate_debug_file_in_section uses the same filename for the
  709.              virtual section-as-bfd like the bfd filename containing the
  710.              section.  Therefore use also non-canonical name form for the same
  711.              file containing the section.  */
  712.           symbol_file_add_separate (abfd, objfile->original_name, add_flags,
  713.                                     objfile);
  714.         }

  715.       do_cleanups (cleanup);
  716.     }
  717.   if ((add_flags & SYMFILE_NO_READ) == 0)
  718.     require_partial_symbols (objfile, 0);
  719. }

  720. /* Initialize entry point information for this objfile.  */

  721. static void
  722. init_entry_point_info (struct objfile *objfile)
  723. {
  724.   struct entry_info *ei = &objfile->per_bfd->ei;

  725.   if (ei->initialized)
  726.     return;
  727.   ei->initialized = 1;

  728.   /* Save startup file's range of PC addresses to help blockframe.c
  729.      decide where the bottom of the stack is.  */

  730.   if (bfd_get_file_flags (objfile->obfd) & EXEC_P)
  731.     {
  732.       /* Executable file -- record its entry point so we'll recognize
  733.          the startup file because it contains the entry point.  */
  734.       ei->entry_point = bfd_get_start_address (objfile->obfd);
  735.       ei->entry_point_p = 1;
  736.     }
  737.   else if (bfd_get_file_flags (objfile->obfd) & DYNAMIC
  738.            && bfd_get_start_address (objfile->obfd) != 0)
  739.     {
  740.       /* Some shared libraries may have entry points set and be
  741.          runnable.  There's no clear way to indicate this, so just check
  742.          for values other than zero.  */
  743.       ei->entry_point = bfd_get_start_address (objfile->obfd);
  744.       ei->entry_point_p = 1;
  745.     }
  746.   else
  747.     {
  748.       /* Examination of non-executable.o files.  Short-circuit this stuff.  */
  749.       ei->entry_point_p = 0;
  750.     }

  751.   if (ei->entry_point_p)
  752.     {
  753.       struct obj_section *osect;
  754.       CORE_ADDR entry_point =  ei->entry_point;
  755.       int found;

  756.       /* Make certain that the address points at real code, and not a
  757.          function descriptor.  */
  758.       entry_point
  759.         = gdbarch_convert_from_func_ptr_addr (get_objfile_arch (objfile),
  760.                                               entry_point,
  761.                                               &current_target);

  762.       /* Remove any ISA markers, so that this matches entries in the
  763.          symbol table.  */
  764.       ei->entry_point
  765.         = gdbarch_addr_bits_remove (get_objfile_arch (objfile), entry_point);

  766.       found = 0;
  767.       ALL_OBJFILE_OSECTIONS (objfile, osect)
  768.         {
  769.           struct bfd_section *sect = osect->the_bfd_section;

  770.           if (entry_point >= bfd_get_section_vma (objfile->obfd, sect)
  771.               && entry_point < (bfd_get_section_vma (objfile->obfd, sect)
  772.                                 + bfd_get_section_size (sect)))
  773.             {
  774.               ei->the_bfd_section_index
  775.                 = gdb_bfd_section_index (objfile->obfd, sect);
  776.               found = 1;
  777.               break;
  778.             }
  779.         }

  780.       if (!found)
  781.         ei->the_bfd_section_index = SECT_OFF_TEXT (objfile);
  782.     }
  783. }

  784. /* Process a symbol file, as either the main file or as a dynamically
  785.    loaded file.

  786.    This function does not set the OBJFILE's entry-point info.

  787.    OBJFILE is where the symbols are to be read from.

  788.    ADDRS is the list of section load addresses.  If the user has given
  789.    an 'add-symbol-file' command, then this is the list of offsets and
  790.    addresses he or she provided as arguments to the command; or, if
  791.    we're handling a shared library, these are the actual addresses the
  792.    sections are loaded at, according to the inferior's dynamic linker
  793.    (as gleaned by GDB's shared library code).  We convert each address
  794.    into an offset from the section VMA's as it appears in the object
  795.    file, and then call the file's sym_offsets function to convert this
  796.    into a format-specific offset table --- a `struct section_offsets'.

  797.    ADD_FLAGS encodes verbosity level, whether this is main symbol or
  798.    an extra symbol file such as dynamically loaded code, and wether
  799.    breakpoint reset should be deferred.  */

  800. static void
  801. syms_from_objfile_1 (struct objfile *objfile,
  802.                      struct section_addr_info *addrs,
  803.                      int add_flags)
  804. {
  805.   struct section_addr_info *local_addr = NULL;
  806.   struct cleanup *old_chain;
  807.   const int mainline = add_flags & SYMFILE_MAINLINE;

  808.   objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd));

  809.   if (objfile->sf == NULL)
  810.     {
  811.       /* No symbols to load, but we still need to make sure
  812.          that the section_offsets table is allocated.  */
  813.       int num_sections = gdb_bfd_count_sections (objfile->obfd);
  814.       size_t size = SIZEOF_N_SECTION_OFFSETS (num_sections);

  815.       objfile->num_sections = num_sections;
  816.       objfile->section_offsets
  817.         = obstack_alloc (&objfile->objfile_obstack, size);
  818.       memset (objfile->section_offsets, 0, size);
  819.       return;
  820.     }

  821.   /* Make sure that partially constructed symbol tables will be cleaned up
  822.      if an error occurs during symbol reading.  */
  823.   old_chain = make_cleanup_free_objfile (objfile);

  824.   /* If ADDRS is NULL, put together a dummy address list.
  825.      We now establish the convention that an addr of zero means
  826.      no load address was specified.  */
  827.   if (! addrs)
  828.     {
  829.       local_addr = alloc_section_addr_info (1);
  830.       make_cleanup (xfree, local_addr);
  831.       addrs = local_addr;
  832.     }

  833.   if (mainline)
  834.     {
  835.       /* We will modify the main symbol table, make sure that all its users
  836.          will be cleaned up if an error occurs during symbol reading.  */
  837.       make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/);

  838.       /* Since no error yet, throw away the old symbol table.  */

  839.       if (symfile_objfile != NULL)
  840.         {
  841.           free_objfile (symfile_objfile);
  842.           gdb_assert (symfile_objfile == NULL);
  843.         }

  844.       /* Currently we keep symbols from the add-symbol-file command.
  845.          If the user wants to get rid of them, they should do "symbol-file"
  846.          without arguments first.  Not sure this is the best behavior
  847.          (PR 2207).  */

  848.       (*objfile->sf->sym_new_init) (objfile);
  849.     }

  850.   /* Convert addr into an offset rather than an absolute address.
  851.      We find the lowest address of a loaded segment in the objfile,
  852.      and assume that <addr> is where that got loaded.

  853.      We no longer warn if the lowest section is not a text segment (as
  854.      happens for the PA64 port.  */
  855.   if (addrs->num_sections > 0)
  856.     addr_info_make_relative (addrs, objfile->obfd);

  857.   /* Initialize symbol reading routines for this objfile, allow complaints to
  858.      appear for this new file, and record how verbose to be, then do the
  859.      initial symbol reading for this file.  */

  860.   (*objfile->sf->sym_init) (objfile);
  861.   clear_complaints (&symfile_complaints, 1, add_flags & SYMFILE_VERBOSE);

  862.   (*objfile->sf->sym_offsets) (objfile, addrs);

  863.   read_symbols (objfile, add_flags);

  864.   /* Discard cleanups as symbol reading was successful.  */

  865.   discard_cleanups (old_chain);
  866.   xfree (local_addr);
  867. }

  868. /* Same as syms_from_objfile_1, but also initializes the objfile
  869.    entry-point info.  */

  870. static void
  871. syms_from_objfile (struct objfile *objfile,
  872.                    struct section_addr_info *addrs,
  873.                    int add_flags)
  874. {
  875.   syms_from_objfile_1 (objfile, addrs, add_flags);
  876.   init_entry_point_info (objfile);
  877. }

  878. /* Perform required actions after either reading in the initial
  879.    symbols for a new objfile, or mapping in the symbols from a reusable
  880.    objfile.  ADD_FLAGS is a bitmask of enum symfile_add_flags.  */

  881. void
  882. new_symfile_objfile (struct objfile *objfile, int add_flags)
  883. {
  884.   /* If this is the main symbol file we have to clean up all users of the
  885.      old main symbol file.  Otherwise it is sufficient to fixup all the
  886.      breakpoints that may have been redefined by this symbol file.  */
  887.   if (add_flags & SYMFILE_MAINLINE)
  888.     {
  889.       /* OK, make it the "real" symbol file.  */
  890.       symfile_objfile = objfile;

  891.       clear_symtab_users (add_flags);
  892.     }
  893.   else if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
  894.     {
  895.       breakpoint_re_set ();
  896.     }

  897.   /* We're done reading the symbol file; finish off complaints.  */
  898.   clear_complaints (&symfile_complaints, 0, add_flags & SYMFILE_VERBOSE);
  899. }

  900. /* Process a symbol file, as either the main file or as a dynamically
  901.    loaded file.

  902.    ABFD is a BFD already open on the file, as from symfile_bfd_open.
  903.    A new reference is acquired by this function.

  904.    For NAME description see allocate_objfile's definition.

  905.    ADD_FLAGS encodes verbosity, whether this is main symbol file or
  906.    extra, such as dynamically loaded code, and what to do with breakpoins.

  907.    ADDRS is as described for syms_from_objfile_1, above.
  908.    ADDRS is ignored when SYMFILE_MAINLINE bit is set in ADD_FLAGS.

  909.    PARENT is the original objfile if ABFD is a separate debug info file.
  910.    Otherwise PARENT is NULL.

  911.    Upon success, returns a pointer to the objfile that was added.
  912.    Upon failure, jumps back to command level (never returns).  */

  913. static struct objfile *
  914. symbol_file_add_with_addrs (bfd *abfd, const char *name, int add_flags,
  915.                             struct section_addr_info *addrs,
  916.                             int flags, struct objfile *parent)
  917. {
  918.   struct objfile *objfile;
  919.   const int from_tty = add_flags & SYMFILE_VERBOSE;
  920.   const int mainline = add_flags & SYMFILE_MAINLINE;
  921.   const int should_print = (print_symbol_loading_p (from_tty, mainline, 1)
  922.                             && (readnow_symbol_files
  923.                                 || (add_flags & SYMFILE_NO_READ) == 0));

  924.   if (readnow_symbol_files)
  925.     {
  926.       flags |= OBJF_READNOW;
  927.       add_flags &= ~SYMFILE_NO_READ;
  928.     }

  929.   /* Give user a chance to burp if we'd be
  930.      interactively wiping out any existing symbols.  */

  931.   if ((have_full_symbols () || have_partial_symbols ())
  932.       && mainline
  933.       && from_tty
  934.       && !query (_("Load new symbol table from \"%s\"? "), name))
  935.     error (_("Not confirmed."));

  936.   objfile = allocate_objfile (abfd, name,
  937.                               flags | (mainline ? OBJF_MAINLINE : 0));

  938.   if (parent)
  939.     add_separate_debug_objfile (objfile, parent);

  940.   /* We either created a new mapped symbol table, mapped an existing
  941.      symbol table file which has not had initial symbol reading
  942.      performed, or need to read an unmapped symbol table.  */
  943.   if (should_print)
  944.     {
  945.       if (deprecated_pre_add_symbol_hook)
  946.         deprecated_pre_add_symbol_hook (name);
  947.       else
  948.         {
  949.           printf_unfiltered (_("Reading symbols from %s..."), name);
  950.           wrap_here ("");
  951.           gdb_flush (gdb_stdout);
  952.         }
  953.     }
  954.   syms_from_objfile (objfile, addrs, add_flags);

  955.   /* We now have at least a partial symbol table.  Check to see if the
  956.      user requested that all symbols be read on initial access via either
  957.      the gdb startup command line or on a per symbol file basis.  Expand
  958.      all partial symbol tables for this objfile if so.  */

  959.   if ((flags & OBJF_READNOW))
  960.     {
  961.       if (should_print)
  962.         {
  963.           printf_unfiltered (_("expanding to full symbols..."));
  964.           wrap_here ("");
  965.           gdb_flush (gdb_stdout);
  966.         }

  967.       if (objfile->sf)
  968.         objfile->sf->qf->expand_all_symtabs (objfile);
  969.     }

  970.   if (should_print && !objfile_has_symbols (objfile))
  971.     {
  972.       wrap_here ("");
  973.       printf_unfiltered (_("(no debugging symbols found)..."));
  974.       wrap_here ("");
  975.     }

  976.   if (should_print)
  977.     {
  978.       if (deprecated_post_add_symbol_hook)
  979.         deprecated_post_add_symbol_hook ();
  980.       else
  981.         printf_unfiltered (_("done.\n"));
  982.     }

  983.   /* We print some messages regardless of whether 'from_tty ||
  984.      info_verbose' is true, so make sure they go out at the right
  985.      time.  */
  986.   gdb_flush (gdb_stdout);

  987.   if (objfile->sf == NULL)
  988.     {
  989.       observer_notify_new_objfile (objfile);
  990.       return objfile;        /* No symbols.  */
  991.     }

  992.   new_symfile_objfile (objfile, add_flags);

  993.   observer_notify_new_objfile (objfile);

  994.   bfd_cache_close_all ();
  995.   return (objfile);
  996. }

  997. /* Add BFD as a separate debug file for OBJFILE.  For NAME description
  998.    see allocate_objfile's definition.  */

  999. void
  1000. symbol_file_add_separate (bfd *bfd, const char *name, int symfile_flags,
  1001.                           struct objfile *objfile)
  1002. {
  1003.   struct objfile *new_objfile;
  1004.   struct section_addr_info *sap;
  1005.   struct cleanup *my_cleanup;

  1006.   /* Create section_addr_info.  We can't directly use offsets from OBJFILE
  1007.      because sections of BFD may not match sections of OBJFILE and because
  1008.      vma may have been modified by tools such as prelink.  */
  1009.   sap = build_section_addr_info_from_objfile (objfile);
  1010.   my_cleanup = make_cleanup_free_section_addr_info (sap);

  1011.   new_objfile = symbol_file_add_with_addrs
  1012.     (bfd, name, symfile_flags, sap,
  1013.      objfile->flags & (OBJF_REORDERED | OBJF_SHARED | OBJF_READNOW
  1014.                        | OBJF_USERLOADED),
  1015.      objfile);

  1016.   do_cleanups (my_cleanup);
  1017. }

  1018. /* Process the symbol file ABFD, as either the main file or as a
  1019.    dynamically loaded file.
  1020.    See symbol_file_add_with_addrs's comments for details.  */

  1021. struct objfile *
  1022. symbol_file_add_from_bfd (bfd *abfd, const char *name, int add_flags,
  1023.                           struct section_addr_info *addrs,
  1024.                           int flags, struct objfile *parent)
  1025. {
  1026.   return symbol_file_add_with_addrs (abfd, name, add_flags, addrs, flags,
  1027.                                      parent);
  1028. }

  1029. /* Process a symbol file, as either the main file or as a dynamically
  1030.    loaded file.  See symbol_file_add_with_addrs's comments for details.  */

  1031. struct objfile *
  1032. symbol_file_add (const char *name, int add_flags,
  1033.                  struct section_addr_info *addrs, int flags)
  1034. {
  1035.   bfd *bfd = symfile_bfd_open (name);
  1036.   struct cleanup *cleanup = make_cleanup_bfd_unref (bfd);
  1037.   struct objfile *objf;

  1038.   objf = symbol_file_add_from_bfd (bfd, name, add_flags, addrs, flags, NULL);
  1039.   do_cleanups (cleanup);
  1040.   return objf;
  1041. }

  1042. /* Call symbol_file_add() with default values and update whatever is
  1043.    affected by the loading of a new main().
  1044.    Used when the file is supplied in the gdb command line
  1045.    and by some targets with special loading requirements.
  1046.    The auxiliary function, symbol_file_add_main_1(), has the flags
  1047.    argument for the switches that can only be specified in the symbol_file
  1048.    command itself.  */

  1049. void
  1050. symbol_file_add_main (const char *args, int from_tty)
  1051. {
  1052.   symbol_file_add_main_1 (args, from_tty, 0);
  1053. }

  1054. static void
  1055. symbol_file_add_main_1 (const char *args, int from_tty, int flags)
  1056. {
  1057.   const int add_flags = (current_inferior ()->symfile_flags
  1058.                          | SYMFILE_MAINLINE | (from_tty ? SYMFILE_VERBOSE : 0));

  1059.   symbol_file_add (args, add_flags, NULL, flags);

  1060.   /* Getting new symbols may change our opinion about
  1061.      what is frameless.  */
  1062.   reinit_frame_cache ();

  1063.   if ((flags & SYMFILE_NO_READ) == 0)
  1064.     set_initial_language ();
  1065. }

  1066. void
  1067. symbol_file_clear (int from_tty)
  1068. {
  1069.   if ((have_full_symbols () || have_partial_symbols ())
  1070.       && from_tty
  1071.       && (symfile_objfile
  1072.           ? !query (_("Discard symbol table from `%s'? "),
  1073.                     objfile_name (symfile_objfile))
  1074.           : !query (_("Discard symbol table? "))))
  1075.     error (_("Not confirmed."));

  1076.   /* solib descriptors may have handles to objfiles.  Wipe them before their
  1077.      objfiles get stale by free_all_objfiles.  */
  1078.   no_shared_libraries (NULL, from_tty);

  1079.   free_all_objfiles ();

  1080.   gdb_assert (symfile_objfile == NULL);
  1081.   if (from_tty)
  1082.     printf_unfiltered (_("No symbol file now.\n"));
  1083. }

  1084. static int
  1085. separate_debug_file_exists (const char *name, unsigned long crc,
  1086.                             struct objfile *parent_objfile)
  1087. {
  1088.   unsigned long file_crc;
  1089.   int file_crc_p;
  1090.   bfd *abfd;
  1091.   struct stat parent_stat, abfd_stat;
  1092.   int verified_as_different;

  1093.   /* Find a separate debug info file as if symbols would be present in
  1094.      PARENT_OBJFILE itself this function would not be called.  .gnu_debuglink
  1095.      section can contain just the basename of PARENT_OBJFILE without any
  1096.      ".debug" suffix as "/usr/lib/debug/path/to/file" is a separate tree where
  1097.      the separate debug infos with the same basename can exist.  */

  1098.   if (filename_cmp (name, objfile_name (parent_objfile)) == 0)
  1099.     return 0;

  1100.   abfd = gdb_bfd_open_maybe_remote (name);

  1101.   if (!abfd)
  1102.     return 0;

  1103.   /* Verify symlinks were not the cause of filename_cmp name difference above.

  1104.      Some operating systems, e.g. Windows, do not provide a meaningful
  1105.      st_ino; they always set it to zero.  (Windows does provide a
  1106.      meaningful st_dev.)  Do not indicate a duplicate library in that
  1107.      case.  While there is no guarantee that a system that provides
  1108.      meaningful inode numbers will never set st_ino to zero, this is
  1109.      merely an optimization, so we do not need to worry about false
  1110.      negatives.  */

  1111.   if (bfd_stat (abfd, &abfd_stat) == 0
  1112.       && abfd_stat.st_ino != 0
  1113.       && bfd_stat (parent_objfile->obfd, &parent_stat) == 0)
  1114.     {
  1115.       if (abfd_stat.st_dev == parent_stat.st_dev
  1116.           && abfd_stat.st_ino == parent_stat.st_ino)
  1117.         {
  1118.           gdb_bfd_unref (abfd);
  1119.           return 0;
  1120.         }
  1121.       verified_as_different = 1;
  1122.     }
  1123.   else
  1124.     verified_as_different = 0;

  1125.   file_crc_p = gdb_bfd_crc (abfd, &file_crc);

  1126.   gdb_bfd_unref (abfd);

  1127.   if (!file_crc_p)
  1128.     return 0;

  1129.   if (crc != file_crc)
  1130.     {
  1131.       unsigned long parent_crc;

  1132.       /* If one (or both) the files are accessed for example the via "remote:"
  1133.          gdbserver way it does not support the bfd_stat operation.  Verify
  1134.          whether those two files are not the same manually.  */

  1135.       if (!verified_as_different)
  1136.         {
  1137.           if (!gdb_bfd_crc (parent_objfile->obfd, &parent_crc))
  1138.             return 0;
  1139.         }

  1140.       if (verified_as_different || parent_crc != file_crc)
  1141.         warning (_("the debug information found in \"%s\""
  1142.                    " does not match \"%s\" (CRC mismatch).\n"),
  1143.                  name, objfile_name (parent_objfile));

  1144.       return 0;
  1145.     }

  1146.   return 1;
  1147. }

  1148. char *debug_file_directory = NULL;
  1149. static void
  1150. show_debug_file_directory (struct ui_file *file, int from_tty,
  1151.                            struct cmd_list_element *c, const char *value)
  1152. {
  1153.   fprintf_filtered (file,
  1154.                     _("The directory where separate debug "
  1155.                       "symbols are searched for is \"%s\".\n"),
  1156.                     value);
  1157. }

  1158. #if ! defined (DEBUG_SUBDIRECTORY)
  1159. #define DEBUG_SUBDIRECTORY ".debug"
  1160. #endif

  1161. /* Find a separate debuginfo file for OBJFILE, using DIR as the directory
  1162.    where the original file resides (may not be the same as
  1163.    dirname(objfile->name) due to symlinks), and DEBUGLINK as the file we are
  1164.    looking for.  CANON_DIR is the "realpath" form of DIR.
  1165.    DIR must contain a trailing '/'.
  1166.    Returns the path of the file with separate debug info, of NULL.  */

  1167. static char *
  1168. find_separate_debug_file (const char *dir,
  1169.                           const char *canon_dir,
  1170.                           const char *debuglink,
  1171.                           unsigned long crc32, struct objfile *objfile)
  1172. {
  1173.   char *debugdir;
  1174.   char *debugfile;
  1175.   int i;
  1176.   VEC (char_ptr) *debugdir_vec;
  1177.   struct cleanup *back_to;
  1178.   int ix;

  1179.   /* Set I to max (strlen (canon_dir), strlen (dir)).  */
  1180.   i = strlen (dir);
  1181.   if (canon_dir != NULL && strlen (canon_dir) > i)
  1182.     i = strlen (canon_dir);

  1183.   debugfile = xmalloc (strlen (debug_file_directory) + 1
  1184.                        + i
  1185.                        + strlen (DEBUG_SUBDIRECTORY)
  1186.                        + strlen ("/")
  1187.                        + strlen (debuglink)
  1188.                        + 1);

  1189.   /* First try in the same directory as the original file.  */
  1190.   strcpy (debugfile, dir);
  1191.   strcat (debugfile, debuglink);

  1192.   if (separate_debug_file_exists (debugfile, crc32, objfile))
  1193.     return debugfile;

  1194.   /* Then try in the subdirectory named DEBUG_SUBDIRECTORY.  */
  1195.   strcpy (debugfile, dir);
  1196.   strcat (debugfile, DEBUG_SUBDIRECTORY);
  1197.   strcat (debugfile, "/");
  1198.   strcat (debugfile, debuglink);

  1199.   if (separate_debug_file_exists (debugfile, crc32, objfile))
  1200.     return debugfile;

  1201.   /* Then try in the global debugfile directories.

  1202.      Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will
  1203.      cause "/..." lookups.  */

  1204.   debugdir_vec = dirnames_to_char_ptr_vec (debug_file_directory);
  1205.   back_to = make_cleanup_free_char_ptr_vec (debugdir_vec);

  1206.   for (ix = 0; VEC_iterate (char_ptr, debugdir_vec, ix, debugdir); ++ix)
  1207.     {
  1208.       strcpy (debugfile, debugdir);
  1209.       strcat (debugfile, "/");
  1210.       strcat (debugfile, dir);
  1211.       strcat (debugfile, debuglink);

  1212.       if (separate_debug_file_exists (debugfile, crc32, objfile))
  1213.         {
  1214.           do_cleanups (back_to);
  1215.           return debugfile;
  1216.         }

  1217.       /* If the file is in the sysroot, try using its base path in the
  1218.          global debugfile directory.  */
  1219.       if (canon_dir != NULL
  1220.           && filename_ncmp (canon_dir, gdb_sysroot,
  1221.                             strlen (gdb_sysroot)) == 0
  1222.           && IS_DIR_SEPARATOR (canon_dir[strlen (gdb_sysroot)]))
  1223.         {
  1224.           strcpy (debugfile, debugdir);
  1225.           strcat (debugfile, canon_dir + strlen (gdb_sysroot));
  1226.           strcat (debugfile, "/");
  1227.           strcat (debugfile, debuglink);

  1228.           if (separate_debug_file_exists (debugfile, crc32, objfile))
  1229.             {
  1230.               do_cleanups (back_to);
  1231.               return debugfile;
  1232.             }
  1233.         }
  1234.     }

  1235.   do_cleanups (back_to);
  1236.   xfree (debugfile);
  1237.   return NULL;
  1238. }

  1239. /* Modify PATH to contain only "[/]directory/" part of PATH.
  1240.    If there were no directory separators in PATH, PATH will be empty
  1241.    string on return.  */

  1242. static void
  1243. terminate_after_last_dir_separator (char *path)
  1244. {
  1245.   int i;

  1246.   /* Strip off the final filename part, leaving the directory name,
  1247.      followed by a slash.  The directory can be relative or absolute.  */
  1248.   for (i = strlen(path) - 1; i >= 0; i--)
  1249.     if (IS_DIR_SEPARATOR (path[i]))
  1250.       break;

  1251.   /* If I is -1 then no directory is present there and DIR will be "".  */
  1252.   path[i + 1] = '\0';
  1253. }

  1254. /* Find separate debuginfo for OBJFILE (using .gnu_debuglink section).
  1255.    Returns pathname, or NULL.  */

  1256. char *
  1257. find_separate_debug_file_by_debuglink (struct objfile *objfile)
  1258. {
  1259.   char *debuglink;
  1260.   char *dir, *canon_dir;
  1261.   char *debugfile;
  1262.   unsigned long crc32;
  1263.   struct cleanup *cleanups;

  1264.   debuglink = bfd_get_debug_link_info (objfile->obfd, &crc32);

  1265.   if (debuglink == NULL)
  1266.     {
  1267.       /* There's no separate debug info, hence there's no way we could
  1268.          load it => no warning.  */
  1269.       return NULL;
  1270.     }

  1271.   cleanups = make_cleanup (xfree, debuglink);
  1272.   dir = xstrdup (objfile_name (objfile));
  1273.   make_cleanup (xfree, dir);
  1274.   terminate_after_last_dir_separator (dir);
  1275.   canon_dir = lrealpath (dir);

  1276.   debugfile = find_separate_debug_file (dir, canon_dir, debuglink,
  1277.                                         crc32, objfile);
  1278.   xfree (canon_dir);

  1279.   if (debugfile == NULL)
  1280.     {
  1281.       /* For PR gdb/9538, try again with realpath (if different from the
  1282.          original).  */

  1283.       struct stat st_buf;

  1284.       if (lstat (objfile_name (objfile), &st_buf) == 0
  1285.           && S_ISLNK (st_buf.st_mode))
  1286.         {
  1287.           char *symlink_dir;

  1288.           symlink_dir = lrealpath (objfile_name (objfile));
  1289.           if (symlink_dir != NULL)
  1290.             {
  1291.               make_cleanup (xfree, symlink_dir);
  1292.               terminate_after_last_dir_separator (symlink_dir);
  1293.               if (strcmp (dir, symlink_dir) != 0)
  1294.                 {
  1295.                   /* Different directory, so try using it.  */
  1296.                   debugfile = find_separate_debug_file (symlink_dir,
  1297.                                                         symlink_dir,
  1298.                                                         debuglink,
  1299.                                                         crc32,
  1300.                                                         objfile);
  1301.                 }
  1302.             }
  1303.         }
  1304.     }

  1305.   do_cleanups (cleanups);
  1306.   return debugfile;
  1307. }

  1308. /* This is the symbol-file command.  Read the file, analyze its
  1309.    symbols, and add a struct symtab to a symtab list.  The syntax of
  1310.    the command is rather bizarre:

  1311.    1. The function buildargv implements various quoting conventions
  1312.    which are undocumented and have little or nothing in common with
  1313.    the way things are quoted (or not quoted) elsewhere in GDB.

  1314.    2. Options are used, which are not generally used in GDB (perhaps
  1315.    "set mapped on", "set readnow on" would be better)

  1316.    3. The order of options matters, which is contrary to GNU
  1317.    conventions (because it is confusing and inconvenient).  */

  1318. void
  1319. symbol_file_command (char *args, int from_tty)
  1320. {
  1321.   dont_repeat ();

  1322.   if (args == NULL)
  1323.     {
  1324.       symbol_file_clear (from_tty);
  1325.     }
  1326.   else
  1327.     {
  1328.       char **argv = gdb_buildargv (args);
  1329.       int flags = OBJF_USERLOADED;
  1330.       struct cleanup *cleanups;
  1331.       char *name = NULL;

  1332.       cleanups = make_cleanup_freeargv (argv);
  1333.       while (*argv != NULL)
  1334.         {
  1335.           if (strcmp (*argv, "-readnow") == 0)
  1336.             flags |= OBJF_READNOW;
  1337.           else if (**argv == '-')
  1338.             error (_("unknown option `%s'"), *argv);
  1339.           else
  1340.             {
  1341.               symbol_file_add_main_1 (*argv, from_tty, flags);
  1342.               name = *argv;
  1343.             }

  1344.           argv++;
  1345.         }

  1346.       if (name == NULL)
  1347.         error (_("no symbol file name was specified"));

  1348.       do_cleanups (cleanups);
  1349.     }
  1350. }

  1351. /* Set the initial language.

  1352.    FIXME: A better solution would be to record the language in the
  1353.    psymtab when reading partial symbols, and then use it (if known) to
  1354.    set the language.  This would be a win for formats that encode the
  1355.    language in an easily discoverable place, such as DWARF.  For
  1356.    stabs, we can jump through hoops looking for specially named
  1357.    symbols or try to intuit the language from the specific type of
  1358.    stabs we find, but we can't do that until later when we read in
  1359.    full symbols.  */

  1360. void
  1361. set_initial_language (void)
  1362. {
  1363.   enum language lang = main_language ();

  1364.   if (lang == language_unknown)
  1365.     {
  1366.       char *name = main_name ();
  1367.       struct symbol *sym = lookup_symbol (name, NULL, VAR_DOMAIN, NULL);

  1368.       if (sym != NULL)
  1369.         lang = SYMBOL_LANGUAGE (sym);
  1370.     }

  1371.   if (lang == language_unknown)
  1372.     {
  1373.       /* Make C the default language */
  1374.       lang = language_c;
  1375.     }

  1376.   set_language (lang);
  1377.   expected_language = current_language; /* Don't warn the user.  */
  1378. }

  1379. /* If NAME is a remote name open the file using remote protocol, otherwise
  1380.    open it normally.  Returns a new reference to the BFD.  On error,
  1381.    returns NULL with the BFD error set.  */

  1382. bfd *
  1383. gdb_bfd_open_maybe_remote (const char *name)
  1384. {
  1385.   bfd *result;

  1386.   if (remote_filename_p (name))
  1387.     result = remote_bfd_open (name, gnutarget);
  1388.   else
  1389.     result = gdb_bfd_open (name, gnutarget, -1);

  1390.   return result;
  1391. }

  1392. /* Open the file specified by NAME and hand it off to BFD for
  1393.    preliminary analysis.  Return a newly initialized bfd *, which
  1394.    includes a newly malloc'd` copy of NAME (tilde-expanded and made
  1395.    absolute).  In case of trouble, error() is called.  */

  1396. bfd *
  1397. symfile_bfd_open (const char *cname)
  1398. {
  1399.   bfd *sym_bfd;
  1400.   int desc;
  1401.   char *name, *absolute_name;
  1402.   struct cleanup *back_to;

  1403.   if (remote_filename_p (cname))
  1404.     {
  1405.       sym_bfd = remote_bfd_open (cname, gnutarget);
  1406.       if (!sym_bfd)
  1407.         error (_("`%s': can't open to read symbols: %s."), cname,
  1408.                bfd_errmsg (bfd_get_error ()));

  1409.       if (!bfd_check_format (sym_bfd, bfd_object))
  1410.         {
  1411.           make_cleanup_bfd_unref (sym_bfd);
  1412.           error (_("`%s': can't read symbols: %s."), cname,
  1413.                  bfd_errmsg (bfd_get_error ()));
  1414.         }

  1415.       return sym_bfd;
  1416.     }

  1417.   name = tilde_expand (cname);        /* Returns 1st new malloc'd copy.  */

  1418.   /* Look down path for it, allocate 2nd new malloc'd copy.  */
  1419.   desc = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, name,
  1420.                 O_RDONLY | O_BINARY, &absolute_name);
  1421. #if defined(__GO32__) || defined(_WIN32) || defined (__CYGWIN__)
  1422.   if (desc < 0)
  1423.     {
  1424.       char *exename = alloca (strlen (name) + 5);

  1425.       strcat (strcpy (exename, name), ".exe");
  1426.       desc = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
  1427.                     exename, O_RDONLY | O_BINARY, &absolute_name);
  1428.     }
  1429. #endif
  1430.   if (desc < 0)
  1431.     {
  1432.       make_cleanup (xfree, name);
  1433.       perror_with_name (name);
  1434.     }

  1435.   xfree (name);
  1436.   name = absolute_name;
  1437.   back_to = make_cleanup (xfree, name);

  1438.   sym_bfd = gdb_bfd_open (name, gnutarget, desc);
  1439.   if (!sym_bfd)
  1440.     error (_("`%s': can't open to read symbols: %s."), name,
  1441.            bfd_errmsg (bfd_get_error ()));
  1442.   bfd_set_cacheable (sym_bfd, 1);

  1443.   if (!bfd_check_format (sym_bfd, bfd_object))
  1444.     {
  1445.       make_cleanup_bfd_unref (sym_bfd);
  1446.       error (_("`%s': can't read symbols: %s."), name,
  1447.              bfd_errmsg (bfd_get_error ()));
  1448.     }

  1449.   do_cleanups (back_to);

  1450.   return sym_bfd;
  1451. }

  1452. /* Return the section index for SECTION_NAME on OBJFILE.  Return -1 if
  1453.    the section was not found.  */

  1454. int
  1455. get_section_index (struct objfile *objfile, char *section_name)
  1456. {
  1457.   asection *sect = bfd_get_section_by_name (objfile->obfd, section_name);

  1458.   if (sect)
  1459.     return sect->index;
  1460.   else
  1461.     return -1;
  1462. }

  1463. /* Link SF into the global symtab_fns list.
  1464.    FLAVOUR is the file format that SF handles.
  1465.    Called on startup by the _initialize routine in each object file format
  1466.    reader, to register information about each format the reader is prepared
  1467.    to handle.  */

  1468. void
  1469. add_symtab_fns (enum bfd_flavour flavour, const struct sym_fns *sf)
  1470. {
  1471.   registered_sym_fns fns = { flavour, sf };

  1472.   VEC_safe_push (registered_sym_fns, symtab_fns, &fns);
  1473. }

  1474. /* Initialize OBJFILE to read symbols from its associated BFD.  It
  1475.    either returns or calls error().  The result is an initialized
  1476.    struct sym_fns in the objfile structure, that contains cached
  1477.    information about the symbol file.  */

  1478. static const struct sym_fns *
  1479. find_sym_fns (bfd *abfd)
  1480. {
  1481.   registered_sym_fns *rsf;
  1482.   enum bfd_flavour our_flavour = bfd_get_flavour (abfd);
  1483.   int i;

  1484.   if (our_flavour == bfd_target_srec_flavour
  1485.       || our_flavour == bfd_target_ihex_flavour
  1486.       || our_flavour == bfd_target_tekhex_flavour)
  1487.     return NULL;        /* No symbols.  */

  1488.   for (i = 0; VEC_iterate (registered_sym_fns, symtab_fns, i, rsf); ++i)
  1489.     if (our_flavour == rsf->sym_flavour)
  1490.       return rsf->sym_fns;

  1491.   error (_("I'm sorry, Dave, I can't do that.  Symbol format `%s' unknown."),
  1492.          bfd_get_target (abfd));
  1493. }


  1494. /* This function runs the load command of our current target.  */

  1495. static void
  1496. load_command (char *arg, int from_tty)
  1497. {
  1498.   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);

  1499.   dont_repeat ();

  1500.   /* The user might be reloading because the binary has changed.  Take
  1501.      this opportunity to check.  */
  1502.   reopen_exec_file ();
  1503.   reread_symbols ();

  1504.   if (arg == NULL)
  1505.     {
  1506.       char *parg;
  1507.       int count = 0;

  1508.       parg = arg = get_exec_file (1);

  1509.       /* Count how many \ " ' tab space there are in the name.  */
  1510.       while ((parg = strpbrk (parg, "\\\"'\t ")))
  1511.         {
  1512.           parg++;
  1513.           count++;
  1514.         }

  1515.       if (count)
  1516.         {
  1517.           /* We need to quote this string so buildargv can pull it apart.  */
  1518.           char *temp = xmalloc (strlen (arg) + count + 1 );
  1519.           char *ptemp = temp;
  1520.           char *prev;

  1521.           make_cleanup (xfree, temp);

  1522.           prev = parg = arg;
  1523.           while ((parg = strpbrk (parg, "\\\"'\t ")))
  1524.             {
  1525.               strncpy (ptemp, prev, parg - prev);
  1526.               ptemp += parg - prev;
  1527.               prev = parg++;
  1528.               *ptemp++ = '\\';
  1529.             }
  1530.           strcpy (ptemp, prev);

  1531.           arg = temp;
  1532.         }
  1533.     }

  1534.   target_load (arg, from_tty);

  1535.   /* After re-loading the executable, we don't really know which
  1536.      overlays are mapped any more.  */
  1537.   overlay_cache_invalid = 1;

  1538.   do_cleanups (cleanup);
  1539. }

  1540. /* This version of "load" should be usable for any target.  Currently
  1541.    it is just used for remote targets, not inftarg.c or core files,
  1542.    on the theory that only in that case is it useful.

  1543.    Avoiding xmodem and the like seems like a win (a) because we don't have
  1544.    to worry about finding it, and (b) On VMS, fork() is very slow and so
  1545.    we don't want to run a subprocess.  On the other hand, I'm not sure how
  1546.    performance compares.  */

  1547. static int validate_download = 0;

  1548. /* Callback service function for generic_load (bfd_map_over_sections).  */

  1549. static void
  1550. add_section_size_callback (bfd *abfd, asection *asec, void *data)
  1551. {
  1552.   bfd_size_type *sum = data;

  1553.   *sum += bfd_get_section_size (asec);
  1554. }

  1555. /* Opaque data for load_section_callback.  */
  1556. struct load_section_data {
  1557.   CORE_ADDR load_offset;
  1558.   struct load_progress_data *progress_data;
  1559.   VEC(memory_write_request_s) *requests;
  1560. };

  1561. /* Opaque data for load_progress.  */
  1562. struct load_progress_data {
  1563.   /* Cumulative data.  */
  1564.   unsigned long write_count;
  1565.   unsigned long data_count;
  1566.   bfd_size_type total_size;
  1567. };

  1568. /* Opaque data for load_progress for a single section.  */
  1569. struct load_progress_section_data {
  1570.   struct load_progress_data *cumulative;

  1571.   /* Per-section data.  */
  1572.   const char *section_name;
  1573.   ULONGEST section_sent;
  1574.   ULONGEST section_size;
  1575.   CORE_ADDR lma;
  1576.   gdb_byte *buffer;
  1577. };

  1578. /* Target write callback routine for progress reporting.  */

  1579. static void
  1580. load_progress (ULONGEST bytes, void *untyped_arg)
  1581. {
  1582.   struct load_progress_section_data *args = untyped_arg;
  1583.   struct load_progress_data *totals;

  1584.   if (args == NULL)
  1585.     /* Writing padding data.  No easy way to get at the cumulative
  1586.        stats, so just ignore this.  */
  1587.     return;

  1588.   totals = args->cumulative;

  1589.   if (bytes == 0 && args->section_sent == 0)
  1590.     {
  1591.       /* The write is just starting.  Let the user know we've started
  1592.          this section.  */
  1593.       ui_out_message (current_uiout, 0, "Loading section %s, size %s lma %s\n",
  1594.                       args->section_name, hex_string (args->section_size),
  1595.                       paddress (target_gdbarch (), args->lma));
  1596.       return;
  1597.     }

  1598.   if (validate_download)
  1599.     {
  1600.       /* Broken memories and broken monitors manifest themselves here
  1601.          when bring new computers to life.  This doubles already slow
  1602.          downloads.  */
  1603.       /* NOTE: cagney/1999-10-18: A more efficient implementation
  1604.          might add a verify_memory() method to the target vector and
  1605.          then use that.  remote.c could implement that method using
  1606.          the ``qCRC'' packet.  */
  1607.       gdb_byte *check = xmalloc (bytes);
  1608.       struct cleanup *verify_cleanups = make_cleanup (xfree, check);

  1609.       if (target_read_memory (args->lma, check, bytes) != 0)
  1610.         error (_("Download verify read failed at %s"),
  1611.                paddress (target_gdbarch (), args->lma));
  1612.       if (memcmp (args->buffer, check, bytes) != 0)
  1613.         error (_("Download verify compare failed at %s"),
  1614.                paddress (target_gdbarch (), args->lma));
  1615.       do_cleanups (verify_cleanups);
  1616.     }
  1617.   totals->data_count += bytes;
  1618.   args->lma += bytes;
  1619.   args->buffer += bytes;
  1620.   totals->write_count += 1;
  1621.   args->section_sent += bytes;
  1622.   if (check_quit_flag ()
  1623.       || (deprecated_ui_load_progress_hook != NULL
  1624.           && deprecated_ui_load_progress_hook (args->section_name,
  1625.                                                args->section_sent)))
  1626.     error (_("Canceled the download"));

  1627.   if (deprecated_show_load_progress != NULL)
  1628.     deprecated_show_load_progress (args->section_name,
  1629.                                    args->section_sent,
  1630.                                    args->section_size,
  1631.                                    totals->data_count,
  1632.                                    totals->total_size);
  1633. }

  1634. /* Callback service function for generic_load (bfd_map_over_sections).  */

  1635. static void
  1636. load_section_callback (bfd *abfd, asection *asec, void *data)
  1637. {
  1638.   struct memory_write_request *new_request;
  1639.   struct load_section_data *args = data;
  1640.   struct load_progress_section_data *section_data;
  1641.   bfd_size_type size = bfd_get_section_size (asec);
  1642.   gdb_byte *buffer;
  1643.   const char *sect_name = bfd_get_section_name (abfd, asec);

  1644.   if ((bfd_get_section_flags (abfd, asec) & SEC_LOAD) == 0)
  1645.     return;

  1646.   if (size == 0)
  1647.     return;

  1648.   new_request = VEC_safe_push (memory_write_request_s,
  1649.                                args->requests, NULL);
  1650.   memset (new_request, 0, sizeof (struct memory_write_request));
  1651.   section_data = xcalloc (1, sizeof (struct load_progress_section_data));
  1652.   new_request->begin = bfd_section_lma (abfd, asec) + args->load_offset;
  1653.   new_request->end = new_request->begin + size; /* FIXME Should size
  1654.                                                    be in instead?  */
  1655.   new_request->data = xmalloc (size);
  1656.   new_request->baton = section_data;

  1657.   buffer = new_request->data;

  1658.   section_data->cumulative = args->progress_data;
  1659.   section_data->section_name = sect_name;
  1660.   section_data->section_size = size;
  1661.   section_data->lma = new_request->begin;
  1662.   section_data->buffer = buffer;

  1663.   bfd_get_section_contents (abfd, asec, buffer, 0, size);
  1664. }

  1665. /* Clean up an entire memory request vector, including load
  1666.    data and progress records.  */

  1667. static void
  1668. clear_memory_write_data (void *arg)
  1669. {
  1670.   VEC(memory_write_request_s) **vec_p = arg;
  1671.   VEC(memory_write_request_s) *vec = *vec_p;
  1672.   int i;
  1673.   struct memory_write_request *mr;

  1674.   for (i = 0; VEC_iterate (memory_write_request_s, vec, i, mr); ++i)
  1675.     {
  1676.       xfree (mr->data);
  1677.       xfree (mr->baton);
  1678.     }
  1679.   VEC_free (memory_write_request_s, vec);
  1680. }

  1681. void
  1682. generic_load (const char *args, int from_tty)
  1683. {
  1684.   bfd *loadfile_bfd;
  1685.   struct timeval start_time, end_time;
  1686.   char *filename;
  1687.   struct cleanup *old_cleanups = make_cleanup (null_cleanup, 0);
  1688.   struct load_section_data cbdata;
  1689.   struct load_progress_data total_progress;
  1690.   struct ui_out *uiout = current_uiout;

  1691.   CORE_ADDR entry;
  1692.   char **argv;

  1693.   memset (&cbdata, 0, sizeof (cbdata));
  1694.   memset (&total_progress, 0, sizeof (total_progress));
  1695.   cbdata.progress_data = &total_progress;

  1696.   make_cleanup (clear_memory_write_data, &cbdata.requests);

  1697.   if (args == NULL)
  1698.     error_no_arg (_("file to load"));

  1699.   argv = gdb_buildargv (args);
  1700.   make_cleanup_freeargv (argv);

  1701.   filename = tilde_expand (argv[0]);
  1702.   make_cleanup (xfree, filename);

  1703.   if (argv[1] != NULL)
  1704.     {
  1705.       const char *endptr;

  1706.       cbdata.load_offset = strtoulst (argv[1], &endptr, 0);

  1707.       /* If the last word was not a valid number then
  1708.          treat it as a file name with spaces in.  */
  1709.       if (argv[1] == endptr)
  1710.         error (_("Invalid download offset:%s."), argv[1]);

  1711.       if (argv[2] != NULL)
  1712.         error (_("Too many parameters."));
  1713.     }

  1714.   /* Open the file for loading.  */
  1715.   loadfile_bfd = gdb_bfd_open (filename, gnutarget, -1);
  1716.   if (loadfile_bfd == NULL)
  1717.     {
  1718.       perror_with_name (filename);
  1719.       return;
  1720.     }

  1721.   make_cleanup_bfd_unref (loadfile_bfd);

  1722.   if (!bfd_check_format (loadfile_bfd, bfd_object))
  1723.     {
  1724.       error (_("\"%s\" is not an object file: %s"), filename,
  1725.              bfd_errmsg (bfd_get_error ()));
  1726.     }

  1727.   bfd_map_over_sections (loadfile_bfd, add_section_size_callback,
  1728.                          (void *) &total_progress.total_size);

  1729.   bfd_map_over_sections (loadfile_bfd, load_section_callback, &cbdata);

  1730.   gettimeofday (&start_time, NULL);

  1731.   if (target_write_memory_blocks (cbdata.requests, flash_discard,
  1732.                                   load_progress) != 0)
  1733.     error (_("Load failed"));

  1734.   gettimeofday (&end_time, NULL);

  1735.   entry = bfd_get_start_address (loadfile_bfd);
  1736.   entry = gdbarch_addr_bits_remove (target_gdbarch (), entry);
  1737.   ui_out_text (uiout, "Start address ");
  1738.   ui_out_field_fmt (uiout, "address", "%s", paddress (target_gdbarch (), entry));
  1739.   ui_out_text (uiout, ", load size ");
  1740.   ui_out_field_fmt (uiout, "load-size", "%lu", total_progress.data_count);
  1741.   ui_out_text (uiout, "\n");
  1742.   /* We were doing this in remote-mips.c, I suspect it is right
  1743.      for other targets too.  */
  1744.   regcache_write_pc (get_current_regcache (), entry);

  1745.   /* Reset breakpoints, now that we have changed the load image.  For
  1746.      instance, breakpoints may have been set (or reset, by
  1747.      post_create_inferior) while connected to the target but before we
  1748.      loaded the program.  In that case, the prologue analyzer could
  1749.      have read instructions from the target to find the right
  1750.      breakpoint locations.  Loading has changed the contents of that
  1751.      memory.  */

  1752.   breakpoint_re_set ();

  1753.   /* FIXME: are we supposed to call symbol_file_add or not?  According
  1754.      to a comment from remote-mips.c (where a call to symbol_file_add
  1755.      was commented out), making the call confuses GDB if more than one
  1756.      file is loaded in.  Some targets do (e.g., remote-vx.c) but
  1757.      others don't (or didn't - perhaps they have all been deleted).  */

  1758.   print_transfer_performance (gdb_stdout, total_progress.data_count,
  1759.                               total_progress.write_count,
  1760.                               &start_time, &end_time);

  1761.   do_cleanups (old_cleanups);
  1762. }

  1763. /* Report how fast the transfer went.  */

  1764. void
  1765. print_transfer_performance (struct ui_file *stream,
  1766.                             unsigned long data_count,
  1767.                             unsigned long write_count,
  1768.                             const struct timeval *start_time,
  1769.                             const struct timeval *end_time)
  1770. {
  1771.   ULONGEST time_count;
  1772.   struct ui_out *uiout = current_uiout;

  1773.   /* Compute the elapsed time in milliseconds, as a tradeoff between
  1774.      accuracy and overflow.  */
  1775.   time_count = (end_time->tv_sec - start_time->tv_sec) * 1000;
  1776.   time_count += (end_time->tv_usec - start_time->tv_usec) / 1000;

  1777.   ui_out_text (uiout, "Transfer rate: ");
  1778.   if (time_count > 0)
  1779.     {
  1780.       unsigned long rate = ((ULONGEST) data_count * 1000) / time_count;

  1781.       if (ui_out_is_mi_like_p (uiout))
  1782.         {
  1783.           ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate * 8);
  1784.           ui_out_text (uiout, " bits/sec");
  1785.         }
  1786.       else if (rate < 1024)
  1787.         {
  1788.           ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate);
  1789.           ui_out_text (uiout, " bytes/sec");
  1790.         }
  1791.       else
  1792.         {
  1793.           ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate / 1024);
  1794.           ui_out_text (uiout, " KB/sec");
  1795.         }
  1796.     }
  1797.   else
  1798.     {
  1799.       ui_out_field_fmt (uiout, "transferred-bits", "%lu", (data_count * 8));
  1800.       ui_out_text (uiout, " bits in <1 sec");
  1801.     }
  1802.   if (write_count > 0)
  1803.     {
  1804.       ui_out_text (uiout, ", ");
  1805.       ui_out_field_fmt (uiout, "write-rate", "%lu", data_count / write_count);
  1806.       ui_out_text (uiout, " bytes/write");
  1807.     }
  1808.   ui_out_text (uiout, ".\n");
  1809. }

  1810. /* This function allows the addition of incrementally linked object files.
  1811.    It does not modify any state in the target, only in the debugger.  */
  1812. /* Note: ezannoni 2000-04-13 This function/command used to have a
  1813.    special case syntax for the rombug target (Rombug is the boot
  1814.    monitor for Microware's OS-9 / OS-9000, see remote-os9k.c). In the
  1815.    rombug case, the user doesn't need to supply a text address,
  1816.    instead a call to target_link() (in target.c) would supply the
  1817.    value to use.  We are now discontinuing this type of ad hoc syntax.  */

  1818. static void
  1819. add_symbol_file_command (char *args, int from_tty)
  1820. {
  1821.   struct gdbarch *gdbarch = get_current_arch ();
  1822.   char *filename = NULL;
  1823.   int flags = OBJF_USERLOADED | OBJF_SHARED;
  1824.   char *arg;
  1825.   int section_index = 0;
  1826.   int argcnt = 0;
  1827.   int sec_num = 0;
  1828.   int i;
  1829.   int expecting_sec_name = 0;
  1830.   int expecting_sec_addr = 0;
  1831.   char **argv;
  1832.   struct objfile *objf;

  1833.   struct sect_opt
  1834.   {
  1835.     char *name;
  1836.     char *value;
  1837.   };

  1838.   struct section_addr_info *section_addrs;
  1839.   struct sect_opt *sect_opts = NULL;
  1840.   size_t num_sect_opts = 0;
  1841.   struct cleanup *my_cleanups = make_cleanup (null_cleanup, NULL);

  1842.   num_sect_opts = 16;
  1843.   sect_opts = (struct sect_opt *) xmalloc (num_sect_opts
  1844.                                            * sizeof (struct sect_opt));

  1845.   dont_repeat ();

  1846.   if (args == NULL)
  1847.     error (_("add-symbol-file takes a file name and an address"));

  1848.   argv = gdb_buildargv (args);
  1849.   make_cleanup_freeargv (argv);

  1850.   for (arg = argv[0], argcnt = 0; arg != NULL; arg = argv[++argcnt])
  1851.     {
  1852.       /* Process the argument.  */
  1853.       if (argcnt == 0)
  1854.         {
  1855.           /* The first argument is the file name.  */
  1856.           filename = tilde_expand (arg);
  1857.           make_cleanup (xfree, filename);
  1858.         }
  1859.       else if (argcnt == 1)
  1860.         {
  1861.           /* The second argument is always the text address at which
  1862.              to load the program.  */
  1863.           sect_opts[section_index].name = ".text";
  1864.           sect_opts[section_index].value = arg;
  1865.           if (++section_index >= num_sect_opts)
  1866.             {
  1867.               num_sect_opts *= 2;
  1868.               sect_opts = ((struct sect_opt *)
  1869.                            xrealloc (sect_opts,
  1870.                                      num_sect_opts
  1871.                                      * sizeof (struct sect_opt)));
  1872.             }
  1873.         }
  1874.       else
  1875.         {
  1876.           /* It's an option (starting with '-') or it's an argument
  1877.              to an option.  */
  1878.           if (expecting_sec_name)
  1879.             {
  1880.               sect_opts[section_index].name = arg;
  1881.               expecting_sec_name = 0;
  1882.             }
  1883.           else if (expecting_sec_addr)
  1884.             {
  1885.               sect_opts[section_index].value = arg;
  1886.               expecting_sec_addr = 0;
  1887.               if (++section_index >= num_sect_opts)
  1888.                 {
  1889.                   num_sect_opts *= 2;
  1890.                   sect_opts = ((struct sect_opt *)
  1891.                                xrealloc (sect_opts,
  1892.                                          num_sect_opts
  1893.                                          * sizeof (struct sect_opt)));
  1894.                 }
  1895.             }
  1896.           else if (strcmp (arg, "-readnow") == 0)
  1897.             flags |= OBJF_READNOW;
  1898.           else if (strcmp (arg, "-s") == 0)
  1899.             {
  1900.               expecting_sec_name = 1;
  1901.               expecting_sec_addr = 1;
  1902.             }
  1903.           else
  1904.             error (_("USAGE: add-symbol-file <filename> <textaddress>"
  1905.                      " [-readnow] [-s <secname> <addr>]*"));
  1906.         }
  1907.     }

  1908.   /* This command takes at least two arguments.  The first one is a
  1909.      filename, and the second is the address where this file has been
  1910.      loaded.  Abort now if this address hasn't been provided by the
  1911.      user.  */
  1912.   if (section_index < 1)
  1913.     error (_("The address where %s has been loaded is missing"), filename);

  1914.   /* Print the prompt for the query below.  And save the arguments into
  1915.      a sect_addr_info structure to be passed around to other
  1916.      functions.  We have to split this up into separate print
  1917.      statements because hex_string returns a local static
  1918.      string.  */

  1919.   printf_unfiltered (_("add symbol table from file \"%s\" at\n"), filename);
  1920.   section_addrs = alloc_section_addr_info (section_index);
  1921.   make_cleanup (xfree, section_addrs);
  1922.   for (i = 0; i < section_index; i++)
  1923.     {
  1924.       CORE_ADDR addr;
  1925.       char *val = sect_opts[i].value;
  1926.       char *sec = sect_opts[i].name;

  1927.       addr = parse_and_eval_address (val);

  1928.       /* Here we store the section offsets in the order they were
  1929.          entered on the command line.  */
  1930.       section_addrs->other[sec_num].name = sec;
  1931.       section_addrs->other[sec_num].addr = addr;
  1932.       printf_unfiltered ("\t%s_addr = %s\n", sec,
  1933.                          paddress (gdbarch, addr));
  1934.       sec_num++;

  1935.       /* The object's sections are initialized when a
  1936.          call is made to build_objfile_section_table (objfile).
  1937.          This happens in reread_symbols.
  1938.          At this point, we don't know what file type this is,
  1939.          so we can't determine what section names are valid.  */
  1940.     }
  1941.   section_addrs->num_sections = sec_num;

  1942.   if (from_tty && (!query ("%s", "")))
  1943.     error (_("Not confirmed."));

  1944.   objf = symbol_file_add (filename, from_tty ? SYMFILE_VERBOSE : 0,
  1945.                           section_addrs, flags);

  1946.   add_target_sections_of_objfile (objf);

  1947.   /* Getting new symbols may change our opinion about what is
  1948.      frameless.  */
  1949.   reinit_frame_cache ();
  1950.   do_cleanups (my_cleanups);
  1951. }


  1952. /* This function removes a symbol file that was added via add-symbol-file.  */

  1953. static void
  1954. remove_symbol_file_command (char *args, int from_tty)
  1955. {
  1956.   char **argv;
  1957.   struct objfile *objf = NULL;
  1958.   struct cleanup *my_cleanups;
  1959.   struct program_space *pspace = current_program_space;
  1960.   struct gdbarch *gdbarch = get_current_arch ();

  1961.   dont_repeat ();

  1962.   if (args == NULL)
  1963.     error (_("remove-symbol-file: no symbol file provided"));

  1964.   my_cleanups = make_cleanup (null_cleanup, NULL);

  1965.   argv = gdb_buildargv (args);

  1966.   if (strcmp (argv[0], "-a") == 0)
  1967.     {
  1968.       /* Interpret the next argument as an address.  */
  1969.       CORE_ADDR addr;

  1970.       if (argv[1] == NULL)
  1971.         error (_("Missing address argument"));

  1972.       if (argv[2] != NULL)
  1973.         error (_("Junk after %s"), argv[1]);

  1974.       addr = parse_and_eval_address (argv[1]);

  1975.       ALL_OBJFILES (objf)
  1976.         {
  1977.           if ((objf->flags & OBJF_USERLOADED) != 0
  1978.               && (objf->flags & OBJF_SHARED) != 0
  1979.               && objf->pspace == pspace && is_addr_in_objfile (addr, objf))
  1980.             break;
  1981.         }
  1982.     }
  1983.   else if (argv[0] != NULL)
  1984.     {
  1985.       /* Interpret the current argument as a file name.  */
  1986.       char *filename;

  1987.       if (argv[1] != NULL)
  1988.         error (_("Junk after %s"), argv[0]);

  1989.       filename = tilde_expand (argv[0]);
  1990.       make_cleanup (xfree, filename);

  1991.       ALL_OBJFILES (objf)
  1992.         {
  1993.           if ((objf->flags & OBJF_USERLOADED) != 0
  1994.               && (objf->flags & OBJF_SHARED) != 0
  1995.               && objf->pspace == pspace
  1996.               && filename_cmp (filename, objfile_name (objf)) == 0)
  1997.             break;
  1998.         }
  1999.     }

  2000.   if (objf == NULL)
  2001.     error (_("No symbol file found"));

  2002.   if (from_tty
  2003.       && !query (_("Remove symbol table from file \"%s\"? "),
  2004.                  objfile_name (objf)))
  2005.     error (_("Not confirmed."));

  2006.   free_objfile (objf);
  2007.   clear_symtab_users (0);

  2008.   do_cleanups (my_cleanups);
  2009. }

  2010. typedef struct objfile *objfilep;

  2011. DEF_VEC_P (objfilep);

  2012. /* Re-read symbols if a symbol-file has changed.  */

  2013. void
  2014. reread_symbols (void)
  2015. {
  2016.   struct objfile *objfile;
  2017.   long new_modtime;
  2018.   struct stat new_statbuf;
  2019.   int res;
  2020.   VEC (objfilep) *new_objfiles = NULL;
  2021.   struct cleanup *all_cleanups;

  2022.   all_cleanups = make_cleanup (VEC_cleanup (objfilep), &new_objfiles);

  2023.   /* With the addition of shared libraries, this should be modified,
  2024.      the load time should be saved in the partial symbol tables, since
  2025.      different tables may come from different source files.  FIXME.
  2026.      This routine should then walk down each partial symbol table
  2027.      and see if the symbol table that it originates from has been changed.  */

  2028.   for (objfile = object_files; objfile; objfile = objfile->next)
  2029.     {
  2030.       if (objfile->obfd == NULL)
  2031.         continue;

  2032.       /* Separate debug objfiles are handled in the main objfile.  */
  2033.       if (objfile->separate_debug_objfile_backlink)
  2034.         continue;

  2035.       /* If this object is from an archive (what you usually create with
  2036.          `ar', often called a `static library' on most systems, though
  2037.          a `shared library' on AIX is also an archive), then you should
  2038.          stat on the archive name, not member name.  */
  2039.       if (objfile->obfd->my_archive)
  2040.         res = stat (objfile->obfd->my_archive->filename, &new_statbuf);
  2041.       else
  2042.         res = stat (objfile_name (objfile), &new_statbuf);
  2043.       if (res != 0)
  2044.         {
  2045.           /* FIXME, should use print_sys_errmsg but it's not filtered.  */
  2046.           printf_unfiltered (_("`%s' has disappeared; keeping its symbols.\n"),
  2047.                              objfile_name (objfile));
  2048.           continue;
  2049.         }
  2050.       new_modtime = new_statbuf.st_mtime;
  2051.       if (new_modtime != objfile->mtime)
  2052.         {
  2053.           struct cleanup *old_cleanups;
  2054.           struct section_offsets *offsets;
  2055.           int num_offsets;
  2056.           char *original_name;

  2057.           printf_unfiltered (_("`%s' has changed; re-reading symbols.\n"),
  2058.                              objfile_name (objfile));

  2059.           /* There are various functions like symbol_file_add,
  2060.              symfile_bfd_open, syms_from_objfile, etc., which might
  2061.              appear to do what we want.  But they have various other
  2062.              effects which we *don't* want.  So we just do stuff
  2063.              ourselves.  We don't worry about mapped files (for one thing,
  2064.              any mapped file will be out of date).  */

  2065.           /* If we get an error, blow away this objfile (not sure if
  2066.              that is the correct response for things like shared
  2067.              libraries).  */
  2068.           old_cleanups = make_cleanup_free_objfile (objfile);
  2069.           /* We need to do this whenever any symbols go away.  */
  2070.           make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/);

  2071.           if (exec_bfd != NULL
  2072.               && filename_cmp (bfd_get_filename (objfile->obfd),
  2073.                                bfd_get_filename (exec_bfd)) == 0)
  2074.             {
  2075.               /* Reload EXEC_BFD without asking anything.  */

  2076.               exec_file_attach (bfd_get_filename (objfile->obfd), 0);
  2077.             }

  2078.           /* Keep the calls order approx. the same as in free_objfile.  */

  2079.           /* Free the separate debug objfiles.  It will be
  2080.              automatically recreated by sym_read.  */
  2081.           free_objfile_separate_debug (objfile);

  2082.           /* Remove any references to this objfile in the global
  2083.              value lists.  */
  2084.           preserve_values (objfile);

  2085.           /* Nuke all the state that we will re-read.  Much of the following
  2086.              code which sets things to NULL really is necessary to tell
  2087.              other parts of GDB that there is nothing currently there.

  2088.              Try to keep the freeing order compatible with free_objfile.  */

  2089.           if (objfile->sf != NULL)
  2090.             {
  2091.               (*objfile->sf->sym_finish) (objfile);
  2092.             }

  2093.           clear_objfile_data (objfile);

  2094.           /* Clean up any state BFD has sitting around.  */
  2095.           {
  2096.             struct bfd *obfd = objfile->obfd;
  2097.             char *obfd_filename;

  2098.             obfd_filename = bfd_get_filename (objfile->obfd);
  2099.             /* Open the new BFD before freeing the old one, so that
  2100.                the filename remains live.  */
  2101.             objfile->obfd = gdb_bfd_open_maybe_remote (obfd_filename);
  2102.             if (objfile->obfd == NULL)
  2103.               {
  2104.                 /* We have to make a cleanup and error here, rather
  2105.                    than erroring later, because once we unref OBFD,
  2106.                    OBFD_FILENAME will be freed.  */
  2107.                 make_cleanup_bfd_unref (obfd);
  2108.                 error (_("Can't open %s to read symbols."), obfd_filename);
  2109.               }
  2110.             gdb_bfd_unref (obfd);
  2111.           }

  2112.           original_name = xstrdup (objfile->original_name);
  2113.           make_cleanup (xfree, original_name);

  2114.           /* bfd_openr sets cacheable to true, which is what we want.  */
  2115.           if (!bfd_check_format (objfile->obfd, bfd_object))
  2116.             error (_("Can't read symbols from %s: %s."), objfile_name (objfile),
  2117.                    bfd_errmsg (bfd_get_error ()));

  2118.           /* Save the offsets, we will nuke them with the rest of the
  2119.              objfile_obstack.  */
  2120.           num_offsets = objfile->num_sections;
  2121.           offsets = ((struct section_offsets *)
  2122.                      alloca (SIZEOF_N_SECTION_OFFSETS (num_offsets)));
  2123.           memcpy (offsets, objfile->section_offsets,
  2124.                   SIZEOF_N_SECTION_OFFSETS (num_offsets));

  2125.           /* FIXME: Do we have to free a whole linked list, or is this
  2126.              enough?  */
  2127.           if (objfile->global_psymbols.list)
  2128.             xfree (objfile->global_psymbols.list);
  2129.           memset (&objfile->global_psymbols, 0,
  2130.                   sizeof (objfile->global_psymbols));
  2131.           if (objfile->static_psymbols.list)
  2132.             xfree (objfile->static_psymbols.list);
  2133.           memset (&objfile->static_psymbols, 0,
  2134.                   sizeof (objfile->static_psymbols));

  2135.           /* Free the obstacks for non-reusable objfiles.  */
  2136.           psymbol_bcache_free (objfile->psymbol_cache);
  2137.           objfile->psymbol_cache = psymbol_bcache_init ();
  2138.           obstack_free (&objfile->objfile_obstack, 0);
  2139.           objfile->sections = NULL;
  2140.           objfile->compunit_symtabs = NULL;
  2141.           objfile->psymtabs = NULL;
  2142.           objfile->psymtabs_addrmap = NULL;
  2143.           objfile->free_psymtabs = NULL;
  2144.           objfile->template_symbols = NULL;

  2145.           /* obstack_init also initializes the obstack so it is
  2146.              empty.  We could use obstack_specify_allocation but
  2147.              gdb_obstack.h specifies the alloc/dealloc functions.  */
  2148.           obstack_init (&objfile->objfile_obstack);

  2149.           /* set_objfile_per_bfd potentially allocates the per-bfd
  2150.              data on the objfile's obstack (if sharing data across
  2151.              multiple users is not possible), so it's important to
  2152.              do it *after* the obstack has been initialized.  */
  2153.           set_objfile_per_bfd (objfile);

  2154.           objfile->original_name = obstack_copy0 (&objfile->objfile_obstack,
  2155.                                                   original_name,
  2156.                                                   strlen (original_name));

  2157.           /* Reset the sym_fns pointer.  The ELF reader can change it
  2158.              based on whether .gdb_index is present, and we need it to
  2159.              start over.  PR symtab/15885  */
  2160.           objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd));

  2161.           build_objfile_section_table (objfile);
  2162.           terminate_minimal_symbol_table (objfile);

  2163.           /* We use the same section offsets as from last time.  I'm not
  2164.              sure whether that is always correct for shared libraries.  */
  2165.           objfile->section_offsets = (struct section_offsets *)
  2166.             obstack_alloc (&objfile->objfile_obstack,
  2167.                            SIZEOF_N_SECTION_OFFSETS (num_offsets));
  2168.           memcpy (objfile->section_offsets, offsets,
  2169.                   SIZEOF_N_SECTION_OFFSETS (num_offsets));
  2170.           objfile->num_sections = num_offsets;

  2171.           /* What the hell is sym_new_init for, anyway?  The concept of
  2172.              distinguishing between the main file and additional files
  2173.              in this way seems rather dubious.  */
  2174.           if (objfile == symfile_objfile)
  2175.             {
  2176.               (*objfile->sf->sym_new_init) (objfile);
  2177.             }

  2178.           (*objfile->sf->sym_init) (objfile);
  2179.           clear_complaints (&symfile_complaints, 1, 1);

  2180.           objfile->flags &= ~OBJF_PSYMTABS_READ;
  2181.           read_symbols (objfile, 0);

  2182.           if (!objfile_has_symbols (objfile))
  2183.             {
  2184.               wrap_here ("");
  2185.               printf_unfiltered (_("(no debugging symbols found)\n"));
  2186.               wrap_here ("");
  2187.             }

  2188.           /* We're done reading the symbol file; finish off complaints.  */
  2189.           clear_complaints (&symfile_complaints, 0, 1);

  2190.           /* Getting new symbols may change our opinion about what is
  2191.              frameless.  */

  2192.           reinit_frame_cache ();

  2193.           /* Discard cleanups as symbol reading was successful.  */
  2194.           discard_cleanups (old_cleanups);

  2195.           /* If the mtime has changed between the time we set new_modtime
  2196.              and now, we *want* this to be out of date, so don't call stat
  2197.              again now.  */
  2198.           objfile->mtime = new_modtime;
  2199.           init_entry_point_info (objfile);

  2200.           VEC_safe_push (objfilep, new_objfiles, objfile);
  2201.         }
  2202.     }

  2203.   if (new_objfiles)
  2204.     {
  2205.       int ix;

  2206.       /* Notify objfiles that we've modified objfile sections.  */
  2207.       objfiles_changed ();

  2208.       clear_symtab_users (0);

  2209.       /* clear_objfile_data for each objfile was called before freeing it and
  2210.          observer_notify_new_objfile (NULL) has been called by
  2211.          clear_symtab_users above.  Notify the new files now.  */
  2212.       for (ix = 0; VEC_iterate (objfilep, new_objfiles, ix, objfile); ix++)
  2213.         observer_notify_new_objfile (objfile);

  2214.       /* At least one objfile has changed, so we can consider that
  2215.          the executable we're debugging has changed too.  */
  2216.       observer_notify_executable_changed ();
  2217.     }

  2218.   do_cleanups (all_cleanups);
  2219. }


  2220. typedef struct
  2221. {
  2222.   char *ext;
  2223.   enum language lang;
  2224. }
  2225. filename_language;

  2226. static filename_language *filename_language_table;
  2227. static int fl_table_size, fl_table_next;

  2228. static void
  2229. add_filename_language (char *ext, enum language lang)
  2230. {
  2231.   if (fl_table_next >= fl_table_size)
  2232.     {
  2233.       fl_table_size += 10;
  2234.       filename_language_table =
  2235.         xrealloc (filename_language_table,
  2236.                   fl_table_size * sizeof (*filename_language_table));
  2237.     }

  2238.   filename_language_table[fl_table_next].ext = xstrdup (ext);
  2239.   filename_language_table[fl_table_next].lang = lang;
  2240.   fl_table_next++;
  2241. }

  2242. static char *ext_args;
  2243. static void
  2244. show_ext_args (struct ui_file *file, int from_tty,
  2245.                struct cmd_list_element *c, const char *value)
  2246. {
  2247.   fprintf_filtered (file,
  2248.                     _("Mapping between filename extension "
  2249.                       "and source language is \"%s\".\n"),
  2250.                     value);
  2251. }

  2252. static void
  2253. set_ext_lang_command (char *args, int from_tty, struct cmd_list_element *e)
  2254. {
  2255.   int i;
  2256.   char *cp = ext_args;
  2257.   enum language lang;

  2258.   /* First arg is filename extension, starting with '.'  */
  2259.   if (*cp != '.')
  2260.     error (_("'%s': Filename extension must begin with '.'"), ext_args);

  2261.   /* Find end of first arg.  */
  2262.   while (*cp && !isspace (*cp))
  2263.     cp++;

  2264.   if (*cp == '\0')
  2265.     error (_("'%s': two arguments required -- "
  2266.              "filename extension and language"),
  2267.            ext_args);

  2268.   /* Null-terminate first arg.  */
  2269.   *cp++ = '\0';

  2270.   /* Find beginning of second arg, which should be a source language.  */
  2271.   cp = skip_spaces (cp);

  2272.   if (*cp == '\0')
  2273.     error (_("'%s': two arguments required -- "
  2274.              "filename extension and language"),
  2275.            ext_args);

  2276.   /* Lookup the language from among those we know.  */
  2277.   lang = language_enum (cp);

  2278.   /* Now lookup the filename extension: do we already know it?  */
  2279.   for (i = 0; i < fl_table_next; i++)
  2280.     if (0 == strcmp (ext_args, filename_language_table[i].ext))
  2281.       break;

  2282.   if (i >= fl_table_next)
  2283.     {
  2284.       /* New file extension.  */
  2285.       add_filename_language (ext_args, lang);
  2286.     }
  2287.   else
  2288.     {
  2289.       /* Redefining a previously known filename extension.  */

  2290.       /* if (from_tty) */
  2291.       /*   query ("Really make files of type %s '%s'?", */
  2292.       /*          ext_args, language_str (lang));           */

  2293.       xfree (filename_language_table[i].ext);
  2294.       filename_language_table[i].ext = xstrdup (ext_args);
  2295.       filename_language_table[i].lang = lang;
  2296.     }
  2297. }

  2298. static void
  2299. info_ext_lang_command (char *args, int from_tty)
  2300. {
  2301.   int i;

  2302.   printf_filtered (_("Filename extensions and the languages they represent:"));
  2303.   printf_filtered ("\n\n");
  2304.   for (i = 0; i < fl_table_next; i++)
  2305.     printf_filtered ("\t%s\t- %s\n",
  2306.                      filename_language_table[i].ext,
  2307.                      language_str (filename_language_table[i].lang));
  2308. }

  2309. static void
  2310. init_filename_language_table (void)
  2311. {
  2312.   if (fl_table_size == 0)        /* Protect against repetition.  */
  2313.     {
  2314.       fl_table_size = 20;
  2315.       fl_table_next = 0;
  2316.       filename_language_table =
  2317.         xmalloc (fl_table_size * sizeof (*filename_language_table));
  2318.       add_filename_language (".c", language_c);
  2319.       add_filename_language (".d", language_d);
  2320.       add_filename_language (".C", language_cplus);
  2321.       add_filename_language (".cc", language_cplus);
  2322.       add_filename_language (".cp", language_cplus);
  2323.       add_filename_language (".cpp", language_cplus);
  2324.       add_filename_language (".cxx", language_cplus);
  2325.       add_filename_language (".c++", language_cplus);
  2326.       add_filename_language (".java", language_java);
  2327.       add_filename_language (".class", language_java);
  2328.       add_filename_language (".m", language_objc);
  2329.       add_filename_language (".f", language_fortran);
  2330.       add_filename_language (".F", language_fortran);
  2331.       add_filename_language (".for", language_fortran);
  2332.       add_filename_language (".FOR", language_fortran);
  2333.       add_filename_language (".ftn", language_fortran);
  2334.       add_filename_language (".FTN", language_fortran);
  2335.       add_filename_language (".fpp", language_fortran);
  2336.       add_filename_language (".FPP", language_fortran);
  2337.       add_filename_language (".f90", language_fortran);
  2338.       add_filename_language (".F90", language_fortran);
  2339.       add_filename_language (".f95", language_fortran);
  2340.       add_filename_language (".F95", language_fortran);
  2341.       add_filename_language (".f03", language_fortran);
  2342.       add_filename_language (".F03", language_fortran);
  2343.       add_filename_language (".f08", language_fortran);
  2344.       add_filename_language (".F08", language_fortran);
  2345.       add_filename_language (".s", language_asm);
  2346.       add_filename_language (".sx", language_asm);
  2347.       add_filename_language (".S", language_asm);
  2348.       add_filename_language (".pas", language_pascal);
  2349.       add_filename_language (".p", language_pascal);
  2350.       add_filename_language (".pp", language_pascal);
  2351.       add_filename_language (".adb", language_ada);
  2352.       add_filename_language (".ads", language_ada);
  2353.       add_filename_language (".a", language_ada);
  2354.       add_filename_language (".ada", language_ada);
  2355.       add_filename_language (".dg", language_ada);
  2356.     }
  2357. }

  2358. enum language
  2359. deduce_language_from_filename (const char *filename)
  2360. {
  2361.   int i;
  2362.   char *cp;

  2363.   if (filename != NULL)
  2364.     if ((cp = strrchr (filename, '.')) != NULL)
  2365.       for (i = 0; i < fl_table_next; i++)
  2366.         if (strcmp (cp, filename_language_table[i].ext) == 0)
  2367.           return filename_language_table[i].lang;

  2368.   return language_unknown;
  2369. }

  2370. /* Allocate and initialize a new symbol table.
  2371.    CUST is from the result of allocate_compunit_symtab.  */

  2372. struct symtab *
  2373. allocate_symtab (struct compunit_symtab *cust, const char *filename)
  2374. {
  2375.   struct objfile *objfile = cust->objfile;
  2376.   struct symtab *symtab
  2377.     = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symtab);

  2378.   symtab->filename = bcache (filename, strlen (filename) + 1,
  2379.                              objfile->per_bfd->filename_cache);
  2380.   symtab->fullname = NULL;
  2381.   symtab->language = deduce_language_from_filename (filename);

  2382.   /* This can be very verbose with lots of headers.
  2383.      Only print at higher debug levels.  */
  2384.   if (symtab_create_debug >= 2)
  2385.     {
  2386.       /* Be a bit clever with debugging messages, and don't print objfile
  2387.          every time, only when it changes.  */
  2388.       static char *last_objfile_name = NULL;

  2389.       if (last_objfile_name == NULL
  2390.           || strcmp (last_objfile_name, objfile_name (objfile)) != 0)
  2391.         {
  2392.           xfree (last_objfile_name);
  2393.           last_objfile_name = xstrdup (objfile_name (objfile));
  2394.           fprintf_unfiltered (gdb_stdlog,
  2395.                               "Creating one or more symtabs for objfile %s ...\n",
  2396.                               last_objfile_name);
  2397.         }
  2398.       fprintf_unfiltered (gdb_stdlog,
  2399.                           "Created symtab %s for module %s.\n",
  2400.                           host_address_to_string (symtab), filename);
  2401.     }

  2402.   /* Add it to CUST's list of symtabs.  */
  2403.   if (cust->filetabs == NULL)
  2404.     {
  2405.       cust->filetabs = symtab;
  2406.       cust->last_filetab = symtab;
  2407.     }
  2408.   else
  2409.     {
  2410.       cust->last_filetab->next = symtab;
  2411.       cust->last_filetab = symtab;
  2412.     }

  2413.   /* Backlink to the containing compunit symtab.  */
  2414.   symtab->compunit_symtab = cust;

  2415.   return symtab;
  2416. }

  2417. /* Allocate and initialize a new compunit.
  2418.    NAME is the name of the main source file, if there is one, or some
  2419.    descriptive text if there are no source files.  */

  2420. struct compunit_symtab *
  2421. allocate_compunit_symtab (struct objfile *objfile, const char *name)
  2422. {
  2423.   struct compunit_symtab *cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
  2424.                                                struct compunit_symtab);
  2425.   const char *saved_name;

  2426.   cu->objfile = objfile;

  2427.   /* The name we record here is only for display/debugging purposes.
  2428.      Just save the basename to avoid path issues (too long for display,
  2429.      relative vs absolute, etc.).  */
  2430.   saved_name = lbasename (name);
  2431.   cu->name = obstack_copy0 (&objfile->objfile_obstack, saved_name,
  2432.                             strlen (saved_name));

  2433.   COMPUNIT_DEBUGFORMAT (cu) = "unknown";

  2434.   if (symtab_create_debug)
  2435.     {
  2436.       fprintf_unfiltered (gdb_stdlog,
  2437.                           "Created compunit symtab %s for %s.\n",
  2438.                           host_address_to_string (cu),
  2439.                           cu->name);
  2440.     }

  2441.   return cu;
  2442. }

  2443. /* Hook CU to the objfile it comes from.  */

  2444. void
  2445. add_compunit_symtab_to_objfile (struct compunit_symtab *cu)
  2446. {
  2447.   cu->next = cu->objfile->compunit_symtabs;
  2448.   cu->objfile->compunit_symtabs = cu;
  2449. }


  2450. /* Reset all data structures in gdb which may contain references to symbol
  2451.    table data.  ADD_FLAGS is a bitmask of enum symfile_add_flags.  */

  2452. void
  2453. clear_symtab_users (int add_flags)
  2454. {
  2455.   /* Someday, we should do better than this, by only blowing away
  2456.      the things that really need to be blown.  */

  2457.   /* Clear the "current" symtab first, because it is no longer valid.
  2458.      breakpoint_re_set may try to access the current symtab.  */
  2459.   clear_current_source_symtab_and_line ();

  2460.   clear_displays ();
  2461.   if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
  2462.     breakpoint_re_set ();
  2463.   clear_last_displayed_sal ();
  2464.   clear_pc_function_cache ();
  2465.   observer_notify_new_objfile (NULL);

  2466.   /* Clear globals which might have pointed into a removed objfile.
  2467.      FIXME: It's not clear which of these are supposed to persist
  2468.      between expressions and which ought to be reset each time.  */
  2469.   expression_context_block = NULL;
  2470.   innermost_block = NULL;

  2471.   /* Varobj may refer to old symbols, perform a cleanup.  */
  2472.   varobj_invalidate ();

  2473. }

  2474. static void
  2475. clear_symtab_users_cleanup (void *ignore)
  2476. {
  2477.   clear_symtab_users (0);
  2478. }

  2479. /* OVERLAYS:
  2480.    The following code implements an abstraction for debugging overlay sections.

  2481.    The target model is as follows:
  2482.    1) The gnu linker will permit multiple sections to be mapped into the
  2483.    same VMA, each with its own unique LMA (or load address).
  2484.    2) It is assumed that some runtime mechanism exists for mapping the
  2485.    sections, one by one, from the load address into the VMA address.
  2486.    3) This code provides a mechanism for gdb to keep track of which
  2487.    sections should be considered to be mapped from the VMA to the LMA.
  2488.    This information is used for symbol lookup, and memory read/write.
  2489.    For instance, if a section has been mapped then its contents
  2490.    should be read from the VMA, otherwise from the LMA.

  2491.    Two levels of debugger support for overlays are available.  One is
  2492.    "manual", in which the debugger relies on the user to tell it which
  2493.    overlays are currently mapped.  This level of support is
  2494.    implemented entirely in the core debugger, and the information about
  2495.    whether a section is mapped is kept in the objfile->obj_section table.

  2496.    The second level of support is "automatic", and is only available if
  2497.    the target-specific code provides functionality to read the target's
  2498.    overlay mapping table, and translate its contents for the debugger
  2499.    (by updating the mapped state information in the obj_section tables).

  2500.    The interface is as follows:
  2501.    User commands:
  2502.    overlay map <name>   -- tell gdb to consider this section mapped
  2503.    overlay unmap <name> -- tell gdb to consider this section unmapped
  2504.    overlay list         -- list the sections that GDB thinks are mapped
  2505.    overlay read-target  -- get the target's state of what's mapped
  2506.    overlay off/manual/auto -- set overlay debugging state
  2507.    Functional interface:
  2508.    find_pc_mapped_section(pc):    if the pc is in the range of a mapped
  2509.    section, return that section.
  2510.    find_pc_overlay(pc):       find any overlay section that contains
  2511.    the pc, either in its VMA or its LMA
  2512.    section_is_mapped(sect):       true if overlay is marked as mapped
  2513.    section_is_overlay(sect):      true if section's VMA != LMA
  2514.    pc_in_mapped_range(pc,sec):    true if pc belongs to section's VMA
  2515.    pc_in_unmapped_range(...):     true if pc belongs to section's LMA
  2516.    sections_overlap(sec1, sec2):  true if mapped sec1 and sec2 ranges overlap
  2517.    overlay_mapped_address(...):   map an address from section's LMA to VMA
  2518.    overlay_unmapped_address(...): map an address from section's VMA to LMA
  2519.    symbol_overlayed_address(...): Return a "current" address for symbol:
  2520.    either in VMA or LMA depending on whether
  2521.    the symbol's section is currently mapped.  */

  2522. /* Overlay debugging state: */

  2523. enum overlay_debugging_state overlay_debugging = ovly_off;
  2524. int overlay_cache_invalid = 0;        /* True if need to refresh mapped state.  */

  2525. /* Function: section_is_overlay (SECTION)
  2526.    Returns true if SECTION has VMA not equal to LMA, ie.
  2527.    SECTION is loaded at an address different from where it will "run".  */

  2528. int
  2529. section_is_overlay (struct obj_section *section)
  2530. {
  2531.   if (overlay_debugging && section)
  2532.     {
  2533.       bfd *abfd = section->objfile->obfd;
  2534.       asection *bfd_section = section->the_bfd_section;

  2535.       if (bfd_section_lma (abfd, bfd_section) != 0
  2536.           && bfd_section_lma (abfd, bfd_section)
  2537.              != bfd_section_vma (abfd, bfd_section))
  2538.         return 1;
  2539.     }

  2540.   return 0;
  2541. }

  2542. /* Function: overlay_invalidate_all (void)
  2543.    Invalidate the mapped state of all overlay sections (mark it as stale).  */

  2544. static void
  2545. overlay_invalidate_all (void)
  2546. {
  2547.   struct objfile *objfile;
  2548.   struct obj_section *sect;

  2549.   ALL_OBJSECTIONS (objfile, sect)
  2550.     if (section_is_overlay (sect))
  2551.       sect->ovly_mapped = -1;
  2552. }

  2553. /* Function: section_is_mapped (SECTION)
  2554.    Returns true if section is an overlay, and is currently mapped.

  2555.    Access to the ovly_mapped flag is restricted to this function, so
  2556.    that we can do automatic update.  If the global flag
  2557.    OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call
  2558.    overlay_invalidate_all.  If the mapped state of the particular
  2559.    section is stale, then call TARGET_OVERLAY_UPDATE to refresh it.  */

  2560. int
  2561. section_is_mapped (struct obj_section *osect)
  2562. {
  2563.   struct gdbarch *gdbarch;

  2564.   if (osect == 0 || !section_is_overlay (osect))
  2565.     return 0;

  2566.   switch (overlay_debugging)
  2567.     {
  2568.     default:
  2569.     case ovly_off:
  2570.       return 0;                        /* overlay debugging off */
  2571.     case ovly_auto:                /* overlay debugging automatic */
  2572.       /* Unles there is a gdbarch_overlay_update function,
  2573.          there's really nothing useful to do here (can't really go auto).  */
  2574.       gdbarch = get_objfile_arch (osect->objfile);
  2575.       if (gdbarch_overlay_update_p (gdbarch))
  2576.         {
  2577.           if (overlay_cache_invalid)
  2578.             {
  2579.               overlay_invalidate_all ();
  2580.               overlay_cache_invalid = 0;
  2581.             }
  2582.           if (osect->ovly_mapped == -1)
  2583.             gdbarch_overlay_update (gdbarch, osect);
  2584.         }
  2585.       /* fall thru to manual case */
  2586.     case ovly_on:                /* overlay debugging manual */
  2587.       return osect->ovly_mapped == 1;
  2588.     }
  2589. }

  2590. /* Function: pc_in_unmapped_range
  2591.    If PC falls into the lma range of SECTION, return true, else false.  */

  2592. CORE_ADDR
  2593. pc_in_unmapped_range (CORE_ADDR pc, struct obj_section *section)
  2594. {
  2595.   if (section_is_overlay (section))
  2596.     {
  2597.       bfd *abfd = section->objfile->obfd;
  2598.       asection *bfd_section = section->the_bfd_section;

  2599.       /* We assume the LMA is relocated by the same offset as the VMA.  */
  2600.       bfd_vma size = bfd_get_section_size (bfd_section);
  2601.       CORE_ADDR offset = obj_section_offset (section);

  2602.       if (bfd_get_section_lma (abfd, bfd_section) + offset <= pc
  2603.           && pc < bfd_get_section_lma (abfd, bfd_section) + offset + size)
  2604.         return 1;
  2605.     }

  2606.   return 0;
  2607. }

  2608. /* Function: pc_in_mapped_range
  2609.    If PC falls into the vma range of SECTION, return true, else false.  */

  2610. CORE_ADDR
  2611. pc_in_mapped_range (CORE_ADDR pc, struct obj_section *section)
  2612. {
  2613.   if (section_is_overlay (section))
  2614.     {
  2615.       if (obj_section_addr (section) <= pc
  2616.           && pc < obj_section_endaddr (section))
  2617.         return 1;
  2618.     }

  2619.   return 0;
  2620. }

  2621. /* Return true if the mapped ranges of sections A and B overlap, false
  2622.    otherwise.  */

  2623. static int
  2624. sections_overlap (struct obj_section *a, struct obj_section *b)
  2625. {
  2626.   CORE_ADDR a_start = obj_section_addr (a);
  2627.   CORE_ADDR a_end = obj_section_endaddr (a);
  2628.   CORE_ADDR b_start = obj_section_addr (b);
  2629.   CORE_ADDR b_end = obj_section_endaddr (b);

  2630.   return (a_start < b_end && b_start < a_end);
  2631. }

  2632. /* Function: overlay_unmapped_address (PC, SECTION)
  2633.    Returns the address corresponding to PC in the unmapped (load) range.
  2634.    May be the same as PC.  */

  2635. CORE_ADDR
  2636. overlay_unmapped_address (CORE_ADDR pc, struct obj_section *section)
  2637. {
  2638.   if (section_is_overlay (section) && pc_in_mapped_range (pc, section))
  2639.     {
  2640.       bfd *abfd = section->objfile->obfd;
  2641.       asection *bfd_section = section->the_bfd_section;

  2642.       return pc + bfd_section_lma (abfd, bfd_section)
  2643.                 - bfd_section_vma (abfd, bfd_section);
  2644.     }

  2645.   return pc;
  2646. }

  2647. /* Function: overlay_mapped_address (PC, SECTION)
  2648.    Returns the address corresponding to PC in the mapped (runtime) range.
  2649.    May be the same as PC.  */

  2650. CORE_ADDR
  2651. overlay_mapped_address (CORE_ADDR pc, struct obj_section *section)
  2652. {
  2653.   if (section_is_overlay (section) && pc_in_unmapped_range (pc, section))
  2654.     {
  2655.       bfd *abfd = section->objfile->obfd;
  2656.       asection *bfd_section = section->the_bfd_section;

  2657.       return pc + bfd_section_vma (abfd, bfd_section)
  2658.                 - bfd_section_lma (abfd, bfd_section);
  2659.     }

  2660.   return pc;
  2661. }

  2662. /* Function: symbol_overlayed_address
  2663.    Return one of two addresses (relative to the VMA or to the LMA),
  2664.    depending on whether the section is mapped or not.  */

  2665. CORE_ADDR
  2666. symbol_overlayed_address (CORE_ADDR address, struct obj_section *section)
  2667. {
  2668.   if (overlay_debugging)
  2669.     {
  2670.       /* If the symbol has no section, just return its regular address.  */
  2671.       if (section == 0)
  2672.         return address;
  2673.       /* If the symbol's section is not an overlay, just return its
  2674.          address.  */
  2675.       if (!section_is_overlay (section))
  2676.         return address;
  2677.       /* If the symbol's section is mapped, just return its address.  */
  2678.       if (section_is_mapped (section))
  2679.         return address;
  2680.       /*
  2681.        * HOWEVER: if the symbol is in an overlay section which is NOT mapped,
  2682.        * then return its LOADED address rather than its vma address!!
  2683.        */
  2684.       return overlay_unmapped_address (address, section);
  2685.     }
  2686.   return address;
  2687. }

  2688. /* Function: find_pc_overlay (PC)
  2689.    Return the best-match overlay section for PC:
  2690.    If PC matches a mapped overlay section's VMA, return that section.
  2691.    Else if PC matches an unmapped section's VMA, return that section.
  2692.    Else if PC matches an unmapped section's LMA, return that section.  */

  2693. struct obj_section *
  2694. find_pc_overlay (CORE_ADDR pc)
  2695. {
  2696.   struct objfile *objfile;
  2697.   struct obj_section *osect, *best_match = NULL;

  2698.   if (overlay_debugging)
  2699.     ALL_OBJSECTIONS (objfile, osect)
  2700.       if (section_is_overlay (osect))
  2701.       {
  2702.         if (pc_in_mapped_range (pc, osect))
  2703.           {
  2704.             if (section_is_mapped (osect))
  2705.               return osect;
  2706.             else
  2707.               best_match = osect;
  2708.           }
  2709.         else if (pc_in_unmapped_range (pc, osect))
  2710.           best_match = osect;
  2711.       }
  2712.   return best_match;
  2713. }

  2714. /* Function: find_pc_mapped_section (PC)
  2715.    If PC falls into the VMA address range of an overlay section that is
  2716.    currently marked as MAPPED, return that section.  Else return NULL.  */

  2717. struct obj_section *
  2718. find_pc_mapped_section (CORE_ADDR pc)
  2719. {
  2720.   struct objfile *objfile;
  2721.   struct obj_section *osect;

  2722.   if (overlay_debugging)
  2723.     ALL_OBJSECTIONS (objfile, osect)
  2724.       if (pc_in_mapped_range (pc, osect) && section_is_mapped (osect))
  2725.         return osect;

  2726.   return NULL;
  2727. }

  2728. /* Function: list_overlays_command
  2729.    Print a list of mapped sections and their PC ranges.  */

  2730. static void
  2731. list_overlays_command (char *args, int from_tty)
  2732. {
  2733.   int nmapped = 0;
  2734.   struct objfile *objfile;
  2735.   struct obj_section *osect;

  2736.   if (overlay_debugging)
  2737.     ALL_OBJSECTIONS (objfile, osect)
  2738.       if (section_is_mapped (osect))
  2739.       {
  2740.         struct gdbarch *gdbarch = get_objfile_arch (objfile);
  2741.         const char *name;
  2742.         bfd_vma lma, vma;
  2743.         int size;

  2744.         vma = bfd_section_vma (objfile->obfd, osect->the_bfd_section);
  2745.         lma = bfd_section_lma (objfile->obfd, osect->the_bfd_section);
  2746.         size = bfd_get_section_size (osect->the_bfd_section);
  2747.         name = bfd_section_name (objfile->obfd, osect->the_bfd_section);

  2748.         printf_filtered ("Section %s, loaded at ", name);
  2749.         fputs_filtered (paddress (gdbarch, lma), gdb_stdout);
  2750.         puts_filtered (" - ");
  2751.         fputs_filtered (paddress (gdbarch, lma + size), gdb_stdout);
  2752.         printf_filtered (", mapped at ");
  2753.         fputs_filtered (paddress (gdbarch, vma), gdb_stdout);
  2754.         puts_filtered (" - ");
  2755.         fputs_filtered (paddress (gdbarch, vma + size), gdb_stdout);
  2756.         puts_filtered ("\n");

  2757.         nmapped++;
  2758.       }
  2759.   if (nmapped == 0)
  2760.     printf_filtered (_("No sections are mapped.\n"));
  2761. }

  2762. /* Function: map_overlay_command
  2763.    Mark the named section as mapped (ie. residing at its VMA address).  */

  2764. static void
  2765. map_overlay_command (char *args, int from_tty)
  2766. {
  2767.   struct objfile *objfile, *objfile2;
  2768.   struct obj_section *sec, *sec2;

  2769.   if (!overlay_debugging)
  2770.     error (_("Overlay debugging not enabled.  Use "
  2771.              "either the 'overlay auto' or\n"
  2772.              "the 'overlay manual' command."));

  2773.   if (args == 0 || *args == 0)
  2774.     error (_("Argument required: name of an overlay section"));

  2775.   /* First, find a section matching the user supplied argument.  */
  2776.   ALL_OBJSECTIONS (objfile, sec)
  2777.     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
  2778.     {
  2779.       /* Now, check to see if the section is an overlay.  */
  2780.       if (!section_is_overlay (sec))
  2781.         continue;                /* not an overlay section */

  2782.       /* Mark the overlay as "mapped".  */
  2783.       sec->ovly_mapped = 1;

  2784.       /* Next, make a pass and unmap any sections that are
  2785.          overlapped by this new section: */
  2786.       ALL_OBJSECTIONS (objfile2, sec2)
  2787.         if (sec2->ovly_mapped && sec != sec2 && sections_overlap (sec, sec2))
  2788.         {
  2789.           if (info_verbose)
  2790.             printf_unfiltered (_("Note: section %s unmapped by overlap\n"),
  2791.                              bfd_section_name (objfile->obfd,
  2792.                                                sec2->the_bfd_section));
  2793.           sec2->ovly_mapped = 0;        /* sec2 overlaps sec: unmap sec2.  */
  2794.         }
  2795.       return;
  2796.     }
  2797.   error (_("No overlay section called %s"), args);
  2798. }

  2799. /* Function: unmap_overlay_command
  2800.    Mark the overlay section as unmapped
  2801.    (ie. resident in its LMA address range, rather than the VMA range).  */

  2802. static void
  2803. unmap_overlay_command (char *args, int from_tty)
  2804. {
  2805.   struct objfile *objfile;
  2806.   struct obj_section *sec;

  2807.   if (!overlay_debugging)
  2808.     error (_("Overlay debugging not enabled.  "
  2809.              "Use either the 'overlay auto' or\n"
  2810.              "the 'overlay manual' command."));

  2811.   if (args == 0 || *args == 0)
  2812.     error (_("Argument required: name of an overlay section"));

  2813.   /* First, find a section matching the user supplied argument.  */
  2814.   ALL_OBJSECTIONS (objfile, sec)
  2815.     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
  2816.     {
  2817.       if (!sec->ovly_mapped)
  2818.         error (_("Section %s is not mapped"), args);
  2819.       sec->ovly_mapped = 0;
  2820.       return;
  2821.     }
  2822.   error (_("No overlay section called %s"), args);
  2823. }

  2824. /* Function: overlay_auto_command
  2825.    A utility command to turn on overlay debugging.
  2826.    Possibly this should be done via a set/show command.  */

  2827. static void
  2828. overlay_auto_command (char *args, int from_tty)
  2829. {
  2830.   overlay_debugging = ovly_auto;
  2831.   enable_overlay_breakpoints ();
  2832.   if (info_verbose)
  2833.     printf_unfiltered (_("Automatic overlay debugging enabled."));
  2834. }

  2835. /* Function: overlay_manual_command
  2836.    A utility command to turn on overlay debugging.
  2837.    Possibly this should be done via a set/show command.  */

  2838. static void
  2839. overlay_manual_command (char *args, int from_tty)
  2840. {
  2841.   overlay_debugging = ovly_on;
  2842.   disable_overlay_breakpoints ();
  2843.   if (info_verbose)
  2844.     printf_unfiltered (_("Overlay debugging enabled."));
  2845. }

  2846. /* Function: overlay_off_command
  2847.    A utility command to turn on overlay debugging.
  2848.    Possibly this should be done via a set/show command.  */

  2849. static void
  2850. overlay_off_command (char *args, int from_tty)
  2851. {
  2852.   overlay_debugging = ovly_off;
  2853.   disable_overlay_breakpoints ();
  2854.   if (info_verbose)
  2855.     printf_unfiltered (_("Overlay debugging disabled."));
  2856. }

  2857. static void
  2858. overlay_load_command (char *args, int from_tty)
  2859. {
  2860.   struct gdbarch *gdbarch = get_current_arch ();

  2861.   if (gdbarch_overlay_update_p (gdbarch))
  2862.     gdbarch_overlay_update (gdbarch, NULL);
  2863.   else
  2864.     error (_("This target does not know how to read its overlay state."));
  2865. }

  2866. /* Function: overlay_command
  2867.    A place-holder for a mis-typed command.  */

  2868. /* Command list chain containing all defined "overlay" subcommands.  */
  2869. static struct cmd_list_element *overlaylist;

  2870. static void
  2871. overlay_command (char *args, int from_tty)
  2872. {
  2873.   printf_unfiltered
  2874.     ("\"overlay\" must be followed by the name of an overlay command.\n");
  2875.   help_list (overlaylist, "overlay ", all_commands, gdb_stdout);
  2876. }

  2877. /* Target Overlays for the "Simplest" overlay manager:

  2878.    This is GDB's default target overlay layer.  It works with the
  2879.    minimal overlay manager supplied as an example by Cygnus.  The
  2880.    entry point is via a function pointer "gdbarch_overlay_update",
  2881.    so targets that use a different runtime overlay manager can
  2882.    substitute their own overlay_update function and take over the
  2883.    function pointer.

  2884.    The overlay_update function pokes around in the target's data structures
  2885.    to see what overlays are mapped, and updates GDB's overlay mapping with
  2886.    this information.

  2887.    In this simple implementation, the target data structures are as follows:
  2888.    unsigned _novlys;            /# number of overlay sections #/
  2889.    unsigned _ovly_table[_novlys][4] = {
  2890.    {VMA, SIZE, LMA, MAPPED},    /# one entry per overlay section #/
  2891.    {..., ...,  ..., ...},
  2892.    }
  2893.    unsigned _novly_regions;     /# number of overlay regions #/
  2894.    unsigned _ovly_region_table[_novly_regions][3] = {
  2895.    {VMA, SIZE, MAPPED_TO_LMA},  /# one entry per overlay region #/
  2896.    {..., ...,  ...},
  2897.    }
  2898.    These functions will attempt to update GDB's mappedness state in the
  2899.    symbol section table, based on the target's mappedness state.

  2900.    To do this, we keep a cached copy of the target's _ovly_table, and
  2901.    attempt to detect when the cached copy is invalidated.  The main
  2902.    entry point is "simple_overlay_update(SECT), which looks up SECT in
  2903.    the cached table and re-reads only the entry for that section from
  2904.    the target (whenever possible).  */

  2905. /* Cached, dynamically allocated copies of the target data structures: */
  2906. static unsigned (*cache_ovly_table)[4] = 0;
  2907. static unsigned cache_novlys = 0;
  2908. static CORE_ADDR cache_ovly_table_base = 0;
  2909. enum ovly_index
  2910.   {
  2911.     VMA, SIZE, LMA, MAPPED
  2912.   };

  2913. /* Throw away the cached copy of _ovly_table.  */

  2914. static void
  2915. simple_free_overlay_table (void)
  2916. {
  2917.   if (cache_ovly_table)
  2918.     xfree (cache_ovly_table);
  2919.   cache_novlys = 0;
  2920.   cache_ovly_table = NULL;
  2921.   cache_ovly_table_base = 0;
  2922. }

  2923. /* Read an array of ints of size SIZE from the target into a local buffer.
  2924.    Convert to host order.  int LEN is number of ints.  */

  2925. static void
  2926. read_target_long_array (CORE_ADDR memaddr, unsigned int *myaddr,
  2927.                         int len, int size, enum bfd_endian byte_order)
  2928. {
  2929.   /* FIXME (alloca): Not safe if array is very large.  */
  2930.   gdb_byte *buf = alloca (len * size);
  2931.   int i;

  2932.   read_memory (memaddr, buf, len * size);
  2933.   for (i = 0; i < len; i++)
  2934.     myaddr[i] = extract_unsigned_integer (size * i + buf, size, byte_order);
  2935. }

  2936. /* Find and grab a copy of the target _ovly_table
  2937.    (and _novlys, which is needed for the table's size).  */

  2938. static int
  2939. simple_read_overlay_table (void)
  2940. {
  2941.   struct bound_minimal_symbol novlys_msym;
  2942.   struct bound_minimal_symbol ovly_table_msym;
  2943.   struct gdbarch *gdbarch;
  2944.   int word_size;
  2945.   enum bfd_endian byte_order;

  2946.   simple_free_overlay_table ();
  2947.   novlys_msym = lookup_minimal_symbol ("_novlys", NULL, NULL);
  2948.   if (! novlys_msym.minsym)
  2949.     {
  2950.       error (_("Error reading inferior's overlay table: "
  2951.              "couldn't find `_novlys' variable\n"
  2952.              "in inferior.  Use `overlay manual' mode."));
  2953.       return 0;
  2954.     }

  2955.   ovly_table_msym = lookup_bound_minimal_symbol ("_ovly_table");
  2956.   if (! ovly_table_msym.minsym)
  2957.     {
  2958.       error (_("Error reading inferior's overlay table: couldn't find "
  2959.              "`_ovly_table' array\n"
  2960.              "in inferior.  Use `overlay manual' mode."));
  2961.       return 0;
  2962.     }

  2963.   gdbarch = get_objfile_arch (ovly_table_msym.objfile);
  2964.   word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
  2965.   byte_order = gdbarch_byte_order (gdbarch);

  2966.   cache_novlys = read_memory_integer (BMSYMBOL_VALUE_ADDRESS (novlys_msym),
  2967.                                       4, byte_order);
  2968.   cache_ovly_table
  2969.     = (void *) xmalloc (cache_novlys * sizeof (*cache_ovly_table));
  2970.   cache_ovly_table_base = BMSYMBOL_VALUE_ADDRESS (ovly_table_msym);
  2971.   read_target_long_array (cache_ovly_table_base,
  2972.                           (unsigned int *) cache_ovly_table,
  2973.                           cache_novlys * 4, word_size, byte_order);

  2974.   return 1;                        /* SUCCESS */
  2975. }

  2976. /* Function: simple_overlay_update_1
  2977.    A helper function for simple_overlay_update.  Assuming a cached copy
  2978.    of _ovly_table exists, look through it to find an entry whose vma,
  2979.    lma and size match those of OSECT.  Re-read the entry and make sure
  2980.    it still matches OSECT (else the table may no longer be valid).
  2981.    Set OSECT's mapped state to match the entry.  Return: 1 for
  2982.    success, 0 for failure.  */

  2983. static int
  2984. simple_overlay_update_1 (struct obj_section *osect)
  2985. {
  2986.   int i, size;
  2987.   bfd *obfd = osect->objfile->obfd;
  2988.   asection *bsect = osect->the_bfd_section;
  2989.   struct gdbarch *gdbarch = get_objfile_arch (osect->objfile);
  2990.   int word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
  2991.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);

  2992.   size = bfd_get_section_size (osect->the_bfd_section);
  2993.   for (i = 0; i < cache_novlys; i++)
  2994.     if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
  2995.         && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect)
  2996.         /* && cache_ovly_table[i][SIZE] == size */ )
  2997.       {
  2998.         read_target_long_array (cache_ovly_table_base + i * word_size,
  2999.                                 (unsigned int *) cache_ovly_table[i],
  3000.                                 4, word_size, byte_order);
  3001.         if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
  3002.             && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect)
  3003.             /* && cache_ovly_table[i][SIZE] == size */ )
  3004.           {
  3005.             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
  3006.             return 1;
  3007.           }
  3008.         else        /* Warning!  Warning!  Target's ovly table has changed!  */
  3009.           return 0;
  3010.       }
  3011.   return 0;
  3012. }

  3013. /* Function: simple_overlay_update
  3014.    If OSECT is NULL, then update all sections' mapped state
  3015.    (after re-reading the entire target _ovly_table).
  3016.    If OSECT is non-NULL, then try to find a matching entry in the
  3017.    cached ovly_table and update only OSECT's mapped state.
  3018.    If a cached entry can't be found or the cache isn't valid, then
  3019.    re-read the entire cache, and go ahead and update all sections.  */

  3020. void
  3021. simple_overlay_update (struct obj_section *osect)
  3022. {
  3023.   struct objfile *objfile;

  3024.   /* Were we given an osect to look up?  NULL means do all of them.  */
  3025.   if (osect)
  3026.     /* Have we got a cached copy of the target's overlay table?  */
  3027.     if (cache_ovly_table != NULL)
  3028.       {
  3029.         /* Does its cached location match what's currently in the
  3030.            symtab?  */
  3031.         struct bound_minimal_symbol minsym
  3032.           = lookup_minimal_symbol ("_ovly_table", NULL, NULL);

  3033.         if (minsym.minsym == NULL)
  3034.           error (_("Error reading inferior's overlay table: couldn't "
  3035.                    "find `_ovly_table' array\n"
  3036.                    "in inferior.  Use `overlay manual' mode."));

  3037.         if (cache_ovly_table_base == BMSYMBOL_VALUE_ADDRESS (minsym))
  3038.           /* Then go ahead and try to look up this single section in
  3039.              the cache.  */
  3040.           if (simple_overlay_update_1 (osect))
  3041.             /* Found it!  We're done.  */
  3042.             return;
  3043.       }

  3044.   /* Cached table no good: need to read the entire table anew.
  3045.      Or else we want all the sections, in which case it's actually
  3046.      more efficient to read the whole table in one block anyway.  */

  3047.   if (! simple_read_overlay_table ())
  3048.     return;

  3049.   /* Now may as well update all sections, even if only one was requested.  */
  3050.   ALL_OBJSECTIONS (objfile, osect)
  3051.     if (section_is_overlay (osect))
  3052.     {
  3053.       int i, size;
  3054.       bfd *obfd = osect->objfile->obfd;
  3055.       asection *bsect = osect->the_bfd_section;

  3056.       size = bfd_get_section_size (bsect);
  3057.       for (i = 0; i < cache_novlys; i++)
  3058.         if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
  3059.             && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect)
  3060.             /* && cache_ovly_table[i][SIZE] == size */ )
  3061.           { /* obj_section matches i'th entry in ovly_table.  */
  3062.             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
  3063.             break;                /* finished with inner for loop: break out.  */
  3064.           }
  3065.     }
  3066. }

  3067. /* Set the output sections and output offsets for section SECTP in
  3068.    ABFD.  The relocation code in BFD will read these offsets, so we
  3069.    need to be sure they're initialized.  We map each section to itself,
  3070.    with no offset; this means that SECTP->vma will be honored.  */

  3071. static void
  3072. symfile_dummy_outputs (bfd *abfd, asection *sectp, void *dummy)
  3073. {
  3074.   sectp->output_section = sectp;
  3075.   sectp->output_offset = 0;
  3076. }

  3077. /* Default implementation for sym_relocate.  */

  3078. bfd_byte *
  3079. default_symfile_relocate (struct objfile *objfile, asection *sectp,
  3080.                           bfd_byte *buf)
  3081. {
  3082.   /* Use sectp->owner instead of objfile->obfd.  sectp may point to a
  3083.      DWO file.  */
  3084.   bfd *abfd = sectp->owner;

  3085.   /* We're only interested in sections with relocation
  3086.      information.  */
  3087.   if ((sectp->flags & SEC_RELOC) == 0)
  3088.     return NULL;

  3089.   /* We will handle section offsets properly elsewhere, so relocate as if
  3090.      all sections begin at 0.  */
  3091.   bfd_map_over_sections (abfd, symfile_dummy_outputs, NULL);

  3092.   return bfd_simple_get_relocated_section_contents (abfd, sectp, buf, NULL);
  3093. }

  3094. /* Relocate the contents of a debug section SECTP in ABFD.  The
  3095.    contents are stored in BUF if it is non-NULL, or returned in a
  3096.    malloc'd buffer otherwise.

  3097.    For some platforms and debug info formats, shared libraries contain
  3098.    relocations against the debug sections (particularly for DWARF-2;
  3099.    one affected platform is PowerPC GNU/Linux, although it depends on
  3100.    the version of the linker in use).  Also, ELF object files naturally
  3101.    have unresolved relocations for their debug sections.  We need to apply
  3102.    the relocations in order to get the locations of symbols correct.
  3103.    Another example that may require relocation processing, is the
  3104.    DWARF-2 .eh_frame section in .o files, although it isn't strictly a
  3105.    debug section.  */

  3106. bfd_byte *
  3107. symfile_relocate_debug_section (struct objfile *objfile,
  3108.                                 asection *sectp, bfd_byte *buf)
  3109. {
  3110.   gdb_assert (objfile->sf->sym_relocate);

  3111.   return (*objfile->sf->sym_relocate) (objfile, sectp, buf);
  3112. }

  3113. struct symfile_segment_data *
  3114. get_symfile_segment_data (bfd *abfd)
  3115. {
  3116.   const struct sym_fns *sf = find_sym_fns (abfd);

  3117.   if (sf == NULL)
  3118.     return NULL;

  3119.   return sf->sym_segments (abfd);
  3120. }

  3121. void
  3122. free_symfile_segment_data (struct symfile_segment_data *data)
  3123. {
  3124.   xfree (data->segment_bases);
  3125.   xfree (data->segment_sizes);
  3126.   xfree (data->segment_info);
  3127.   xfree (data);
  3128. }

  3129. /* Given:
  3130.    - DATA, containing segment addresses from the object file ABFD, and
  3131.      the mapping from ABFD's sections onto the segments that own them,
  3132.      and
  3133.    - SEGMENT_BASES[0 .. NUM_SEGMENT_BASES - 1], holding the actual
  3134.      segment addresses reported by the target,
  3135.    store the appropriate offsets for each section in OFFSETS.

  3136.    If there are fewer entries in SEGMENT_BASES than there are segments
  3137.    in DATA, then apply SEGMENT_BASES' last entry to all the segments.

  3138.    If there are more entries, then ignore the extra.  The target may
  3139.    not be able to distinguish between an empty data segment and a
  3140.    missing data segment; a missing text segment is less plausible.  */

  3141. int
  3142. symfile_map_offsets_to_segments (bfd *abfd,
  3143.                                  const struct symfile_segment_data *data,
  3144.                                  struct section_offsets *offsets,
  3145.                                  int num_segment_bases,
  3146.                                  const CORE_ADDR *segment_bases)
  3147. {
  3148.   int i;
  3149.   asection *sect;

  3150.   /* It doesn't make sense to call this function unless you have some
  3151.      segment base addresses.  */
  3152.   gdb_assert (num_segment_bases > 0);

  3153.   /* If we do not have segment mappings for the object file, we
  3154.      can not relocate it by segments.  */
  3155.   gdb_assert (data != NULL);
  3156.   gdb_assert (data->num_segments > 0);

  3157.   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
  3158.     {
  3159.       int which = data->segment_info[i];

  3160.       gdb_assert (0 <= which && which <= data->num_segments);

  3161.       /* Don't bother computing offsets for sections that aren't
  3162.          loaded as part of any segment.  */
  3163.       if (! which)
  3164.         continue;

  3165.       /* Use the last SEGMENT_BASES entry as the address of any extra
  3166.          segments mentioned in DATA->segment_info.  */
  3167.       if (which > num_segment_bases)
  3168.         which = num_segment_bases;

  3169.       offsets->offsets[i] = (segment_bases[which - 1]
  3170.                              - data->segment_bases[which - 1]);
  3171.     }

  3172.   return 1;
  3173. }

  3174. static void
  3175. symfile_find_segment_sections (struct objfile *objfile)
  3176. {
  3177.   bfd *abfd = objfile->obfd;
  3178.   int i;
  3179.   asection *sect;
  3180.   struct symfile_segment_data *data;

  3181.   data = get_symfile_segment_data (objfile->obfd);
  3182.   if (data == NULL)
  3183.     return;

  3184.   if (data->num_segments != 1 && data->num_segments != 2)
  3185.     {
  3186.       free_symfile_segment_data (data);
  3187.       return;
  3188.     }

  3189.   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
  3190.     {
  3191.       int which = data->segment_info[i];

  3192.       if (which == 1)
  3193.         {
  3194.           if (objfile->sect_index_text == -1)
  3195.             objfile->sect_index_text = sect->index;

  3196.           if (objfile->sect_index_rodata == -1)
  3197.             objfile->sect_index_rodata = sect->index;
  3198.         }
  3199.       else if (which == 2)
  3200.         {
  3201.           if (objfile->sect_index_data == -1)
  3202.             objfile->sect_index_data = sect->index;

  3203.           if (objfile->sect_index_bss == -1)
  3204.             objfile->sect_index_bss = sect->index;
  3205.         }
  3206.     }

  3207.   free_symfile_segment_data (data);
  3208. }

  3209. /* Listen for free_objfile events.  */

  3210. static void
  3211. symfile_free_objfile (struct objfile *objfile)
  3212. {
  3213.   /* Remove the target sections owned by this objfile.  */
  3214.   if (objfile != NULL)
  3215.     remove_target_sections ((void *) objfile);
  3216. }

  3217. /* Wrapper around the quick_symbol_functions expand_symtabs_matching "method".
  3218.    Expand all symtabs that match the specified criteria.
  3219.    See quick_symbol_functions.expand_symtabs_matching for details.  */

  3220. void
  3221. expand_symtabs_matching (expand_symtabs_file_matcher_ftype *file_matcher,
  3222.                          expand_symtabs_symbol_matcher_ftype *symbol_matcher,
  3223.                          enum search_domain kind,
  3224.                          void *data)
  3225. {
  3226.   struct objfile *objfile;

  3227.   ALL_OBJFILES (objfile)
  3228.   {
  3229.     if (objfile->sf)
  3230.       objfile->sf->qf->expand_symtabs_matching (objfile, file_matcher,
  3231.                                                 symbol_matcher, kind,
  3232.                                                 data);
  3233.   }
  3234. }

  3235. /* Wrapper around the quick_symbol_functions map_symbol_filenames "method".
  3236.    Map function FUN over every file.
  3237.    See quick_symbol_functions.map_symbol_filenames for details.  */

  3238. void
  3239. map_symbol_filenames (symbol_filename_ftype *fun, void *data,
  3240.                       int need_fullname)
  3241. {
  3242.   struct objfile *objfile;

  3243.   ALL_OBJFILES (objfile)
  3244.   {
  3245.     if (objfile->sf)
  3246.       objfile->sf->qf->map_symbol_filenames (objfile, fun, data,
  3247.                                              need_fullname);
  3248.   }
  3249. }

  3250. void
  3251. _initialize_symfile (void)
  3252. {
  3253.   struct cmd_list_element *c;

  3254.   observer_attach_free_objfile (symfile_free_objfile);

  3255.   c = add_cmd ("symbol-file", class_files, symbol_file_command, _("\
  3256. Load symbol table from executable file FILE.\n\
  3257. The `file' command can also load symbol tables, as well as setting the file\n\
  3258. to execute."), &cmdlist);
  3259.   set_cmd_completer (c, filename_completer);

  3260.   c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command, _("\
  3261. Load symbols from FILE, assuming FILE has been dynamically loaded.\n\
  3262. Usage: add-symbol-file FILE ADDR [-s <SECT> <SECT_ADDR> -s <SECT> <SECT_ADDR>\
  3263. ...]\nADDR is the starting address of the file's text.\n\
  3264. The optional arguments are section-name section-address pairs and\n\
  3265. should be specified if the data and bss segments are not contiguous\n\
  3266. with the text.  SECT is a section name to be loaded at SECT_ADDR."),
  3267.                &cmdlist);
  3268.   set_cmd_completer (c, filename_completer);

  3269.   c = add_cmd ("remove-symbol-file", class_files,
  3270.                remove_symbol_file_command, _("\
  3271. Remove a symbol file added via the add-symbol-file command.\n\
  3272. Usage: remove-symbol-file FILENAME\n\
  3273.        remove-symbol-file -a ADDRESS\n\
  3274. The file to remove can be identified by its filename or by an address\n\
  3275. that lies within the boundaries of this symbol file in memory."),
  3276.                &cmdlist);

  3277.   c = add_cmd ("load", class_files, load_command, _("\
  3278. Dynamically load FILE into the running program, and record its symbols\n\
  3279. for access from GDB.\n\
  3280. A load OFFSET may also be given."), &cmdlist);
  3281.   set_cmd_completer (c, filename_completer);

  3282.   add_prefix_cmd ("overlay", class_support, overlay_command,
  3283.                   _("Commands for debugging overlays."), &overlaylist,
  3284.                   "overlay ", 0, &cmdlist);

  3285.   add_com_alias ("ovly", "overlay", class_alias, 1);
  3286.   add_com_alias ("ov", "overlay", class_alias, 1);

  3287.   add_cmd ("map-overlay", class_support, map_overlay_command,
  3288.            _("Assert that an overlay section is mapped."), &overlaylist);

  3289.   add_cmd ("unmap-overlay", class_support, unmap_overlay_command,
  3290.            _("Assert that an overlay section is unmapped."), &overlaylist);

  3291.   add_cmd ("list-overlays", class_support, list_overlays_command,
  3292.            _("List mappings of overlay sections."), &overlaylist);

  3293.   add_cmd ("manual", class_support, overlay_manual_command,
  3294.            _("Enable overlay debugging."), &overlaylist);
  3295.   add_cmd ("off", class_support, overlay_off_command,
  3296.            _("Disable overlay debugging."), &overlaylist);
  3297.   add_cmd ("auto", class_support, overlay_auto_command,
  3298.            _("Enable automatic overlay debugging."), &overlaylist);
  3299.   add_cmd ("load-target", class_support, overlay_load_command,
  3300.            _("Read the overlay mapping state from the target."), &overlaylist);

  3301.   /* Filename extension to source language lookup table: */
  3302.   init_filename_language_table ();
  3303.   add_setshow_string_noescape_cmd ("extension-language", class_files,
  3304.                                    &ext_args, _("\
  3305. Set mapping between filename extension and source language."), _("\
  3306. Show mapping between filename extension and source language."), _("\
  3307. Usage: set extension-language .foo bar"),
  3308.                                    set_ext_lang_command,
  3309.                                    show_ext_args,
  3310.                                    &setlist, &showlist);

  3311.   add_info ("extensions", info_ext_lang_command,
  3312.             _("All filename extensions associated with a source language."));

  3313.   add_setshow_optional_filename_cmd ("debug-file-directory", class_support,
  3314.                                      &debug_file_directory, _("\
  3315. Set the directories where separate debug symbols are searched for."), _("\
  3316. Show the directories where separate debug symbols are searched for."), _("\
  3317. Separate debug symbols are first searched for in the same\n\
  3318. directory as the binary, then in the `" DEBUG_SUBDIRECTORY "' subdirectory,\n\
  3319. and lastly at the path of the directory of the binary with\n\
  3320. each global debug-file-directory component prepended."),
  3321.                                      NULL,
  3322.                                      show_debug_file_directory,
  3323.                                      &setlist, &showlist);

  3324.   add_setshow_enum_cmd ("symbol-loading", no_class,
  3325.                         print_symbol_loading_enums, &print_symbol_loading,
  3326.                         _("\
  3327. Set printing of symbol loading messages."), _("\
  3328. Show printing of symbol loading messages."), _("\
  3329. off   == turn all messages off\n\
  3330. brief == print messages for the executable,\n\
  3331.          and brief messages for shared libraries\n\
  3332. full  == print messages for the executable,\n\
  3333.          and messages for each shared library."),
  3334.                         NULL,
  3335.                         NULL,
  3336.                         &setprintlist, &showprintlist);
  3337. }