80f990295036092f4ce103dfb56216a4379c0a55
[external/binutils.git] / gdb / symfile.c
1 /* Generic symbol file reading for the GNU debugger, GDB.
2    Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998
3    Free Software Foundation, Inc.
4    Contributed by Cygnus Support, using pieces from other GDB modules.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23 #include "defs.h"
24 #include "symtab.h"
25 #include "gdbtypes.h"
26 #include "gdbcore.h"
27 #include "frame.h"
28 #include "target.h"
29 #include "value.h"
30 #include "symfile.h"
31 #include "objfiles.h"
32 #include "gdbcmd.h"
33 #include "breakpoint.h"
34 #include "language.h"
35 #include "complaints.h"
36 #include "demangle.h"
37 #include "inferior.h"           /* for write_pc */
38 #include "gdb-stabs.h"
39 #include "obstack.h"
40
41 #include <assert.h>
42 #include <sys/types.h>
43 #include <fcntl.h>
44 #include "gdb_string.h"
45 #include "gdb_stat.h"
46 #include <ctype.h>
47 #include <time.h>
48
49 #ifndef O_BINARY
50 #define O_BINARY 0
51 #endif
52
53 #ifdef HPUXHPPA
54
55 /* Some HP-UX related globals to clear when a new "main"
56    symbol file is loaded. HP-specific.  */
57
58 extern int hp_som_som_object_present;
59 extern int hp_cxx_exception_support_initialized;
60 #define RESET_HP_UX_GLOBALS() do {\
61                                     hp_som_som_object_present = 0;             /* indicates HP-compiled code */        \
62                                     hp_cxx_exception_support_initialized = 0;  /* must reinitialize exception stuff */ \
63                               } while (0)
64 #endif
65
66 int (*ui_load_progress_hook) (const char *section, unsigned long num);
67 void (*pre_add_symbol_hook) PARAMS ((char *));
68 void (*post_add_symbol_hook) PARAMS ((void));
69 void (*target_new_objfile_hook) PARAMS ((struct objfile *));
70
71 /* Global variables owned by this file */
72 int readnow_symbol_files;       /* Read full symbols immediately */
73
74 struct complaint oldsyms_complaint =
75 {
76   "Replacing old symbols for `%s'", 0, 0
77 };
78
79 struct complaint empty_symtab_complaint =
80 {
81   "Empty symbol table found for `%s'", 0, 0
82 };
83
84 struct complaint unknown_option_complaint =
85 {
86   "Unknown option `%s' ignored", 0, 0
87 };
88
89 /* External variables and functions referenced. */
90
91 extern int info_verbose;
92
93 extern void report_transfer_performance PARAMS ((unsigned long,
94                                                  time_t, time_t));
95
96 /* Functions this file defines */
97
98 #if 0
99 static int simple_read_overlay_region_table PARAMS ((void));
100 static void simple_free_overlay_region_table PARAMS ((void));
101 #endif
102
103 static void set_initial_language PARAMS ((void));
104
105 static void load_command PARAMS ((char *, int));
106
107 static void add_symbol_file_command PARAMS ((char *, int));
108
109 static void add_shared_symbol_files_command PARAMS ((char *, int));
110
111 static void cashier_psymtab PARAMS ((struct partial_symtab *));
112
113 static int compare_psymbols PARAMS ((const void *, const void *));
114
115 static int compare_symbols PARAMS ((const void *, const void *));
116
117 bfd *symfile_bfd_open PARAMS ((char *));
118
119 static void find_sym_fns PARAMS ((struct objfile *));
120
121 static void decrement_reading_symtab PARAMS ((void *));
122
123 static void overlay_invalidate_all PARAMS ((void));
124
125 static int overlay_is_mapped PARAMS ((struct obj_section *));
126
127 void list_overlays_command PARAMS ((char *, int));
128
129 void map_overlay_command PARAMS ((char *, int));
130
131 void unmap_overlay_command PARAMS ((char *, int));
132
133 static void overlay_auto_command PARAMS ((char *, int));
134
135 static void overlay_manual_command PARAMS ((char *, int));
136
137 static void overlay_off_command PARAMS ((char *, int));
138
139 static void overlay_load_command PARAMS ((char *, int));
140
141 static void overlay_command PARAMS ((char *, int));
142
143 static void simple_free_overlay_table PARAMS ((void));
144
145 static void read_target_long_array PARAMS ((CORE_ADDR, unsigned int *, int));
146
147 static int simple_read_overlay_table PARAMS ((void));
148
149 static int simple_overlay_update_1 PARAMS ((struct obj_section *));
150
151 static void add_filename_language PARAMS ((char *ext, enum language lang));
152
153 static void set_ext_lang_command PARAMS ((char *args, int from_tty));
154
155 static void info_ext_lang_command PARAMS ((char *args, int from_tty));
156
157 static void init_filename_language_table PARAMS ((void));
158
159 void _initialize_symfile PARAMS ((void));
160
161 /* List of all available sym_fns.  On gdb startup, each object file reader
162    calls add_symtab_fns() to register information on each format it is
163    prepared to read. */
164
165 static struct sym_fns *symtab_fns = NULL;
166
167 /* Flag for whether user will be reloading symbols multiple times.
168    Defaults to ON for VxWorks, otherwise OFF.  */
169
170 #ifdef SYMBOL_RELOADING_DEFAULT
171 int symbol_reloading = SYMBOL_RELOADING_DEFAULT;
172 #else
173 int symbol_reloading = 0;
174 #endif
175
176 /* If non-zero, then on HP-UX (i.e., platforms that use somsolib.c),
177    this variable is interpreted as a threshhold.  If adding a new
178    library's symbol table to those already known to the debugger would
179    exceed this threshhold, then the shlib's symbols are not added.
180
181    If non-zero on other platforms, shared library symbols will be added
182    automatically when the inferior is created, new libraries are loaded,
183    or when attaching to the inferior.  This is almost always what users
184    will want to have happen; but for very large programs, the startup
185    time will be excessive, and so if this is a problem, the user can
186    clear this flag and then add the shared library symbols as needed.
187    Note that there is a potential for confusion, since if the shared
188    library symbols are not loaded, commands like "info fun" will *not*
189    report all the functions that are actually present. 
190
191    Note that HP-UX interprets this variable to mean, "threshhold size
192    in megabytes, where zero means never add".  Other platforms interpret
193    this variable to mean, "always add if non-zero, never add if zero."
194  */
195
196 int auto_solib_add = 1;
197 \f
198
199 /* Since this function is called from within qsort, in an ANSI environment
200    it must conform to the prototype for qsort, which specifies that the
201    comparison function takes two "void *" pointers. */
202
203 static int
204 compare_symbols (s1p, s2p)
205      const PTR s1p;
206      const PTR s2p;
207 {
208   register struct symbol **s1, **s2;
209
210   s1 = (struct symbol **) s1p;
211   s2 = (struct symbol **) s2p;
212
213   return (STRCMP (SYMBOL_NAME (*s1), SYMBOL_NAME (*s2)));
214 }
215
216 /*
217
218    LOCAL FUNCTION
219
220    compare_psymbols -- compare two partial symbols by name
221
222    DESCRIPTION
223
224    Given pointers to pointers to two partial symbol table entries,
225    compare them by name and return -N, 0, or +N (ala strcmp).
226    Typically used by sorting routines like qsort().
227
228    NOTES
229
230    Does direct compare of first two characters before punting
231    and passing to strcmp for longer compares.  Note that the
232    original version had a bug whereby two null strings or two
233    identically named one character strings would return the
234    comparison of memory following the null byte.
235
236  */
237
238 static int
239 compare_psymbols (s1p, s2p)
240      const PTR s1p;
241      const PTR s2p;
242 {
243   register char *st1 = SYMBOL_NAME (*(struct partial_symbol **) s1p);
244   register char *st2 = SYMBOL_NAME (*(struct partial_symbol **) s2p);
245
246   if ((st1[0] - st2[0]) || !st1[0])
247     {
248       return (st1[0] - st2[0]);
249     }
250   else if ((st1[1] - st2[1]) || !st1[1])
251     {
252       return (st1[1] - st2[1]);
253     }
254   else
255     {
256       /* Note: I replaced the STRCMP line (commented out below)
257        * with a simpler "strcmp()" which compares the 2 strings
258        * from the beginning. (STRCMP is a macro which first compares
259        * the initial characters, then falls back on strcmp).
260        * The reason is that the STRCMP line was tickling a C compiler
261        * bug on HP-UX 10.30, which is avoided with the simpler
262        * code. The performance gain from the more complicated code
263        * is negligible, given that we have already checked the
264        * initial 2 characters above. I reported the compiler bug,
265        * and once it is fixed the original line can be put back. RT
266        */
267       /* return ( STRCMP (st1 + 2, st2 + 2)); */
268       return (strcmp (st1, st2));
269     }
270 }
271
272 void
273 sort_pst_symbols (pst)
274      struct partial_symtab *pst;
275 {
276   /* Sort the global list; don't sort the static list */
277
278   qsort (pst->objfile->global_psymbols.list + pst->globals_offset,
279          pst->n_global_syms, sizeof (struct partial_symbol *),
280          compare_psymbols);
281 }
282
283 /* Call sort_block_syms to sort alphabetically the symbols of one block.  */
284
285 void
286 sort_block_syms (b)
287      register struct block *b;
288 {
289   qsort (&BLOCK_SYM (b, 0), BLOCK_NSYMS (b),
290          sizeof (struct symbol *), compare_symbols);
291 }
292
293 /* Call sort_symtab_syms to sort alphabetically
294    the symbols of each block of one symtab.  */
295
296 void
297 sort_symtab_syms (s)
298      register struct symtab *s;
299 {
300   register struct blockvector *bv;
301   int nbl;
302   int i;
303   register struct block *b;
304
305   if (s == 0)
306     return;
307   bv = BLOCKVECTOR (s);
308   nbl = BLOCKVECTOR_NBLOCKS (bv);
309   for (i = 0; i < nbl; i++)
310     {
311       b = BLOCKVECTOR_BLOCK (bv, i);
312       if (BLOCK_SHOULD_SORT (b))
313         sort_block_syms (b);
314     }
315 }
316
317 /* Make a null terminated copy of the string at PTR with SIZE characters in
318    the obstack pointed to by OBSTACKP .  Returns the address of the copy.
319    Note that the string at PTR does not have to be null terminated, I.E. it
320    may be part of a larger string and we are only saving a substring. */
321
322 char *
323 obsavestring (ptr, size, obstackp)
324      char *ptr;
325      int size;
326      struct obstack *obstackp;
327 {
328   register char *p = (char *) obstack_alloc (obstackp, size + 1);
329   /* Open-coded memcpy--saves function call time.  These strings are usually
330      short.  FIXME: Is this really still true with a compiler that can
331      inline memcpy? */
332   {
333     register char *p1 = ptr;
334     register char *p2 = p;
335     char *end = ptr + size;
336     while (p1 != end)
337       *p2++ = *p1++;
338   }
339   p[size] = 0;
340   return p;
341 }
342
343 /* Concatenate strings S1, S2 and S3; return the new string.  Space is found
344    in the obstack pointed to by OBSTACKP.  */
345
346 char *
347 obconcat (obstackp, s1, s2, s3)
348      struct obstack *obstackp;
349      const char *s1, *s2, *s3;
350 {
351   register int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
352   register char *val = (char *) obstack_alloc (obstackp, len);
353   strcpy (val, s1);
354   strcat (val, s2);
355   strcat (val, s3);
356   return val;
357 }
358
359 /* True if we are nested inside psymtab_to_symtab. */
360
361 int currently_reading_symtab = 0;
362
363 static void
364 decrement_reading_symtab (dummy)
365      void *dummy;
366 {
367   currently_reading_symtab--;
368 }
369
370 /* Get the symbol table that corresponds to a partial_symtab.
371    This is fast after the first time you do it.  In fact, there
372    is an even faster macro PSYMTAB_TO_SYMTAB that does the fast
373    case inline.  */
374
375 struct symtab *
376 psymtab_to_symtab (pst)
377      register struct partial_symtab *pst;
378 {
379   /* If it's been looked up before, return it. */
380   if (pst->symtab)
381     return pst->symtab;
382
383   /* If it has not yet been read in, read it.  */
384   if (!pst->readin)
385     {
386       struct cleanup *back_to = make_cleanup (decrement_reading_symtab, NULL);
387       currently_reading_symtab++;
388       (*pst->read_symtab) (pst);
389       do_cleanups (back_to);
390     }
391
392   return pst->symtab;
393 }
394
395 /* Initialize entry point information for this objfile. */
396
397 void
398 init_entry_point_info (objfile)
399      struct objfile *objfile;
400 {
401   /* Save startup file's range of PC addresses to help blockframe.c
402      decide where the bottom of the stack is.  */
403
404   if (bfd_get_file_flags (objfile->obfd) & EXEC_P)
405     {
406       /* Executable file -- record its entry point so we'll recognize
407          the startup file because it contains the entry point.  */
408       objfile->ei.entry_point = bfd_get_start_address (objfile->obfd);
409     }
410   else
411     {
412       /* Examination of non-executable.o files.  Short-circuit this stuff.  */
413       objfile->ei.entry_point = INVALID_ENTRY_POINT;
414     }
415   objfile->ei.entry_file_lowpc = INVALID_ENTRY_LOWPC;
416   objfile->ei.entry_file_highpc = INVALID_ENTRY_HIGHPC;
417   objfile->ei.entry_func_lowpc = INVALID_ENTRY_LOWPC;
418   objfile->ei.entry_func_highpc = INVALID_ENTRY_HIGHPC;
419   objfile->ei.main_func_lowpc = INVALID_ENTRY_LOWPC;
420   objfile->ei.main_func_highpc = INVALID_ENTRY_HIGHPC;
421 }
422
423 /* Get current entry point address.  */
424
425 CORE_ADDR
426 entry_point_address ()
427 {
428   return symfile_objfile ? symfile_objfile->ei.entry_point : 0;
429 }
430
431 /* Remember the lowest-addressed loadable section we've seen.  
432    This function is called via bfd_map_over_sections. 
433
434    In case of equal vmas, the section with the largest size becomes the
435    lowest-addressed loadable section.
436
437    If the vmas and sizes are equal, the last section is considered the
438    lowest-addressed loadable section.  */
439
440 void
441 find_lowest_section (abfd, sect, obj)
442      bfd *abfd;
443      asection *sect;
444      PTR obj;
445 {
446   asection **lowest = (asection **) obj;
447
448   if (0 == (bfd_get_section_flags (abfd, sect) & SEC_LOAD))
449     return;
450   if (!*lowest)
451     *lowest = sect;             /* First loadable section */
452   else if (bfd_section_vma (abfd, *lowest) > bfd_section_vma (abfd, sect))
453     *lowest = sect;             /* A lower loadable section */
454   else if (bfd_section_vma (abfd, *lowest) == bfd_section_vma (abfd, sect)
455            && (bfd_section_size (abfd, (*lowest))
456                <= bfd_section_size (abfd, sect)))
457     *lowest = sect;
458 }
459
460 /* Parse the user's idea of an offset for dynamic linking, into our idea
461    of how to represent it for fast symbol reading.  This is the default 
462    version of the sym_fns.sym_offsets function for symbol readers that
463    don't need to do anything special.  It allocates a section_offsets table
464    for the objectfile OBJFILE and stuffs ADDR into all of the offsets.  */
465
466 void
467 default_symfile_offsets (objfile, addrs)
468      struct objfile *objfile;
469      struct section_addr_info *addrs;
470 {
471   int i;
472
473   objfile->num_sections = SECT_OFF_MAX;
474   objfile->section_offsets = (struct section_offsets *)
475     obstack_alloc (&objfile->psymbol_obstack, SIZEOF_SECTION_OFFSETS);
476   memset (objfile->section_offsets, 0, SIZEOF_SECTION_OFFSETS);
477
478   /* If user explicitly specified values for data and bss, set them here. */
479   
480   if (addrs->text_addr)
481     ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT) = addrs->text_addr;
482   if (addrs->data_addr)
483     ANOFFSET (objfile->section_offsets, SECT_OFF_DATA) = addrs->data_addr;
484   if (addrs->bss_addr)
485     ANOFFSET (objfile->section_offsets, SECT_OFF_BSS)  = addrs->bss_addr;
486     
487   /* Now calculate offsets for other sections. */
488   for (i = 0; i < MAX_SECTIONS && addrs->other[i].name; i++)
489     {
490       struct other_sections *osp ;
491
492       osp = &addrs->other[i] ;
493       if (addrs->other[i].addr == 0)
494         continue;
495 #if 0
496       if (strcmp (".text", osp->name) == 0)
497         SECT_OFF_TEXT = osp->sectindex ;
498       else if (strcmp (".data", osp->name) == 0)
499         SECT_OFF_DATA = osp->sectindex ;
500       else if (strcmp (".bss", osp->name) == 0)
501         SECT_OFF_BSS =  osp->sectindex ;
502 #endif
503       /* Record all sections in offsets */
504       ANOFFSET (objfile->section_offsets, osp->sectindex) = osp->addr;
505     }
506 }
507
508
509 /* Process a symbol file, as either the main file or as a dynamically
510    loaded file.
511
512    OBJFILE is where the symbols are to be read from.
513
514    ADDR is the address where the text segment was loaded, unless the
515    objfile is the main symbol file, in which case it is zero.
516
517    MAINLINE is nonzero if this is the main symbol file, or zero if
518    it's an extra symbol file such as dynamically loaded code.
519
520    VERBO is nonzero if the caller has printed a verbose message about
521    the symbol reading (and complaints can be more terse about it).  */
522
523 void
524 syms_from_objfile (objfile, addrs, mainline, verbo)
525      struct objfile *objfile;
526      struct section_addr_info *addrs;
527      int mainline;
528      int verbo;
529 {
530   struct section_offsets *section_offsets;
531   asection *lower_sect;
532   asection *sect;
533   CORE_ADDR lower_offset;
534   struct section_addr_info local_addr;
535   struct cleanup *old_chain;
536   int i;
537
538   /* If ADDRS is NULL, initialize the local section_addr_info struct and
539      point ADDRS to it.  We now establish the convention that an addr of
540      zero means no load address was specified. */
541
542   if (addrs == NULL)
543     {
544       memset (&local_addr, 0, sizeof (local_addr));
545       addrs = &local_addr;
546     }
547
548   init_entry_point_info (objfile);
549   find_sym_fns (objfile);
550
551   /* Make sure that partially constructed symbol tables will be cleaned up
552      if an error occurs during symbol reading.  */
553   old_chain = make_cleanup ((make_cleanup_func) free_objfile, objfile);
554
555   if (mainline)
556     {
557       /* We will modify the main symbol table, make sure that all its users
558          will be cleaned up if an error occurs during symbol reading.  */
559       make_cleanup ((make_cleanup_func) clear_symtab_users, 0);
560
561       /* Since no error yet, throw away the old symbol table.  */
562
563       if (symfile_objfile != NULL)
564         {
565           free_objfile (symfile_objfile);
566           symfile_objfile = NULL;
567         }
568
569       /* Currently we keep symbols from the add-symbol-file command.
570          If the user wants to get rid of them, they should do "symbol-file"
571          without arguments first.  Not sure this is the best behavior
572          (PR 2207).  */
573
574       (*objfile->sf->sym_new_init) (objfile);
575     }
576
577   /* Convert addr into an offset rather than an absolute address.
578      We find the lowest address of a loaded segment in the objfile,
579      and assume that <addr> is where that got loaded.
580
581      We no longer warn if the lowest section is not a text segment (as
582      happens for the PA64 port.  */
583   if (mainline)
584     {
585       /* No offset from objfile addresses.  */
586       addrs -> text_addr = 0;
587       addrs -> data_addr = 0;
588       addrs -> bss_addr = 0;
589     }
590   else
591     {
592       /* Find lowest loadable section to be used as starting point for 
593          continguous sections. FIXME!! won't work without call to find
594          .text first, but this assumes text is lowest section. */
595       lower_sect = bfd_get_section_by_name (objfile->obfd, ".text");
596       if (lower_sect == NULL)
597         bfd_map_over_sections (objfile->obfd, find_lowest_section,
598                                (PTR) &lower_sect);
599       if (lower_sect == NULL)
600         warning ("no loadable sections found in added symbol-file %s",
601                  objfile->name);
602       else if ((bfd_get_section_flags (objfile->obfd, lower_sect) & SEC_CODE)
603                == 0)
604         warning ("Lowest section in %s is %s at %s",
605                  objfile->name,
606                  bfd_section_name (objfile->obfd, lower_sect),
607                  paddr (bfd_section_vma (objfile->obfd, lower_sect)));
608       if (lower_sect != NULL)
609         lower_offset = bfd_section_vma (objfile->obfd, lower_sect);
610       else
611         lower_offset = 0;
612  
613        /* Calculate offsets for the loadable sections.
614          FIXME! Sections must be in order of increasing loadable section
615          so that contiguous sections can use the lower-offset!!!
616  
617           Adjust offsets if the segments are not contiguous.
618           If the section is contiguous, its offset should be set to
619          the offset of the highest loadable section lower than it
620          (the loadable section directly below it in memory).
621          this_offset = lower_offset = lower_addr - lower_orig_addr */
622
623       /* FIXME: These sections will not need special treatment because ALL
624          sections are in the other sections table */
625  
626       if (addrs->text_addr != 0)
627         {
628           sect = bfd_get_section_by_name (objfile->obfd, ".text");
629           if (sect)
630             {
631               addrs->text_addr -= bfd_section_vma (objfile->obfd, sect);
632               lower_offset = addrs->text_addr;
633             }
634         }
635       else 
636         /* ??? who's below me? */
637         addrs->text_addr = lower_offset;
638  
639       if (addrs->data_addr != 0)
640         {
641           sect = bfd_get_section_by_name (objfile->obfd, ".data");
642           if (sect)
643             {
644               addrs->data_addr -= bfd_section_vma (objfile->obfd, sect);
645               lower_offset = addrs->data_addr;
646             }
647         }
648       else
649         addrs->data_addr = lower_offset;
650  
651       if (addrs->bss_addr != 0)
652         {
653           sect = bfd_get_section_by_name (objfile->obfd, ".bss");
654           if (sect)
655             {
656               addrs->bss_addr -= bfd_section_vma (objfile->obfd, sect);
657               lower_offset = addrs->bss_addr;
658             }
659         }
660       else
661         addrs->bss_addr = lower_offset;
662   
663        /* Now calculate offsets for other sections. */
664       for (i=0 ; i < MAX_SECTIONS && addrs->other[i].name; i++)
665         {
666          
667           if (addrs->other[i].addr != 0)
668             {
669               sect=bfd_get_section_by_name(objfile->obfd, addrs->other[i].name);
670               if (sect)
671                 {
672                   addrs->other[i].addr -= bfd_section_vma (objfile->obfd, sect);
673                   lower_offset = addrs->other[i].addr;
674                   addrs->other[i].sectindex = sect->index ;
675                 }
676               else
677                 {
678                   warning ("section %s not found in %s", addrs->other[i].name, 
679                            objfile->name);
680                   addrs->other[i].addr = 0;
681                 }
682             }
683           else
684             addrs->other[i].addr = lower_offset;
685         }
686     }
687
688   /* Initialize symbol reading routines for this objfile, allow complaints to
689      appear for this new file, and record how verbose to be, then do the
690      initial symbol reading for this file. */
691
692   (*objfile->sf->sym_init) (objfile);
693   clear_complaints (1, verbo);
694
695   (*objfile->sf->sym_offsets) (objfile, addrs);
696
697 #ifndef IBM6000_TARGET
698   /* This is a SVR4/SunOS specific hack, I think.  In any event, it
699      screws RS/6000.  sym_offsets should be doing this sort of thing,
700      because it knows the mapping between bfd sections and
701      section_offsets.  */
702   /* This is a hack.  As far as I can tell, section offsets are not
703      target dependent.  They are all set to addr with a couple of
704      exceptions.  The exceptions are sysvr4 shared libraries, whose
705      offsets are kept in solib structures anyway and rs6000 xcoff
706      which handles shared libraries in a completely unique way.
707
708      Section offsets are built similarly, except that they are built
709      by adding addr in all cases because there is no clear mapping
710      from section_offsets into actual sections.  Note that solib.c
711      has a different algorithm for finding section offsets.
712
713      These should probably all be collapsed into some target
714      independent form of shared library support.  FIXME.  */
715
716   if (addrs)
717     {
718       struct obj_section *s;
719
720         /* Map section offsets in "addr" back to the object's 
721            sections by comparing the section names with bfd's 
722            section names.  Then adjust the section address by
723            the offset. */ /* for gdb/13815 */
724  
725       ALL_OBJFILE_OSECTIONS (objfile, s)
726         {
727           CORE_ADDR s_addr = 0;
728           int i;
729
730           if (strcmp (s->the_bfd_section->name, ".text") == 0)
731             s_addr = addrs->text_addr;
732           else if (strcmp (s->the_bfd_section->name, ".data") == 0)
733             s_addr = addrs->data_addr;
734           else if (strcmp (s->the_bfd_section->name, ".bss") == 0)
735             s_addr = addrs->bss_addr;
736           else 
737             for (i = 0; !s_addr && addrs->other[i].name; i++)
738               if (strcmp (s->the_bfd_section->name, addrs->other[i].name) == 0)
739                 s_addr = addrs->other[i].addr; /* end added for gdb/13815 */
740  
741           s->addr -= s->offset;
742           s->addr += s_addr;
743           s->endaddr -= s->offset;
744           s->endaddr += s_addr;
745           s->offset += s_addr;
746         }
747     }
748 #endif /* not IBM6000_TARGET */
749
750   (*objfile->sf->sym_read) (objfile, mainline);
751
752   if (!have_partial_symbols () && !have_full_symbols ())
753     {
754       wrap_here ("");
755       printf_filtered ("(no debugging symbols found)...");
756       wrap_here ("");
757     }
758
759   /* Don't allow char * to have a typename (else would get caddr_t).
760      Ditto void *.  FIXME: Check whether this is now done by all the
761      symbol readers themselves (many of them now do), and if so remove
762      it from here.  */
763
764   TYPE_NAME (lookup_pointer_type (builtin_type_char)) = 0;
765   TYPE_NAME (lookup_pointer_type (builtin_type_void)) = 0;
766
767   /* Mark the objfile has having had initial symbol read attempted.  Note
768      that this does not mean we found any symbols... */
769
770   objfile->flags |= OBJF_SYMS;
771
772   /* Discard cleanups as symbol reading was successful.  */
773
774   discard_cleanups (old_chain);
775
776   /* Call this after reading in a new symbol table to give target
777      dependant code a crack at the new symbols.  For instance, this
778      could be used to update the values of target-specific symbols GDB
779      needs to keep track of (such as _sigtramp, or whatever).  */
780
781   TARGET_SYMFILE_POSTREAD (objfile);
782 }
783
784 /* Perform required actions after either reading in the initial
785    symbols for a new objfile, or mapping in the symbols from a reusable
786    objfile. */
787
788 void
789 new_symfile_objfile (objfile, mainline, verbo)
790      struct objfile *objfile;
791      int mainline;
792      int verbo;
793 {
794
795   /* If this is the main symbol file we have to clean up all users of the
796      old main symbol file. Otherwise it is sufficient to fixup all the
797      breakpoints that may have been redefined by this symbol file.  */
798   if (mainline)
799     {
800       /* OK, make it the "real" symbol file.  */
801       symfile_objfile = objfile;
802
803       clear_symtab_users ();
804     }
805   else
806     {
807       breakpoint_re_set ();
808     }
809
810   /* We're done reading the symbol file; finish off complaints.  */
811   clear_complaints (0, verbo);
812 }
813
814 /* Process a symbol file, as either the main file or as a dynamically
815    loaded file.
816
817    NAME is the file name (which will be tilde-expanded and made
818    absolute herein) (but we don't free or modify NAME itself).
819    FROM_TTY says how verbose to be.  MAINLINE specifies whether this
820    is the main symbol file, or whether it's an extra symbol file such
821    as dynamically loaded code.  If !mainline, ADDR is the address
822    where the text segment was loaded.
823
824    Upon success, returns a pointer to the objfile that was added.
825    Upon failure, jumps back to command level (never returns). */
826
827 struct objfile *
828 symbol_file_add (name, from_tty, addrs, mainline, flags)
829      char *name;
830      int from_tty;
831      struct section_addr_info *addrs;
832      int mainline;
833      int flags;
834 {
835   struct objfile *objfile;
836   struct partial_symtab *psymtab;
837   bfd *abfd;
838
839   /* Open a bfd for the file, and give user a chance to burp if we'd be
840      interactively wiping out any existing symbols.  */
841
842   abfd = symfile_bfd_open (name);
843
844   if ((have_full_symbols () || have_partial_symbols ())
845       && mainline
846       && from_tty
847       && !query ("Load new symbol table from \"%s\"? ", name))
848     error ("Not confirmed.");
849
850   objfile = allocate_objfile (abfd, flags);
851
852   /* If the objfile uses a mapped symbol file, and we have a psymtab for
853      it, then skip reading any symbols at this time. */
854
855   if ((objfile->flags & OBJF_MAPPED) && (objfile->flags & OBJF_SYMS))
856     {
857       /* We mapped in an existing symbol table file that already has had
858          initial symbol reading performed, so we can skip that part.  Notify
859          the user that instead of reading the symbols, they have been mapped.
860        */
861       if (from_tty || info_verbose)
862         {
863           printf_filtered ("Mapped symbols for %s...", name);
864           wrap_here ("");
865           gdb_flush (gdb_stdout);
866         }
867       init_entry_point_info (objfile);
868       find_sym_fns (objfile);
869     }
870   else
871     {
872       /* We either created a new mapped symbol table, mapped an existing
873          symbol table file which has not had initial symbol reading
874          performed, or need to read an unmapped symbol table. */
875       if (from_tty || info_verbose)
876         {
877           if (pre_add_symbol_hook)
878             pre_add_symbol_hook (name);
879           else
880             {
881               printf_filtered ("Reading symbols from %s...", name);
882               wrap_here ("");
883               gdb_flush (gdb_stdout);
884             }
885         }
886       syms_from_objfile (objfile, addrs, mainline, from_tty);
887     }
888
889   /* We now have at least a partial symbol table.  Check to see if the
890      user requested that all symbols be read on initial access via either
891      the gdb startup command line or on a per symbol file basis.  Expand
892      all partial symbol tables for this objfile if so. */
893
894   if ((flags & OBJF_READNOW) || readnow_symbol_files)
895     {
896       if (from_tty || info_verbose)
897         {
898           printf_filtered ("expanding to full symbols...");
899           wrap_here ("");
900           gdb_flush (gdb_stdout);
901         }
902
903       for (psymtab = objfile->psymtabs;
904            psymtab != NULL;
905            psymtab = psymtab->next)
906         {
907           psymtab_to_symtab (psymtab);
908         }
909     }
910
911   if (from_tty || info_verbose)
912     {
913       if (post_add_symbol_hook)
914         post_add_symbol_hook ();
915       else
916         {
917           printf_filtered ("done.\n");
918           gdb_flush (gdb_stdout);
919         }
920     }
921
922   new_symfile_objfile (objfile, mainline, from_tty);
923
924   if (target_new_objfile_hook)
925     target_new_objfile_hook (objfile);
926
927   return (objfile);
928 }
929
930 /* This is the symbol-file command.  Read the file, analyze its
931    symbols, and add a struct symtab to a symtab list.  The syntax of
932    the command is rather bizarre--(1) buildargv implements various
933    quoting conventions which are undocumented and have little or
934    nothing in common with the way things are quoted (or not quoted)
935    elsewhere in GDB, (2) options are used, which are not generally
936    used in GDB (perhaps "set mapped on", "set readnow on" would be
937    better), (3) the order of options matters, which is contrary to GNU
938    conventions (because it is confusing and inconvenient).  */
939
940 void
941 symbol_file_command (args, from_tty)
942      char *args;
943      int from_tty;
944 {
945   char **argv;
946   char *name = NULL;
947   CORE_ADDR text_relocation = 0;        /* text_relocation */
948   struct cleanup *cleanups;
949   int flags = OBJF_USERLOADED;
950
951   dont_repeat ();
952
953   if (args == NULL)
954     {
955       if ((have_full_symbols () || have_partial_symbols ())
956           && from_tty
957           && !query ("Discard symbol table from `%s'? ",
958                      symfile_objfile->name))
959         error ("Not confirmed.");
960       free_all_objfiles ();
961
962       /* solib descriptors may have handles to objfiles.  Since their
963          storage has just been released, we'd better wipe the solib
964          descriptors as well.
965        */
966 #if defined(SOLIB_RESTART)
967       SOLIB_RESTART ();
968 #endif
969
970       symfile_objfile = NULL;
971       if (from_tty)
972         {
973           printf_unfiltered ("No symbol file now.\n");
974         }
975 #ifdef HPUXHPPA
976       RESET_HP_UX_GLOBALS ();
977 #endif
978     }
979   else
980     {
981       if ((argv = buildargv (args)) == NULL)
982         {
983           nomem (0);
984         }
985       cleanups = make_cleanup_freeargv (argv);
986       while (*argv != NULL)
987         {
988           if (STREQ (*argv, "-mapped"))
989             {
990               flags |= OBJF_MAPPED;
991             }
992           else if (STREQ (*argv, "-readnow"))
993             {
994               flags |= OBJF_READNOW;
995             }
996           else if (**argv == '-')
997             {
998               error ("unknown option `%s'", *argv);
999             }
1000           else
1001             {
1002               char *p;
1003
1004               name = *argv;
1005
1006               /* this is for rombug remote only, to get the text relocation by
1007                  using link command */
1008               p = strrchr (name, '/');
1009               if (p != NULL)
1010                 p++;
1011               else
1012                 p = name;
1013
1014               target_link (p, &text_relocation);
1015
1016               if (text_relocation == (CORE_ADDR) 0)
1017                 return;
1018               else if (text_relocation == (CORE_ADDR) -1)
1019                 {
1020                   symbol_file_add (name, from_tty, NULL, 1, flags);
1021 #ifdef HPUXHPPA
1022                   RESET_HP_UX_GLOBALS ();
1023 #endif
1024                 }
1025               else
1026                 {
1027                   struct section_addr_info section_addrs;
1028                   memset (&section_addrs, 0, sizeof (section_addrs));
1029                   section_addrs.text_addr = (CORE_ADDR) text_relocation;
1030                   symbol_file_add (name, from_tty, &section_addrs, 0, flags);
1031                 }
1032
1033               /* Getting new symbols may change our opinion about what is
1034                  frameless.  */
1035               reinit_frame_cache ();
1036
1037               set_initial_language ();
1038             }
1039           argv++;
1040         }
1041
1042       if (name == NULL)
1043         {
1044           error ("no symbol file name was specified");
1045         }
1046       TUIDO (((TuiOpaqueFuncPtr) tuiDisplayMainFunction));
1047       do_cleanups (cleanups);
1048     }
1049 }
1050
1051 /* Set the initial language.
1052
1053    A better solution would be to record the language in the psymtab when reading
1054    partial symbols, and then use it (if known) to set the language.  This would
1055    be a win for formats that encode the language in an easily discoverable place,
1056    such as DWARF.  For stabs, we can jump through hoops looking for specially
1057    named symbols or try to intuit the language from the specific type of stabs
1058    we find, but we can't do that until later when we read in full symbols.
1059    FIXME.  */
1060
1061 static void
1062 set_initial_language ()
1063 {
1064   struct partial_symtab *pst;
1065   enum language lang = language_unknown;
1066
1067   pst = find_main_psymtab ();
1068   if (pst != NULL)
1069     {
1070       if (pst->filename != NULL)
1071         {
1072           lang = deduce_language_from_filename (pst->filename);
1073         }
1074       if (lang == language_unknown)
1075         {
1076           /* Make C the default language */
1077           lang = language_c;
1078         }
1079       set_language (lang);
1080       expected_language = current_language;     /* Don't warn the user */
1081     }
1082 }
1083
1084 /* Open file specified by NAME and hand it off to BFD for preliminary
1085    analysis.  Result is a newly initialized bfd *, which includes a newly
1086    malloc'd` copy of NAME (tilde-expanded and made absolute).
1087    In case of trouble, error() is called.  */
1088
1089 bfd *
1090 symfile_bfd_open (name)
1091      char *name;
1092 {
1093   bfd *sym_bfd;
1094   int desc;
1095   char *absolute_name;
1096
1097
1098
1099   name = tilde_expand (name);   /* Returns 1st new malloc'd copy */
1100
1101   /* Look down path for it, allocate 2nd new malloc'd copy.  */
1102   desc = openp (getenv ("PATH"), 1, name, O_RDONLY | O_BINARY, 0, &absolute_name);
1103 #if defined(__GO32__) || defined(_WIN32)
1104   if (desc < 0)
1105     {
1106       char *exename = alloca (strlen (name) + 5);
1107       strcat (strcpy (exename, name), ".exe");
1108       desc = openp (getenv ("PATH"), 1, exename, O_RDONLY | O_BINARY,
1109                     0, &absolute_name);
1110     }
1111 #endif
1112   if (desc < 0)
1113     {
1114       make_cleanup (free, name);
1115       perror_with_name (name);
1116     }
1117   free (name);                  /* Free 1st new malloc'd copy */
1118   name = absolute_name;         /* Keep 2nd malloc'd copy in bfd */
1119   /* It'll be freed in free_objfile(). */
1120
1121   sym_bfd = bfd_fdopenr (name, gnutarget, desc);
1122   if (!sym_bfd)
1123     {
1124       close (desc);
1125       make_cleanup (free, name);
1126       error ("\"%s\": can't open to read symbols: %s.", name,
1127              bfd_errmsg (bfd_get_error ()));
1128     }
1129   sym_bfd->cacheable = true;
1130
1131   if (!bfd_check_format (sym_bfd, bfd_object))
1132     {
1133       /* FIXME: should be checking for errors from bfd_close (for one thing,
1134          on error it does not free all the storage associated with the
1135          bfd).  */
1136       bfd_close (sym_bfd);      /* This also closes desc */
1137       make_cleanup (free, name);
1138       error ("\"%s\": can't read symbols: %s.", name,
1139              bfd_errmsg (bfd_get_error ()));
1140     }
1141   return (sym_bfd);
1142 }
1143
1144 /* Link a new symtab_fns into the global symtab_fns list.  Called on gdb
1145    startup by the _initialize routine in each object file format reader,
1146    to register information about each format the the reader is prepared
1147    to handle. */
1148
1149 void
1150 add_symtab_fns (sf)
1151      struct sym_fns *sf;
1152 {
1153   sf->next = symtab_fns;
1154   symtab_fns = sf;
1155 }
1156
1157
1158 /* Initialize to read symbols from the symbol file sym_bfd.  It either
1159    returns or calls error().  The result is an initialized struct sym_fns
1160    in the objfile structure, that contains cached information about the
1161    symbol file.  */
1162
1163 static void
1164 find_sym_fns (objfile)
1165      struct objfile *objfile;
1166 {
1167   struct sym_fns *sf;
1168   enum bfd_flavour our_flavour = bfd_get_flavour (objfile->obfd);
1169   char *our_target = bfd_get_target (objfile->obfd);
1170
1171   /* Special kludge for RS/6000 and PowerMac.  See xcoffread.c.  */
1172   if (STREQ (our_target, "aixcoff-rs6000") ||
1173       STREQ (our_target, "xcoff-powermac"))
1174     our_flavour = (enum bfd_flavour) -1;
1175
1176   /* Special kludge for apollo.  See dstread.c.  */
1177   if (STREQN (our_target, "apollo", 6))
1178     our_flavour = (enum bfd_flavour) -2;
1179
1180   for (sf = symtab_fns; sf != NULL; sf = sf->next)
1181     {
1182       if (our_flavour == sf->sym_flavour)
1183         {
1184           objfile->sf = sf;
1185           return;
1186         }
1187     }
1188   error ("I'm sorry, Dave, I can't do that.  Symbol format `%s' unknown.",
1189          bfd_get_target (objfile->obfd));
1190 }
1191 \f
1192 /* This function runs the load command of our current target.  */
1193
1194 static void
1195 load_command (arg, from_tty)
1196      char *arg;
1197      int from_tty;
1198 {
1199   if (arg == NULL)
1200     arg = get_exec_file (1);
1201   target_load (arg, from_tty);
1202 }
1203
1204 /* This version of "load" should be usable for any target.  Currently
1205    it is just used for remote targets, not inftarg.c or core files,
1206    on the theory that only in that case is it useful.
1207
1208    Avoiding xmodem and the like seems like a win (a) because we don't have
1209    to worry about finding it, and (b) On VMS, fork() is very slow and so
1210    we don't want to run a subprocess.  On the other hand, I'm not sure how
1211    performance compares.  */
1212
1213 static int download_write_size = 512;
1214 static int validate_download = 0;
1215
1216 void
1217 generic_load (char *args, int from_tty)
1218 {
1219   asection *s;
1220   bfd *loadfile_bfd;
1221   time_t start_time, end_time;  /* Start and end times of download */
1222   unsigned long data_count = 0; /* Number of bytes transferred to memory */
1223   unsigned long write_count = 0;        /* Number of writes needed. */
1224   unsigned long load_offset;    /* offset to add to vma for each section */
1225   char *filename;
1226   struct cleanup *old_cleanups;
1227   char *offptr;
1228
1229   /* Parse the input argument - the user can specify a load offset as
1230      a second argument. */
1231   filename = xmalloc (strlen (args) + 1);
1232   old_cleanups = make_cleanup (free, filename);
1233   strcpy (filename, args);
1234   offptr = strchr (filename, ' ');
1235   if (offptr != NULL)
1236     {
1237       char *endptr;
1238       load_offset = strtoul (offptr, &endptr, 0);
1239       if (offptr == endptr)
1240         error ("Invalid download offset:%s\n", offptr);
1241       *offptr = '\0';
1242     }
1243   else
1244     load_offset = 0;
1245
1246   /* Open the file for loading. */
1247   loadfile_bfd = bfd_openr (filename, gnutarget);
1248   if (loadfile_bfd == NULL)
1249     {
1250       perror_with_name (filename);
1251       return;
1252     }
1253
1254   /* FIXME: should be checking for errors from bfd_close (for one thing,
1255      on error it does not free all the storage associated with the
1256      bfd).  */
1257   make_cleanup ((make_cleanup_func) bfd_close, loadfile_bfd);
1258
1259   if (!bfd_check_format (loadfile_bfd, bfd_object))
1260     {
1261       error ("\"%s\" is not an object file: %s", filename,
1262              bfd_errmsg (bfd_get_error ()));
1263     }
1264
1265   start_time = time (NULL);
1266
1267   for (s = loadfile_bfd->sections; s; s = s->next)
1268     {
1269       if (s->flags & SEC_LOAD)
1270         {
1271           CORE_ADDR size = bfd_get_section_size_before_reloc (s);
1272           if (size > 0)
1273             {
1274               char *buffer;
1275               struct cleanup *old_chain;
1276               CORE_ADDR lma = s->lma + load_offset;
1277               CORE_ADDR block_size;
1278               int err;
1279               const char *sect_name = bfd_get_section_name (loadfile_bfd, s);
1280               CORE_ADDR sent;
1281
1282               if (download_write_size > 0 && size > download_write_size)
1283                 block_size = download_write_size;
1284               else
1285                 block_size = size;
1286
1287               buffer = xmalloc (size);
1288               old_chain = make_cleanup (free, buffer);
1289
1290               /* Is this really necessary?  I guess it gives the user something
1291                  to look at during a long download.  */
1292               fprintf_unfiltered (gdb_stdout,
1293                                   "Loading section %s, size 0x%s lma 0x%s\n",
1294                                   sect_name, paddr_nz (size), paddr_nz (lma));
1295
1296               bfd_get_section_contents (loadfile_bfd, s, buffer, 0, size);
1297
1298               sent = 0;
1299               do
1300                 {
1301                   CORE_ADDR len;
1302                   CORE_ADDR this_transfer = size - sent;
1303                   if (this_transfer >= block_size)
1304                     this_transfer = block_size;
1305                   len = target_write_memory_partial (lma, buffer,
1306                                                      this_transfer, &err);
1307                   if (err)
1308                     break;
1309                   if (validate_download)
1310                     {
1311                       /* Broken memories and broken monitors manifest
1312                          themselves here when bring new computers to
1313                          life.  This doubles already slow downloads.  */
1314                       /* NOTE: cagney/1999-10-18: A more efficient
1315                          implementation might add a verify_memory()
1316                          method to the target vector and then use
1317                          that.  remote.c could implement that method
1318                          using the ``qCRC'' packet.  */
1319                       char *check = xmalloc (len);
1320                       struct cleanup *verify_cleanups = make_cleanup (free, check);
1321                       if (target_read_memory (lma, check, len) != 0)
1322                         error ("Download verify read failed at 0x%s",
1323                                paddr (lma));
1324                       if (memcmp (buffer, check, len) != 0)
1325                         error ("Download verify compare failed at 0x%s",
1326                                paddr (lma));
1327                       do_cleanups (verify_cleanups);
1328                     }
1329                   data_count += len;
1330                   lma += len;
1331                   buffer += len;
1332                   write_count += 1;
1333                   sent += len;
1334                   if (quit_flag
1335                       || (ui_load_progress_hook != NULL
1336                           && ui_load_progress_hook (sect_name, sent)))
1337                     error ("Canceled the download");
1338                 }
1339               while (sent < size);
1340
1341               if (err != 0)
1342                 error ("Memory access error while loading section %s.", sect_name);
1343
1344               do_cleanups (old_chain);
1345             }
1346         }
1347     }
1348
1349   end_time = time (NULL);
1350   {
1351     CORE_ADDR entry;
1352     entry = bfd_get_start_address (loadfile_bfd);
1353     fprintf_unfiltered (gdb_stdout,
1354                         "Start address 0x%s , load size %ld\n",
1355                         paddr_nz (entry), data_count);
1356     /* We were doing this in remote-mips.c, I suspect it is right
1357        for other targets too.  */
1358     write_pc (entry);
1359   }
1360
1361   /* FIXME: are we supposed to call symbol_file_add or not?  According to
1362      a comment from remote-mips.c (where a call to symbol_file_add was
1363      commented out), making the call confuses GDB if more than one file is
1364      loaded in.  remote-nindy.c had no call to symbol_file_add, but remote-vx.c
1365      does.  */
1366
1367   print_transfer_performance (gdb_stdout, data_count, write_count,
1368                               end_time - start_time);
1369
1370   do_cleanups (old_cleanups);
1371 }
1372
1373 /* Report how fast the transfer went. */
1374
1375 /* DEPRECATED: cagney/1999-10-18: report_transfer_performance is being
1376    replaced by print_transfer_performance (with a very different
1377    function signature). */
1378
1379 void
1380 report_transfer_performance (data_count, start_time, end_time)
1381      unsigned long data_count;
1382      time_t start_time, end_time;
1383 {
1384   print_transfer_performance (gdb_stdout, data_count, end_time - start_time, 0);
1385 }
1386
1387 void
1388 print_transfer_performance (struct gdb_file *stream,
1389                             unsigned long data_count,
1390                             unsigned long write_count,
1391                             unsigned long time_count)
1392 {
1393   fprintf_unfiltered (stream, "Transfer rate: ");
1394   if (time_count > 0)
1395     fprintf_unfiltered (stream, "%ld bits/sec", (data_count * 8) / time_count);
1396   else
1397     fprintf_unfiltered (stream, "%ld bits in <1 sec", (data_count * 8));
1398   if (write_count > 0)
1399     fprintf_unfiltered (stream, ", %ld bytes/write", data_count / write_count);
1400   fprintf_unfiltered (stream, ".\n");
1401 }
1402
1403 /* This function allows the addition of incrementally linked object files.
1404    It does not modify any state in the target, only in the debugger.  */
1405
1406 /* ARGSUSED */
1407 static void
1408 add_symbol_file_command (args, from_tty)
1409      char *args;
1410      int from_tty;
1411 {
1412   char *name = NULL;
1413   CORE_ADDR text_addr;
1414   int flags = OBJF_USERLOADED;
1415   char *arg;
1416   int expecting_option = 0;
1417   int option_index = 0;
1418   int argcnt = 0;
1419   int sec_num = 0;
1420   int i;
1421   struct
1422   {
1423     enum { OPT_SECTION } type;
1424     char *name;
1425     char *value;
1426   } opt[SECT_OFF_MAX];
1427   struct section_addr_info section_addrs;
1428
1429   dont_repeat ();
1430
1431   if (args == NULL)
1432     {
1433       error ("add-symbol-file takes a file name and an address");
1434     }
1435
1436   /* Make a copy of the string that we can safely write into. */
1437
1438   args = strdup (args);
1439   make_cleanup (free, args);
1440
1441   /* Ensure section_addrs is initialized */
1442   memset (&section_addrs, 0, sizeof (section_addrs));
1443
1444   /* Pick off any -option args and the file name. */
1445
1446   while (*args != '\000')
1447     {
1448       while (isspace (*args))
1449         {
1450           args++;
1451         }
1452       arg = args;
1453       while ((*args != '\000') && !isspace (*args))
1454         {
1455           args++;
1456         }
1457       if (*args != '\000')
1458         {
1459           *args++ = '\000';
1460         }
1461       if (*arg != '-')
1462         {
1463           if (expecting_option)
1464             {
1465               opt[option_index++].value = arg;
1466               expecting_option = 0;
1467             }
1468           else
1469             {
1470               switch (argcnt)
1471                 {
1472                 case 0:
1473                   name = arg;
1474                   break;
1475                 case 1: 
1476                   opt[option_index].type = OPT_SECTION;
1477                   opt[option_index].name = ".text";
1478                   opt[option_index++].value = arg;
1479                   break;
1480                 case 2: 
1481                   opt[option_index].type = OPT_SECTION;
1482                   opt[option_index].name = ".data";
1483                   opt[option_index++].value = arg;
1484                   break;
1485                 case 3: 
1486                   opt[option_index].type = OPT_SECTION;
1487                   opt[option_index].name = ".bss";
1488                   opt[option_index++].value = arg;
1489                   break;
1490                 default:
1491                   warning ("Too many arguments entered; see \"help add-symbol-file\" for command syntax.");
1492                 }
1493               argcnt++;
1494             }
1495         }
1496       else if (STREQ (arg, "-mapped"))
1497         {
1498           flags |= OBJF_MAPPED;
1499         }
1500       else if (STREQ (arg, "-readnow"))
1501         {
1502           flags |= OBJF_READNOW;
1503         }
1504       else if (STREQN (arg, "-T", 2))
1505         {
1506           if (option_index >= SECT_OFF_MAX)
1507             {
1508               warning ("Number of options exceeds maximum allowed.");
1509             }
1510           else
1511             {
1512               expecting_option = 1;
1513               opt[option_index].type = OPT_SECTION;
1514               opt[option_index].name = arg + 2;
1515             }
1516         }
1517       else 
1518         {
1519           error ("Unknown option `%s'", arg);
1520         }
1521     }
1522
1523   if (name == NULL)
1524     {
1525       error ("add-symbol-file takes a file name");
1526     }
1527   name = tilde_expand (name);
1528   make_cleanup (free, name);
1529
1530   if (option_index > 0)
1531     {
1532       /* Print the prompt for the query below.
1533          We have to split this up into 3 print statements because
1534          local_hex_string returns a local static string. */
1535  
1536       printf_filtered ("add symbol table from file \"%s\" at\n", name);
1537       for (i = 0; i < option_index; i++)
1538         {
1539           switch (opt[i].type)
1540             {
1541             case OPT_SECTION:
1542               {
1543                 CORE_ADDR addr;
1544                 char *val = opt[i].value;
1545                 char *sec = opt[i].name;
1546  
1547                 val = opt[i].value;
1548                 if (val[0] == '0' && val[1] == 'x')
1549                   addr = strtoul (val+2, NULL, 16);
1550                 else
1551                   addr = strtoul (val, NULL, 10);
1552  
1553                 if (strcmp (sec, ".text") == 0)
1554                   section_addrs.text_addr = addr;
1555                 else if (strcmp (sec, ".data") == 0)
1556                   section_addrs.data_addr = addr;
1557                 else if (strcmp (sec, ".bss") == 0)
1558                   section_addrs.bss_addr = addr;
1559                 /* Add the section to the others even if it is a
1560                    text data or bss section. This is redundent but
1561                    eventually, none will be given special treatment */
1562                 {
1563                   section_addrs.other[sec_num].name = strdup (sec);
1564                   make_cleanup (free, section_addrs.other[sec_num].name);
1565                   section_addrs.other[sec_num++].addr = addr;
1566                   printf_filtered ("\t%s_addr = %s\n",
1567                                    sec, 
1568                                    local_hex_string ((unsigned long)addr));
1569                 }
1570  
1571                 /* The object's sections are initialized when a 
1572                    call is made to build_objfile_section_table (objfile).
1573                    This happens in reread_symbols. 
1574                    At this point, we don't know what file type this is,
1575                    so we can't determine what section names are valid.  */
1576               }
1577               break;
1578             default:
1579               complain (&unknown_option_complaint, opt[i].name);
1580             }
1581         }
1582       /* Eventually, these hard coded names will be obsolete */
1583       /* All the addresses will be on the others section */
1584     }
1585   else
1586     {
1587       CORE_ADDR text_addr;
1588       target_link (name, &text_addr);  
1589       if (text_addr == (CORE_ADDR) -1)
1590         error("Don't know how to get text start location for this file");
1591       section_addrs.text_addr = text_addr;
1592       section_addrs.data_addr = 0;
1593       section_addrs.bss_addr = 0;
1594       printf_filtered("add symbol table from file \"%s\" at text_addr = %s?\n",
1595                       name, local_hex_string ((unsigned long)text_addr));
1596     }
1597   if (from_tty && (!query ("%s", "")))
1598     error ("Not confirmed.");
1599
1600   symbol_file_add (name, from_tty, &section_addrs, 0, flags);
1601
1602   /* Getting new symbols may change our opinion about what is
1603      frameless.  */
1604   reinit_frame_cache ();
1605 }
1606 \f
1607 static void
1608 add_shared_symbol_files_command (args, from_tty)
1609      char *args;
1610      int from_tty;
1611 {
1612 #ifdef ADD_SHARED_SYMBOL_FILES
1613   ADD_SHARED_SYMBOL_FILES (args, from_tty);
1614 #else
1615   error ("This command is not available in this configuration of GDB.");
1616 #endif
1617 }
1618 \f
1619 /* Re-read symbols if a symbol-file has changed.  */
1620 void
1621 reread_symbols ()
1622 {
1623   struct objfile *objfile;
1624   long new_modtime;
1625   int reread_one = 0;
1626   struct stat new_statbuf;
1627   int res;
1628
1629   /* With the addition of shared libraries, this should be modified,
1630      the load time should be saved in the partial symbol tables, since
1631      different tables may come from different source files.  FIXME.
1632      This routine should then walk down each partial symbol table
1633      and see if the symbol table that it originates from has been changed */
1634
1635   for (objfile = object_files; objfile; objfile = objfile->next)
1636     {
1637       if (objfile->obfd)
1638         {
1639 #ifdef IBM6000_TARGET
1640           /* If this object is from a shared library, then you should
1641              stat on the library name, not member name. */
1642
1643           if (objfile->obfd->my_archive)
1644             res = stat (objfile->obfd->my_archive->filename, &new_statbuf);
1645           else
1646 #endif
1647             res = stat (objfile->name, &new_statbuf);
1648           if (res != 0)
1649             {
1650               /* FIXME, should use print_sys_errmsg but it's not filtered. */
1651               printf_filtered ("`%s' has disappeared; keeping its symbols.\n",
1652                                objfile->name);
1653               continue;
1654             }
1655           new_modtime = new_statbuf.st_mtime;
1656           if (new_modtime != objfile->mtime)
1657             {
1658               struct cleanup *old_cleanups;
1659               struct section_offsets *offsets;
1660               int num_offsets;
1661               char *obfd_filename;
1662
1663               printf_filtered ("`%s' has changed; re-reading symbols.\n",
1664                                objfile->name);
1665
1666               /* There are various functions like symbol_file_add,
1667                  symfile_bfd_open, syms_from_objfile, etc., which might
1668                  appear to do what we want.  But they have various other
1669                  effects which we *don't* want.  So we just do stuff
1670                  ourselves.  We don't worry about mapped files (for one thing,
1671                  any mapped file will be out of date).  */
1672
1673               /* If we get an error, blow away this objfile (not sure if
1674                  that is the correct response for things like shared
1675                  libraries).  */
1676               old_cleanups = make_cleanup ((make_cleanup_func) free_objfile,
1677                                            objfile);
1678               /* We need to do this whenever any symbols go away.  */
1679               make_cleanup ((make_cleanup_func) clear_symtab_users, 0);
1680
1681               /* Clean up any state BFD has sitting around.  We don't need
1682                  to close the descriptor but BFD lacks a way of closing the
1683                  BFD without closing the descriptor.  */
1684               obfd_filename = bfd_get_filename (objfile->obfd);
1685               if (!bfd_close (objfile->obfd))
1686                 error ("Can't close BFD for %s: %s", objfile->name,
1687                        bfd_errmsg (bfd_get_error ()));
1688               objfile->obfd = bfd_openr (obfd_filename, gnutarget);
1689               if (objfile->obfd == NULL)
1690                 error ("Can't open %s to read symbols.", objfile->name);
1691               /* bfd_openr sets cacheable to true, which is what we want.  */
1692               if (!bfd_check_format (objfile->obfd, bfd_object))
1693                 error ("Can't read symbols from %s: %s.", objfile->name,
1694                        bfd_errmsg (bfd_get_error ()));
1695
1696               /* Save the offsets, we will nuke them with the rest of the
1697                  psymbol_obstack.  */
1698               num_offsets = objfile->num_sections;
1699               offsets = (struct section_offsets *) alloca (SIZEOF_SECTION_OFFSETS);
1700               memcpy (offsets, objfile->section_offsets, SIZEOF_SECTION_OFFSETS);
1701
1702               /* Nuke all the state that we will re-read.  Much of the following
1703                  code which sets things to NULL really is necessary to tell
1704                  other parts of GDB that there is nothing currently there.  */
1705
1706               /* FIXME: Do we have to free a whole linked list, or is this
1707                  enough?  */
1708               if (objfile->global_psymbols.list)
1709                 mfree (objfile->md, objfile->global_psymbols.list);
1710               memset (&objfile->global_psymbols, 0,
1711                       sizeof (objfile->global_psymbols));
1712               if (objfile->static_psymbols.list)
1713                 mfree (objfile->md, objfile->static_psymbols.list);
1714               memset (&objfile->static_psymbols, 0,
1715                       sizeof (objfile->static_psymbols));
1716
1717               /* Free the obstacks for non-reusable objfiles */
1718               obstack_free (&objfile->psymbol_cache.cache, 0);
1719               memset (&objfile->psymbol_cache, 0,
1720                       sizeof (objfile->psymbol_cache));
1721               obstack_free (&objfile->psymbol_obstack, 0);
1722               obstack_free (&objfile->symbol_obstack, 0);
1723               obstack_free (&objfile->type_obstack, 0);
1724               objfile->sections = NULL;
1725               objfile->symtabs = NULL;
1726               objfile->psymtabs = NULL;
1727               objfile->free_psymtabs = NULL;
1728               objfile->msymbols = NULL;
1729               objfile->minimal_symbol_count = 0;
1730               objfile->fundamental_types = NULL;
1731               if (objfile->sf != NULL)
1732                 {
1733                   (*objfile->sf->sym_finish) (objfile);
1734                 }
1735
1736               /* We never make this a mapped file.  */
1737               objfile->md = NULL;
1738               /* obstack_specify_allocation also initializes the obstack so
1739                  it is empty.  */
1740               obstack_specify_allocation (&objfile->psymbol_cache.cache, 0, 0,
1741                                           xmalloc, free);
1742               obstack_specify_allocation (&objfile->psymbol_obstack, 0, 0,
1743                                           xmalloc, free);
1744               obstack_specify_allocation (&objfile->symbol_obstack, 0, 0,
1745                                           xmalloc, free);
1746               obstack_specify_allocation (&objfile->type_obstack, 0, 0,
1747                                           xmalloc, free);
1748               if (build_objfile_section_table (objfile))
1749                 {
1750                   error ("Can't find the file sections in `%s': %s",
1751                          objfile->name, bfd_errmsg (bfd_get_error ()));
1752                 }
1753
1754               /* We use the same section offsets as from last time.  I'm not
1755                  sure whether that is always correct for shared libraries.  */
1756               objfile->section_offsets = (struct section_offsets *)
1757                 obstack_alloc (&objfile->psymbol_obstack, SIZEOF_SECTION_OFFSETS);
1758               memcpy (objfile->section_offsets, offsets, SIZEOF_SECTION_OFFSETS);
1759               objfile->num_sections = num_offsets;
1760
1761               /* What the hell is sym_new_init for, anyway?  The concept of
1762                  distinguishing between the main file and additional files
1763                  in this way seems rather dubious.  */
1764               if (objfile == symfile_objfile)
1765                 {
1766                   (*objfile->sf->sym_new_init) (objfile);
1767 #ifdef HPUXHPPA
1768                   RESET_HP_UX_GLOBALS ();
1769 #endif
1770                 }
1771
1772               (*objfile->sf->sym_init) (objfile);
1773               clear_complaints (1, 1);
1774               /* The "mainline" parameter is a hideous hack; I think leaving it
1775                  zero is OK since dbxread.c also does what it needs to do if
1776                  objfile->global_psymbols.size is 0.  */
1777               (*objfile->sf->sym_read) (objfile, 0);
1778               if (!have_partial_symbols () && !have_full_symbols ())
1779                 {
1780                   wrap_here ("");
1781                   printf_filtered ("(no debugging symbols found)\n");
1782                   wrap_here ("");
1783                 }
1784               objfile->flags |= OBJF_SYMS;
1785
1786               /* We're done reading the symbol file; finish off complaints.  */
1787               clear_complaints (0, 1);
1788
1789               /* Getting new symbols may change our opinion about what is
1790                  frameless.  */
1791
1792               reinit_frame_cache ();
1793
1794               /* Discard cleanups as symbol reading was successful.  */
1795               discard_cleanups (old_cleanups);
1796
1797               /* If the mtime has changed between the time we set new_modtime
1798                  and now, we *want* this to be out of date, so don't call stat
1799                  again now.  */
1800               objfile->mtime = new_modtime;
1801               reread_one = 1;
1802
1803               /* Call this after reading in a new symbol table to give target
1804                  dependant code a crack at the new symbols.  For instance, this
1805                  could be used to update the values of target-specific symbols GDB
1806                  needs to keep track of (such as _sigtramp, or whatever).  */
1807
1808               TARGET_SYMFILE_POSTREAD (objfile);
1809             }
1810         }
1811     }
1812
1813   if (reread_one)
1814     clear_symtab_users ();
1815 }
1816 \f
1817
1818
1819 typedef struct
1820 {
1821   char *ext;
1822   enum language lang;
1823 }
1824 filename_language;
1825
1826 static filename_language *filename_language_table;
1827 static int fl_table_size, fl_table_next;
1828
1829 static void
1830 add_filename_language (ext, lang)
1831      char *ext;
1832      enum language lang;
1833 {
1834   if (fl_table_next >= fl_table_size)
1835     {
1836       fl_table_size += 10;
1837       filename_language_table = realloc (filename_language_table,
1838                                          fl_table_size);
1839     }
1840
1841   filename_language_table[fl_table_next].ext = strsave (ext);
1842   filename_language_table[fl_table_next].lang = lang;
1843   fl_table_next++;
1844 }
1845
1846 static char *ext_args;
1847
1848 static void
1849 set_ext_lang_command (args, from_tty)
1850      char *args;
1851      int from_tty;
1852 {
1853   int i;
1854   char *cp = ext_args;
1855   enum language lang;
1856
1857   /* First arg is filename extension, starting with '.' */
1858   if (*cp != '.')
1859     error ("'%s': Filename extension must begin with '.'", ext_args);
1860
1861   /* Find end of first arg.  */
1862   while (*cp && !isspace (*cp))
1863     cp++;
1864
1865   if (*cp == '\0')
1866     error ("'%s': two arguments required -- filename extension and language",
1867            ext_args);
1868
1869   /* Null-terminate first arg */
1870   *cp++ = '\0';
1871
1872   /* Find beginning of second arg, which should be a source language.  */
1873   while (*cp && isspace (*cp))
1874     cp++;
1875
1876   if (*cp == '\0')
1877     error ("'%s': two arguments required -- filename extension and language",
1878            ext_args);
1879
1880   /* Lookup the language from among those we know.  */
1881   lang = language_enum (cp);
1882
1883   /* Now lookup the filename extension: do we already know it?  */
1884   for (i = 0; i < fl_table_next; i++)
1885     if (0 == strcmp (ext_args, filename_language_table[i].ext))
1886       break;
1887
1888   if (i >= fl_table_next)
1889     {
1890       /* new file extension */
1891       add_filename_language (ext_args, lang);
1892     }
1893   else
1894     {
1895       /* redefining a previously known filename extension */
1896
1897       /* if (from_tty) */
1898       /*   query ("Really make files of type %s '%s'?", */
1899       /*          ext_args, language_str (lang));           */
1900
1901       free (filename_language_table[i].ext);
1902       filename_language_table[i].ext = strsave (ext_args);
1903       filename_language_table[i].lang = lang;
1904     }
1905 }
1906
1907 static void
1908 info_ext_lang_command (args, from_tty)
1909      char *args;
1910      int from_tty;
1911 {
1912   int i;
1913
1914   printf_filtered ("Filename extensions and the languages they represent:");
1915   printf_filtered ("\n\n");
1916   for (i = 0; i < fl_table_next; i++)
1917     printf_filtered ("\t%s\t- %s\n",
1918                      filename_language_table[i].ext,
1919                      language_str (filename_language_table[i].lang));
1920 }
1921
1922 static void
1923 init_filename_language_table ()
1924 {
1925   if (fl_table_size == 0)       /* protect against repetition */
1926     {
1927       fl_table_size = 20;
1928       fl_table_next = 0;
1929       filename_language_table =
1930         xmalloc (fl_table_size * sizeof (*filename_language_table));
1931       add_filename_language (".c", language_c);
1932       add_filename_language (".C", language_cplus);
1933       add_filename_language (".cc", language_cplus);
1934       add_filename_language (".cp", language_cplus);
1935       add_filename_language (".cpp", language_cplus);
1936       add_filename_language (".cxx", language_cplus);
1937       add_filename_language (".c++", language_cplus);
1938       add_filename_language (".java", language_java);
1939       add_filename_language (".class", language_java);
1940       add_filename_language (".ch", language_chill);
1941       add_filename_language (".c186", language_chill);
1942       add_filename_language (".c286", language_chill);
1943       add_filename_language (".f", language_fortran);
1944       add_filename_language (".F", language_fortran);
1945       add_filename_language (".s", language_asm);
1946       add_filename_language (".S", language_asm);
1947     }
1948 }
1949
1950 enum language
1951 deduce_language_from_filename (filename)
1952      char *filename;
1953 {
1954   int i;
1955   char *cp;
1956
1957   if (filename != NULL)
1958     if ((cp = strrchr (filename, '.')) != NULL)
1959       for (i = 0; i < fl_table_next; i++)
1960         if (strcmp (cp, filename_language_table[i].ext) == 0)
1961           return filename_language_table[i].lang;
1962
1963   return language_unknown;
1964 }
1965 \f
1966 /* allocate_symtab:
1967
1968    Allocate and partly initialize a new symbol table.  Return a pointer
1969    to it.  error() if no space.
1970
1971    Caller must set these fields:
1972    LINETABLE(symtab)
1973    symtab->blockvector
1974    symtab->dirname
1975    symtab->free_code
1976    symtab->free_ptr
1977    possibly free_named_symtabs (symtab->filename);
1978  */
1979
1980 struct symtab *
1981 allocate_symtab (filename, objfile)
1982      char *filename;
1983      struct objfile *objfile;
1984 {
1985   register struct symtab *symtab;
1986
1987   symtab = (struct symtab *)
1988     obstack_alloc (&objfile->symbol_obstack, sizeof (struct symtab));
1989   memset (symtab, 0, sizeof (*symtab));
1990   symtab->filename = obsavestring (filename, strlen (filename),
1991                                    &objfile->symbol_obstack);
1992   symtab->fullname = NULL;
1993   symtab->language = deduce_language_from_filename (filename);
1994   symtab->debugformat = obsavestring ("unknown", 7,
1995                                       &objfile->symbol_obstack);
1996
1997   /* Hook it to the objfile it comes from */
1998
1999   symtab->objfile = objfile;
2000   symtab->next = objfile->symtabs;
2001   objfile->symtabs = symtab;
2002
2003   /* FIXME: This should go away.  It is only defined for the Z8000,
2004      and the Z8000 definition of this macro doesn't have anything to
2005      do with the now-nonexistent EXTRA_SYMTAB_INFO macro, it's just
2006      here for convenience.  */
2007 #ifdef INIT_EXTRA_SYMTAB_INFO
2008   INIT_EXTRA_SYMTAB_INFO (symtab);
2009 #endif
2010
2011   return (symtab);
2012 }
2013
2014 struct partial_symtab *
2015 allocate_psymtab (filename, objfile)
2016      char *filename;
2017      struct objfile *objfile;
2018 {
2019   struct partial_symtab *psymtab;
2020
2021   if (objfile->free_psymtabs)
2022     {
2023       psymtab = objfile->free_psymtabs;
2024       objfile->free_psymtabs = psymtab->next;
2025     }
2026   else
2027     psymtab = (struct partial_symtab *)
2028       obstack_alloc (&objfile->psymbol_obstack,
2029                      sizeof (struct partial_symtab));
2030
2031   memset (psymtab, 0, sizeof (struct partial_symtab));
2032   psymtab->filename = obsavestring (filename, strlen (filename),
2033                                     &objfile->psymbol_obstack);
2034   psymtab->symtab = NULL;
2035
2036   /* Prepend it to the psymtab list for the objfile it belongs to.
2037      Psymtabs are searched in most recent inserted -> least recent
2038      inserted order. */
2039
2040   psymtab->objfile = objfile;
2041   psymtab->next = objfile->psymtabs;
2042   objfile->psymtabs = psymtab;
2043 #if 0
2044   {
2045     struct partial_symtab **prev_pst;
2046     psymtab->objfile = objfile;
2047     psymtab->next = NULL;
2048     prev_pst = &(objfile->psymtabs);
2049     while ((*prev_pst) != NULL)
2050       prev_pst = &((*prev_pst)->next);
2051     (*prev_pst) = psymtab;
2052   }
2053 #endif
2054
2055   return (psymtab);
2056 }
2057
2058 void
2059 discard_psymtab (pst)
2060      struct partial_symtab *pst;
2061 {
2062   struct partial_symtab **prev_pst;
2063
2064   /* From dbxread.c:
2065      Empty psymtabs happen as a result of header files which don't
2066      have any symbols in them.  There can be a lot of them.  But this
2067      check is wrong, in that a psymtab with N_SLINE entries but
2068      nothing else is not empty, but we don't realize that.  Fixing
2069      that without slowing things down might be tricky.  */
2070
2071   /* First, snip it out of the psymtab chain */
2072
2073   prev_pst = &(pst->objfile->psymtabs);
2074   while ((*prev_pst) != pst)
2075     prev_pst = &((*prev_pst)->next);
2076   (*prev_pst) = pst->next;
2077
2078   /* Next, put it on a free list for recycling */
2079
2080   pst->next = pst->objfile->free_psymtabs;
2081   pst->objfile->free_psymtabs = pst;
2082 }
2083 \f
2084
2085 /* Reset all data structures in gdb which may contain references to symbol
2086    table data.  */
2087
2088 void
2089 clear_symtab_users ()
2090 {
2091   /* Someday, we should do better than this, by only blowing away
2092      the things that really need to be blown.  */
2093   clear_value_history ();
2094   clear_displays ();
2095   clear_internalvars ();
2096   breakpoint_re_set ();
2097   set_default_breakpoint (0, 0, 0, 0);
2098   current_source_symtab = 0;
2099   current_source_line = 0;
2100   clear_pc_function_cache ();
2101   if (target_new_objfile_hook)
2102     target_new_objfile_hook (NULL);
2103 }
2104
2105 /* clear_symtab_users_once:
2106
2107    This function is run after symbol reading, or from a cleanup.
2108    If an old symbol table was obsoleted, the old symbol table
2109    has been blown away, but the other GDB data structures that may 
2110    reference it have not yet been cleared or re-directed.  (The old
2111    symtab was zapped, and the cleanup queued, in free_named_symtab()
2112    below.)
2113
2114    This function can be queued N times as a cleanup, or called
2115    directly; it will do all the work the first time, and then will be a
2116    no-op until the next time it is queued.  This works by bumping a
2117    counter at queueing time.  Much later when the cleanup is run, or at
2118    the end of symbol processing (in case the cleanup is discarded), if
2119    the queued count is greater than the "done-count", we do the work
2120    and set the done-count to the queued count.  If the queued count is
2121    less than or equal to the done-count, we just ignore the call.  This
2122    is needed because reading a single .o file will often replace many
2123    symtabs (one per .h file, for example), and we don't want to reset
2124    the breakpoints N times in the user's face.
2125
2126    The reason we both queue a cleanup, and call it directly after symbol
2127    reading, is because the cleanup protects us in case of errors, but is
2128    discarded if symbol reading is successful.  */
2129
2130 #if 0
2131 /* FIXME:  As free_named_symtabs is currently a big noop this function
2132    is no longer needed.  */
2133 static void
2134 clear_symtab_users_once PARAMS ((void));
2135
2136 static int clear_symtab_users_queued;
2137 static int clear_symtab_users_done;
2138
2139 static void
2140 clear_symtab_users_once ()
2141 {
2142   /* Enforce once-per-`do_cleanups'-semantics */
2143   if (clear_symtab_users_queued <= clear_symtab_users_done)
2144     return;
2145   clear_symtab_users_done = clear_symtab_users_queued;
2146
2147   clear_symtab_users ();
2148 }
2149 #endif
2150
2151 /* Delete the specified psymtab, and any others that reference it.  */
2152
2153 static void
2154 cashier_psymtab (pst)
2155      struct partial_symtab *pst;
2156 {
2157   struct partial_symtab *ps, *pprev = NULL;
2158   int i;
2159
2160   /* Find its previous psymtab in the chain */
2161   for (ps = pst->objfile->psymtabs; ps; ps = ps->next)
2162     {
2163       if (ps == pst)
2164         break;
2165       pprev = ps;
2166     }
2167
2168   if (ps)
2169     {
2170       /* Unhook it from the chain.  */
2171       if (ps == pst->objfile->psymtabs)
2172         pst->objfile->psymtabs = ps->next;
2173       else
2174         pprev->next = ps->next;
2175
2176       /* FIXME, we can't conveniently deallocate the entries in the
2177          partial_symbol lists (global_psymbols/static_psymbols) that
2178          this psymtab points to.  These just take up space until all
2179          the psymtabs are reclaimed.  Ditto the dependencies list and
2180          filename, which are all in the psymbol_obstack.  */
2181
2182       /* We need to cashier any psymtab that has this one as a dependency... */
2183     again:
2184       for (ps = pst->objfile->psymtabs; ps; ps = ps->next)
2185         {
2186           for (i = 0; i < ps->number_of_dependencies; i++)
2187             {
2188               if (ps->dependencies[i] == pst)
2189                 {
2190                   cashier_psymtab (ps);
2191                   goto again;   /* Must restart, chain has been munged. */
2192                 }
2193             }
2194         }
2195     }
2196 }
2197
2198 /* If a symtab or psymtab for filename NAME is found, free it along
2199    with any dependent breakpoints, displays, etc.
2200    Used when loading new versions of object modules with the "add-file"
2201    command.  This is only called on the top-level symtab or psymtab's name;
2202    it is not called for subsidiary files such as .h files.
2203
2204    Return value is 1 if we blew away the environment, 0 if not.
2205    FIXME.  The return valu appears to never be used.
2206
2207    FIXME.  I think this is not the best way to do this.  We should
2208    work on being gentler to the environment while still cleaning up
2209    all stray pointers into the freed symtab.  */
2210
2211 int
2212 free_named_symtabs (name)
2213      char *name;
2214 {
2215 #if 0
2216   /* FIXME:  With the new method of each objfile having it's own
2217      psymtab list, this function needs serious rethinking.  In particular,
2218      why was it ever necessary to toss psymtabs with specific compilation
2219      unit filenames, as opposed to all psymtabs from a particular symbol
2220      file?  -- fnf
2221      Well, the answer is that some systems permit reloading of particular
2222      compilation units.  We want to blow away any old info about these
2223      compilation units, regardless of which objfiles they arrived in. --gnu.  */
2224
2225   register struct symtab *s;
2226   register struct symtab *prev;
2227   register struct partial_symtab *ps;
2228   struct blockvector *bv;
2229   int blewit = 0;
2230
2231   /* We only wack things if the symbol-reload switch is set.  */
2232   if (!symbol_reloading)
2233     return 0;
2234
2235   /* Some symbol formats have trouble providing file names... */
2236   if (name == 0 || *name == '\0')
2237     return 0;
2238
2239   /* Look for a psymtab with the specified name.  */
2240
2241 again2:
2242   for (ps = partial_symtab_list; ps; ps = ps->next)
2243     {
2244       if (STREQ (name, ps->filename))
2245         {
2246           cashier_psymtab (ps); /* Blow it away...and its little dog, too.  */
2247           goto again2;          /* Must restart, chain has been munged */
2248         }
2249     }
2250
2251   /* Look for a symtab with the specified name.  */
2252
2253   for (s = symtab_list; s; s = s->next)
2254     {
2255       if (STREQ (name, s->filename))
2256         break;
2257       prev = s;
2258     }
2259
2260   if (s)
2261     {
2262       if (s == symtab_list)
2263         symtab_list = s->next;
2264       else
2265         prev->next = s->next;
2266
2267       /* For now, queue a delete for all breakpoints, displays, etc., whether
2268          or not they depend on the symtab being freed.  This should be
2269          changed so that only those data structures affected are deleted.  */
2270
2271       /* But don't delete anything if the symtab is empty.
2272          This test is necessary due to a bug in "dbxread.c" that
2273          causes empty symtabs to be created for N_SO symbols that
2274          contain the pathname of the object file.  (This problem
2275          has been fixed in GDB 3.9x).  */
2276
2277       bv = BLOCKVECTOR (s);
2278       if (BLOCKVECTOR_NBLOCKS (bv) > 2
2279           || BLOCK_NSYMS (BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK))
2280           || BLOCK_NSYMS (BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK)))
2281         {
2282           complain (&oldsyms_complaint, name);
2283
2284           clear_symtab_users_queued++;
2285           make_cleanup (clear_symtab_users_once, 0);
2286           blewit = 1;
2287         }
2288       else
2289         {
2290           complain (&empty_symtab_complaint, name);
2291         }
2292
2293       free_symtab (s);
2294     }
2295   else
2296     {
2297       /* It is still possible that some breakpoints will be affected
2298          even though no symtab was found, since the file might have
2299          been compiled without debugging, and hence not be associated
2300          with a symtab.  In order to handle this correctly, we would need
2301          to keep a list of text address ranges for undebuggable files.
2302          For now, we do nothing, since this is a fairly obscure case.  */
2303       ;
2304     }
2305
2306   /* FIXME, what about the minimal symbol table? */
2307   return blewit;
2308 #else
2309   return (0);
2310 #endif
2311 }
2312 \f
2313 /* Allocate and partially fill a partial symtab.  It will be
2314    completely filled at the end of the symbol list.
2315
2316    FILENAME is the name of the symbol-file we are reading from. */
2317
2318 struct partial_symtab *
2319 start_psymtab_common (objfile, section_offsets,
2320                       filename, textlow, global_syms, static_syms)
2321      struct objfile *objfile;
2322      struct section_offsets *section_offsets;
2323      char *filename;
2324      CORE_ADDR textlow;
2325      struct partial_symbol **global_syms;
2326      struct partial_symbol **static_syms;
2327 {
2328   struct partial_symtab *psymtab;
2329
2330   psymtab = allocate_psymtab (filename, objfile);
2331   psymtab->section_offsets = section_offsets;
2332   psymtab->textlow = textlow;
2333   psymtab->texthigh = psymtab->textlow;         /* default */
2334   psymtab->globals_offset = global_syms - objfile->global_psymbols.list;
2335   psymtab->statics_offset = static_syms - objfile->static_psymbols.list;
2336   return (psymtab);
2337 }
2338 \f
2339 /* Add a symbol with a long value to a psymtab.
2340    Since one arg is a struct, we pass in a ptr and deref it (sigh).  */
2341
2342 void
2343 add_psymbol_to_list (name, namelength, namespace, class, list, val, coreaddr,
2344                      language, objfile)
2345      char *name;
2346      int namelength;
2347      namespace_enum namespace;
2348      enum address_class class;
2349      struct psymbol_allocation_list *list;
2350      long val;                  /* Value as a long */
2351      CORE_ADDR coreaddr;        /* Value as a CORE_ADDR */
2352      enum language language;
2353      struct objfile *objfile;
2354 {
2355   register struct partial_symbol *psym;
2356   char *buf = alloca (namelength + 1);
2357   /* psymbol is static so that there will be no uninitialized gaps in the
2358      structure which might contain random data, causing cache misses in
2359      bcache. */
2360   static struct partial_symbol psymbol;
2361
2362   /* Create local copy of the partial symbol */
2363   memcpy (buf, name, namelength);
2364   buf[namelength] = '\0';
2365   SYMBOL_NAME (&psymbol) = bcache (buf, namelength + 1, &objfile->psymbol_cache);
2366   /* val and coreaddr are mutually exclusive, one of them *will* be zero */
2367   if (val != 0)
2368     {
2369       SYMBOL_VALUE (&psymbol) = val;
2370     }
2371   else
2372     {
2373       SYMBOL_VALUE_ADDRESS (&psymbol) = coreaddr;
2374     }
2375   SYMBOL_SECTION (&psymbol) = 0;
2376   SYMBOL_LANGUAGE (&psymbol) = language;
2377   PSYMBOL_NAMESPACE (&psymbol) = namespace;
2378   PSYMBOL_CLASS (&psymbol) = class;
2379   SYMBOL_INIT_LANGUAGE_SPECIFIC (&psymbol, language);
2380
2381   /* Stash the partial symbol away in the cache */
2382   psym = bcache (&psymbol, sizeof (struct partial_symbol), &objfile->psymbol_cache);
2383
2384   /* Save pointer to partial symbol in psymtab, growing symtab if needed. */
2385   if (list->next >= list->list + list->size)
2386     {
2387       extend_psymbol_list (list, objfile);
2388     }
2389   *list->next++ = psym;
2390   OBJSTAT (objfile, n_psyms++);
2391 }
2392
2393 /* Add a symbol with a long value to a psymtab. This differs from
2394  * add_psymbol_to_list above in taking both a mangled and a demangled
2395  * name. */
2396
2397 void
2398 add_psymbol_with_dem_name_to_list (name, namelength, dem_name, dem_namelength,
2399                    namespace, class, list, val, coreaddr, language, objfile)
2400      char *name;
2401      int namelength;
2402      char *dem_name;
2403      int dem_namelength;
2404      namespace_enum namespace;
2405      enum address_class class;
2406      struct psymbol_allocation_list *list;
2407      long val;                  /* Value as a long */
2408      CORE_ADDR coreaddr;        /* Value as a CORE_ADDR */
2409      enum language language;
2410      struct objfile *objfile;
2411 {
2412   register struct partial_symbol *psym;
2413   char *buf = alloca (namelength + 1);
2414   /* psymbol is static so that there will be no uninitialized gaps in the
2415      structure which might contain random data, causing cache misses in
2416      bcache. */
2417   static struct partial_symbol psymbol;
2418
2419   /* Create local copy of the partial symbol */
2420
2421   memcpy (buf, name, namelength);
2422   buf[namelength] = '\0';
2423   SYMBOL_NAME (&psymbol) = bcache (buf, namelength + 1, &objfile->psymbol_cache);
2424
2425   buf = alloca (dem_namelength + 1);
2426   memcpy (buf, dem_name, dem_namelength);
2427   buf[dem_namelength] = '\0';
2428
2429   switch (language)
2430     {
2431     case language_c:
2432     case language_cplus:
2433       SYMBOL_CPLUS_DEMANGLED_NAME (&psymbol) =
2434         bcache (buf, dem_namelength + 1, &objfile->psymbol_cache);
2435       break;
2436     case language_chill:
2437       SYMBOL_CHILL_DEMANGLED_NAME (&psymbol) =
2438         bcache (buf, dem_namelength + 1, &objfile->psymbol_cache);
2439
2440       /* FIXME What should be done for the default case? Ignoring for now. */
2441     }
2442
2443   /* val and coreaddr are mutually exclusive, one of them *will* be zero */
2444   if (val != 0)
2445     {
2446       SYMBOL_VALUE (&psymbol) = val;
2447     }
2448   else
2449     {
2450       SYMBOL_VALUE_ADDRESS (&psymbol) = coreaddr;
2451     }
2452   SYMBOL_SECTION (&psymbol) = 0;
2453   SYMBOL_LANGUAGE (&psymbol) = language;
2454   PSYMBOL_NAMESPACE (&psymbol) = namespace;
2455   PSYMBOL_CLASS (&psymbol) = class;
2456   SYMBOL_INIT_LANGUAGE_SPECIFIC (&psymbol, language);
2457
2458   /* Stash the partial symbol away in the cache */
2459   psym = bcache (&psymbol, sizeof (struct partial_symbol), &objfile->psymbol_cache);
2460
2461   /* Save pointer to partial symbol in psymtab, growing symtab if needed. */
2462   if (list->next >= list->list + list->size)
2463     {
2464       extend_psymbol_list (list, objfile);
2465     }
2466   *list->next++ = psym;
2467   OBJSTAT (objfile, n_psyms++);
2468 }
2469
2470 /* Initialize storage for partial symbols.  */
2471
2472 void
2473 init_psymbol_list (objfile, total_symbols)
2474      struct objfile *objfile;
2475      int total_symbols;
2476 {
2477   /* Free any previously allocated psymbol lists.  */
2478
2479   if (objfile->global_psymbols.list)
2480     {
2481       mfree (objfile->md, (PTR) objfile->global_psymbols.list);
2482     }
2483   if (objfile->static_psymbols.list)
2484     {
2485       mfree (objfile->md, (PTR) objfile->static_psymbols.list);
2486     }
2487
2488   /* Current best guess is that approximately a twentieth
2489      of the total symbols (in a debugging file) are global or static
2490      oriented symbols */
2491
2492   objfile->global_psymbols.size = total_symbols / 10;
2493   objfile->static_psymbols.size = total_symbols / 10;
2494
2495   if (objfile->global_psymbols.size > 0)
2496     {
2497       objfile->global_psymbols.next =
2498         objfile->global_psymbols.list = (struct partial_symbol **)
2499         xmmalloc (objfile->md, (objfile->global_psymbols.size
2500                                 * sizeof (struct partial_symbol *)));
2501     }
2502   if (objfile->static_psymbols.size > 0)
2503     {
2504       objfile->static_psymbols.next =
2505         objfile->static_psymbols.list = (struct partial_symbol **)
2506         xmmalloc (objfile->md, (objfile->static_psymbols.size
2507                                 * sizeof (struct partial_symbol *)));
2508     }
2509 }
2510
2511 /* OVERLAYS:
2512    The following code implements an abstraction for debugging overlay sections.
2513
2514    The target model is as follows:
2515    1) The gnu linker will permit multiple sections to be mapped into the
2516    same VMA, each with its own unique LMA (or load address).
2517    2) It is assumed that some runtime mechanism exists for mapping the
2518    sections, one by one, from the load address into the VMA address.
2519    3) This code provides a mechanism for gdb to keep track of which 
2520    sections should be considered to be mapped from the VMA to the LMA.
2521    This information is used for symbol lookup, and memory read/write.
2522    For instance, if a section has been mapped then its contents 
2523    should be read from the VMA, otherwise from the LMA.
2524
2525    Two levels of debugger support for overlays are available.  One is
2526    "manual", in which the debugger relies on the user to tell it which
2527    overlays are currently mapped.  This level of support is
2528    implemented entirely in the core debugger, and the information about
2529    whether a section is mapped is kept in the objfile->obj_section table.
2530
2531    The second level of support is "automatic", and is only available if
2532    the target-specific code provides functionality to read the target's
2533    overlay mapping table, and translate its contents for the debugger
2534    (by updating the mapped state information in the obj_section tables).
2535
2536    The interface is as follows:
2537    User commands:
2538    overlay map <name>   -- tell gdb to consider this section mapped
2539    overlay unmap <name> -- tell gdb to consider this section unmapped
2540    overlay list         -- list the sections that GDB thinks are mapped
2541    overlay read-target  -- get the target's state of what's mapped
2542    overlay off/manual/auto -- set overlay debugging state
2543    Functional interface:
2544    find_pc_mapped_section(pc):    if the pc is in the range of a mapped
2545    section, return that section.
2546    find_pc_overlay(pc):       find any overlay section that contains 
2547    the pc, either in its VMA or its LMA
2548    overlay_is_mapped(sect):       true if overlay is marked as mapped
2549    section_is_overlay(sect):      true if section's VMA != LMA
2550    pc_in_mapped_range(pc,sec):    true if pc belongs to section's VMA
2551    pc_in_unmapped_range(...):     true if pc belongs to section's LMA
2552    overlay_mapped_address(...):   map an address from section's LMA to VMA
2553    overlay_unmapped_address(...): map an address from section's VMA to LMA
2554    symbol_overlayed_address(...): Return a "current" address for symbol:
2555    either in VMA or LMA depending on whether
2556    the symbol's section is currently mapped
2557  */
2558
2559 /* Overlay debugging state: */
2560
2561 int overlay_debugging = 0;      /* 0 == off, 1 == manual, -1 == auto */
2562 int overlay_cache_invalid = 0;  /* True if need to refresh mapped state */
2563
2564 /* Target vector for refreshing overlay mapped state */
2565 static void simple_overlay_update PARAMS ((struct obj_section *));
2566 void (*target_overlay_update) PARAMS ((struct obj_section *))
2567 = simple_overlay_update;
2568
2569 /* Function: section_is_overlay (SECTION)
2570    Returns true if SECTION has VMA not equal to LMA, ie. 
2571    SECTION is loaded at an address different from where it will "run".  */
2572
2573 int
2574 section_is_overlay (section)
2575      asection *section;
2576 {
2577   if (overlay_debugging)
2578     if (section && section->lma != 0 &&
2579         section->vma != section->lma)
2580       return 1;
2581
2582   return 0;
2583 }
2584
2585 /* Function: overlay_invalidate_all (void)
2586    Invalidate the mapped state of all overlay sections (mark it as stale).  */
2587
2588 static void
2589 overlay_invalidate_all ()
2590 {
2591   struct objfile *objfile;
2592   struct obj_section *sect;
2593
2594   ALL_OBJSECTIONS (objfile, sect)
2595     if (section_is_overlay (sect->the_bfd_section))
2596     sect->ovly_mapped = -1;
2597 }
2598
2599 /* Function: overlay_is_mapped (SECTION)
2600    Returns true if section is an overlay, and is currently mapped. 
2601    Private: public access is thru function section_is_mapped.
2602
2603    Access to the ovly_mapped flag is restricted to this function, so
2604    that we can do automatic update.  If the global flag
2605    OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call
2606    overlay_invalidate_all.  If the mapped state of the particular
2607    section is stale, then call TARGET_OVERLAY_UPDATE to refresh it.  */
2608
2609 static int
2610 overlay_is_mapped (osect)
2611      struct obj_section *osect;
2612 {
2613   if (osect == 0 || !section_is_overlay (osect->the_bfd_section))
2614     return 0;
2615
2616   switch (overlay_debugging)
2617     {
2618     default:
2619     case 0:
2620       return 0;                 /* overlay debugging off */
2621     case -1:                    /* overlay debugging automatic */
2622       /* Unles there is a target_overlay_update function, 
2623          there's really nothing useful to do here (can't really go auto)  */
2624       if (target_overlay_update)
2625         {
2626           if (overlay_cache_invalid)
2627             {
2628               overlay_invalidate_all ();
2629               overlay_cache_invalid = 0;
2630             }
2631           if (osect->ovly_mapped == -1)
2632             (*target_overlay_update) (osect);
2633         }
2634       /* fall thru to manual case */
2635     case 1:                     /* overlay debugging manual */
2636       return osect->ovly_mapped == 1;
2637     }
2638 }
2639
2640 /* Function: section_is_mapped
2641    Returns true if section is an overlay, and is currently mapped.  */
2642
2643 int
2644 section_is_mapped (section)
2645      asection *section;
2646 {
2647   struct objfile *objfile;
2648   struct obj_section *osect;
2649
2650   if (overlay_debugging)
2651     if (section && section_is_overlay (section))
2652       ALL_OBJSECTIONS (objfile, osect)
2653         if (osect->the_bfd_section == section)
2654         return overlay_is_mapped (osect);
2655
2656   return 0;
2657 }
2658
2659 /* Function: pc_in_unmapped_range
2660    If PC falls into the lma range of SECTION, return true, else false.  */
2661
2662 CORE_ADDR
2663 pc_in_unmapped_range (pc, section)
2664      CORE_ADDR pc;
2665      asection *section;
2666 {
2667   int size;
2668
2669   if (overlay_debugging)
2670     if (section && section_is_overlay (section))
2671       {
2672         size = bfd_get_section_size_before_reloc (section);
2673         if (section->lma <= pc && pc < section->lma + size)
2674           return 1;
2675       }
2676   return 0;
2677 }
2678
2679 /* Function: pc_in_mapped_range
2680    If PC falls into the vma range of SECTION, return true, else false.  */
2681
2682 CORE_ADDR
2683 pc_in_mapped_range (pc, section)
2684      CORE_ADDR pc;
2685      asection *section;
2686 {
2687   int size;
2688
2689   if (overlay_debugging)
2690     if (section && section_is_overlay (section))
2691       {
2692         size = bfd_get_section_size_before_reloc (section);
2693         if (section->vma <= pc && pc < section->vma + size)
2694           return 1;
2695       }
2696   return 0;
2697 }
2698
2699 /* Function: overlay_unmapped_address (PC, SECTION)
2700    Returns the address corresponding to PC in the unmapped (load) range.
2701    May be the same as PC.  */
2702
2703 CORE_ADDR
2704 overlay_unmapped_address (pc, section)
2705      CORE_ADDR pc;
2706      asection *section;
2707 {
2708   if (overlay_debugging)
2709     if (section && section_is_overlay (section) &&
2710         pc_in_mapped_range (pc, section))
2711       return pc + section->lma - section->vma;
2712
2713   return pc;
2714 }
2715
2716 /* Function: overlay_mapped_address (PC, SECTION)
2717    Returns the address corresponding to PC in the mapped (runtime) range.
2718    May be the same as PC.  */
2719
2720 CORE_ADDR
2721 overlay_mapped_address (pc, section)
2722      CORE_ADDR pc;
2723      asection *section;
2724 {
2725   if (overlay_debugging)
2726     if (section && section_is_overlay (section) &&
2727         pc_in_unmapped_range (pc, section))
2728       return pc + section->vma - section->lma;
2729
2730   return pc;
2731 }
2732
2733
2734 /* Function: symbol_overlayed_address 
2735    Return one of two addresses (relative to the VMA or to the LMA),
2736    depending on whether the section is mapped or not.  */
2737
2738 CORE_ADDR
2739 symbol_overlayed_address (address, section)
2740      CORE_ADDR address;
2741      asection *section;
2742 {
2743   if (overlay_debugging)
2744     {
2745       /* If the symbol has no section, just return its regular address. */
2746       if (section == 0)
2747         return address;
2748       /* If the symbol's section is not an overlay, just return its address */
2749       if (!section_is_overlay (section))
2750         return address;
2751       /* If the symbol's section is mapped, just return its address */
2752       if (section_is_mapped (section))
2753         return address;
2754       /*
2755        * HOWEVER: if the symbol is in an overlay section which is NOT mapped,
2756        * then return its LOADED address rather than its vma address!!
2757        */
2758       return overlay_unmapped_address (address, section);
2759     }
2760   return address;
2761 }
2762
2763 /* Function: find_pc_overlay (PC) 
2764    Return the best-match overlay section for PC:
2765    If PC matches a mapped overlay section's VMA, return that section.
2766    Else if PC matches an unmapped section's VMA, return that section.
2767    Else if PC matches an unmapped section's LMA, return that section.  */
2768
2769 asection *
2770 find_pc_overlay (pc)
2771      CORE_ADDR pc;
2772 {
2773   struct objfile *objfile;
2774   struct obj_section *osect, *best_match = NULL;
2775
2776   if (overlay_debugging)
2777     ALL_OBJSECTIONS (objfile, osect)
2778       if (section_is_overlay (osect->the_bfd_section))
2779       {
2780         if (pc_in_mapped_range (pc, osect->the_bfd_section))
2781           {
2782             if (overlay_is_mapped (osect))
2783               return osect->the_bfd_section;
2784             else
2785               best_match = osect;
2786           }
2787         else if (pc_in_unmapped_range (pc, osect->the_bfd_section))
2788           best_match = osect;
2789       }
2790   return best_match ? best_match->the_bfd_section : NULL;
2791 }
2792
2793 /* Function: find_pc_mapped_section (PC)
2794    If PC falls into the VMA address range of an overlay section that is 
2795    currently marked as MAPPED, return that section.  Else return NULL.  */
2796
2797 asection *
2798 find_pc_mapped_section (pc)
2799      CORE_ADDR pc;
2800 {
2801   struct objfile *objfile;
2802   struct obj_section *osect;
2803
2804   if (overlay_debugging)
2805     ALL_OBJSECTIONS (objfile, osect)
2806       if (pc_in_mapped_range (pc, osect->the_bfd_section) &&
2807           overlay_is_mapped (osect))
2808       return osect->the_bfd_section;
2809
2810   return NULL;
2811 }
2812
2813 /* Function: list_overlays_command
2814    Print a list of mapped sections and their PC ranges */
2815
2816 void
2817 list_overlays_command (args, from_tty)
2818      char *args;
2819      int from_tty;
2820 {
2821   int nmapped = 0;
2822   struct objfile *objfile;
2823   struct obj_section *osect;
2824
2825   if (overlay_debugging)
2826     ALL_OBJSECTIONS (objfile, osect)
2827       if (overlay_is_mapped (osect))
2828       {
2829         const char *name;
2830         bfd_vma lma, vma;
2831         int size;
2832
2833         vma = bfd_section_vma (objfile->obfd, osect->the_bfd_section);
2834         lma = bfd_section_lma (objfile->obfd, osect->the_bfd_section);
2835         size = bfd_get_section_size_before_reloc (osect->the_bfd_section);
2836         name = bfd_section_name (objfile->obfd, osect->the_bfd_section);
2837
2838         printf_filtered ("Section %s, loaded at ", name);
2839         print_address_numeric (lma, 1, gdb_stdout);
2840         puts_filtered (" - ");
2841         print_address_numeric (lma + size, 1, gdb_stdout);
2842         printf_filtered (", mapped at ");
2843         print_address_numeric (vma, 1, gdb_stdout);
2844         puts_filtered (" - ");
2845         print_address_numeric (vma + size, 1, gdb_stdout);
2846         puts_filtered ("\n");
2847
2848         nmapped++;
2849       }
2850   if (nmapped == 0)
2851     printf_filtered ("No sections are mapped.\n");
2852 }
2853
2854 /* Function: map_overlay_command
2855    Mark the named section as mapped (ie. residing at its VMA address).  */
2856
2857 void
2858 map_overlay_command (args, from_tty)
2859      char *args;
2860      int from_tty;
2861 {
2862   struct objfile *objfile, *objfile2;
2863   struct obj_section *sec, *sec2;
2864   asection *bfdsec;
2865
2866   if (!overlay_debugging)
2867     error ("Overlay debugging not enabled.  Use the 'OVERLAY ON' command.");
2868
2869   if (args == 0 || *args == 0)
2870     error ("Argument required: name of an overlay section");
2871
2872   /* First, find a section matching the user supplied argument */
2873   ALL_OBJSECTIONS (objfile, sec)
2874     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
2875     {
2876       /* Now, check to see if the section is an overlay. */
2877       bfdsec = sec->the_bfd_section;
2878       if (!section_is_overlay (bfdsec))
2879         continue;               /* not an overlay section */
2880
2881       /* Mark the overlay as "mapped" */
2882       sec->ovly_mapped = 1;
2883
2884       /* Next, make a pass and unmap any sections that are
2885          overlapped by this new section: */
2886       ALL_OBJSECTIONS (objfile2, sec2)
2887         if (sec2->ovly_mapped &&
2888             sec != sec2 &&
2889             sec->the_bfd_section != sec2->the_bfd_section &&
2890             (pc_in_mapped_range (sec2->addr, sec->the_bfd_section) ||
2891              pc_in_mapped_range (sec2->endaddr, sec->the_bfd_section)))
2892         {
2893           if (info_verbose)
2894             printf_filtered ("Note: section %s unmapped by overlap\n",
2895                              bfd_section_name (objfile->obfd,
2896                                                sec2->the_bfd_section));
2897           sec2->ovly_mapped = 0;        /* sec2 overlaps sec: unmap sec2 */
2898         }
2899       return;
2900     }
2901   error ("No overlay section called %s", args);
2902 }
2903
2904 /* Function: unmap_overlay_command
2905    Mark the overlay section as unmapped 
2906    (ie. resident in its LMA address range, rather than the VMA range).  */
2907
2908 void
2909 unmap_overlay_command (args, from_tty)
2910      char *args;
2911      int from_tty;
2912 {
2913   struct objfile *objfile;
2914   struct obj_section *sec;
2915
2916   if (!overlay_debugging)
2917     error ("Overlay debugging not enabled.  Use the 'OVERLAY ON' command.");
2918
2919   if (args == 0 || *args == 0)
2920     error ("Argument required: name of an overlay section");
2921
2922   /* First, find a section matching the user supplied argument */
2923   ALL_OBJSECTIONS (objfile, sec)
2924     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
2925     {
2926       if (!sec->ovly_mapped)
2927         error ("Section %s is not mapped", args);
2928       sec->ovly_mapped = 0;
2929       return;
2930     }
2931   error ("No overlay section called %s", args);
2932 }
2933
2934 /* Function: overlay_auto_command
2935    A utility command to turn on overlay debugging.
2936    Possibly this should be done via a set/show command. */
2937
2938 static void
2939 overlay_auto_command (args, from_tty)
2940      char *args;
2941      int from_tty;
2942 {
2943   overlay_debugging = -1;
2944   if (info_verbose)
2945     printf_filtered ("Automatic overlay debugging enabled.");
2946 }
2947
2948 /* Function: overlay_manual_command
2949    A utility command to turn on overlay debugging.
2950    Possibly this should be done via a set/show command. */
2951
2952 static void
2953 overlay_manual_command (args, from_tty)
2954      char *args;
2955      int from_tty;
2956 {
2957   overlay_debugging = 1;
2958   if (info_verbose)
2959     printf_filtered ("Overlay debugging enabled.");
2960 }
2961
2962 /* Function: overlay_off_command
2963    A utility command to turn on overlay debugging.
2964    Possibly this should be done via a set/show command. */
2965
2966 static void
2967 overlay_off_command (args, from_tty)
2968      char *args;
2969      int from_tty;
2970 {
2971   overlay_debugging = 0;
2972   if (info_verbose)
2973     printf_filtered ("Overlay debugging disabled.");
2974 }
2975
2976 static void
2977 overlay_load_command (args, from_tty)
2978      char *args;
2979      int from_tty;
2980 {
2981   if (target_overlay_update)
2982     (*target_overlay_update) (NULL);
2983   else
2984     error ("This target does not know how to read its overlay state.");
2985 }
2986
2987 /* Function: overlay_command
2988    A place-holder for a mis-typed command */
2989
2990 /* Command list chain containing all defined "overlay" subcommands. */
2991 struct cmd_list_element *overlaylist;
2992
2993 static void
2994 overlay_command (args, from_tty)
2995      char *args;
2996      int from_tty;
2997 {
2998   printf_unfiltered
2999     ("\"overlay\" must be followed by the name of an overlay command.\n");
3000   help_list (overlaylist, "overlay ", -1, gdb_stdout);
3001 }
3002
3003
3004 /* Target Overlays for the "Simplest" overlay manager:
3005
3006    This is GDB's default target overlay layer.  It works with the 
3007    minimal overlay manager supplied as an example by Cygnus.  The 
3008    entry point is via a function pointer "target_overlay_update", 
3009    so targets that use a different runtime overlay manager can 
3010    substitute their own overlay_update function and take over the
3011    function pointer.
3012
3013    The overlay_update function pokes around in the target's data structures
3014    to see what overlays are mapped, and updates GDB's overlay mapping with
3015    this information.
3016
3017    In this simple implementation, the target data structures are as follows:
3018    unsigned _novlys;            /# number of overlay sections #/
3019    unsigned _ovly_table[_novlys][4] = {
3020    {VMA, SIZE, LMA, MAPPED},    /# one entry per overlay section #/
3021    {..., ...,  ..., ...},
3022    }
3023    unsigned _novly_regions;     /# number of overlay regions #/
3024    unsigned _ovly_region_table[_novly_regions][3] = {
3025    {VMA, SIZE, MAPPED_TO_LMA},  /# one entry per overlay region #/
3026    {..., ...,  ...},
3027    }
3028    These functions will attempt to update GDB's mappedness state in the
3029    symbol section table, based on the target's mappedness state.
3030
3031    To do this, we keep a cached copy of the target's _ovly_table, and
3032    attempt to detect when the cached copy is invalidated.  The main
3033    entry point is "simple_overlay_update(SECT), which looks up SECT in
3034    the cached table and re-reads only the entry for that section from
3035    the target (whenever possible).
3036  */
3037
3038 /* Cached, dynamically allocated copies of the target data structures: */
3039 static unsigned (*cache_ovly_table)[4] = 0;
3040 #if 0
3041 static unsigned (*cache_ovly_region_table)[3] = 0;
3042 #endif
3043 static unsigned cache_novlys = 0;
3044 #if 0
3045 static unsigned cache_novly_regions = 0;
3046 #endif
3047 static CORE_ADDR cache_ovly_table_base = 0;
3048 #if 0
3049 static CORE_ADDR cache_ovly_region_table_base = 0;
3050 #endif
3051 enum ovly_index
3052   {
3053     VMA, SIZE, LMA, MAPPED
3054   };
3055 #define TARGET_LONG_BYTES (TARGET_LONG_BIT / TARGET_CHAR_BIT)
3056
3057 /* Throw away the cached copy of _ovly_table */
3058 static void
3059 simple_free_overlay_table ()
3060 {
3061   if (cache_ovly_table)
3062     free (cache_ovly_table);
3063   cache_novlys = 0;
3064   cache_ovly_table = NULL;
3065   cache_ovly_table_base = 0;
3066 }
3067
3068 #if 0
3069 /* Throw away the cached copy of _ovly_region_table */
3070 static void
3071 simple_free_overlay_region_table ()
3072 {
3073   if (cache_ovly_region_table)
3074     free (cache_ovly_region_table);
3075   cache_novly_regions = 0;
3076   cache_ovly_region_table = NULL;
3077   cache_ovly_region_table_base = 0;
3078 }
3079 #endif
3080
3081 /* Read an array of ints from the target into a local buffer.
3082    Convert to host order.  int LEN is number of ints  */
3083 static void
3084 read_target_long_array (memaddr, myaddr, len)
3085      CORE_ADDR memaddr;
3086      unsigned int *myaddr;
3087      int len;
3088 {
3089   char *buf = alloca (len * TARGET_LONG_BYTES);
3090   int i;
3091
3092   read_memory (memaddr, buf, len * TARGET_LONG_BYTES);
3093   for (i = 0; i < len; i++)
3094     myaddr[i] = extract_unsigned_integer (TARGET_LONG_BYTES * i + buf,
3095                                           TARGET_LONG_BYTES);
3096 }
3097
3098 /* Find and grab a copy of the target _ovly_table
3099    (and _novlys, which is needed for the table's size) */
3100 static int
3101 simple_read_overlay_table ()
3102 {
3103   struct minimal_symbol *msym;
3104
3105   simple_free_overlay_table ();
3106   msym = lookup_minimal_symbol ("_novlys", 0, 0);
3107   if (msym != NULL)
3108     cache_novlys = read_memory_integer (SYMBOL_VALUE_ADDRESS (msym), 4);
3109   else
3110     return 0;                   /* failure */
3111   cache_ovly_table = (void *) xmalloc (cache_novlys * sizeof (*cache_ovly_table));
3112   if (cache_ovly_table != NULL)
3113     {
3114       msym = lookup_minimal_symbol ("_ovly_table", 0, 0);
3115       if (msym != NULL)
3116         {
3117           cache_ovly_table_base = SYMBOL_VALUE_ADDRESS (msym);
3118           read_target_long_array (cache_ovly_table_base,
3119                                   (int *) cache_ovly_table,
3120                                   cache_novlys * 4);
3121         }
3122       else
3123         return 0;               /* failure */
3124     }
3125   else
3126     return 0;                   /* failure */
3127   return 1;                     /* SUCCESS */
3128 }
3129
3130 #if 0
3131 /* Find and grab a copy of the target _ovly_region_table
3132    (and _novly_regions, which is needed for the table's size) */
3133 static int
3134 simple_read_overlay_region_table ()
3135 {
3136   struct minimal_symbol *msym;
3137
3138   simple_free_overlay_region_table ();
3139   msym = lookup_minimal_symbol ("_novly_regions", 0, 0);
3140   if (msym != NULL)
3141     cache_novly_regions = read_memory_integer (SYMBOL_VALUE_ADDRESS (msym), 4);
3142   else
3143     return 0;                   /* failure */
3144   cache_ovly_region_table = (void *) xmalloc (cache_novly_regions * 12);
3145   if (cache_ovly_region_table != NULL)
3146     {
3147       msym = lookup_minimal_symbol ("_ovly_region_table", 0, 0);
3148       if (msym != NULL)
3149         {
3150           cache_ovly_region_table_base = SYMBOL_VALUE_ADDRESS (msym);
3151           read_target_long_array (cache_ovly_region_table_base,
3152                                   (int *) cache_ovly_region_table,
3153                                   cache_novly_regions * 3);
3154         }
3155       else
3156         return 0;               /* failure */
3157     }
3158   else
3159     return 0;                   /* failure */
3160   return 1;                     /* SUCCESS */
3161 }
3162 #endif
3163
3164 /* Function: simple_overlay_update_1 
3165    A helper function for simple_overlay_update.  Assuming a cached copy
3166    of _ovly_table exists, look through it to find an entry whose vma,
3167    lma and size match those of OSECT.  Re-read the entry and make sure
3168    it still matches OSECT (else the table may no longer be valid).
3169    Set OSECT's mapped state to match the entry.  Return: 1 for
3170    success, 0 for failure.  */
3171
3172 static int
3173 simple_overlay_update_1 (osect)
3174      struct obj_section *osect;
3175 {
3176   int i, size;
3177
3178   size = bfd_get_section_size_before_reloc (osect->the_bfd_section);
3179   for (i = 0; i < cache_novlys; i++)
3180     if (cache_ovly_table[i][VMA] == osect->the_bfd_section->vma &&
3181         cache_ovly_table[i][LMA] == osect->the_bfd_section->lma         /* &&
3182                                                                            cache_ovly_table[i][SIZE] == size */ )
3183       {
3184         read_target_long_array (cache_ovly_table_base + i * TARGET_LONG_BYTES,
3185                                 (int *) cache_ovly_table[i], 4);
3186         if (cache_ovly_table[i][VMA] == osect->the_bfd_section->vma &&
3187             cache_ovly_table[i][LMA] == osect->the_bfd_section->lma     /* &&
3188                                                                            cache_ovly_table[i][SIZE] == size */ )
3189           {
3190             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
3191             return 1;
3192           }
3193         else                    /* Warning!  Warning!  Target's ovly table has changed! */
3194           return 0;
3195       }
3196   return 0;
3197 }
3198
3199 /* Function: simple_overlay_update
3200    If OSECT is NULL, then update all sections' mapped state 
3201    (after re-reading the entire target _ovly_table). 
3202    If OSECT is non-NULL, then try to find a matching entry in the 
3203    cached ovly_table and update only OSECT's mapped state.
3204    If a cached entry can't be found or the cache isn't valid, then 
3205    re-read the entire cache, and go ahead and update all sections.  */
3206
3207 static void
3208 simple_overlay_update (osect)
3209      struct obj_section *osect;
3210 {
3211   struct objfile *objfile;
3212
3213   /* Were we given an osect to look up?  NULL means do all of them. */
3214   if (osect)
3215     /* Have we got a cached copy of the target's overlay table? */
3216     if (cache_ovly_table != NULL)
3217       /* Does its cached location match what's currently in the symtab? */
3218       if (cache_ovly_table_base ==
3219           SYMBOL_VALUE_ADDRESS (lookup_minimal_symbol ("_ovly_table", 0, 0)))
3220         /* Then go ahead and try to look up this single section in the cache */
3221         if (simple_overlay_update_1 (osect))
3222           /* Found it!  We're done. */
3223           return;
3224
3225   /* Cached table no good: need to read the entire table anew.
3226      Or else we want all the sections, in which case it's actually
3227      more efficient to read the whole table in one block anyway.  */
3228
3229   if (simple_read_overlay_table () == 0)        /* read failed?  No table? */
3230     {
3231       warning ("Failed to read the target overlay mapping table.");
3232       return;
3233     }
3234   /* Now may as well update all sections, even if only one was requested. */
3235   ALL_OBJSECTIONS (objfile, osect)
3236     if (section_is_overlay (osect->the_bfd_section))
3237     {
3238       int i, size;
3239
3240       size = bfd_get_section_size_before_reloc (osect->the_bfd_section);
3241       for (i = 0; i < cache_novlys; i++)
3242         if (cache_ovly_table[i][VMA] == osect->the_bfd_section->vma &&
3243             cache_ovly_table[i][LMA] == osect->the_bfd_section->lma     /* &&
3244                                                                            cache_ovly_table[i][SIZE] == size */ )
3245           {                     /* obj_section matches i'th entry in ovly_table */
3246             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
3247             break;              /* finished with inner for loop: break out */
3248           }
3249     }
3250 }
3251
3252
3253 void
3254 _initialize_symfile ()
3255 {
3256   struct cmd_list_element *c;
3257
3258   c = add_cmd ("symbol-file", class_files, symbol_file_command,
3259                "Load symbol table from executable file FILE.\n\
3260 The `file' command can also load symbol tables, as well as setting the file\n\
3261 to execute.", &cmdlist);
3262   c->completer = filename_completer;
3263
3264   c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command,
3265                "Usage: add-symbol-file FILE ADDR [DATA_ADDR [BSS_ADDR]]\n\
3266 or:    add-symbol-file FILE -T<SECT> <SECT_ADDR> -T<SECT> <SECT_ADDR> ...\n\
3267 Load the symbols from FILE, assuming FILE has been dynamically loaded.\n\
3268 ADDR is the starting address of the file's text.\n\
3269 The optional arguments, DATA_ADDR and BSS_ADDR, should be specified\n\
3270 if the data and bss segments are not contiguous with the text.\n\
3271 For complicated cases, SECT is a section name to be loaded at SECT_ADDR.",
3272                &cmdlist);
3273   c->completer = filename_completer;
3274
3275   c = add_cmd ("add-shared-symbol-files", class_files,
3276                add_shared_symbol_files_command,
3277    "Load the symbols from shared objects in the dynamic linker's link map.",
3278                &cmdlist);
3279   c = add_alias_cmd ("assf", "add-shared-symbol-files", class_files, 1,
3280                      &cmdlist);
3281
3282   c = add_cmd ("load", class_files, load_command,
3283                "Dynamically load FILE into the running program, and record its symbols\n\
3284 for access from GDB.", &cmdlist);
3285   c->completer = filename_completer;
3286
3287   add_show_from_set
3288     (add_set_cmd ("symbol-reloading", class_support, var_boolean,
3289                   (char *) &symbol_reloading,
3290             "Set dynamic symbol table reloading multiple times in one run.",
3291                   &setlist),
3292      &showlist);
3293
3294   add_prefix_cmd ("overlay", class_support, overlay_command,
3295                   "Commands for debugging overlays.", &overlaylist,
3296                   "overlay ", 0, &cmdlist);
3297
3298   add_com_alias ("ovly", "overlay", class_alias, 1);
3299   add_com_alias ("ov", "overlay", class_alias, 1);
3300
3301   add_cmd ("map-overlay", class_support, map_overlay_command,
3302            "Assert that an overlay section is mapped.", &overlaylist);
3303
3304   add_cmd ("unmap-overlay", class_support, unmap_overlay_command,
3305            "Assert that an overlay section is unmapped.", &overlaylist);
3306
3307   add_cmd ("list-overlays", class_support, list_overlays_command,
3308            "List mappings of overlay sections.", &overlaylist);
3309
3310   add_cmd ("manual", class_support, overlay_manual_command,
3311            "Enable overlay debugging.", &overlaylist);
3312   add_cmd ("off", class_support, overlay_off_command,
3313            "Disable overlay debugging.", &overlaylist);
3314   add_cmd ("auto", class_support, overlay_auto_command,
3315            "Enable automatic overlay debugging.", &overlaylist);
3316   add_cmd ("load-target", class_support, overlay_load_command,
3317            "Read the overlay mapping state from the target.", &overlaylist);
3318
3319   /* Filename extension to source language lookup table: */
3320   init_filename_language_table ();
3321   c = add_set_cmd ("extension-language", class_files, var_string_noescape,
3322                    (char *) &ext_args,
3323                    "Set mapping between filename extension and source language.\n\
3324 Usage: set extension-language .foo bar",
3325                    &setlist);
3326   c->function.cfunc = set_ext_lang_command;
3327
3328   add_info ("extensions", info_ext_lang_command,
3329             "All filename extensions associated with a source language.");
3330
3331   add_show_from_set
3332     (add_set_cmd ("download-write-size", class_obscure,
3333                   var_integer, (char *) &download_write_size,
3334                   "Set the write size used when downloading a program.\n"
3335                   "Only used when downloading a program onto a remote\n"
3336                   "target. Specify zero, or a negative value, to disable\n"
3337                   "blocked writes. The actual size of each transfer is also\n"
3338                   "limited by the size of the target packet and the memory\n"
3339                   "cache.\n",
3340                   &setlist),
3341      &showlist);
3342 }