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