* symfile.c (generic_load): Check return code of target_write_memory.
[external/binutils.git] / gdb / symfile.c
1 /* Generic symbol file reading for the GNU debugger, GDB.
2    Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1996
3    Free Software Foundation, Inc.
4    Contributed by Cygnus Support, using pieces from other GDB modules.
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330, 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
40 #include <assert.h>
41 #include <sys/types.h>
42 #include <fcntl.h>
43 #include "gdb_string.h"
44 #include "gdb_stat.h"
45 #include <ctype.h>
46 #include <time.h>
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 #ifndef O_BINARY
52 #define O_BINARY 0
53 #endif
54
55 /* Global variables owned by this file */
56 int readnow_symbol_files;               /* Read full symbols immediately */
57
58 struct complaint oldsyms_complaint = {
59   "Replacing old symbols for `%s'", 0, 0
60 };
61
62 struct complaint empty_symtab_complaint = {
63   "Empty symbol table found for `%s'", 0, 0
64 };
65
66 /* External variables and functions referenced. */
67
68 extern int info_verbose;
69
70 extern void report_transfer_performance PARAMS ((unsigned long,
71                                                  time_t, time_t));
72
73 /* Functions this file defines */
74
75 #if 0
76 static int simple_read_overlay_region_table PARAMS ((void));
77 static void simple_free_overlay_region_table PARAMS ((void));
78 #endif
79
80 static void set_initial_language PARAMS ((void));
81
82 static void load_command PARAMS ((char *, int));
83
84 static void add_symbol_file_command PARAMS ((char *, int));
85
86 static void add_shared_symbol_files_command PARAMS ((char *, int));
87
88 static void cashier_psymtab PARAMS ((struct partial_symtab *));
89
90 static int compare_psymbols PARAMS ((const void *, const void *));
91
92 static int compare_symbols PARAMS ((const void *, const void *));
93
94 static bfd *symfile_bfd_open PARAMS ((char *));
95
96 static void find_sym_fns PARAMS ((struct objfile *));
97
98 static void decrement_reading_symtab PARAMS ((void *));
99
100 /* List of all available sym_fns.  On gdb startup, each object file reader
101    calls add_symtab_fns() to register information on each format it is
102    prepared to read. */
103
104 static struct sym_fns *symtab_fns = NULL;
105
106 /* Flag for whether user will be reloading symbols multiple times.
107    Defaults to ON for VxWorks, otherwise OFF.  */
108
109 #ifdef SYMBOL_RELOADING_DEFAULT
110 int symbol_reloading = SYMBOL_RELOADING_DEFAULT;
111 #else
112 int symbol_reloading = 0;
113 #endif
114
115 /* If true, then shared library symbols will be added automatically
116    when the inferior is created, new libraries are loaded, or when
117    attaching to the inferior.  This is almost always what users
118    will want to have happen; but for very large programs, the startup
119    time will be excessive, and so if this is a problem, the user can
120    clear this flag and then add the shared library symbols as needed.
121    Note that there is a potential for confusion, since if the shared
122    library symbols are not loaded, commands like "info fun" will *not*
123    report all the functions that are actually present.  */
124
125 int auto_solib_add = 1;
126
127 \f
128 /* Since this function is called from within qsort, in an ANSI environment
129    it must conform to the prototype for qsort, which specifies that the
130    comparison function takes two "void *" pointers. */
131
132 static int
133 compare_symbols (s1p, s2p)
134      const PTR s1p;
135      const PTR s2p;
136 {
137   register struct symbol **s1, **s2;
138
139   s1 = (struct symbol **) s1p;
140   s2 = (struct symbol **) s2p;
141
142   return (STRCMP (SYMBOL_NAME (*s1), SYMBOL_NAME (*s2)));
143 }
144
145 /*
146
147 LOCAL FUNCTION
148
149         compare_psymbols -- compare two partial symbols by name
150
151 DESCRIPTION
152
153         Given pointers to pointers to two partial symbol table entries,
154         compare them by name and return -N, 0, or +N (ala strcmp).
155         Typically used by sorting routines like qsort().
156
157 NOTES
158
159         Does direct compare of first two characters before punting
160         and passing to strcmp for longer compares.  Note that the
161         original version had a bug whereby two null strings or two
162         identically named one character strings would return the
163         comparison of memory following the null byte.
164
165  */
166
167 static int
168 compare_psymbols (s1p, s2p)
169      const PTR s1p;
170      const PTR s2p;
171 {
172   register char *st1 = SYMBOL_NAME (*(struct partial_symbol **) s1p);
173   register char *st2 = SYMBOL_NAME (*(struct partial_symbol **) s2p);
174
175   if ((st1[0] - st2[0]) || !st1[0])
176     {
177       return (st1[0] - st2[0]);
178     }
179   else if ((st1[1] - st2[1]) || !st1[1])
180     {
181       return (st1[1] - st2[1]);
182     }
183   else
184     {
185       return (STRCMP (st1 + 2, st2 + 2));
186     }
187 }
188
189 void
190 sort_pst_symbols (pst)
191      struct partial_symtab *pst;
192 {
193   /* Sort the global list; don't sort the static list */
194
195   qsort (pst -> objfile -> global_psymbols.list + pst -> globals_offset,
196          pst -> n_global_syms, sizeof (struct partial_symbol *),
197          compare_psymbols);
198 }
199
200 /* Call sort_block_syms to sort alphabetically the symbols of one block.  */
201
202 void
203 sort_block_syms (b)
204      register struct block *b;
205 {
206   qsort (&BLOCK_SYM (b, 0), BLOCK_NSYMS (b),
207          sizeof (struct symbol *), compare_symbols);
208 }
209
210 /* Call sort_symtab_syms to sort alphabetically
211    the symbols of each block of one symtab.  */
212
213 void
214 sort_symtab_syms (s)
215      register struct symtab *s;
216 {
217   register struct blockvector *bv;
218   int nbl;
219   int i;
220   register struct block *b;
221
222   if (s == 0)
223     return;
224   bv = BLOCKVECTOR (s);
225   nbl = BLOCKVECTOR_NBLOCKS (bv);
226   for (i = 0; i < nbl; i++)
227     {
228       b = BLOCKVECTOR_BLOCK (bv, i);
229       if (BLOCK_SHOULD_SORT (b))
230         sort_block_syms (b);
231     }
232 }
233
234 /* Make a null terminated copy of the string at PTR with SIZE characters in
235    the obstack pointed to by OBSTACKP .  Returns the address of the copy.
236    Note that the string at PTR does not have to be null terminated, I.E. it
237    may be part of a larger string and we are only saving a substring. */
238
239 char *
240 obsavestring (ptr, size, obstackp)
241      char *ptr;
242      int size;
243      struct obstack *obstackp;
244 {
245   register char *p = (char *) obstack_alloc (obstackp, size + 1);
246   /* Open-coded memcpy--saves function call time.  These strings are usually
247      short.  FIXME: Is this really still true with a compiler that can
248      inline memcpy? */
249   {
250     register char *p1 = ptr;
251     register char *p2 = p;
252     char *end = ptr + size;
253     while (p1 != end)
254       *p2++ = *p1++;
255   }
256   p[size] = 0;
257   return p;
258 }
259
260 /* Concatenate strings S1, S2 and S3; return the new string.  Space is found
261    in the obstack pointed to by OBSTACKP.  */
262
263 char *
264 obconcat (obstackp, s1, s2, s3)
265      struct obstack *obstackp;
266      const char *s1, *s2, *s3;
267 {
268   register int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
269   register char *val = (char *) obstack_alloc (obstackp, len);
270   strcpy (val, s1);
271   strcat (val, s2);
272   strcat (val, s3);
273   return val;
274 }
275
276 /* True if we are nested inside psymtab_to_symtab. */
277
278 int currently_reading_symtab = 0;
279
280 static void
281 decrement_reading_symtab (dummy)
282      void *dummy;
283 {
284   currently_reading_symtab--;
285 }
286
287 /* Get the symbol table that corresponds to a partial_symtab.
288    This is fast after the first time you do it.  In fact, there
289    is an even faster macro PSYMTAB_TO_SYMTAB that does the fast
290    case inline.  */
291
292 struct symtab *
293 psymtab_to_symtab (pst)
294      register struct partial_symtab *pst;
295 {
296   /* If it's been looked up before, return it. */
297   if (pst->symtab)
298     return pst->symtab;
299
300   /* If it has not yet been read in, read it.  */
301   if (!pst->readin)
302     { 
303       struct cleanup *back_to = make_cleanup (decrement_reading_symtab, NULL);
304       currently_reading_symtab++;
305       (*pst->read_symtab) (pst);
306       do_cleanups (back_to);
307     }
308
309   return pst->symtab;
310 }
311
312 /* Initialize entry point information for this objfile. */
313
314 void
315 init_entry_point_info (objfile)
316      struct objfile *objfile;
317 {
318   /* Save startup file's range of PC addresses to help blockframe.c
319      decide where the bottom of the stack is.  */
320
321   if (bfd_get_file_flags (objfile -> obfd) & EXEC_P)
322     {
323       /* Executable file -- record its entry point so we'll recognize
324          the startup file because it contains the entry point.  */
325       objfile -> ei.entry_point = bfd_get_start_address (objfile -> obfd);
326     }
327   else
328     {
329       /* Examination of non-executable.o files.  Short-circuit this stuff.  */
330       objfile -> ei.entry_point = INVALID_ENTRY_POINT;
331     }
332   objfile -> ei.entry_file_lowpc = INVALID_ENTRY_LOWPC;
333   objfile -> ei.entry_file_highpc = INVALID_ENTRY_HIGHPC;
334   objfile -> ei.entry_func_lowpc = INVALID_ENTRY_LOWPC;
335   objfile -> ei.entry_func_highpc = INVALID_ENTRY_HIGHPC;
336   objfile -> ei.main_func_lowpc = INVALID_ENTRY_LOWPC;
337   objfile -> ei.main_func_highpc = INVALID_ENTRY_HIGHPC;
338 }
339
340 /* Get current entry point address.  */
341
342 CORE_ADDR
343 entry_point_address()
344 {
345   return symfile_objfile ? symfile_objfile->ei.entry_point : 0;
346 }
347
348 /* Remember the lowest-addressed loadable section we've seen.  
349    This function is called via bfd_map_over_sections. 
350
351    In case of equal vmas, the section with the largest size becomes the
352    lowest-addressed loadable section.
353
354    If the vmas and sizes are equal, the last section is considered the
355    lowest-addressed loadable section.  */
356
357 void
358 find_lowest_section (abfd, sect, obj)
359      bfd *abfd;
360      asection *sect;
361      PTR obj;
362 {
363   asection **lowest = (asection **)obj;
364
365   if (0 == (bfd_get_section_flags (abfd, sect) & SEC_LOAD))
366     return;
367   if (!*lowest)
368     *lowest = sect;             /* First loadable section */
369   else if (bfd_section_vma (abfd, *lowest) > bfd_section_vma (abfd, sect))
370     *lowest = sect;             /* A lower loadable section */
371   else if (bfd_section_vma (abfd, *lowest) == bfd_section_vma (abfd, sect)
372            && (bfd_section_size (abfd, (*lowest))
373                <= bfd_section_size (abfd, sect)))
374     *lowest = sect;
375 }
376
377 /* Parse the user's idea of an offset for dynamic linking, into our idea
378    of how to represent it for fast symbol reading.  This is the default 
379    version of the sym_fns.sym_offsets function for symbol readers that
380    don't need to do anything special.  It allocates a section_offsets table
381    for the objectfile OBJFILE and stuffs ADDR into all of the offsets.  */
382
383 struct section_offsets *
384 default_symfile_offsets (objfile, addr)
385      struct objfile *objfile;
386      CORE_ADDR addr;
387 {
388   struct section_offsets *section_offsets;
389   int i;
390
391   objfile->num_sections = SECT_OFF_MAX;
392   section_offsets = (struct section_offsets *)
393     obstack_alloc (&objfile -> psymbol_obstack, SIZEOF_SECTION_OFFSETS);
394
395   for (i = 0; i < SECT_OFF_MAX; i++)
396     ANOFFSET (section_offsets, i) = addr;
397   
398   return section_offsets;
399 }
400
401
402 /* Process a symbol file, as either the main file or as a dynamically
403    loaded file.
404
405    NAME is the file name (which will be tilde-expanded and made
406    absolute herein) (but we don't free or modify NAME itself).
407    FROM_TTY says how verbose to be.  MAINLINE specifies whether this
408    is the main symbol file, or whether it's an extra symbol file such
409    as dynamically loaded code.  If !mainline, ADDR is the address
410    where the text segment was loaded.  If VERBO, the caller has printed
411    a verbose message about the symbol reading (and complaints can be
412    more terse about it).  */
413
414 void
415 syms_from_objfile (objfile, addr, mainline, verbo)
416      struct objfile *objfile;
417      CORE_ADDR addr;
418      int mainline;
419      int verbo;
420 {
421   struct section_offsets *section_offsets;
422   asection *lowest_sect;
423   struct cleanup *old_chain;
424
425   init_entry_point_info (objfile);
426   find_sym_fns (objfile);
427
428   /* Make sure that partially constructed symbol tables will be cleaned up
429      if an error occurs during symbol reading.  */
430   old_chain = make_cleanup (free_objfile, objfile);
431
432   if (mainline) 
433     {
434       /* We will modify the main symbol table, make sure that all its users
435          will be cleaned up if an error occurs during symbol reading.  */
436       make_cleanup (clear_symtab_users, 0);
437
438       /* Since no error yet, throw away the old symbol table.  */
439
440       if (symfile_objfile != NULL)
441         {
442           free_objfile (symfile_objfile);
443           symfile_objfile = NULL;
444         }
445
446       /* Currently we keep symbols from the add-symbol-file command.
447          If the user wants to get rid of them, they should do "symbol-file"
448          without arguments first.  Not sure this is the best behavior
449          (PR 2207).  */
450
451       (*objfile -> sf -> sym_new_init) (objfile);
452     }
453
454   /* Convert addr into an offset rather than an absolute address.
455      We find the lowest address of a loaded segment in the objfile,
456      and assume that <addr> is where that got loaded.  Due to historical
457      precedent, we warn if that doesn't happen to be a text segment.  */
458
459   if (mainline)
460     {
461       addr = 0;         /* No offset from objfile addresses.  */
462     }
463   else
464     {
465       lowest_sect = bfd_get_section_by_name (objfile->obfd, ".text");
466       if (lowest_sect == NULL)
467         bfd_map_over_sections (objfile->obfd, find_lowest_section,
468                                (PTR) &lowest_sect);
469
470       if (lowest_sect == NULL)
471         warning ("no loadable sections found in added symbol-file %s",
472                  objfile->name);
473       else if ((bfd_get_section_flags (objfile->obfd, lowest_sect) & SEC_CODE)
474                == 0)
475         /* FIXME-32x64--assumes bfd_vma fits in long.  */
476         warning ("Lowest section in %s is %s at 0x%lx",
477                  objfile->name,
478                  bfd_section_name (objfile->obfd, lowest_sect),
479                  (unsigned long) bfd_section_vma (objfile->obfd, lowest_sect));
480
481       if (lowest_sect)
482         addr -= bfd_section_vma (objfile->obfd, lowest_sect);
483     }
484
485   /* Initialize symbol reading routines for this objfile, allow complaints to
486      appear for this new file, and record how verbose to be, then do the
487      initial symbol reading for this file. */
488
489   (*objfile -> sf -> sym_init) (objfile);
490   clear_complaints (1, verbo);
491
492   section_offsets = (*objfile -> sf -> sym_offsets) (objfile, addr);
493   objfile->section_offsets = section_offsets;
494
495 #ifndef IBM6000_TARGET
496   /* This is a SVR4/SunOS specific hack, I think.  In any event, it
497      screws RS/6000.  sym_offsets should be doing this sort of thing,
498      because it knows the mapping between bfd sections and
499      section_offsets.  */
500   /* This is a hack.  As far as I can tell, section offsets are not
501      target dependent.  They are all set to addr with a couple of
502      exceptions.  The exceptions are sysvr4 shared libraries, whose
503      offsets are kept in solib structures anyway and rs6000 xcoff
504      which handles shared libraries in a completely unique way.
505
506      Section offsets are built similarly, except that they are built
507      by adding addr in all cases because there is no clear mapping
508      from section_offsets into actual sections.  Note that solib.c
509      has a different algorythm for finding section offsets.
510
511      These should probably all be collapsed into some target
512      independent form of shared library support.  FIXME.  */
513
514   if (addr)
515     {
516       struct obj_section *s;
517
518       for (s = objfile->sections; s < objfile->sections_end; ++s)
519         {
520           s->addr -= s->offset;
521           s->addr += addr;
522           s->endaddr -= s->offset;
523           s->endaddr += addr;
524           s->offset += addr;
525         }
526     }
527 #endif /* not IBM6000_TARGET */
528
529   (*objfile -> sf -> sym_read) (objfile, section_offsets, mainline);
530
531   if (!have_partial_symbols () && !have_full_symbols ())
532     {
533       wrap_here ("");
534       printf_filtered ("(no debugging symbols found)...");
535       wrap_here ("");
536     }
537
538   /* Don't allow char * to have a typename (else would get caddr_t).
539      Ditto void *.  FIXME: Check whether this is now done by all the
540      symbol readers themselves (many of them now do), and if so remove
541      it from here.  */
542
543   TYPE_NAME (lookup_pointer_type (builtin_type_char)) = 0;
544   TYPE_NAME (lookup_pointer_type (builtin_type_void)) = 0;
545
546   /* Mark the objfile has having had initial symbol read attempted.  Note
547      that this does not mean we found any symbols... */
548
549   objfile -> flags |= OBJF_SYMS;
550
551   /* Discard cleanups as symbol reading was successful.  */
552
553   discard_cleanups (old_chain);
554
555 /* Call this after reading in a new symbol table to give target dependant code
556    a crack at the new symbols.  For instance, this could be used to update the
557    values of target-specific symbols GDB needs to keep track of (such as
558    _sigtramp, or whatever).  */
559
560   TARGET_SYMFILE_POSTREAD (objfile);
561 }
562
563 /* Perform required actions after either reading in the initial
564    symbols for a new objfile, or mapping in the symbols from a reusable
565    objfile. */
566    
567 void
568 new_symfile_objfile (objfile, mainline, verbo)
569      struct objfile *objfile;
570      int mainline;
571      int verbo;
572 {
573
574   /* If this is the main symbol file we have to clean up all users of the
575      old main symbol file. Otherwise it is sufficient to fixup all the
576      breakpoints that may have been redefined by this symbol file.  */
577   if (mainline)
578     {
579       /* OK, make it the "real" symbol file.  */
580       symfile_objfile = objfile;
581
582       clear_symtab_users ();
583     }
584   else
585     {
586       breakpoint_re_set ();
587     }
588
589   /* We're done reading the symbol file; finish off complaints.  */
590   clear_complaints (0, verbo);
591 }
592
593 /* Process a symbol file, as either the main file or as a dynamically
594    loaded file.
595
596    NAME is the file name (which will be tilde-expanded and made
597    absolute herein) (but we don't free or modify NAME itself).
598    FROM_TTY says how verbose to be.  MAINLINE specifies whether this
599    is the main symbol file, or whether it's an extra symbol file such
600    as dynamically loaded code.  If !mainline, ADDR is the address
601    where the text segment was loaded.
602
603    Upon success, returns a pointer to the objfile that was added.
604    Upon failure, jumps back to command level (never returns). */
605
606 struct objfile *
607 symbol_file_add (name, from_tty, addr, mainline, mapped, readnow)
608      char *name;
609      int from_tty;
610      CORE_ADDR addr;
611      int mainline;
612      int mapped;
613      int readnow;
614 {
615   struct objfile *objfile;
616   struct partial_symtab *psymtab;
617   bfd *abfd;
618
619   /* Open a bfd for the file, and give user a chance to burp if we'd be
620      interactively wiping out any existing symbols.  */
621
622   abfd = symfile_bfd_open (name);
623
624   if ((have_full_symbols () || have_partial_symbols ())
625       && mainline
626       && from_tty
627       && !query ("Load new symbol table from \"%s\"? ", name))
628       error ("Not confirmed.");
629
630   objfile = allocate_objfile (abfd, mapped);
631
632   /* If the objfile uses a mapped symbol file, and we have a psymtab for
633      it, then skip reading any symbols at this time. */
634
635   if ((objfile -> flags & OBJF_MAPPED) && (objfile -> flags & OBJF_SYMS))
636     {
637       /* We mapped in an existing symbol table file that already has had
638          initial symbol reading performed, so we can skip that part.  Notify
639          the user that instead of reading the symbols, they have been mapped.
640          */
641       if (from_tty || info_verbose)
642         {
643           printf_filtered ("Mapped symbols for %s...", name);
644           wrap_here ("");
645           gdb_flush (gdb_stdout);
646         }
647       init_entry_point_info (objfile);
648       find_sym_fns (objfile);
649     }
650   else
651     {
652       /* We either created a new mapped symbol table, mapped an existing
653          symbol table file which has not had initial symbol reading
654          performed, or need to read an unmapped symbol table. */
655       if (from_tty || info_verbose)
656         {
657           printf_filtered ("Reading symbols from %s...", name);
658           wrap_here ("");
659           gdb_flush (gdb_stdout);
660         }
661       syms_from_objfile (objfile, addr, mainline, from_tty);
662     }      
663
664   /* We now have at least a partial symbol table.  Check to see if the
665      user requested that all symbols be read on initial access via either
666      the gdb startup command line or on a per symbol file basis.  Expand
667      all partial symbol tables for this objfile if so. */
668
669   if (readnow || readnow_symbol_files)
670     {
671       if (from_tty || info_verbose)
672         {
673           printf_filtered ("expanding to full symbols...");
674           wrap_here ("");
675           gdb_flush (gdb_stdout);
676         }
677
678       for (psymtab = objfile -> psymtabs;
679            psymtab != NULL;
680            psymtab = psymtab -> next)
681         {
682           psymtab_to_symtab (psymtab);
683         }
684     }
685
686   if (from_tty || info_verbose)
687     {
688       printf_filtered ("done.\n");
689       gdb_flush (gdb_stdout);
690     }
691
692   new_symfile_objfile (objfile, mainline, from_tty);
693
694   target_new_objfile (objfile);
695
696   return (objfile);
697 }
698
699 /* This is the symbol-file command.  Read the file, analyze its
700    symbols, and add a struct symtab to a symtab list.  The syntax of
701    the command is rather bizarre--(1) buildargv implements various
702    quoting conventions which are undocumented and have little or
703    nothing in common with the way things are quoted (or not quoted)
704    elsewhere in GDB, (2) options are used, which are not generally
705    used in GDB (perhaps "set mapped on", "set readnow on" would be
706    better), (3) the order of options matters, which is contrary to GNU
707    conventions (because it is confusing and inconvenient).  */
708
709 void
710 symbol_file_command (args, from_tty)
711      char *args;
712      int from_tty;
713 {
714   char **argv;
715   char *name = NULL;
716   CORE_ADDR text_relocation = 0;                /* text_relocation */
717   struct cleanup *cleanups;
718   int mapped = 0;
719   int readnow = 0;
720
721   dont_repeat ();
722
723   if (args == NULL)
724     {
725       if ((have_full_symbols () || have_partial_symbols ())
726           && from_tty
727           && !query ("Discard symbol table from `%s'? ",
728                      symfile_objfile -> name))
729         error ("Not confirmed.");
730       free_all_objfiles ();
731       symfile_objfile = NULL;
732       if (from_tty)
733         {
734           printf_unfiltered ("No symbol file now.\n");
735         }
736     }
737   else
738     {
739       if ((argv = buildargv (args)) == NULL)
740         {
741           nomem (0);
742         }
743       cleanups = make_cleanup (freeargv, (char *) argv);
744       while (*argv != NULL)
745         {
746           if (STREQ (*argv, "-mapped"))
747             {
748               mapped = 1;
749             }
750           else if (STREQ (*argv, "-readnow"))
751             {
752               readnow = 1;
753             }
754           else if (**argv == '-')
755             {
756               error ("unknown option `%s'", *argv);
757             }
758           else
759             {
760             char *p;
761
762               name = *argv;
763
764               /* this is for rombug remote only, to get the text relocation by
765               using link command */
766               p = strrchr(name, '/');
767               if (p != NULL) p++;
768               else p = name;
769
770               target_link(p, &text_relocation);
771
772               if (text_relocation == (CORE_ADDR)0)
773                 return;
774               else if (text_relocation == (CORE_ADDR)-1)
775                 symbol_file_add (name, from_tty, (CORE_ADDR)0, 1, mapped,
776                                  readnow);
777               else
778                 symbol_file_add (name, from_tty, (CORE_ADDR)text_relocation,
779                                  0, mapped, readnow);
780
781               /* Getting new symbols may change our opinion about what is
782                  frameless.  */
783               reinit_frame_cache ();
784
785               set_initial_language ();
786             }
787           argv++;
788         }
789
790       if (name == NULL)
791         {
792           error ("no symbol file name was specified");
793         }
794       do_cleanups (cleanups);
795     }
796 }
797
798 /* Set the initial language.
799
800    A better solution would be to record the language in the psymtab when reading
801    partial symbols, and then use it (if known) to set the language.  This would
802    be a win for formats that encode the language in an easily discoverable place,
803    such as DWARF.  For stabs, we can jump through hoops looking for specially
804    named symbols or try to intuit the language from the specific type of stabs
805    we find, but we can't do that until later when we read in full symbols.
806    FIXME.  */
807
808 static void
809 set_initial_language ()
810 {
811   struct partial_symtab *pst;
812   enum language lang = language_unknown;        
813
814   pst = find_main_psymtab ();
815   if (pst != NULL)
816     {
817       if (pst -> filename != NULL)
818         {
819           lang = deduce_language_from_filename (pst -> filename);
820         }
821       if (lang == language_unknown)
822         {
823             /* Make C the default language */
824             lang = language_c;
825         }
826       set_language (lang);
827       expected_language = current_language;     /* Don't warn the user */
828     }
829 }
830
831 /* Open file specified by NAME and hand it off to BFD for preliminary
832    analysis.  Result is a newly initialized bfd *, which includes a newly
833    malloc'd` copy of NAME (tilde-expanded and made absolute).
834    In case of trouble, error() is called.  */
835
836 static bfd *
837 symfile_bfd_open (name)
838      char *name;
839 {
840   bfd *sym_bfd;
841   int desc;
842   char *absolute_name;
843
844   name = tilde_expand (name);   /* Returns 1st new malloc'd copy */
845
846   /* Look down path for it, allocate 2nd new malloc'd copy.  */
847   desc = openp (getenv ("PATH"), 1, name, O_RDONLY | O_BINARY, 0, &absolute_name);
848 #if defined(__GO32__) || defined(_WIN32)
849   if (desc < 0)
850     {
851       char *exename = alloca (strlen (name) + 5);
852       strcat (strcpy (exename, name), ".exe");
853       desc = openp (getenv ("PATH"), 1, exename, O_RDONLY | O_BINARY,
854                     0, &absolute_name);
855     }
856 #endif
857   if (desc < 0)
858     {
859       make_cleanup (free, name);
860       perror_with_name (name);
861     }
862   free (name);                  /* Free 1st new malloc'd copy */
863   name = absolute_name;         /* Keep 2nd malloc'd copy in bfd */
864                                 /* It'll be freed in free_objfile(). */
865
866   sym_bfd = bfd_fdopenr (name, gnutarget, desc);
867   if (!sym_bfd)
868     {
869       close (desc);
870       make_cleanup (free, name);
871       error ("\"%s\": can't open to read symbols: %s.", name,
872              bfd_errmsg (bfd_get_error ()));
873     }
874   sym_bfd->cacheable = true;
875
876   if (!bfd_check_format (sym_bfd, bfd_object))
877     {
878       /* FIXME: should be checking for errors from bfd_close (for one thing,
879          on error it does not free all the storage associated with the
880          bfd).  */
881       bfd_close (sym_bfd);      /* This also closes desc */
882       make_cleanup (free, name);
883       error ("\"%s\": can't read symbols: %s.", name,
884              bfd_errmsg (bfd_get_error ()));
885     }
886
887   return (sym_bfd);
888 }
889
890 /* Link a new symtab_fns into the global symtab_fns list.  Called on gdb
891    startup by the _initialize routine in each object file format reader,
892    to register information about each format the the reader is prepared
893    to handle. */
894
895 void
896 add_symtab_fns (sf)
897      struct sym_fns *sf;
898 {
899   sf->next = symtab_fns;
900   symtab_fns = sf;
901 }
902
903
904 /* Initialize to read symbols from the symbol file sym_bfd.  It either
905    returns or calls error().  The result is an initialized struct sym_fns
906    in the objfile structure, that contains cached information about the
907    symbol file.  */
908
909 static void
910 find_sym_fns (objfile)
911      struct objfile *objfile;
912 {
913   struct sym_fns *sf;
914   enum bfd_flavour our_flavour = bfd_get_flavour (objfile -> obfd);
915   char *our_target = bfd_get_target (objfile -> obfd);
916
917   /* Special kludge for RS/6000 and PowerMac.  See xcoffread.c.  */
918   if (STREQ (our_target, "aixcoff-rs6000") ||
919       STREQ (our_target, "xcoff-powermac"))
920     our_flavour = (enum bfd_flavour)-1;
921
922   /* Special kludge for apollo.  See dstread.c.  */
923   if (STREQN (our_target, "apollo", 6))
924     our_flavour = (enum bfd_flavour)-2;
925
926   for (sf = symtab_fns; sf != NULL; sf = sf -> next)
927     {
928       if (our_flavour == sf -> sym_flavour)
929         {
930           objfile -> sf = sf;
931           return;
932         }
933     }
934   error ("I'm sorry, Dave, I can't do that.  Symbol format `%s' unknown.",
935          bfd_get_target (objfile -> obfd));
936 }
937 \f
938 /* This function runs the load command of our current target.  */
939
940 static void
941 load_command (arg, from_tty)
942      char *arg;
943      int from_tty;
944 {
945   if (arg == NULL)
946     arg = get_exec_file (1);
947   target_load (arg, from_tty);
948 }
949
950 /* This version of "load" should be usable for any target.  Currently
951    it is just used for remote targets, not inftarg.c or core files,
952    on the theory that only in that case is it useful.
953
954    Avoiding xmodem and the like seems like a win (a) because we don't have
955    to worry about finding it, and (b) On VMS, fork() is very slow and so
956    we don't want to run a subprocess.  On the other hand, I'm not sure how
957    performance compares.  */
958 void
959 generic_load (filename, from_tty)
960     char *filename;
961     int from_tty;
962 {
963   struct cleanup *old_cleanups;
964   asection *s;
965   bfd *loadfile_bfd;
966   time_t start_time, end_time;  /* Start and end times of download */
967   unsigned long data_count = 0; /* Number of bytes transferred to memory */
968   int n; 
969   unsigned long load_offset = 0;        /* offset to add to vma for each section */
970   char buf[128];
971
972   /* enable user to specify address for downloading as 2nd arg to load */
973   n = sscanf(filename, "%s 0x%lx", buf, &load_offset);
974   if (n > 1 ) 
975     filename = buf;
976   else
977     load_offset = 0;
978
979   loadfile_bfd = bfd_openr (filename, gnutarget);
980   if (loadfile_bfd == NULL)
981     {
982       perror_with_name (filename);
983       return;
984     }
985   /* FIXME: should be checking for errors from bfd_close (for one thing,
986      on error it does not free all the storage associated with the
987      bfd).  */
988   old_cleanups = make_cleanup (bfd_close, loadfile_bfd);
989
990   if (!bfd_check_format (loadfile_bfd, bfd_object)) 
991     {
992       error ("\"%s\" is not an object file: %s", filename,
993              bfd_errmsg (bfd_get_error ()));
994     }
995   
996   start_time = time (NULL);
997
998   for (s = loadfile_bfd->sections; s; s = s->next) 
999     {
1000       if (s->flags & SEC_LOAD) 
1001         {
1002           bfd_size_type size;
1003
1004           size = bfd_get_section_size_before_reloc (s);
1005           if (size > 0)
1006             {
1007               char *buffer;
1008               struct cleanup *old_chain;
1009               bfd_vma lma;
1010
1011               data_count += size;
1012
1013               buffer = xmalloc (size);
1014               old_chain = make_cleanup (free, buffer);
1015
1016               lma = s->lma;
1017               lma += load_offset;
1018
1019               /* Is this really necessary?  I guess it gives the user something
1020                  to look at during a long download.  */
1021               printf_filtered ("Loading section %s, size 0x%lx lma ",
1022                                bfd_get_section_name (loadfile_bfd, s),
1023                                (unsigned long) size);
1024               print_address_numeric (lma, 1, gdb_stdout);
1025               printf_filtered ("\n");
1026
1027               bfd_get_section_contents (loadfile_bfd, s, buffer, 0, size);
1028
1029               if (target_write_memory (lma, buffer, size) != 0)
1030                 error ("Memory access error while loading section %s.", 
1031                        bfd_get_section_name (loadfile_bfd, s));
1032
1033               do_cleanups (old_chain);
1034             }
1035         }
1036     }
1037
1038   end_time = time (NULL);
1039
1040   printf_filtered ("Start address 0x%lx\n", loadfile_bfd->start_address);
1041
1042   /* We were doing this in remote-mips.c, I suspect it is right
1043      for other targets too.  */
1044   write_pc (loadfile_bfd->start_address);
1045
1046   /* FIXME: are we supposed to call symbol_file_add or not?  According to
1047      a comment from remote-mips.c (where a call to symbol_file_add was
1048      commented out), making the call confuses GDB if more than one file is
1049      loaded in.  remote-nindy.c had no call to symbol_file_add, but remote-vx.c
1050      does.  */
1051
1052   report_transfer_performance (data_count, start_time, end_time);
1053
1054   do_cleanups (old_cleanups);
1055 }
1056
1057 /* Report how fast the transfer went. */
1058
1059 void
1060 report_transfer_performance (data_count, start_time, end_time)
1061 unsigned long data_count;
1062 time_t start_time, end_time;
1063 {
1064   printf_filtered ("Transfer rate: ");
1065   if (end_time != start_time)
1066     printf_filtered ("%d bits/sec",
1067                      (data_count * 8) / (end_time - start_time));
1068   else
1069     printf_filtered ("%d bits in <1 sec", (data_count * 8));
1070   printf_filtered (".\n");
1071 }
1072
1073 /* This function allows the addition of incrementally linked object files.
1074    It does not modify any state in the target, only in the debugger.  */
1075
1076 /* ARGSUSED */
1077 static void
1078 add_symbol_file_command (args, from_tty)
1079      char *args;
1080      int from_tty;
1081 {
1082   char *name = NULL;
1083   CORE_ADDR text_addr;
1084   char *arg;
1085   int readnow = 0;
1086   int mapped = 0;
1087   
1088   dont_repeat ();
1089
1090   if (args == NULL)
1091     {
1092       error ("add-symbol-file takes a file name and an address");
1093     }
1094
1095   /* Make a copy of the string that we can safely write into. */
1096
1097   args = strdup (args);
1098   make_cleanup (free, args);
1099
1100   /* Pick off any -option args and the file name. */
1101
1102   while ((*args != '\000') && (name == NULL))
1103     {
1104       while (isspace (*args)) {args++;}
1105       arg = args;
1106       while ((*args != '\000') && !isspace (*args)) {args++;}
1107       if (*args != '\000')
1108         {
1109           *args++ = '\000';
1110         }
1111       if (*arg != '-')
1112         {
1113           name = arg;
1114         }
1115       else if (STREQ (arg, "-mapped"))
1116         {
1117           mapped = 1;
1118         }
1119       else if (STREQ (arg, "-readnow"))
1120         {
1121           readnow = 1;
1122         }
1123       else
1124         {
1125           error ("unknown option `%s'", arg);
1126         }
1127     }
1128
1129   /* After picking off any options and the file name, args should be
1130      left pointing at the remainder of the command line, which should
1131      be the address expression to evaluate. */
1132
1133   if (name == NULL)
1134     {
1135       error ("add-symbol-file takes a file name");
1136     }
1137   name = tilde_expand (name);
1138   make_cleanup (free, name);
1139
1140   if (*args != '\000')
1141     {
1142       text_addr = parse_and_eval_address (args);
1143     }
1144   else
1145     {
1146       target_link(name, &text_addr);
1147       if (text_addr == (CORE_ADDR)-1)
1148         error("Don't know how to get text start location for this file");
1149     }
1150
1151   /* FIXME-32x64: Assumes text_addr fits in a long.  */
1152   if (!query ("add symbol table from file \"%s\" at text_addr = %s?\n",
1153               name, local_hex_string ((unsigned long)text_addr)))
1154     error ("Not confirmed.");
1155
1156   symbol_file_add (name, 0, text_addr, 0, mapped, readnow);
1157
1158   /* Getting new symbols may change our opinion about what is
1159      frameless.  */
1160   reinit_frame_cache ();
1161 }
1162 \f
1163 static void
1164 add_shared_symbol_files_command  (args, from_tty)
1165      char *args;
1166      int from_tty;
1167 {
1168 #ifdef ADD_SHARED_SYMBOL_FILES
1169   ADD_SHARED_SYMBOL_FILES (args, from_tty);
1170 #else
1171   error ("This command is not available in this configuration of GDB.");
1172 #endif  
1173 }
1174 \f
1175 /* Re-read symbols if a symbol-file has changed.  */
1176 void
1177 reread_symbols ()
1178 {
1179   struct objfile *objfile;
1180   long new_modtime;
1181   int reread_one = 0;
1182   struct stat new_statbuf;
1183   int res;
1184
1185   /* With the addition of shared libraries, this should be modified,
1186      the load time should be saved in the partial symbol tables, since
1187      different tables may come from different source files.  FIXME.
1188      This routine should then walk down each partial symbol table
1189      and see if the symbol table that it originates from has been changed */
1190
1191   for (objfile = object_files; objfile; objfile = objfile->next) {
1192     if (objfile->obfd) {
1193 #ifdef IBM6000_TARGET
1194      /* If this object is from a shared library, then you should
1195         stat on the library name, not member name. */
1196
1197      if (objfile->obfd->my_archive)
1198        res = stat (objfile->obfd->my_archive->filename, &new_statbuf);
1199      else
1200 #endif
1201       res = stat (objfile->name, &new_statbuf);
1202       if (res != 0) {
1203         /* FIXME, should use print_sys_errmsg but it's not filtered. */
1204         printf_filtered ("`%s' has disappeared; keeping its symbols.\n",
1205                          objfile->name);
1206         continue;
1207       }
1208       new_modtime = new_statbuf.st_mtime;
1209       if (new_modtime != objfile->mtime)
1210         {
1211           struct cleanup *old_cleanups;
1212           struct section_offsets *offsets;
1213           int num_offsets;
1214           int section_offsets_size;
1215           char *obfd_filename;
1216
1217           printf_filtered ("`%s' has changed; re-reading symbols.\n",
1218                            objfile->name);
1219
1220           /* There are various functions like symbol_file_add,
1221              symfile_bfd_open, syms_from_objfile, etc., which might
1222              appear to do what we want.  But they have various other
1223              effects which we *don't* want.  So we just do stuff
1224              ourselves.  We don't worry about mapped files (for one thing,
1225              any mapped file will be out of date).  */
1226
1227           /* If we get an error, blow away this objfile (not sure if
1228              that is the correct response for things like shared
1229              libraries).  */
1230           old_cleanups = make_cleanup (free_objfile, objfile);
1231           /* We need to do this whenever any symbols go away.  */
1232           make_cleanup (clear_symtab_users, 0);
1233
1234           /* Clean up any state BFD has sitting around.  We don't need
1235              to close the descriptor but BFD lacks a way of closing the
1236              BFD without closing the descriptor.  */
1237           obfd_filename = bfd_get_filename (objfile->obfd);
1238           if (!bfd_close (objfile->obfd))
1239             error ("Can't close BFD for %s: %s", objfile->name,
1240                    bfd_errmsg (bfd_get_error ()));
1241           objfile->obfd = bfd_openr (obfd_filename, gnutarget);
1242           if (objfile->obfd == NULL)
1243             error ("Can't open %s to read symbols.", objfile->name);
1244           /* bfd_openr sets cacheable to true, which is what we want.  */
1245           if (!bfd_check_format (objfile->obfd, bfd_object))
1246             error ("Can't read symbols from %s: %s.", objfile->name,
1247                    bfd_errmsg (bfd_get_error ()));
1248
1249           /* Save the offsets, we will nuke them with the rest of the
1250              psymbol_obstack.  */
1251           num_offsets = objfile->num_sections;
1252           section_offsets_size =
1253             sizeof (struct section_offsets)
1254               + sizeof (objfile->section_offsets->offsets) * num_offsets;
1255           offsets = (struct section_offsets *) alloca (section_offsets_size);
1256           memcpy (offsets, objfile->section_offsets, section_offsets_size);
1257
1258           /* Nuke all the state that we will re-read.  Much of the following
1259              code which sets things to NULL really is necessary to tell
1260              other parts of GDB that there is nothing currently there.  */
1261
1262           /* FIXME: Do we have to free a whole linked list, or is this
1263              enough?  */
1264           if (objfile->global_psymbols.list)
1265             mfree (objfile->md, objfile->global_psymbols.list);
1266           memset (&objfile -> global_psymbols, 0,
1267                   sizeof (objfile -> global_psymbols));
1268           if (objfile->static_psymbols.list)
1269             mfree (objfile->md, objfile->static_psymbols.list);
1270           memset (&objfile -> static_psymbols, 0,
1271                   sizeof (objfile -> static_psymbols));
1272
1273           /* Free the obstacks for non-reusable objfiles */
1274           obstack_free (&objfile -> psymbol_cache.cache, 0);
1275           memset (&objfile -> psymbol_cache, 0,
1276                   sizeof (objfile -> psymbol_cache));
1277           obstack_free (&objfile -> psymbol_obstack, 0);
1278           obstack_free (&objfile -> symbol_obstack, 0);
1279           obstack_free (&objfile -> type_obstack, 0);
1280           objfile->sections = NULL;
1281           objfile->symtabs = NULL;
1282           objfile->psymtabs = NULL;
1283           objfile->free_psymtabs = NULL;
1284           objfile->msymbols = NULL;
1285           objfile->minimal_symbol_count= 0;
1286           objfile->fundamental_types = NULL;
1287           if (objfile -> sf != NULL)
1288             {
1289               (*objfile -> sf -> sym_finish) (objfile);
1290             }
1291
1292           /* We never make this a mapped file.  */
1293           objfile -> md = NULL;
1294           /* obstack_specify_allocation also initializes the obstack so
1295              it is empty.  */
1296           obstack_specify_allocation (&objfile -> psymbol_cache.cache, 0, 0,
1297                                       xmalloc, free);
1298           obstack_specify_allocation (&objfile -> psymbol_obstack, 0, 0,
1299                                       xmalloc, free);
1300           obstack_specify_allocation (&objfile -> symbol_obstack, 0, 0,
1301                                       xmalloc, free);
1302           obstack_specify_allocation (&objfile -> type_obstack, 0, 0,
1303                                       xmalloc, free);
1304           if (build_objfile_section_table (objfile))
1305             {
1306               error ("Can't find the file sections in `%s': %s", 
1307                      objfile -> name, bfd_errmsg (bfd_get_error ()));
1308             }
1309
1310           /* We use the same section offsets as from last time.  I'm not
1311              sure whether that is always correct for shared libraries.  */
1312           objfile->section_offsets = (struct section_offsets *)
1313             obstack_alloc (&objfile -> psymbol_obstack, section_offsets_size);
1314           memcpy (objfile->section_offsets, offsets, section_offsets_size);
1315           objfile->num_sections = num_offsets;
1316
1317           /* What the hell is sym_new_init for, anyway?  The concept of
1318              distinguishing between the main file and additional files
1319              in this way seems rather dubious.  */
1320           if (objfile == symfile_objfile)
1321             (*objfile->sf->sym_new_init) (objfile);
1322
1323           (*objfile->sf->sym_init) (objfile);
1324           clear_complaints (1, 1);
1325           /* The "mainline" parameter is a hideous hack; I think leaving it
1326              zero is OK since dbxread.c also does what it needs to do if
1327              objfile->global_psymbols.size is 0.  */
1328           (*objfile->sf->sym_read) (objfile, objfile->section_offsets, 0);
1329           if (!have_partial_symbols () && !have_full_symbols ())
1330             {
1331               wrap_here ("");
1332               printf_filtered ("(no debugging symbols found)\n");
1333               wrap_here ("");
1334             }
1335           objfile -> flags |= OBJF_SYMS;
1336
1337           /* We're done reading the symbol file; finish off complaints.  */
1338           clear_complaints (0, 1);
1339
1340           /* Getting new symbols may change our opinion about what is
1341              frameless.  */
1342
1343           reinit_frame_cache ();
1344
1345           /* Discard cleanups as symbol reading was successful.  */
1346           discard_cleanups (old_cleanups);
1347
1348           /* If the mtime has changed between the time we set new_modtime
1349              and now, we *want* this to be out of date, so don't call stat
1350              again now.  */
1351           objfile->mtime = new_modtime;
1352           reread_one = 1;
1353
1354           /* Call this after reading in a new symbol table to give target
1355              dependant code a crack at the new symbols.  For instance, this
1356              could be used to update the values of target-specific symbols GDB
1357              needs to keep track of (such as _sigtramp, or whatever).  */
1358
1359           TARGET_SYMFILE_POSTREAD (objfile);
1360         }
1361     }
1362   }
1363
1364   if (reread_one)
1365     clear_symtab_users ();
1366 }
1367
1368 \f
1369 enum language
1370 deduce_language_from_filename (filename)
1371      char *filename;
1372 {
1373   char *c;
1374   
1375   if (0 == filename) 
1376     ; /* Get default */
1377   else if (0 == (c = strrchr (filename, '.')))
1378     ; /* Get default. */
1379   else if (STREQ (c, ".c"))
1380     return language_c;
1381   else if (STREQ (c, ".cc") || STREQ (c, ".C") || STREQ (c, ".cxx")
1382            || STREQ (c, ".cpp") || STREQ (c, ".cp") || STREQ (c, ".c++"))
1383     return language_cplus;
1384   else if (STREQ (c, ".java"))
1385     return language_java;
1386   else if (STREQ (c, ".ch") || STREQ (c, ".c186") || STREQ (c, ".c286"))
1387     return language_chill;
1388   else if (STREQ (c, ".f") || STREQ (c, ".F"))
1389     return language_fortran;
1390   else if (STREQ (c, ".mod"))
1391     return language_m2;
1392   else if (STREQ (c, ".s") || STREQ (c, ".S"))
1393     return language_asm;
1394
1395   return language_unknown;              /* default */
1396 }
1397 \f
1398 /* allocate_symtab:
1399
1400    Allocate and partly initialize a new symbol table.  Return a pointer
1401    to it.  error() if no space.
1402
1403    Caller must set these fields:
1404         LINETABLE(symtab)
1405         symtab->blockvector
1406         symtab->dirname
1407         symtab->free_code
1408         symtab->free_ptr
1409         initialize any EXTRA_SYMTAB_INFO
1410         possibly free_named_symtabs (symtab->filename);
1411  */
1412
1413 struct symtab *
1414 allocate_symtab (filename, objfile)
1415      char *filename;
1416      struct objfile *objfile;
1417 {
1418   register struct symtab *symtab;
1419
1420   symtab = (struct symtab *)
1421     obstack_alloc (&objfile -> symbol_obstack, sizeof (struct symtab));
1422   memset (symtab, 0, sizeof (*symtab));
1423   symtab -> filename = obsavestring (filename, strlen (filename),
1424                                      &objfile -> symbol_obstack);
1425   symtab -> fullname = NULL;
1426   symtab -> language = deduce_language_from_filename (filename);
1427
1428   /* Hook it to the objfile it comes from */
1429
1430   symtab -> objfile = objfile;
1431   symtab -> next = objfile -> symtabs;
1432   objfile -> symtabs = symtab;
1433
1434 #ifdef INIT_EXTRA_SYMTAB_INFO
1435   INIT_EXTRA_SYMTAB_INFO (symtab);
1436 #endif
1437
1438   return (symtab);
1439 }
1440
1441 struct partial_symtab *
1442 allocate_psymtab (filename, objfile)
1443      char *filename;
1444      struct objfile *objfile;
1445 {
1446   struct partial_symtab *psymtab;
1447
1448   if (objfile -> free_psymtabs)
1449     {
1450       psymtab = objfile -> free_psymtabs;
1451       objfile -> free_psymtabs = psymtab -> next;
1452     }
1453   else
1454     psymtab = (struct partial_symtab *)
1455       obstack_alloc (&objfile -> psymbol_obstack,
1456                      sizeof (struct partial_symtab));
1457
1458   memset (psymtab, 0, sizeof (struct partial_symtab));
1459   psymtab -> filename = obsavestring (filename, strlen (filename),
1460                                       &objfile -> psymbol_obstack);
1461   psymtab -> symtab = NULL;
1462
1463   /* Hook it to the objfile it comes from */
1464
1465   psymtab -> objfile = objfile;
1466   psymtab -> next = objfile -> psymtabs;
1467   objfile -> psymtabs = psymtab;
1468   
1469   return (psymtab);
1470 }
1471
1472 \f
1473 /* Reset all data structures in gdb which may contain references to symbol
1474    table data.  */
1475
1476 void
1477 clear_symtab_users ()
1478 {
1479   /* Someday, we should do better than this, by only blowing away
1480      the things that really need to be blown.  */
1481   clear_value_history ();
1482   clear_displays ();
1483   clear_internalvars ();
1484   breakpoint_re_set ();
1485   set_default_breakpoint (0, 0, 0, 0);
1486   current_source_symtab = 0;
1487   current_source_line = 0;
1488   clear_pc_function_cache ();
1489   target_new_objfile (NULL);
1490 }
1491
1492 /* clear_symtab_users_once:
1493
1494    This function is run after symbol reading, or from a cleanup.
1495    If an old symbol table was obsoleted, the old symbol table
1496    has been blown away, but the other GDB data structures that may 
1497    reference it have not yet been cleared or re-directed.  (The old
1498    symtab was zapped, and the cleanup queued, in free_named_symtab()
1499    below.)
1500
1501    This function can be queued N times as a cleanup, or called
1502    directly; it will do all the work the first time, and then will be a
1503    no-op until the next time it is queued.  This works by bumping a
1504    counter at queueing time.  Much later when the cleanup is run, or at
1505    the end of symbol processing (in case the cleanup is discarded), if
1506    the queued count is greater than the "done-count", we do the work
1507    and set the done-count to the queued count.  If the queued count is
1508    less than or equal to the done-count, we just ignore the call.  This
1509    is needed because reading a single .o file will often replace many
1510    symtabs (one per .h file, for example), and we don't want to reset
1511    the breakpoints N times in the user's face.
1512
1513    The reason we both queue a cleanup, and call it directly after symbol
1514    reading, is because the cleanup protects us in case of errors, but is
1515    discarded if symbol reading is successful.  */
1516
1517 #if 0
1518 /* FIXME:  As free_named_symtabs is currently a big noop this function
1519    is no longer needed.  */
1520 static void
1521 clear_symtab_users_once PARAMS ((void));
1522
1523 static int clear_symtab_users_queued;
1524 static int clear_symtab_users_done;
1525
1526 static void
1527 clear_symtab_users_once ()
1528 {
1529   /* Enforce once-per-`do_cleanups'-semantics */
1530   if (clear_symtab_users_queued <= clear_symtab_users_done)
1531     return;
1532   clear_symtab_users_done = clear_symtab_users_queued;
1533
1534   clear_symtab_users ();
1535 }
1536 #endif
1537
1538 /* Delete the specified psymtab, and any others that reference it.  */
1539
1540 static void
1541 cashier_psymtab (pst)
1542      struct partial_symtab *pst;
1543 {
1544   struct partial_symtab *ps, *pprev = NULL;
1545   int i;
1546
1547   /* Find its previous psymtab in the chain */
1548   for (ps = pst->objfile->psymtabs; ps; ps = ps->next) {
1549     if (ps == pst)
1550       break;
1551     pprev = ps;
1552   }
1553
1554   if (ps) {
1555     /* Unhook it from the chain.  */
1556     if (ps == pst->objfile->psymtabs)
1557       pst->objfile->psymtabs = ps->next;
1558     else
1559       pprev->next = ps->next;
1560
1561     /* FIXME, we can't conveniently deallocate the entries in the
1562        partial_symbol lists (global_psymbols/static_psymbols) that
1563        this psymtab points to.  These just take up space until all
1564        the psymtabs are reclaimed.  Ditto the dependencies list and
1565        filename, which are all in the psymbol_obstack.  */
1566
1567     /* We need to cashier any psymtab that has this one as a dependency... */
1568 again:
1569     for (ps = pst->objfile->psymtabs; ps; ps = ps->next) {
1570       for (i = 0; i < ps->number_of_dependencies; i++) {
1571         if (ps->dependencies[i] == pst) {
1572           cashier_psymtab (ps);
1573           goto again;           /* Must restart, chain has been munged. */
1574         }
1575       }
1576     }
1577   }
1578 }
1579
1580 /* If a symtab or psymtab for filename NAME is found, free it along
1581    with any dependent breakpoints, displays, etc.
1582    Used when loading new versions of object modules with the "add-file"
1583    command.  This is only called on the top-level symtab or psymtab's name;
1584    it is not called for subsidiary files such as .h files.
1585
1586    Return value is 1 if we blew away the environment, 0 if not.
1587    FIXME.  The return valu appears to never be used.
1588
1589    FIXME.  I think this is not the best way to do this.  We should
1590    work on being gentler to the environment while still cleaning up
1591    all stray pointers into the freed symtab.  */
1592
1593 int
1594 free_named_symtabs (name)
1595      char *name;
1596 {
1597 #if 0
1598   /* FIXME:  With the new method of each objfile having it's own
1599      psymtab list, this function needs serious rethinking.  In particular,
1600      why was it ever necessary to toss psymtabs with specific compilation
1601      unit filenames, as opposed to all psymtabs from a particular symbol
1602      file?  -- fnf
1603      Well, the answer is that some systems permit reloading of particular
1604      compilation units.  We want to blow away any old info about these
1605      compilation units, regardless of which objfiles they arrived in. --gnu.  */
1606
1607   register struct symtab *s;
1608   register struct symtab *prev;
1609   register struct partial_symtab *ps;
1610   struct blockvector *bv;
1611   int blewit = 0;
1612
1613   /* We only wack things if the symbol-reload switch is set.  */
1614   if (!symbol_reloading)
1615     return 0;
1616
1617   /* Some symbol formats have trouble providing file names... */
1618   if (name == 0 || *name == '\0')
1619     return 0;
1620
1621   /* Look for a psymtab with the specified name.  */
1622
1623 again2:
1624   for (ps = partial_symtab_list; ps; ps = ps->next) {
1625     if (STREQ (name, ps->filename)) {
1626       cashier_psymtab (ps);     /* Blow it away...and its little dog, too.  */
1627       goto again2;              /* Must restart, chain has been munged */
1628     }
1629   }
1630
1631   /* Look for a symtab with the specified name.  */
1632
1633   for (s = symtab_list; s; s = s->next)
1634     {
1635       if (STREQ (name, s->filename))
1636         break;
1637       prev = s;
1638     }
1639
1640   if (s)
1641     {
1642       if (s == symtab_list)
1643         symtab_list = s->next;
1644       else
1645         prev->next = s->next;
1646
1647       /* For now, queue a delete for all breakpoints, displays, etc., whether
1648          or not they depend on the symtab being freed.  This should be
1649          changed so that only those data structures affected are deleted.  */
1650
1651       /* But don't delete anything if the symtab is empty.
1652          This test is necessary due to a bug in "dbxread.c" that
1653          causes empty symtabs to be created for N_SO symbols that
1654          contain the pathname of the object file.  (This problem
1655          has been fixed in GDB 3.9x).  */
1656
1657       bv = BLOCKVECTOR (s);
1658       if (BLOCKVECTOR_NBLOCKS (bv) > 2
1659           || BLOCK_NSYMS (BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK))
1660           || BLOCK_NSYMS (BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK)))
1661         {
1662           complain (&oldsyms_complaint, name);
1663
1664           clear_symtab_users_queued++;
1665           make_cleanup (clear_symtab_users_once, 0);
1666           blewit = 1;
1667         } else {
1668           complain (&empty_symtab_complaint, name);
1669         }
1670
1671       free_symtab (s);
1672     }
1673   else
1674     {
1675       /* It is still possible that some breakpoints will be affected
1676          even though no symtab was found, since the file might have
1677          been compiled without debugging, and hence not be associated
1678          with a symtab.  In order to handle this correctly, we would need
1679          to keep a list of text address ranges for undebuggable files.
1680          For now, we do nothing, since this is a fairly obscure case.  */
1681       ;
1682     }
1683
1684   /* FIXME, what about the minimal symbol table? */
1685   return blewit;
1686 #else
1687   return (0);
1688 #endif
1689 }
1690 \f
1691 /* Allocate and partially fill a partial symtab.  It will be
1692    completely filled at the end of the symbol list.
1693
1694    SYMFILE_NAME is the name of the symbol-file we are reading from, and ADDR
1695    is the address relative to which its symbols are (incremental) or 0
1696    (normal). */
1697
1698
1699 struct partial_symtab *
1700 start_psymtab_common (objfile, section_offsets,
1701                       filename, textlow, global_syms, static_syms)
1702      struct objfile *objfile;
1703      struct section_offsets *section_offsets;
1704      char *filename;
1705      CORE_ADDR textlow;
1706      struct partial_symbol **global_syms;
1707      struct partial_symbol **static_syms;
1708 {
1709   struct partial_symtab *psymtab;
1710
1711   psymtab = allocate_psymtab (filename, objfile);
1712   psymtab -> section_offsets = section_offsets;
1713   psymtab -> textlow = textlow;
1714   psymtab -> texthigh = psymtab -> textlow;  /* default */
1715   psymtab -> globals_offset = global_syms - objfile -> global_psymbols.list;
1716   psymtab -> statics_offset = static_syms - objfile -> static_psymbols.list;
1717   return (psymtab);
1718 }
1719 \f
1720 /* Add a symbol with a long value to a psymtab.
1721    Since one arg is a struct, we pass in a ptr and deref it (sigh).  */
1722
1723 void
1724 add_psymbol_to_list (name, namelength, namespace, class, list, val, coreaddr,
1725                      language, objfile)
1726      char *name;
1727      int namelength;
1728      namespace_enum namespace;
1729      enum address_class class;
1730      struct psymbol_allocation_list *list;
1731      long val;                                  /* Value as a long */
1732      CORE_ADDR coreaddr;                        /* Value as a CORE_ADDR */
1733      enum language language;
1734      struct objfile *objfile;
1735 {
1736   register struct partial_symbol *psym;
1737   char *buf = alloca (namelength + 1);
1738   /* psymbol is static so that there will be no uninitialized gaps in the
1739      structure which might contain random data, causing cache misses in
1740      bcache. */
1741   static struct partial_symbol psymbol;
1742
1743   /* Create local copy of the partial symbol */
1744   memcpy (buf, name, namelength);
1745   buf[namelength] = '\0';
1746   SYMBOL_NAME (&psymbol) = bcache (buf, namelength + 1, &objfile->psymbol_cache);
1747   /* val and coreaddr are mutually exclusive, one of them *will* be zero */
1748   if (val != 0)
1749     {
1750       SYMBOL_VALUE (&psymbol) = val;
1751     }
1752   else
1753     {
1754       SYMBOL_VALUE_ADDRESS (&psymbol) = coreaddr;
1755     }
1756   SYMBOL_SECTION (&psymbol) = 0;
1757   SYMBOL_LANGUAGE (&psymbol) = language;
1758   PSYMBOL_NAMESPACE (&psymbol) = namespace;
1759   PSYMBOL_CLASS (&psymbol) = class;
1760   SYMBOL_INIT_LANGUAGE_SPECIFIC (&psymbol, language);
1761
1762   /* Stash the partial symbol away in the cache */
1763   psym = bcache (&psymbol, sizeof (struct partial_symbol), &objfile->psymbol_cache);
1764
1765   /* Save pointer to partial symbol in psymtab, growing symtab if needed. */
1766   if (list->next >= list->list + list->size)
1767     {
1768       extend_psymbol_list (list, objfile);
1769     }
1770   *list->next++ = psym;
1771   OBJSTAT (objfile, n_psyms++);
1772 }
1773
1774 /* Initialize storage for partial symbols.  */
1775
1776 void
1777 init_psymbol_list (objfile, total_symbols)
1778      struct objfile *objfile;
1779      int total_symbols;
1780 {
1781   /* Free any previously allocated psymbol lists.  */
1782   
1783   if (objfile -> global_psymbols.list)
1784     {
1785       mfree (objfile -> md, (PTR)objfile -> global_psymbols.list);
1786     }
1787   if (objfile -> static_psymbols.list)
1788     {
1789       mfree (objfile -> md, (PTR)objfile -> static_psymbols.list);
1790     }
1791   
1792   /* Current best guess is that approximately a twentieth
1793      of the total symbols (in a debugging file) are global or static
1794      oriented symbols */
1795   
1796   objfile -> global_psymbols.size = total_symbols / 10;
1797   objfile -> static_psymbols.size = total_symbols / 10;
1798   objfile -> global_psymbols.next =
1799     objfile -> global_psymbols.list = (struct partial_symbol **)
1800       xmmalloc (objfile -> md, objfile -> global_psymbols.size
1801                              * sizeof (struct partial_symbol *));
1802   objfile -> static_psymbols.next =
1803     objfile -> static_psymbols.list = (struct partial_symbol **)
1804       xmmalloc (objfile -> md, objfile -> static_psymbols.size
1805                              * sizeof (struct partial_symbol *));
1806 }
1807
1808 /* OVERLAYS:
1809    The following code implements an abstraction for debugging overlay sections.
1810
1811    The target model is as follows:
1812    1) The gnu linker will permit multiple sections to be mapped into the
1813       same VMA, each with its own unique LMA (or load address).
1814    2) It is assumed that some runtime mechanism exists for mapping the
1815       sections, one by one, from the load address into the VMA address.
1816    3) This code provides a mechanism for gdb to keep track of which 
1817       sections should be considered to be mapped from the VMA to the LMA.
1818       This information is used for symbol lookup, and memory read/write.
1819       For instance, if a section has been mapped then its contents 
1820       should be read from the VMA, otherwise from the LMA.
1821
1822    Two levels of debugger support for overlays are available.  One is
1823    "manual", in which the debugger relies on the user to tell it which
1824    overlays are currently mapped.  This level of support is
1825    implemented entirely in the core debugger, and the information about
1826    whether a section is mapped is kept in the objfile->obj_section table.
1827
1828    The second level of support is "automatic", and is only available if
1829    the target-specific code provides functionality to read the target's
1830    overlay mapping table, and translate its contents for the debugger
1831    (by updating the mapped state information in the obj_section tables).
1832
1833    The interface is as follows:
1834      User commands:
1835        overlay map <name>       -- tell gdb to consider this section mapped
1836        overlay unmap <name>     -- tell gdb to consider this section unmapped
1837        overlay list             -- list the sections that GDB thinks are mapped
1838        overlay read-target      -- get the target's state of what's mapped
1839        overlay off/manual/auto -- set overlay debugging state
1840      Functional interface:
1841        find_pc_mapped_section(pc):    if the pc is in the range of a mapped
1842                                       section, return that section.
1843        find_pc_overlay(pc):           find any overlay section that contains 
1844                                       the pc, either in its VMA or its LMA
1845        overlay_is_mapped(sect):       true if overlay is marked as mapped
1846        section_is_overlay(sect):      true if section's VMA != LMA
1847        pc_in_mapped_range(pc,sec):    true if pc belongs to section's VMA
1848        pc_in_unmapped_range(...):     true if pc belongs to section's LMA
1849        overlay_mapped_address(...):   map an address from section's LMA to VMA
1850        overlay_unmapped_address(...): map an address from section's VMA to LMA
1851        symbol_overlayed_address(...): Return a "current" address for symbol:
1852                                       either in VMA or LMA depending on whether
1853                                       the symbol's section is currently mapped
1854  */
1855
1856 /* Overlay debugging state: */
1857
1858 int overlay_debugging = 0;      /* 0 == off, 1 == manual, -1 == auto */
1859 int overlay_cache_invalid = 0;  /* True if need to refresh mapped state */
1860
1861 /* Target vector for refreshing overlay mapped state */
1862 static void simple_overlay_update PARAMS ((struct obj_section *));
1863 void (*target_overlay_update) PARAMS ((struct obj_section *)) 
1864      = simple_overlay_update;
1865
1866 /* Function: section_is_overlay (SECTION)
1867    Returns true if SECTION has VMA not equal to LMA, ie. 
1868    SECTION is loaded at an address different from where it will "run".  */
1869
1870 int
1871 section_is_overlay (section)
1872      asection *section;
1873 {
1874   if (overlay_debugging)
1875     if (section && section->lma != 0 &&
1876         section->vma != section->lma)
1877       return 1;
1878
1879   return 0;
1880 }
1881
1882 /* Function: overlay_invalidate_all (void)
1883    Invalidate the mapped state of all overlay sections (mark it as stale).  */
1884
1885 static void
1886 overlay_invalidate_all ()
1887 {
1888   struct objfile     *objfile;
1889   struct obj_section *sect;
1890
1891   ALL_OBJSECTIONS (objfile, sect)
1892     if (section_is_overlay (sect->the_bfd_section))
1893       sect->ovly_mapped = -1;
1894 }
1895
1896 /* Function: overlay_is_mapped (SECTION)
1897    Returns true if section is an overlay, and is currently mapped. 
1898    Private: public access is thru function section_is_mapped.
1899
1900    Access to the ovly_mapped flag is restricted to this function, so
1901    that we can do automatic update.  If the global flag
1902    OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call
1903    overlay_invalidate_all.  If the mapped state of the particular
1904    section is stale, then call TARGET_OVERLAY_UPDATE to refresh it.  */
1905
1906 static int 
1907 overlay_is_mapped (osect)
1908      struct obj_section *osect;
1909 {
1910   if (osect == 0 || !section_is_overlay (osect->the_bfd_section))
1911     return 0;
1912
1913   switch (overlay_debugging) 
1914     {
1915     default:
1916     case 0:     return 0;       /* overlay debugging off */
1917     case -1:                    /* overlay debugging automatic */
1918       /* Unles there is a target_overlay_update function, 
1919          there's really nothing useful to do here (can't really go auto)  */
1920       if (target_overlay_update)
1921         {
1922           if (overlay_cache_invalid)
1923             {
1924               overlay_invalidate_all ();
1925               overlay_cache_invalid = 0;
1926             }
1927           if (osect->ovly_mapped == -1)
1928             (*target_overlay_update) (osect);
1929         }
1930       /* fall thru to manual case */
1931     case 1:                     /* overlay debugging manual */
1932       return osect->ovly_mapped == 1;
1933     }
1934 }
1935
1936 /* Function: section_is_mapped
1937    Returns true if section is an overlay, and is currently mapped.  */
1938
1939 int
1940 section_is_mapped (section)
1941      asection *section;
1942 {
1943   struct objfile     *objfile;
1944   struct obj_section *osect;
1945
1946   if (overlay_debugging)
1947     if (section && section_is_overlay (section))
1948       ALL_OBJSECTIONS (objfile, osect)
1949         if (osect->the_bfd_section == section)
1950           return overlay_is_mapped (osect);
1951
1952   return 0;
1953 }
1954
1955 /* Function: pc_in_unmapped_range
1956    If PC falls into the lma range of SECTION, return true, else false.  */
1957
1958 CORE_ADDR
1959 pc_in_unmapped_range (pc, section)
1960      CORE_ADDR pc;
1961      asection *section;
1962 {
1963   int size;
1964
1965   if (overlay_debugging)
1966     if (section && section_is_overlay (section))
1967       {
1968         size = bfd_get_section_size_before_reloc (section);
1969         if (section->lma <= pc && pc < section->lma + size)
1970           return 1;
1971       }
1972   return 0;
1973 }
1974
1975 /* Function: pc_in_mapped_range
1976    If PC falls into the vma range of SECTION, return true, else false.  */
1977
1978 CORE_ADDR
1979 pc_in_mapped_range (pc, section)
1980      CORE_ADDR pc;
1981      asection *section;
1982 {
1983   int size;
1984
1985   if (overlay_debugging)
1986     if (section && section_is_overlay (section))
1987       {
1988         size = bfd_get_section_size_before_reloc (section);
1989         if (section->vma <= pc && pc < section->vma + size)
1990           return 1;
1991       }
1992   return 0;
1993 }
1994
1995 /* Function: overlay_unmapped_address (PC, SECTION)
1996    Returns the address corresponding to PC in the unmapped (load) range.
1997    May be the same as PC.  */
1998
1999 CORE_ADDR
2000 overlay_unmapped_address (pc, section)
2001      CORE_ADDR pc;
2002      asection *section;
2003 {
2004   if (overlay_debugging)
2005     if (section && section_is_overlay (section) &&
2006         pc_in_mapped_range (pc, section))
2007       return pc + section->lma - section->vma;
2008
2009   return pc;
2010 }
2011
2012 /* Function: overlay_mapped_address (PC, SECTION)
2013    Returns the address corresponding to PC in the mapped (runtime) range.
2014    May be the same as PC.  */
2015
2016 CORE_ADDR
2017 overlay_mapped_address (pc, section)
2018      CORE_ADDR pc;
2019      asection *section;
2020 {
2021   if (overlay_debugging)
2022     if (section && section_is_overlay (section) &&
2023         pc_in_unmapped_range (pc, section))
2024       return pc + section->vma - section->lma;
2025
2026   return pc;
2027 }
2028
2029
2030 /* Function: symbol_overlayed_address 
2031    Return one of two addresses (relative to the VMA or to the LMA),
2032    depending on whether the section is mapped or not.  */
2033
2034 CORE_ADDR 
2035 symbol_overlayed_address (address, section)
2036      CORE_ADDR address;
2037      asection *section;
2038 {
2039   if (overlay_debugging)
2040     {
2041       /* If the symbol has no section, just return its regular address. */
2042       if (section == 0)
2043         return address;
2044       /* If the symbol's section is not an overlay, just return its address */
2045       if (!section_is_overlay (section))
2046         return address;
2047       /* If the symbol's section is mapped, just return its address */
2048       if (section_is_mapped (section))
2049         return address;
2050       /*
2051        * HOWEVER: if the symbol is in an overlay section which is NOT mapped,
2052        * then return its LOADED address rather than its vma address!!
2053        */
2054       return overlay_unmapped_address (address, section);
2055     }
2056   return address;
2057 }
2058
2059 /* Function: find_pc_overlay (PC) 
2060    Return the best-match overlay section for PC:
2061    If PC matches a mapped overlay section's VMA, return that section.
2062    Else if PC matches an unmapped section's VMA, return that section.
2063    Else if PC matches an unmapped section's LMA, return that section.  */
2064
2065 asection *
2066 find_pc_overlay (pc)
2067      CORE_ADDR pc;
2068 {
2069   struct objfile     *objfile;
2070   struct obj_section *osect, *best_match = NULL;
2071
2072   if (overlay_debugging)
2073     ALL_OBJSECTIONS (objfile, osect)
2074       if (section_is_overlay (osect->the_bfd_section))
2075         {
2076           if (pc_in_mapped_range (pc, osect->the_bfd_section))
2077             {
2078               if (overlay_is_mapped (osect))
2079                 return osect->the_bfd_section;
2080               else
2081                 best_match = osect;
2082             }
2083           else if (pc_in_unmapped_range (pc, osect->the_bfd_section))
2084             best_match = osect;
2085         }
2086   return best_match ? best_match->the_bfd_section : NULL;
2087 }
2088
2089 /* Function: find_pc_mapped_section (PC)
2090    If PC falls into the VMA address range of an overlay section that is 
2091    currently marked as MAPPED, return that section.  Else return NULL.  */
2092
2093 asection *
2094 find_pc_mapped_section (pc)
2095      CORE_ADDR pc;
2096 {
2097   struct objfile     *objfile;
2098   struct obj_section *osect;
2099
2100   if (overlay_debugging)
2101     ALL_OBJSECTIONS (objfile, osect)
2102       if (pc_in_mapped_range (pc, osect->the_bfd_section) &&
2103           overlay_is_mapped (osect))
2104         return osect->the_bfd_section;
2105
2106   return NULL;
2107 }
2108
2109 /* Function: list_overlays_command
2110    Print a list of mapped sections and their PC ranges */
2111
2112 void
2113 list_overlays_command (args, from_tty)
2114      char *args;
2115      int from_tty;
2116 {
2117   int                nmapped = 0;
2118   struct objfile     *objfile;
2119   struct obj_section *osect;
2120
2121   if (overlay_debugging)
2122     ALL_OBJSECTIONS (objfile, osect)
2123       if (overlay_is_mapped (osect))
2124         {
2125           const char *name;
2126           bfd_vma     lma, vma;
2127           int         size;
2128
2129           vma  = bfd_section_vma (objfile->obfd, osect->the_bfd_section);
2130           lma  = bfd_section_lma (objfile->obfd, osect->the_bfd_section);
2131           size = bfd_get_section_size_before_reloc (osect->the_bfd_section);
2132           name = bfd_section_name (objfile->obfd, osect->the_bfd_section);
2133           printf_filtered ("Section %s, loaded at %08x - %08x, ",
2134                            name, lma, lma + size);
2135           printf_filtered ("mapped at %08x - %08x\n", 
2136                            vma, vma + size);
2137           nmapped ++;
2138         }
2139   if (nmapped == 0)
2140     printf_filtered ("No sections are mapped.\n");
2141 }
2142
2143 /* Function: map_overlay_command
2144    Mark the named section as mapped (ie. residing at its VMA address).  */
2145
2146 void
2147 map_overlay_command (args, from_tty)
2148      char *args;
2149      int   from_tty;
2150 {
2151   struct objfile     *objfile, *objfile2;
2152   struct obj_section *sec,     *sec2;
2153   asection           *bfdsec;
2154
2155   if (!overlay_debugging)
2156     error ("Overlay debugging not enabled.  Use the 'OVERLAY ON' command.");
2157
2158   if (args == 0 || *args == 0)
2159     error ("Argument required: name of an overlay section");
2160
2161   /* First, find a section matching the user supplied argument */
2162   ALL_OBJSECTIONS (objfile, sec)
2163     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
2164       { 
2165         /* Now, check to see if the section is an overlay. */
2166         bfdsec = sec->the_bfd_section;
2167         if (!section_is_overlay (bfdsec))
2168           continue;             /* not an overlay section */
2169
2170         /* Mark the overlay as "mapped" */
2171         sec->ovly_mapped = 1;
2172
2173         /* Next, make a pass and unmap any sections that are
2174            overlapped by this new section: */
2175         ALL_OBJSECTIONS (objfile2, sec2)
2176           if (sec2->ovly_mapped &&
2177               sec != sec2 &&
2178               sec->the_bfd_section != sec2->the_bfd_section &&
2179               (pc_in_mapped_range (sec2->addr,    sec->the_bfd_section) ||
2180                pc_in_mapped_range (sec2->endaddr, sec->the_bfd_section)))
2181             {
2182               if (info_verbose)
2183                 printf_filtered ("Note: section %s unmapped by overlap\n",
2184                                  bfd_section_name (objfile->obfd, 
2185                                                    sec2->the_bfd_section));
2186               sec2->ovly_mapped = 0;    /* sec2 overlaps sec: unmap sec2 */
2187             }
2188         return;
2189       }
2190   error ("No overlay section called %s", args);
2191 }
2192
2193 /* Function: unmap_overlay_command
2194    Mark the overlay section as unmapped 
2195    (ie. resident in its LMA address range, rather than the VMA range).  */
2196
2197 void
2198 unmap_overlay_command (args, from_tty)
2199      char *args;
2200      int   from_tty;
2201 {
2202   struct objfile     *objfile;
2203   struct obj_section *sec;
2204
2205   if (!overlay_debugging)
2206     error ("Overlay debugging not enabled.  Use the 'OVERLAY ON' command.");
2207
2208   if (args == 0 || *args == 0)
2209     error ("Argument required: name of an overlay section");
2210
2211   /* First, find a section matching the user supplied argument */
2212   ALL_OBJSECTIONS (objfile, sec)
2213     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
2214       {
2215         if (!sec->ovly_mapped)
2216           error ("Section %s is not mapped", args);
2217         sec->ovly_mapped = 0;
2218         return;
2219       }
2220   error ("No overlay section called %s", args);
2221 }
2222
2223 /* Function: overlay_auto_command
2224    A utility command to turn on overlay debugging.
2225    Possibly this should be done via a set/show command. */
2226
2227 static void
2228 overlay_auto_command (args, from_tty)
2229 {
2230   overlay_debugging = -1;
2231   if (info_verbose)
2232     printf_filtered ("Automatic overlay debugging enabled.");
2233 }
2234
2235 /* Function: overlay_manual_command
2236    A utility command to turn on overlay debugging.
2237    Possibly this should be done via a set/show command. */
2238
2239 static void
2240 overlay_manual_command (args, from_tty)
2241 {
2242   overlay_debugging = 1;
2243   if (info_verbose)
2244     printf_filtered ("Overlay debugging enabled.");
2245 }
2246
2247 /* Function: overlay_off_command
2248    A utility command to turn on overlay debugging.
2249    Possibly this should be done via a set/show command. */
2250
2251 static void
2252 overlay_off_command (args, from_tty)
2253 {
2254   overlay_debugging = 0;
2255   if (info_verbose)
2256     printf_filtered ("Overlay debugging disabled.");
2257 }
2258
2259 static void
2260 overlay_load_command (args, from_tty)
2261 {
2262   if (target_overlay_update)
2263     (*target_overlay_update) (NULL);
2264   else
2265     error ("This target does not know how to read its overlay state.");
2266 }
2267
2268 /* Function: overlay_command
2269    A place-holder for a mis-typed command */
2270
2271 /* Command list chain containing all defined "overlay" subcommands. */
2272 struct cmd_list_element *overlaylist;
2273
2274 static void
2275 overlay_command (args, from_tty)
2276      char *args;
2277      int from_tty;
2278 {
2279   printf_unfiltered 
2280     ("\"overlay\" must be followed by the name of an overlay command.\n");
2281   help_list (overlaylist, "overlay ", -1, gdb_stdout);
2282 }
2283
2284
2285 /* Target Overlays for the "Simplest" overlay manager:
2286
2287    This is GDB's default target overlay layer.  It works with the 
2288    minimal overlay manager supplied as an example by Cygnus.  The 
2289    entry point is via a function pointer "target_overlay_update", 
2290    so targets that use a different runtime overlay manager can 
2291    substitute their own overlay_update function and take over the
2292    function pointer.
2293
2294    The overlay_update function pokes around in the target's data structures
2295    to see what overlays are mapped, and updates GDB's overlay mapping with
2296    this information.
2297
2298    In this simple implementation, the target data structures are as follows:
2299         unsigned _novlys;               /# number of overlay sections #/
2300         unsigned _ovly_table[_novlys][4] = {
2301           {VMA, SIZE, LMA, MAPPED},     /# one entry per overlay section #/
2302           {..., ...,  ..., ...},
2303         }
2304         unsigned _novly_regions;        /# number of overlay regions #/
2305         unsigned _ovly_region_table[_novly_regions][3] = {
2306           {VMA, SIZE, MAPPED_TO_LMA},   /# one entry per overlay region #/
2307           {..., ...,  ...},
2308         }
2309    These functions will attempt to update GDB's mappedness state in the
2310    symbol section table, based on the target's mappedness state.
2311
2312    To do this, we keep a cached copy of the target's _ovly_table, and
2313    attempt to detect when the cached copy is invalidated.  The main
2314    entry point is "simple_overlay_update(SECT), which looks up SECT in
2315    the cached table and re-reads only the entry for that section from
2316    the target (whenever possible).
2317  */
2318
2319 /* Cached, dynamically allocated copies of the target data structures: */
2320 static unsigned  (*cache_ovly_table)[4] = 0;
2321 #if 0
2322 static unsigned  (*cache_ovly_region_table)[3] = 0;
2323 #endif
2324 static unsigned  cache_novlys = 0;
2325 #if 0
2326 static unsigned  cache_novly_regions = 0;
2327 #endif
2328 static CORE_ADDR cache_ovly_table_base = 0;
2329 #if 0
2330 static CORE_ADDR cache_ovly_region_table_base = 0;
2331 #endif
2332 enum   ovly_index { VMA, SIZE, LMA, MAPPED};
2333 #define TARGET_INT_BYTES (TARGET_INT_BIT / TARGET_CHAR_BIT)
2334
2335 /* Throw away the cached copy of _ovly_table */
2336 static void
2337 simple_free_overlay_table ()
2338 {
2339   if (cache_ovly_table)
2340     free(cache_ovly_table);
2341   cache_novlys     = 0;
2342   cache_ovly_table = NULL;
2343   cache_ovly_table_base = 0;
2344 }
2345
2346 #if 0
2347 /* Throw away the cached copy of _ovly_region_table */
2348 static void
2349 simple_free_overlay_region_table ()
2350 {
2351   if (cache_ovly_region_table)
2352     free(cache_ovly_region_table);
2353   cache_novly_regions     = 0;
2354   cache_ovly_region_table = NULL;
2355   cache_ovly_region_table_base = 0;
2356 }
2357 #endif
2358
2359 /* Read an array of ints from the target into a local buffer.
2360    Convert to host order.  int LEN is number of ints  */
2361 static void
2362 read_target_int_array (memaddr, myaddr, len)
2363      CORE_ADDR     memaddr;
2364      unsigned int *myaddr;
2365      int           len;
2366 {
2367   char *buf = alloca (len * TARGET_INT_BYTES);
2368   int           i;
2369
2370   read_memory (memaddr, buf, len * TARGET_INT_BYTES);
2371   for (i = 0; i < len; i++)
2372     myaddr[i] = extract_unsigned_integer (TARGET_INT_BYTES * i + buf, 
2373                                           TARGET_INT_BYTES);
2374 }
2375
2376 /* Find and grab a copy of the target _ovly_table
2377    (and _novlys, which is needed for the table's size) */
2378 static int 
2379 simple_read_overlay_table ()
2380 {
2381   struct minimal_symbol *msym;
2382
2383   simple_free_overlay_table ();
2384   msym = lookup_minimal_symbol ("_novlys", 0, 0);
2385   if (msym != NULL)
2386     cache_novlys = read_memory_integer (SYMBOL_VALUE_ADDRESS (msym), 4);
2387   else 
2388     return 0;   /* failure */
2389   cache_ovly_table = (void *) xmalloc (cache_novlys * sizeof(*cache_ovly_table));
2390   if (cache_ovly_table != NULL)
2391     {
2392       msym = lookup_minimal_symbol ("_ovly_table", 0, 0);
2393       if (msym != NULL)
2394         {
2395           cache_ovly_table_base = SYMBOL_VALUE_ADDRESS (msym);
2396           read_target_int_array (cache_ovly_table_base, 
2397                                  (int *) cache_ovly_table, 
2398                                  cache_novlys * 4);
2399         }
2400       else 
2401         return 0;       /* failure */
2402     }
2403   else 
2404     return 0;   /* failure */
2405   return 1;     /* SUCCESS */
2406 }
2407
2408 #if 0
2409 /* Find and grab a copy of the target _ovly_region_table
2410    (and _novly_regions, which is needed for the table's size) */
2411 static int 
2412 simple_read_overlay_region_table ()
2413 {
2414   struct minimal_symbol *msym;
2415
2416   simple_free_overlay_region_table ();
2417   msym = lookup_minimal_symbol ("_novly_regions", 0, 0);
2418   if (msym != NULL)
2419     cache_novly_regions = read_memory_integer (SYMBOL_VALUE_ADDRESS (msym), 4);
2420   else 
2421     return 0;   /* failure */
2422   cache_ovly_region_table = (void *) xmalloc (cache_novly_regions * 12);
2423   if (cache_ovly_region_table != NULL)
2424     {
2425       msym = lookup_minimal_symbol ("_ovly_region_table", 0, 0);
2426       if (msym != NULL)
2427         {
2428           cache_ovly_region_table_base = SYMBOL_VALUE_ADDRESS (msym);
2429           read_target_int_array (cache_ovly_region_table_base, 
2430                                  (int *) cache_ovly_region_table, 
2431                                  cache_novly_regions * 3);
2432         }
2433       else 
2434         return 0;       /* failure */
2435     }
2436   else 
2437     return 0;   /* failure */
2438   return 1;     /* SUCCESS */
2439 }
2440 #endif
2441
2442 /* Function: simple_overlay_update_1 
2443    A helper function for simple_overlay_update.  Assuming a cached copy
2444    of _ovly_table exists, look through it to find an entry whose vma,
2445    lma and size match those of OSECT.  Re-read the entry and make sure
2446    it still matches OSECT (else the table may no longer be valid).
2447    Set OSECT's mapped state to match the entry.  Return: 1 for
2448    success, 0 for failure.  */
2449
2450 static int
2451 simple_overlay_update_1 (osect)
2452      struct obj_section *osect;
2453 {
2454   int i, size;
2455
2456   size = bfd_get_section_size_before_reloc (osect->the_bfd_section);
2457   for (i = 0; i < cache_novlys; i++)
2458     if (cache_ovly_table[i][VMA]  == osect->the_bfd_section->vma &&
2459         cache_ovly_table[i][LMA]  == osect->the_bfd_section->lma &&
2460         cache_ovly_table[i][SIZE] == size)
2461       {
2462         read_target_int_array (cache_ovly_table_base + i * TARGET_INT_BYTES,
2463                                (int *) &cache_ovly_table[i], 4);
2464         if (cache_ovly_table[i][VMA]  == osect->the_bfd_section->vma &&
2465             cache_ovly_table[i][LMA]  == osect->the_bfd_section->lma &&
2466             cache_ovly_table[i][SIZE] == size)
2467           {
2468             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
2469             return 1;
2470           }
2471         else    /* Warning!  Warning!  Target's ovly table has changed! */
2472           return 0;
2473       }
2474   return 0;
2475 }
2476
2477 /* Function: simple_overlay_update
2478    If OSECT is NULL, then update all sections' mapped state 
2479    (after re-reading the entire target _ovly_table). 
2480    If OSECT is non-NULL, then try to find a matching entry in the 
2481    cached ovly_table and update only OSECT's mapped state.
2482    If a cached entry can't be found or the cache isn't valid, then 
2483    re-read the entire cache, and go ahead and update all sections.  */
2484
2485 static void
2486 simple_overlay_update (osect)
2487      struct obj_section *osect;
2488 {
2489   struct objfile        *objfile;
2490
2491   /* Were we given an osect to look up?  NULL means do all of them. */
2492   if (osect)
2493     /* Have we got a cached copy of the target's overlay table? */
2494     if (cache_ovly_table != NULL)
2495       /* Does its cached location match what's currently in the symtab? */
2496       if (cache_ovly_table_base == 
2497           SYMBOL_VALUE_ADDRESS (lookup_minimal_symbol ("_ovly_table", 0, 0)))
2498         /* Then go ahead and try to look up this single section in the cache */
2499         if (simple_overlay_update_1 (osect))
2500           /* Found it!  We're done. */
2501           return;
2502
2503   /* Cached table no good: need to read the entire table anew.
2504      Or else we want all the sections, in which case it's actually
2505      more efficient to read the whole table in one block anyway.  */
2506
2507   if (simple_read_overlay_table () == 0)        /* read failed?  No table? */
2508     {
2509       warning ("Failed to read the target overlay mapping table.");
2510       return;
2511     }
2512   /* Now may as well update all sections, even if only one was requested. */
2513   ALL_OBJSECTIONS (objfile, osect)
2514     if (section_is_overlay (osect->the_bfd_section))
2515       {
2516         int i, size;
2517
2518         size = bfd_get_section_size_before_reloc (osect->the_bfd_section);
2519         for (i = 0; i < cache_novlys; i++)
2520           if (cache_ovly_table[i][VMA]  == osect->the_bfd_section->vma &&
2521               cache_ovly_table[i][LMA]  == osect->the_bfd_section->lma &&
2522               cache_ovly_table[i][SIZE] == size)
2523             { /* obj_section matches i'th entry in ovly_table */
2524               osect->ovly_mapped = cache_ovly_table[i][MAPPED];
2525               break;    /* finished with inner for loop: break out */
2526             }
2527       }
2528 }
2529
2530
2531 void
2532 _initialize_symfile ()
2533 {
2534   struct cmd_list_element *c;
2535   
2536   c = add_cmd ("symbol-file", class_files, symbol_file_command,
2537    "Load symbol table from executable file FILE.\n\
2538 The `file' command can also load symbol tables, as well as setting the file\n\
2539 to execute.", &cmdlist);
2540   c->completer = filename_completer;
2541
2542   c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command,
2543    "Usage: add-symbol-file FILE ADDR\n\
2544 Load the symbols from FILE, assuming FILE has been dynamically loaded.\n\
2545 ADDR is the starting address of the file's text.",
2546                &cmdlist);
2547   c->completer = filename_completer;
2548
2549   c = add_cmd ("add-shared-symbol-files", class_files,
2550                add_shared_symbol_files_command,
2551    "Load the symbols from shared objects in the dynamic linker's link map.",
2552                &cmdlist);
2553   c = add_alias_cmd ("assf", "add-shared-symbol-files", class_files, 1,
2554                      &cmdlist);
2555
2556   c = add_cmd ("load", class_files, load_command,
2557    "Dynamically load FILE into the running program, and record its symbols\n\
2558 for access from GDB.", &cmdlist);
2559   c->completer = filename_completer;
2560
2561   add_show_from_set
2562     (add_set_cmd ("symbol-reloading", class_support, var_boolean,
2563                   (char *)&symbol_reloading,
2564           "Set dynamic symbol table reloading multiple times in one run.",
2565                   &setlist),
2566      &showlist);
2567
2568   add_prefix_cmd ("overlay", class_support, overlay_command, 
2569                   "Commands for debugging overlays.", &overlaylist, 
2570                   "overlay ", 0, &cmdlist);
2571
2572   add_com_alias ("ovly", "overlay", class_alias, 1);
2573   add_com_alias ("ov", "overlay", class_alias, 1);
2574
2575   add_cmd ("map-overlay", class_support, map_overlay_command, 
2576            "Assert that an overlay section is mapped.", &overlaylist);
2577
2578   add_cmd ("unmap-overlay", class_support, unmap_overlay_command, 
2579            "Assert that an overlay section is unmapped.", &overlaylist);
2580
2581   add_cmd ("list-overlays", class_support, list_overlays_command, 
2582            "List mappings of overlay sections.", &overlaylist);
2583
2584   add_cmd ("manual", class_support, overlay_manual_command, 
2585            "Enable overlay debugging.", &overlaylist);
2586   add_cmd ("off", class_support, overlay_off_command, 
2587            "Disable overlay debugging.", &overlaylist);
2588   add_cmd ("auto", class_support, overlay_auto_command, 
2589            "Enable automatic overlay debugging.", &overlaylist);
2590   add_cmd ("load-target", class_support, overlay_load_command, 
2591            "Read the overlay mapping state from the target.", &overlaylist);
2592 }