* symfile.c (symbol_file_command): strcmp => !strcmp.
[platform/upstream/binutils.git] / gdb / symfile.c
1 /* Generic symbol file reading for the GNU debugger, GDB.
2    Copyright 1990, 1991, 1992 Free Software Foundation, Inc.
3    Contributed by Cygnus Support, using pieces from other GDB modules.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include <stdio.h>
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 "gdbcmd.h"
31 #include "breakpoint.h"
32 #include "state.h"
33
34 #include <obstack.h>
35 #include <assert.h>
36
37 #include <sys/types.h>
38 #include <fcntl.h>
39 #include <string.h>
40 #include <sys/stat.h>
41
42 /* Global variables owned by this file */
43
44 CORE_ADDR entry_point;                  /* Where execution starts in symfile */
45 struct sym_fns *symtab_fns = NULL;      /* List of all available sym_fns.  */
46
47 /* External variables and functions referenced. */
48
49 extern int info_verbose;
50
51 extern CORE_ADDR startup_file_start;    /* From blockframe.c */
52 extern CORE_ADDR startup_file_end;      /* From blockframe.c */
53
54 /* Functions this file defines */
55
56 static void
57 load_command PARAMS ((char *, int));
58
59 static void
60 add_symbol_file_command PARAMS ((char *, int));
61
62 static struct objfile *
63 symbol_file_add_digested PARAMS ((sfd *, int));
64
65 static void
66 cashier_psymtab PARAMS ((struct partial_symtab *));
67
68 static int
69 compare_psymbols PARAMS ((const void *, const void *));
70
71 static int
72 compare_symbols PARAMS ((const void *, const void *));
73
74 static struct objfile *
75 symfile_open PARAMS ((char *, int));
76
77 static struct sym_fns *
78 symfile_init PARAMS ((struct objfile *));
79
80 static void
81 clear_symtab_users_once PARAMS ((void));
82
83 /* Saves the sym_fns of the current symbol table, so we can call
84    the right XXX_new_init function when we free it.  FIXME.  This
85    should be extended to calling the new_init function for each
86    existing symtab or psymtab, since the main symbol file and 
87    subsequent added symbol files can have different types.  */
88
89 static struct sym_fns *symfile_fns;
90
91 /* When we need to allocate a new type, we need to know which type_obstack
92    to allocate the type on, since there is one for each objfile.  The places
93    where types are allocated are deeply buried in function call hierarchies
94    which know nothing about objfiles, so rather than trying to pass a
95    particular objfile down to them, we just do an end run around them and
96    set current_objfile to be whatever objfile we expect to be using at the
97    time types are being allocated.  For instance, when we start reading
98    symbols for a particular objfile, we set current_objfile to point to that
99    objfile, and when we are done, we set it back to NULL, to ensure that we
100    never put a type someplace other than where we are expecting to put it.
101    FIXME:  Maybe we should review the entire type handling system and
102    see if there is a better way to avoid this problem. */
103
104 struct objfile *current_objfile = NULL;
105
106 /* The object file that the main symbol table was loaded from (e.g. the
107    argument to the "symbol-file" or "file" command).  */
108
109 struct objfile *symfile_objfile = NULL;
110
111 /* Structures with which to manage partial symbol allocation.  */
112
113 struct psymbol_allocation_list global_psymbols = {0}, static_psymbols = {0};
114
115 /* Flag for whether user will be reloading symbols multiple times.
116    Defaults to ON for VxWorks, otherwise OFF.  */
117
118 #ifdef SYMBOL_RELOADING_DEFAULT
119 int symbol_reloading = SYMBOL_RELOADING_DEFAULT;
120 #else
121 int symbol_reloading = 0;
122 #endif
123
124 /* Structure to manage complaints about symbol file contents.  */
125
126 struct complaint complaint_root[1] = {
127   {(char *) 0, 0, complaint_root},
128 };
129
130 /* Some actual complaints.  */
131
132 struct complaint oldsyms_complaint = {
133         "Replacing old symbols for `%s'", 0, 0 };
134
135 struct complaint empty_symtab_complaint = {
136         "Empty symbol table found for `%s'", 0, 0 };
137
138 \f
139 /* In the following sort, we always make sure that
140    register debug symbol declarations always come before regular
141    debug symbol declarations (as might happen when parameters are
142    then put into registers by the compiler).
143
144    Since this function is called from within qsort, in an ANSI environment
145    it must conform to the prototype for qsort, which specifies that the
146    comparison function takes two "void *" pointers. */
147
148 static int
149 compare_symbols (s1p, s2p)
150      const PTR s1p;
151      const PTR s2p;
152 {
153   register struct symbol **s1, **s2;
154   register int namediff;
155
156   s1 = (struct symbol **) s1p;
157   s2 = (struct symbol **) s2p;
158
159   /* Compare the initial characters.  */
160   namediff = SYMBOL_NAME (*s1)[0] - SYMBOL_NAME (*s2)[0];
161   if (namediff != 0) return namediff;
162
163   /* If they match, compare the rest of the names.  */
164   namediff = strcmp (SYMBOL_NAME (*s1), SYMBOL_NAME (*s2));
165   if (namediff != 0) return namediff;
166
167   /* For symbols of the same name, registers should come first.  */
168   return ((SYMBOL_CLASS (*s2) == LOC_REGISTER)
169           - (SYMBOL_CLASS (*s1) == LOC_REGISTER));
170 }
171
172 /*
173
174 LOCAL FUNCTION
175
176         compare_psymbols -- compare two partial symbols by name
177
178 DESCRIPTION
179
180         Given pointer to two partial symbol table entries, compare
181         them by name and return -N, 0, or +N (ala strcmp).  Typically
182         used by sorting routines like qsort().
183
184 NOTES
185
186         Does direct compare of first two characters before punting
187         and passing to strcmp for longer compares.  Note that the
188         original version had a bug whereby two null strings or two
189         identically named one character strings would return the
190         comparison of memory following the null byte.
191
192  */
193
194 static int
195 compare_psymbols (s1p, s2p)
196      const PTR s1p;
197      const PTR s2p;
198 {
199   register char *st1 = SYMBOL_NAME ((struct partial_symbol *) s1p);
200   register char *st2 = SYMBOL_NAME ((struct partial_symbol *) s2p);
201
202   if ((st1[0] - st2[0]) || !st1[0])
203     {
204       return (st1[0] - st2[0]);
205     }
206   else if ((st1[1] - st2[1]) || !st1[1])
207     {
208       return (st1[1] - st2[1]);
209     }
210   else
211     {
212       return (strcmp (st1 + 2, st2 + 2));
213     }
214 }
215
216 void
217 sort_pst_symbols (pst)
218      struct partial_symtab *pst;
219 {
220   /* Sort the global list; don't sort the static list */
221
222   qsort (pst -> objfile -> global_psymbols.list + pst -> globals_offset,
223          pst -> n_global_syms, sizeof (struct partial_symbol),
224          compare_psymbols);
225 }
226
227 /* Call sort_block_syms to sort alphabetically the symbols of one block.  */
228
229 void
230 sort_block_syms (b)
231      register struct block *b;
232 {
233   qsort (&BLOCK_SYM (b, 0), BLOCK_NSYMS (b),
234          sizeof (struct symbol *), compare_symbols);
235 }
236
237 /* Call sort_symtab_syms to sort alphabetically
238    the symbols of each block of one symtab.  */
239
240 void
241 sort_symtab_syms (s)
242      register struct symtab *s;
243 {
244   register struct blockvector *bv;
245   int nbl;
246   int i;
247   register struct block *b;
248
249   if (s == 0)
250     return;
251   bv = BLOCKVECTOR (s);
252   nbl = BLOCKVECTOR_NBLOCKS (bv);
253   for (i = 0; i < nbl; i++)
254     {
255       b = BLOCKVECTOR_BLOCK (bv, i);
256       if (BLOCK_SHOULD_SORT (b))
257         sort_block_syms (b);
258     }
259 }
260
261 void
262 sort_all_symtab_syms ()
263 {
264   register struct symtab *s;
265   register struct objfile *objfile;
266
267   for (objfile = object_files; objfile != NULL; objfile = objfile -> next)
268     {
269       for (s = objfile -> symtabs; s != NULL; s = s -> next)
270         {
271           sort_symtab_syms (s);
272         }
273     }
274 }
275
276 /* Make a copy of the string at PTR with SIZE characters in the symbol obstack
277    (and add a null character at the end in the copy).
278    Returns the address of the copy.  */
279
280 char *
281 obsavestring (ptr, size, obstackp)
282      char *ptr;
283      int size;
284      struct obstack *obstackp;
285 {
286   register char *p = (char *) obstack_alloc (obstackp, size + 1);
287   /* Open-coded bcopy--saves function call time.
288      These strings are usually short.  */
289   {
290     register char *p1 = ptr;
291     register char *p2 = p;
292     char *end = ptr + size;
293     while (p1 != end)
294       *p2++ = *p1++;
295   }
296   p[size] = 0;
297   return p;
298 }
299
300 /* Concatenate strings S1, S2 and S3; return the new string.
301    Space is found in the symbol_obstack.  */
302
303 char *
304 obconcat (obstackp, s1, s2, s3)
305      struct obstack *obstackp;
306      const char *s1, *s2, *s3;
307 {
308   register int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
309   register char *val = (char *) obstack_alloc (obstackp, len);
310   strcpy (val, s1);
311   strcat (val, s2);
312   strcat (val, s3);
313   return val;
314 }
315
316 /* Get the symbol table that corresponds to a partial_symtab.
317    This is fast after the first time you do it.  In fact, there
318    is an even faster macro PSYMTAB_TO_SYMTAB that does the fast
319    case inline.  */
320
321 struct symtab *
322 psymtab_to_symtab (pst)
323      register struct partial_symtab *pst;
324 {
325   /* If it's been looked up before, return it. */
326   if (pst->symtab)
327     return pst->symtab;
328
329   /* If it has not yet been read in, read it.  */
330   if (!pst->readin)
331     { 
332       (*pst->read_symtab) (pst);
333     }
334
335   return pst->symtab;
336 }
337
338 /* Process a symbol file, as either the main file or as a dynamically
339    loaded file.
340
341    NAME is the file name (which will be tilde-expanded and made
342    absolute herein) (but we don't free or modify NAME itself).
343    FROM_TTY says how verbose to be.  MAINLINE specifies whether this
344    is the main symbol file, or whether it's an extra symbol file such
345    as dynamically loaded code.  If !mainline, ADDR is the address
346    where the text segment was loaded.  If VERBO, the caller has printed
347    a verbose message about the symbol reading (and complaints can be
348    more terse about it).  */
349
350 void
351 syms_from_objfile (objfile, addr, mainline, verbo)
352      struct objfile *objfile;
353      CORE_ADDR addr;
354      int mainline;
355      int verbo;
356 {
357   asection *text_sect;
358   struct sym_fns *sf;
359   bfd *sym_bfd = objfile->obfd;
360
361   /* There is a distinction between having no symbol table
362      (we refuse to read the file, leaving the old set of symbols around)
363      and having no debugging symbols in your symbol table (we read
364      the file and end up with a mostly empty symbol table).  */
365
366   if (!(bfd_get_file_flags (sym_bfd) & HAS_SYMS))
367     return;
368
369   /* Save startup file's range of PC addresses to help blockframe.c
370      decide where the bottom of the stack is.  */
371   if (bfd_get_file_flags (sym_bfd) & EXEC_P)
372     {
373       /* Executable file -- record its entry point so we'll recognize
374          the startup file because it contains the entry point.  */
375       entry_point = bfd_get_start_address (sym_bfd);
376     }
377   else
378     {
379       /* Examination of non-executable.o files.  Short-circuit this stuff.  */
380       /* ~0 will not be in any file, we hope.  */
381       entry_point = ~0;
382       /* set the startup file to be an empty range.  */
383       startup_file_start = 0;
384       startup_file_end = 0;
385     }
386
387   sf = symfile_init (objfile);
388
389   if (mainline) 
390     {
391       /* Since no error yet, throw away the old symbol table.  */
392
393       if (symfile_objfile)
394         free_objfile (symfile_objfile);
395       symfile_objfile = NULL;
396
397       (*sf->sym_new_init) ();
398
399       /* For mainline, caller didn't know the specified address of the
400          text section.  We fix that here.  */
401       text_sect = bfd_get_section_by_name (sym_bfd, ".text");
402       addr = bfd_section_vma (sym_bfd, text_sect);
403     }
404
405   /* Allow complaints to appear for this new file, and record how
406      verbose to be. */
407
408   clear_complaints(1, verbo);
409
410   (*sf->sym_read) (sf, addr, mainline);
411
412   /* Don't allow char * to have a typename (else would get caddr_t.)  */
413   /* Ditto void *.  FIXME should do this for all the builtin types.  */
414
415   TYPE_NAME (lookup_pointer_type (builtin_type_char)) = 0;
416   TYPE_NAME (lookup_pointer_type (builtin_type_void)) = 0;
417
418   if (mainline)
419     {
420       /* OK, make it the "real" symbol file.  */
421       symfile_objfile = objfile;
422       symfile_fns = sf;
423     }
424
425   /* If we have wiped out any old symbol tables, clean up.  */
426   clear_symtab_users_once ();
427
428   /* We're done reading the symbol file; finish off complaints.  */
429   clear_complaints(0, verbo);
430
431   /* Setup the breakpoint(s) for trapping longjmp(), as it may have been
432      defined by this new file. */
433   create_longjmp_breakpoint();
434 }
435
436 /* Reload a predigested symbol file from a dumped state file.
437
438    FIXME:  For now, we load only the first dumped objfile that we
439    find, for two reasons.  (1) Our custom malloc and mmap'd sbrk
440    implementation only supports one mmap'd objfile at a time, so we
441    can only create state files with one dumped objfile in them and
442    would have no way to deal with multiple dumped objfiles when reading
443    the state file back in even if we could create them.  (2) We currently
444    have no way to select a specific objfile to load from a state file
445    containing a dump of more than one objfile, so we just select the
446    first one we encounter.  */
447
448 static struct objfile *
449 symbol_file_add_digested (asfd, from_tty)
450      sfd *asfd;
451      int from_tty;
452 {
453   struct objfile *objfile;
454   bfd *sym_bfd;
455
456   /* First locate and map in the dumped symbol information */
457
458   objfile = objfile_from_statefile (asfd);
459
460   /* Push this file onto the head of the linked list of other such files. */
461
462   objfile -> next = object_files;
463   object_files = objfile;
464
465 #if 0   /* FIXME: Things to deal with... */
466   objfile -> obfd = abfd;
467   objfile -> mtime = bfd_get_mtime (abfd);
468   obstack_full_begin (&objfile -> psymbol_obstack, 0, 0, xmalloc, free);
469   obstack_full_begin (&objfile -> symbol_obstack, 0, 0, xmalloc, free);
470   obstack_full_begin (&objfile -> type_obstack, 0, 0, xmalloc, free);
471 #endif
472
473 }
474
475 /* Process a symbol file, as either the main file or as a dynamically
476    loaded file.
477
478    NAME is the file name (which will be tilde-expanded and made
479    absolute herein) (but we don't free or modify NAME itself).
480    FROM_TTY says how verbose to be.  MAINLINE specifies whether this
481    is the main symbol file, or whether it's an extra symbol file such
482    as dynamically loaded code.  If !mainline, ADDR is the address
483    where the text segment was loaded.
484
485    Upon success, returns a pointer to the objfile that was added.
486    Upon failure, jumps back to command level (never returns). */
487
488 struct objfile *
489 symbol_file_add (name, from_tty, addr, mainline, dumpable)
490      char *name;
491      int from_tty;
492      CORE_ADDR addr;
493      int mainline;
494      int dumpable;
495 {
496   struct objfile *objfile;
497   bfd *sym_bfd;
498
499   objfile = symfile_open (name, dumpable);
500   sym_bfd = objfile->obfd;
501
502   /* There is a distinction between having no symbol table
503      (we refuse to read the file, leaving the old set of symbols around)
504      and having no debugging symbols in your symbol table (we read
505      the file and end up with a mostly empty symbol table, but with lots
506      of stuff in the minimal symbol table).  */
507
508   if (!(bfd_get_file_flags (sym_bfd) & HAS_SYMS))
509     {
510       error ("%s has no symbol-table", name);
511     }
512
513   if ((have_full_symbols () || have_partial_symbols ())
514       && mainline
515       && from_tty
516       && !query ("Load new symbol table from \"%s\"? ", name))
517     error ("Not confirmed.");
518
519   if (from_tty || info_verbose)
520     {
521       printf_filtered ("Reading symbols from %s...", name);
522       wrap_here ("");
523       fflush (stdout);
524     }
525
526   syms_from_objfile (objfile, addr, mainline, from_tty);
527
528   if (from_tty || info_verbose)
529     {
530       printf_filtered ("done.\n");
531       fflush (stdout);
532     }
533   return (objfile);
534 }
535
536 /* This is the symbol-file command.  Read the file, analyze its symbols,
537    and add a struct symtab to a symtab list.  */
538
539 void
540 symbol_file_command (args, from_tty)
541      char *args;
542      int from_tty;
543 {
544   char **argv;
545   char *name;
546   struct cleanup *cleanups;
547   struct objfile *objfile;
548   struct partial_symtab *psymtab;
549   sfd *sym_sfd;
550   int dumpable = 0;
551   int readnow = 0;
552
553   dont_repeat ();
554
555   if (args == NULL)
556     {
557       if (symfile_objfile)
558         {
559           if ((have_full_symbols () || have_partial_symbols ())
560               && from_tty
561               && !query ("Discard symbol table from `%s'? ",
562                          symfile_objfile -> name))
563             error ("Not confirmed.");
564           free_objfile (symfile_objfile);
565         }
566       symfile_objfile = NULL;
567       /* FIXME, this does not account for the main file and subsequent
568          files (shared libs, dynloads, etc) having different formats. 
569          It only calls the cleanup routine for the main file's format.  */
570       if (symfile_fns)
571         {
572           (*symfile_fns -> sym_new_init) ();
573           free (symfile_fns);
574           symfile_fns = 0;
575         }
576     }
577   else
578     {
579       if ((argv = buildargv (args)) == NULL)
580         {
581           fatal ("virtual memory exhausted.", 0);
582         }
583       cleanups = make_cleanup (freeargv, (char *) argv);
584
585       name = *argv;
586       while (*++argv != NULL)
587         {
588           if (!strcmp (*argv, "dumpable"))
589             {
590               dumpable = 1;
591             }
592           else if (!strcmp (*argv, "readnow"))
593             {
594               readnow = 1;
595             }
596         }
597
598       if (name != NULL)
599         {
600           if ((sym_sfd = sfd_fopen (name, "r")) != NULL)
601             {
602               (void) symbol_file_add_digested (sym_sfd, from_tty);
603             }
604           else
605             {
606               /* Getting new symbols may change our opinion about what is
607                  frameless.  */
608               reinit_frame_cache ();
609               objfile = symbol_file_add (name, from_tty, (CORE_ADDR)0, 1,
610                                          dumpable);
611               if (readnow)
612                 {
613                   for (psymtab = objfile -> psymtabs;
614                        psymtab != NULL;
615                        psymtab = psymtab -> next)
616                     {
617                       (void) psymtab_to_symtab (psymtab);
618                     }
619                 }
620             }
621         }
622       do_cleanups (cleanups);
623     }
624 }
625
626 /* Open NAME and hand it off to BFD for preliminary analysis.  Result
627    is newly malloc'd struct objfile *, which includes a newly malloc'd`
628    copy of NAME (tilde-expanded and made absolute).
629    In case of trouble, error() is called.  */
630
631 static struct objfile *
632 symfile_open (name, dumpable)
633      char *name;
634      int dumpable;
635 {
636   bfd *sym_bfd;
637   int desc;
638   char *absolute_name;
639   struct objfile *objfile;
640
641   name = tilde_expand (name);   /* Returns 1st new malloc'd copy */
642
643   /* Look down path for it, allocate 2nd new malloc'd copy.  */
644   desc = openp (getenv ("PATH"), 1, name, O_RDONLY, 0, &absolute_name);
645   if (desc < 0) {
646     make_cleanup (free, name);
647     perror_with_name (name);
648   }
649   free (name);                  /* Free 1st new malloc'd copy */
650   name = absolute_name;         /* Keep 2nd malloc'd copy in bfd */
651
652   sym_bfd = bfd_fdopenr (name, NULL, desc);
653   if (!sym_bfd)
654     {
655       close (desc);
656       make_cleanup (free, name);
657       error ("Could not open `%s' to read symbols: %s",
658              name, bfd_errmsg (bfd_error));
659     }
660
661   if (!bfd_check_format (sym_bfd, bfd_object)) {
662     bfd_close (sym_bfd);        /* This also closes desc */
663     make_cleanup (free, name);
664     error ("\"%s\": can't read symbols: %s.",
665            name, bfd_errmsg (bfd_error));
666   }
667
668   objfile = allocate_objfile (sym_bfd, name, dumpable);
669   return objfile;
670 }
671
672 /* Link a new symtab_fns into the global symtab_fns list.
673    Called by various _initialize routines.  */
674
675 void
676 add_symtab_fns (sf)
677      struct sym_fns *sf;
678 {
679   sf->next = symtab_fns;
680   symtab_fns = sf;
681 }
682
683
684 /* Initialize to read symbols from the symbol file sym_bfd.  It either
685    returns or calls error().  The result is a malloc'd struct sym_fns
686    that contains cached information about the symbol file.  */
687
688 static struct sym_fns *
689 symfile_init (objfile)
690      struct objfile *objfile;
691 {
692   struct sym_fns *sf, *sf2;
693   bfd *sym_bfd = objfile->obfd;
694
695   for (sf = symtab_fns; sf != NULL; sf = sf->next)
696     {
697       if (!strncmp (bfd_get_target (sym_bfd), sf->sym_name, sf->sym_namelen))
698         {
699           sf2 = (struct sym_fns *)xmalloc (sizeof (*sf2));      
700           /* FIXME, who frees this? */
701           *sf2 = *sf;
702           sf2->objfile = objfile;
703           sf2->sym_bfd = sym_bfd;
704           sf2->sym_private = 0;                 /* Not alloc'd yet */
705           (*sf2->sym_init) (sf2);
706           return sf2;
707         }
708     }
709   error ("I'm sorry, Dave, I can't do that.  Symbol format `%s' unknown.",
710          bfd_get_target (sym_bfd));
711   return 0; /* Appease lint.  */
712 }
713 \f
714 /* This function runs the load command of our current target.  */
715
716 static void
717 load_command (arg, from_tty)
718      char *arg;
719      int from_tty;
720 {
721   target_load (arg, from_tty);
722 }
723
724 /* This function allows the addition of incrementally linked object files.
725    It does not modify any state in the target, only in the debugger.  */
726
727 /* ARGSUSED */
728 static void
729 add_symbol_file_command (arg_string, from_tty)
730      char *arg_string;
731      int from_tty;
732 {
733   char *name;
734   CORE_ADDR text_addr;
735   
736   /* Getting new symbols may change our opinion about what is
737      frameless.  */
738   reinit_frame_cache ();
739
740   if (arg_string == 0)
741     error ("add-symbol-file takes a file name and an address");
742
743   arg_string = tilde_expand (arg_string);
744   make_cleanup (free, arg_string);
745
746   for( ; *arg_string == ' '; arg_string++ );
747   name = arg_string;
748   for( ; *arg_string && *arg_string != ' ' ; arg_string++ );
749   *arg_string++ = (char) 0;
750
751   if (name[0] == 0)
752     error ("add-symbol-file takes a file name and an address");
753
754   text_addr = parse_and_eval_address (arg_string);
755
756   dont_repeat ();
757
758   if (!query ("add symbol table from file \"%s\" at text_addr = %s?\n",
759               name, local_hex_string (text_addr)))
760     error ("Not confirmed.");
761
762   (void) symbol_file_add (name, 0, text_addr, 0, 0);
763 }
764 \f
765 /* Re-read symbols if a symbol-file has changed.  */
766 void
767 reread_symbols ()
768 {
769   struct objfile *objfile;
770   long new_modtime;
771   int reread_one = 0;
772
773   /* With the addition of shared libraries, this should be modified,
774      the load time should be saved in the partial symbol tables, since
775      different tables may come from different source files.  FIXME.
776      This routine should then walk down each partial symbol table
777      and see if the symbol table that it originates from has been changed */
778
779 the_big_top:
780   for (objfile = object_files; objfile; objfile = objfile->next) {
781     if (objfile->obfd) {
782       new_modtime = bfd_get_mtime (objfile->obfd);
783       if (new_modtime != objfile->mtime) {
784         printf_filtered ("`%s' has changed; re-reading symbols.\n",
785                          objfile->name);
786         /* FIXME, this should use a different command...that would only
787            affect this objfile's symbols, and would reset objfile->mtime.
788                 (objfile->mtime = new_modtime;)
789            HOWEVER, that command isn't written yet -- so call symbol_file_
790            command, and restart the scan from the top, because it munges
791            the object_files list.  */
792         symbol_file_command (objfile->name, 0);
793         reread_one = 1;
794         goto the_big_top;       /* Start over.  */
795       }
796     }
797   }
798
799   if (reread_one)
800     breakpoint_re_set ();
801 }
802
803 \f
804 /* Functions to handle complaints during symbol reading.  */
805
806 /* How many complaints about a particular thing should be printed before
807    we stop whining about it?  Default is no whining at all, since so many
808    systems have ill-constructed symbol files.  */
809
810 static unsigned stop_whining = 0;
811
812 /* Should each complaint be self explanatory, or should we assume that
813    a series of complaints is being produced? 
814    case 0:  self explanatory message.
815    case 1:  First message of a series that must start off with explanation.
816    case 2:  Subsequent message, when user already knows we are reading
817             symbols and we can just state our piece.  */
818
819 static int complaint_series = 0;
820
821 /* Print a complaint about the input symbols, and link the complaint block
822    into a chain for later handling.  */
823
824 void
825 complain (complaint, val)
826      struct complaint *complaint;
827      char *val;
828 {
829   complaint->counter++;
830   if (complaint->next == 0) {
831     complaint->next = complaint_root->next;
832     complaint_root->next = complaint;
833   }
834   if (complaint->counter > stop_whining)
835     return;
836   wrap_here ("");
837
838   switch (complaint_series + (info_verbose << 1)) {
839
840   /* Isolated messages, must be self-explanatory.  */
841   case 0:
842     puts_filtered ("During symbol reading, ");
843     wrap_here("");
844     printf_filtered (complaint->message, val);
845     puts_filtered (".\n");
846     break;
847
848   /* First of a series, without `set verbose'.  */
849   case 1:
850     puts_filtered ("During symbol reading...");
851     printf_filtered (complaint->message, val);
852     puts_filtered ("...");
853     wrap_here("");
854     complaint_series++;
855     break;
856
857   /* Subsequent messages of a series, or messages under `set verbose'.
858      (We'll already have produced a "Reading in symbols for XXX..." message
859       and will clean up at the end with a newline.)  */
860   default:
861     printf_filtered (complaint->message, val);
862     puts_filtered ("...");
863     wrap_here("");
864   }
865 }
866
867 /* Clear out all complaint counters that have ever been incremented.
868    If sym_reading is 1, be less verbose about successive complaints,
869    since the messages are appearing all together during a command that
870    reads symbols (rather than scattered around as psymtabs get fleshed
871    out into symtabs at random times).  If noisy is 1, we are in a
872    noisy symbol reading command, and our caller will print enough
873    context for the user to figure it out.  */
874
875 void
876 clear_complaints (sym_reading, noisy)
877      int sym_reading;
878      int noisy;
879 {
880   struct complaint *p;
881
882   for (p = complaint_root->next; p != complaint_root; p = p->next)
883     p->counter = 0;
884
885   if (!sym_reading && !noisy && complaint_series > 1) {
886     /* Terminate previous series, since caller won't.  */
887     puts_filtered ("\n");
888   }
889
890   complaint_series = sym_reading? 1 + noisy: 0;
891 }
892 \f
893 enum language
894 deduce_language_from_filename (filename)
895      char *filename;
896 {
897   char *c = strrchr (filename, '.');
898   
899   if (!c) ; /* Get default. */
900   else if(!strcmp(c,".mod"))
901      return language_m2;
902   else if(!strcmp(c,".c"))
903      return language_c;
904   else if(!strcmp(c,".cc") || !strcmp(c,".C"))
905      return language_cplus;
906
907   return language_unknown;              /* default */
908 }
909 \f
910 /* allocate_symtab:
911
912    Allocate and partly initialize a new symbol table.  Return a pointer
913    to it.  error() if no space.
914
915    Caller must set these fields:
916         LINETABLE(symtab)
917         symtab->blockvector
918         symtab->dirname
919         symtab->free_code
920         symtab->free_ptr
921         initialize any EXTRA_SYMTAB_INFO
922         possibly free_named_symtabs (symtab->filename);
923  */
924
925 struct symtab *
926 allocate_symtab (filename, objfile)
927      char *filename;
928      struct objfile *objfile;
929 {
930   register struct symtab *symtab;
931
932   symtab = (struct symtab *)
933     obstack_alloc (&objfile -> symbol_obstack, sizeof (struct symtab));
934   (void) memset (symtab, 0, sizeof (*symtab));
935   symtab -> filename = obsavestring (filename, strlen (filename),
936                                      &objfile -> symbol_obstack);
937   symtab -> fullname = NULL;
938   symtab -> language = deduce_language_from_filename (filename);
939
940   /* Hook it to the objfile it comes from */
941
942   symtab -> objfile = objfile;
943   symtab -> next = objfile -> symtabs;
944   objfile -> symtabs = symtab;
945
946 #ifdef INIT_EXTRA_SYMTAB_INFO
947   INIT_EXTRA_SYMTAB_INFO (symtab);
948 #endif
949
950   return (symtab);
951 }
952
953 struct partial_symtab *
954 allocate_psymtab (filename, objfile)
955      char *filename;
956      struct objfile *objfile;
957 {
958   struct partial_symtab *psymtab;
959
960   psymtab = (struct partial_symtab *)
961     obstack_alloc (&objfile -> psymbol_obstack,
962                    sizeof (struct partial_symtab));
963   (void) memset (psymtab, 0, sizeof (struct partial_symtab));
964   psymtab -> filename = obsavestring (filename, strlen (filename),
965                                       &objfile -> psymbol_obstack);
966   psymtab -> symtab = NULL;
967
968   /* Hook it to the objfile it comes from */
969
970   psymtab -> objfile = objfile;
971   psymtab -> next = objfile -> psymtabs;
972   objfile -> psymtabs = psymtab;
973   
974   return (psymtab);
975 }
976
977 \f
978 /* clear_symtab_users_once:
979
980    This function is run after symbol reading, or from a cleanup.
981    If an old symbol table was obsoleted, the old symbol table
982    has been blown away, but the other GDB data structures that may 
983    reference it have not yet been cleared or re-directed.  (The old
984    symtab was zapped, and the cleanup queued, in free_named_symtab()
985    below.)
986
987    This function can be queued N times as a cleanup, or called
988    directly; it will do all the work the first time, and then will be a
989    no-op until the next time it is queued.  This works by bumping a
990    counter at queueing time.  Much later when the cleanup is run, or at
991    the end of symbol processing (in case the cleanup is discarded), if
992    the queued count is greater than the "done-count", we do the work
993    and set the done-count to the queued count.  If the queued count is
994    less than or equal to the done-count, we just ignore the call.  This
995    is needed because reading a single .o file will often replace many
996    symtabs (one per .h file, for example), and we don't want to reset
997    the breakpoints N times in the user's face.
998
999    The reason we both queue a cleanup, and call it directly after symbol
1000    reading, is because the cleanup protects us in case of errors, but is
1001    discarded if symbol reading is successful.  */
1002
1003 static int clear_symtab_users_queued;
1004 static int clear_symtab_users_done;
1005
1006 static void
1007 clear_symtab_users_once ()
1008 {
1009   /* Enforce once-per-`do_cleanups'-semantics */
1010   if (clear_symtab_users_queued <= clear_symtab_users_done)
1011     return;
1012   clear_symtab_users_done = clear_symtab_users_queued;
1013
1014   printf ("Resetting debugger state after updating old symbol tables\n");
1015
1016   /* Someday, we should do better than this, by only blowing away
1017      the things that really need to be blown.  */
1018   clear_value_history ();
1019   clear_displays ();
1020   clear_internalvars ();
1021   breakpoint_re_set ();
1022   set_default_breakpoint (0, 0, 0, 0);
1023   current_source_symtab = 0;
1024 }
1025
1026 /* Delete the specified psymtab, and any others that reference it.  */
1027
1028 static void
1029 cashier_psymtab (pst)
1030      struct partial_symtab *pst;
1031 {
1032   struct partial_symtab *ps, *pprev;
1033   int i;
1034
1035   /* Find its previous psymtab in the chain */
1036   for (ps = pst->objfile->psymtabs; ps; ps = ps->next) {
1037     if (ps == pst)
1038       break;
1039     pprev = ps;
1040   }
1041
1042   if (ps) {
1043     /* Unhook it from the chain.  */
1044     if (ps == pst->objfile->psymtabs)
1045       pst->objfile->psymtabs = ps->next;
1046     else
1047       pprev->next = ps->next;
1048
1049     /* FIXME, we can't conveniently deallocate the entries in the
1050        partial_symbol lists (global_psymbols/static_psymbols) that
1051        this psymtab points to.  These just take up space until all
1052        the psymtabs are reclaimed.  Ditto the dependencies list and
1053        filename, which are all in the psymbol_obstack.  */
1054
1055     /* We need to cashier any psymtab that has this one as a dependency... */
1056 again:
1057     for (ps = pst->objfile->psymtabs; ps; ps = ps->next) {
1058       for (i = 0; i < ps->number_of_dependencies; i++) {
1059         if (ps->dependencies[i] == pst) {
1060           cashier_psymtab (ps);
1061           goto again;           /* Must restart, chain has been munged. */
1062         }
1063       }
1064     }
1065   }
1066 }
1067
1068 /* If a symtab or psymtab for filename NAME is found, free it along
1069    with any dependent breakpoints, displays, etc.
1070    Used when loading new versions of object modules with the "add-file"
1071    command.  This is only called on the top-level symtab or psymtab's name;
1072    it is not called for subsidiary files such as .h files.
1073
1074    Return value is 1 if we blew away the environment, 0 if not.
1075    FIXME.  The return valu appears to never be used.
1076
1077    FIXME.  I think this is not the best way to do this.  We should
1078    work on being gentler to the environment while still cleaning up
1079    all stray pointers into the freed symtab.  */
1080
1081 int
1082 free_named_symtabs (name)
1083      char *name;
1084 {
1085   register struct symtab *s;
1086   register struct symtab *prev;
1087   register struct partial_symtab *ps;
1088   struct blockvector *bv;
1089   int blewit = 0;
1090
1091 #if 0
1092   /* FIXME:  With the new method of each objfile having it's own
1093      psymtab list, this function needs serious rethinking.  In particular,
1094      why was it ever necessary to toss psymtabs with specific compilation
1095      unit filenames, as opposed to all psymtabs from a particular symbol
1096      file. */
1097
1098   /* We only wack things if the symbol-reload switch is set.  */
1099   if (!symbol_reloading)
1100     return 0;
1101
1102   /* Some symbol formats have trouble providing file names... */
1103   if (name == 0 || *name == '\0')
1104     return 0;
1105
1106   /* Look for a psymtab with the specified name.  */
1107
1108 again2:
1109   for (ps = partial_symtab_list; ps; ps = ps->next) {
1110     if (!strcmp (name, ps->filename)) {
1111       cashier_psymtab (ps);     /* Blow it away...and its little dog, too.  */
1112       goto again2;              /* Must restart, chain has been munged */
1113     }
1114   }
1115
1116   /* Look for a symtab with the specified name.  */
1117
1118   for (s = symtab_list; s; s = s->next)
1119     {
1120       if (!strcmp (name, s->filename))
1121         break;
1122       prev = s;
1123     }
1124
1125   if (s)
1126     {
1127       if (s == symtab_list)
1128         symtab_list = s->next;
1129       else
1130         prev->next = s->next;
1131
1132       /* For now, queue a delete for all breakpoints, displays, etc., whether
1133          or not they depend on the symtab being freed.  This should be
1134          changed so that only those data structures affected are deleted.  */
1135
1136       /* But don't delete anything if the symtab is empty.
1137          This test is necessary due to a bug in "dbxread.c" that
1138          causes empty symtabs to be created for N_SO symbols that
1139          contain the pathname of the object file.  (This problem
1140          has been fixed in GDB 3.9x).  */
1141
1142       bv = BLOCKVECTOR (s);
1143       if (BLOCKVECTOR_NBLOCKS (bv) > 2
1144           || BLOCK_NSYMS (BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK))
1145           || BLOCK_NSYMS (BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK)))
1146         {
1147           complain (&oldsyms_complaint, name);
1148
1149           clear_symtab_users_queued++;
1150           make_cleanup (clear_symtab_users_once, 0);
1151           blewit = 1;
1152         } else {
1153           complain (&empty_symtab_complaint, name);
1154         }
1155
1156       free_symtab (s);
1157     }
1158   else
1159     {
1160       /* It is still possible that some breakpoints will be affected
1161          even though no symtab was found, since the file might have
1162          been compiled without debugging, and hence not be associated
1163          with a symtab.  In order to handle this correctly, we would need
1164          to keep a list of text address ranges for undebuggable files.
1165          For now, we do nothing, since this is a fairly obscure case.  */
1166       ;
1167     }
1168
1169   /* FIXME, what about the minimal symbol table? */
1170   return blewit;
1171 #else
1172   return (0);
1173 #endif
1174 }
1175 \f
1176 /* Allocate and partially fill a partial symtab.  It will be
1177    completely filled at the end of the symbol list.
1178
1179    SYMFILE_NAME is the name of the symbol-file we are reading from, and ADDR
1180    is the address relative to which its symbols are (incremental) or 0
1181    (normal). */
1182
1183
1184 struct partial_symtab *
1185 start_psymtab_common (objfile, addr,
1186                       filename, textlow, global_syms, static_syms)
1187      struct objfile *objfile;
1188      CORE_ADDR addr;
1189      char *filename;
1190      CORE_ADDR textlow;
1191      struct partial_symbol *global_syms;
1192      struct partial_symbol *static_syms;
1193 {
1194   struct partial_symtab *psymtab;
1195
1196   psymtab = allocate_psymtab (filename, objfile);
1197   psymtab -> addr = addr;
1198   psymtab -> textlow = textlow;
1199   psymtab -> texthigh = psymtab -> textlow;  /* default */
1200   psymtab -> globals_offset = global_syms - objfile -> global_psymbols.list;
1201   psymtab -> statics_offset = static_syms - objfile -> static_psymbols.list;
1202   return (psymtab);
1203 }
1204
1205 \f
1206 void
1207 _initialize_symfile ()
1208 {
1209
1210   add_com ("symbol-file", class_files, symbol_file_command,
1211    "Load symbol table from executable file FILE.\n\
1212 The `file' command can also load symbol tables, as well as setting the file\n\
1213 to execute.");
1214
1215   add_com ("add-symbol-file", class_files, add_symbol_file_command,
1216    "Load the symbols from FILE, assuming FILE has been dynamically loaded.\n\
1217 The second argument provides the starting address of the file's text.");
1218
1219   add_com ("load", class_files, load_command,
1220    "Dynamically load FILE into the running program, and record its symbols\n\
1221 for access from GDB.");
1222
1223   add_show_from_set
1224     (add_set_cmd ("complaints", class_support, var_zinteger,
1225                   (char *)&stop_whining,
1226           "Set max number of complaints about incorrect symbols.",
1227                   &setlist),
1228      &showlist);
1229
1230   add_show_from_set
1231     (add_set_cmd ("symbol-reloading", class_support, var_boolean,
1232                   (char *)&symbol_reloading,
1233           "Set dynamic symbol table reloading multiple times in one run.",
1234                   &setlist),
1235      &showlist);
1236
1237 }