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