OSDN Git Service

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