OSDN Git Service

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