* buildsym.c (add_symbol_to_list): Delete outdated comment.
[external/binutils.git] / gdb / buildsym.c
1 /* Support routines for building symbol tables in GDB's internal format.
2    Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
3    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2007, 2008, 2009,
4    2010, 2011 Free Software Foundation, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.  */
20
21 /* This module provides subroutines used for creating and adding to
22    the symbol table.  These routines are called from various symbol-
23    file-reading routines.
24
25    Routines to support specific debugging information formats (stabs,
26    DWARF, etc) belong somewhere else.  */
27
28 #include "defs.h"
29 #include "bfd.h"
30 #include "gdb_obstack.h"
31 #include "symtab.h"
32 #include "symfile.h"
33 #include "objfiles.h"
34 #include "gdbtypes.h"
35 #include "gdb_assert.h"
36 #include "complaints.h"
37 #include "gdb_string.h"
38 #include "expression.h"         /* For "enum exp_opcode" used by...  */
39 #include "bcache.h"
40 #include "filenames.h"          /* For DOSish file names.  */
41 #include "macrotab.h"
42 #include "demangle.h"           /* Needed by SYMBOL_INIT_DEMANGLED_NAME.  */
43 #include "block.h"
44 #include "cp-support.h"
45 #include "dictionary.h"
46 #include "addrmap.h"
47
48 /* Ask buildsym.h to define the vars it normally declares `extern'.  */
49 #define EXTERN
50 /**/
51 #include "buildsym.h"           /* Our own declarations.  */
52 #undef  EXTERN
53
54 /* For cleanup_undefined_types and finish_global_stabs (somewhat
55    questionable--see comment where we call them).  */
56
57 #include "stabsread.h"
58
59 /* List of subfiles.  */
60
61 static struct subfile *subfiles;
62
63 /* List of free `struct pending' structures for reuse.  */
64
65 static struct pending *free_pendings;
66
67 /* Non-zero if symtab has line number info.  This prevents an
68    otherwise empty symtab from being tossed.  */
69
70 static int have_line_numbers;
71
72 /* The mutable address map for the compilation unit whose symbols
73    we're currently reading.  The symtabs' shared blockvector will
74    point to a fixed copy of this.  */
75 static struct addrmap *pending_addrmap;
76
77 /* The obstack on which we allocate pending_addrmap.
78    If pending_addrmap is NULL, this is uninitialized; otherwise, it is
79    initialized (and holds pending_addrmap).  */
80 static struct obstack pending_addrmap_obstack;
81
82 /* Non-zero if we recorded any ranges in the addrmap that are
83    different from those in the blockvector already.  We set this to
84    zero when we start processing a symfile, and if it's still zero at
85    the end, then we just toss the addrmap.  */
86 static int pending_addrmap_interesting;
87
88 \f
89 static int compare_line_numbers (const void *ln1p, const void *ln2p);
90 \f
91
92 /* Initial sizes of data structures.  These are realloc'd larger if
93    needed, and realloc'd down to the size actually used, when
94    completed.  */
95
96 #define INITIAL_CONTEXT_STACK_SIZE      10
97 #define INITIAL_LINE_VECTOR_LENGTH      1000
98 \f
99
100 /* Maintain the lists of symbols and blocks.  */
101
102 /* Add a pending list to free_pendings.  */
103 void
104 add_free_pendings (struct pending *list)
105 {
106   struct pending *link = list;
107
108   if (list)
109     {
110       while (link->next) link = link->next;
111       link->next = free_pendings;
112       free_pendings = list;
113     }
114 }
115
116 /* Add a symbol to one of the lists of symbols.  */
117
118 void
119 add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
120 {
121   struct pending *link;
122
123   /* If this is an alias for another symbol, don't add it.  */
124   if (symbol->ginfo.name && symbol->ginfo.name[0] == '#')
125     return;
126
127   /* We keep PENDINGSIZE symbols in each link of the list.  If we
128      don't have a link with room in it, add a new link.  */
129   if (*listhead == NULL || (*listhead)->nsyms == PENDINGSIZE)
130     {
131       if (free_pendings)
132         {
133           link = free_pendings;
134           free_pendings = link->next;
135         }
136       else
137         {
138           link = (struct pending *) xmalloc (sizeof (struct pending));
139         }
140
141       link->next = *listhead;
142       *listhead = link;
143       link->nsyms = 0;
144     }
145
146   (*listhead)->symbol[(*listhead)->nsyms++] = symbol;
147 }
148
149 /* Find a symbol named NAME on a LIST.  NAME need not be
150    '\0'-terminated; LENGTH is the length of the name.  */
151
152 struct symbol *
153 find_symbol_in_list (struct pending *list, char *name, int length)
154 {
155   int j;
156   char *pp;
157
158   while (list != NULL)
159     {
160       for (j = list->nsyms; --j >= 0;)
161         {
162           pp = SYMBOL_LINKAGE_NAME (list->symbol[j]);
163           if (*pp == *name && strncmp (pp, name, length) == 0
164               && pp[length] == '\0')
165             {
166               return (list->symbol[j]);
167             }
168         }
169       list = list->next;
170     }
171   return (NULL);
172 }
173
174 /* At end of reading syms, or in case of quit, really free as many
175    `struct pending's as we can easily find.  */
176
177 void
178 really_free_pendings (void *dummy)
179 {
180   struct pending *next, *next1;
181
182   for (next = free_pendings; next; next = next1)
183     {
184       next1 = next->next;
185       xfree ((void *) next);
186     }
187   free_pendings = NULL;
188
189   free_pending_blocks ();
190
191   for (next = file_symbols; next != NULL; next = next1)
192     {
193       next1 = next->next;
194       xfree ((void *) next);
195     }
196   file_symbols = NULL;
197
198   for (next = global_symbols; next != NULL; next = next1)
199     {
200       next1 = next->next;
201       xfree ((void *) next);
202     }
203   global_symbols = NULL;
204
205   if (pending_macros)
206     free_macro_table (pending_macros);
207
208   if (pending_addrmap)
209     {
210       obstack_free (&pending_addrmap_obstack, NULL);
211       pending_addrmap = NULL;
212     }
213 }
214
215 /* This function is called to discard any pending blocks.  */
216
217 void
218 free_pending_blocks (void)
219 {
220   /* The links are made in the objfile_obstack, so we only need to
221      reset PENDING_BLOCKS.  */
222   pending_blocks = NULL;
223 }
224
225 /* Take one of the lists of symbols and make a block from it.  Keep
226    the order the symbols have in the list (reversed from the input
227    file).  Put the block on the list of pending blocks.  */
228
229 struct block *
230 finish_block (struct symbol *symbol, struct pending **listhead,
231               struct pending_block *old_blocks,
232               CORE_ADDR start, CORE_ADDR end,
233               struct objfile *objfile)
234 {
235   struct gdbarch *gdbarch = get_objfile_arch (objfile);
236   struct pending *next, *next1;
237   struct block *block;
238   struct pending_block *pblock;
239   struct pending_block *opblock;
240
241   block = allocate_block (&objfile->objfile_obstack);
242
243   if (symbol)
244     {
245       BLOCK_DICT (block) = dict_create_linear (&objfile->objfile_obstack,
246                                                *listhead);
247     }
248   else
249     {
250       BLOCK_DICT (block) = dict_create_hashed (&objfile->objfile_obstack,
251                                                *listhead);
252     }
253
254   BLOCK_START (block) = start;
255   BLOCK_END (block) = end;
256   /* Superblock filled in when containing block is made.  */
257   BLOCK_SUPERBLOCK (block) = NULL;
258   BLOCK_NAMESPACE (block) = NULL;
259
260   /* Put the block in as the value of the symbol that names it.  */
261
262   if (symbol)
263     {
264       struct type *ftype = SYMBOL_TYPE (symbol);
265       struct dict_iterator iter;
266       SYMBOL_BLOCK_VALUE (symbol) = block;
267       BLOCK_FUNCTION (block) = symbol;
268
269       if (TYPE_NFIELDS (ftype) <= 0)
270         {
271           /* No parameter type information is recorded with the
272              function's type.  Set that from the type of the
273              parameter symbols.  */
274           int nparams = 0, iparams;
275           struct symbol *sym;
276           ALL_BLOCK_SYMBOLS (block, iter, sym)
277             {
278               if (SYMBOL_IS_ARGUMENT (sym))
279                 nparams++;
280             }
281           if (nparams > 0)
282             {
283               TYPE_NFIELDS (ftype) = nparams;
284               TYPE_FIELDS (ftype) = (struct field *)
285                 TYPE_ALLOC (ftype, nparams * sizeof (struct field));
286
287               iparams = 0;
288               ALL_BLOCK_SYMBOLS (block, iter, sym)
289                 {
290                   if (iparams == nparams)
291                     break;
292
293                   if (SYMBOL_IS_ARGUMENT (sym))
294                     {
295                       TYPE_FIELD_TYPE (ftype, iparams) = SYMBOL_TYPE (sym);
296                       TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
297                       iparams++;
298                     }
299                 }
300             }
301         }
302     }
303   else
304     {
305       BLOCK_FUNCTION (block) = NULL;
306     }
307
308   /* Now "free" the links of the list, and empty the list.  */
309
310   for (next = *listhead; next; next = next1)
311     {
312       next1 = next->next;
313       next->next = free_pendings;
314       free_pendings = next;
315     }
316   *listhead = NULL;
317
318   /* Check to be sure that the blocks have an end address that is
319      greater than starting address.  */
320
321   if (BLOCK_END (block) < BLOCK_START (block))
322     {
323       if (symbol)
324         {
325           complaint (&symfile_complaints,
326                      _("block end address less than block "
327                        "start address in %s (patched it)"),
328                      SYMBOL_PRINT_NAME (symbol));
329         }
330       else
331         {
332           complaint (&symfile_complaints,
333                      _("block end address %s less than block "
334                        "start address %s (patched it)"),
335                      paddress (gdbarch, BLOCK_END (block)),
336                      paddress (gdbarch, BLOCK_START (block)));
337         }
338       /* Better than nothing.  */
339       BLOCK_END (block) = BLOCK_START (block);
340     }
341
342   /* Install this block as the superblock of all blocks made since the
343      start of this scope that don't have superblocks yet.  */
344
345   opblock = NULL;
346   for (pblock = pending_blocks; 
347        pblock && pblock != old_blocks; 
348        pblock = pblock->next)
349     {
350       if (BLOCK_SUPERBLOCK (pblock->block) == NULL)
351         {
352           /* Check to be sure the blocks are nested as we receive
353              them.  If the compiler/assembler/linker work, this just
354              burns a small amount of time.
355
356              Skip blocks which correspond to a function; they're not
357              physically nested inside this other blocks, only
358              lexically nested.  */
359           if (BLOCK_FUNCTION (pblock->block) == NULL
360               && (BLOCK_START (pblock->block) < BLOCK_START (block)
361                   || BLOCK_END (pblock->block) > BLOCK_END (block)))
362             {
363               if (symbol)
364                 {
365                   complaint (&symfile_complaints,
366                              _("inner block not inside outer block in %s"),
367                              SYMBOL_PRINT_NAME (symbol));
368                 }
369               else
370                 {
371                   complaint (&symfile_complaints,
372                              _("inner block (%s-%s) not "
373                                "inside outer block (%s-%s)"),
374                              paddress (gdbarch, BLOCK_START (pblock->block)),
375                              paddress (gdbarch, BLOCK_END (pblock->block)),
376                              paddress (gdbarch, BLOCK_START (block)),
377                              paddress (gdbarch, BLOCK_END (block)));
378                 }
379               if (BLOCK_START (pblock->block) < BLOCK_START (block))
380                 BLOCK_START (pblock->block) = BLOCK_START (block);
381               if (BLOCK_END (pblock->block) > BLOCK_END (block))
382                 BLOCK_END (pblock->block) = BLOCK_END (block);
383             }
384           BLOCK_SUPERBLOCK (pblock->block) = block;
385         }
386       opblock = pblock;
387     }
388
389   block_set_using (block, using_directives, &objfile->objfile_obstack);
390   using_directives = NULL;
391
392   record_pending_block (objfile, block, opblock);
393
394   return block;
395 }
396
397
398 /* Record BLOCK on the list of all blocks in the file.  Put it after
399    OPBLOCK, or at the beginning if opblock is NULL.  This puts the
400    block in the list after all its subblocks.
401
402    Allocate the pending block struct in the objfile_obstack to save
403    time.  This wastes a little space.  FIXME: Is it worth it?  */
404
405 void
406 record_pending_block (struct objfile *objfile, struct block *block,
407                       struct pending_block *opblock)
408 {
409   struct pending_block *pblock;
410
411   pblock = (struct pending_block *)
412     obstack_alloc (&objfile->objfile_obstack, sizeof (struct pending_block));
413   pblock->block = block;
414   if (opblock)
415     {
416       pblock->next = opblock->next;
417       opblock->next = pblock;
418     }
419   else
420     {
421       pblock->next = pending_blocks;
422       pending_blocks = pblock;
423     }
424 }
425
426
427 /* Record that the range of addresses from START to END_INCLUSIVE
428    (inclusive, like it says) belongs to BLOCK.  BLOCK's start and end
429    addresses must be set already.  You must apply this function to all
430    BLOCK's children before applying it to BLOCK.
431
432    If a call to this function complicates the picture beyond that
433    already provided by BLOCK_START and BLOCK_END, then we create an
434    address map for the block.  */
435 void
436 record_block_range (struct block *block,
437                     CORE_ADDR start, CORE_ADDR end_inclusive)
438 {
439   /* If this is any different from the range recorded in the block's
440      own BLOCK_START and BLOCK_END, then note that the address map has
441      become interesting.  Note that even if this block doesn't have
442      any "interesting" ranges, some later block might, so we still
443      need to record this block in the addrmap.  */
444   if (start != BLOCK_START (block)
445       || end_inclusive + 1 != BLOCK_END (block))
446     pending_addrmap_interesting = 1;
447
448   if (! pending_addrmap)
449     {
450       obstack_init (&pending_addrmap_obstack);
451       pending_addrmap = addrmap_create_mutable (&pending_addrmap_obstack);
452     }
453
454   addrmap_set_empty (pending_addrmap, start, end_inclusive, block);
455 }
456
457
458 static struct blockvector *
459 make_blockvector (struct objfile *objfile)
460 {
461   struct pending_block *next;
462   struct blockvector *blockvector;
463   int i;
464
465   /* Count the length of the list of blocks.  */
466
467   for (next = pending_blocks, i = 0; next; next = next->next, i++)
468     {;
469     }
470
471   blockvector = (struct blockvector *)
472     obstack_alloc (&objfile->objfile_obstack,
473                    (sizeof (struct blockvector)
474                     + (i - 1) * sizeof (struct block *)));
475
476   /* Copy the blocks into the blockvector.  This is done in reverse
477      order, which happens to put the blocks into the proper order
478      (ascending starting address).  finish_block has hair to insert
479      each block into the list after its subblocks in order to make
480      sure this is true.  */
481
482   BLOCKVECTOR_NBLOCKS (blockvector) = i;
483   for (next = pending_blocks; next; next = next->next)
484     {
485       BLOCKVECTOR_BLOCK (blockvector, --i) = next->block;
486     }
487
488   free_pending_blocks ();
489
490   /* If we needed an address map for this symtab, record it in the
491      blockvector.  */
492   if (pending_addrmap && pending_addrmap_interesting)
493     BLOCKVECTOR_MAP (blockvector)
494       = addrmap_create_fixed (pending_addrmap, &objfile->objfile_obstack);
495   else
496     BLOCKVECTOR_MAP (blockvector) = 0;
497         
498   /* Some compilers output blocks in the wrong order, but we depend on
499      their being in the right order so we can binary search.  Check the
500      order and moan about it.  */
501   if (BLOCKVECTOR_NBLOCKS (blockvector) > 1)
502     {
503       for (i = 1; i < BLOCKVECTOR_NBLOCKS (blockvector); i++)
504         {
505           if (BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i - 1))
506               > BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i)))
507             {
508               CORE_ADDR start
509                 = BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i));
510
511               complaint (&symfile_complaints, _("block at %s out of order"),
512                          hex_string ((LONGEST) start));
513             }
514         }
515     }
516
517   return (blockvector);
518 }
519 \f
520 /* Start recording information about source code that came from an
521    included (or otherwise merged-in) source file with a different
522    name.  NAME is the name of the file (cannot be NULL), DIRNAME is
523    the directory in which the file was compiled (or NULL if not
524    known).  */
525
526 void
527 start_subfile (const char *name, const char *dirname)
528 {
529   struct subfile *subfile;
530
531   /* See if this subfile is already known as a subfile of the current
532      main source file.  */
533
534   for (subfile = subfiles; subfile; subfile = subfile->next)
535     {
536       char *subfile_name;
537
538       /* If NAME is an absolute path, and this subfile is not, then
539          attempt to create an absolute path to compare.  */
540       if (IS_ABSOLUTE_PATH (name)
541           && !IS_ABSOLUTE_PATH (subfile->name)
542           && subfile->dirname != NULL)
543         subfile_name = concat (subfile->dirname, SLASH_STRING,
544                                subfile->name, (char *) NULL);
545       else
546         subfile_name = subfile->name;
547
548       if (FILENAME_CMP (subfile_name, name) == 0)
549         {
550           current_subfile = subfile;
551           if (subfile_name != subfile->name)
552             xfree (subfile_name);
553           return;
554         }
555       if (subfile_name != subfile->name)
556         xfree (subfile_name);
557     }
558
559   /* This subfile is not known.  Add an entry for it.  Make an entry
560      for this subfile in the list of all subfiles of the current main
561      source file.  */
562
563   subfile = (struct subfile *) xmalloc (sizeof (struct subfile));
564   memset ((char *) subfile, 0, sizeof (struct subfile));
565   subfile->next = subfiles;
566   subfiles = subfile;
567   current_subfile = subfile;
568
569   /* Save its name and compilation directory name.  */
570   subfile->name = (name == NULL) ? NULL : xstrdup (name);
571   subfile->dirname = (dirname == NULL) ? NULL : xstrdup (dirname);
572
573   /* Initialize line-number recording for this subfile.  */
574   subfile->line_vector = NULL;
575
576   /* Default the source language to whatever can be deduced from the
577      filename.  If nothing can be deduced (such as for a C/C++ include
578      file with a ".h" extension), then inherit whatever language the
579      previous subfile had.  This kludgery is necessary because there
580      is no standard way in some object formats to record the source
581      language.  Also, when symtabs are allocated we try to deduce a
582      language then as well, but it is too late for us to use that
583      information while reading symbols, since symtabs aren't allocated
584      until after all the symbols have been processed for a given
585      source file.  */
586
587   subfile->language = deduce_language_from_filename (subfile->name);
588   if (subfile->language == language_unknown
589       && subfile->next != NULL)
590     {
591       subfile->language = subfile->next->language;
592     }
593
594   /* Initialize the debug format string to NULL.  We may supply it
595      later via a call to record_debugformat.  */
596   subfile->debugformat = NULL;
597
598   /* Similarly for the producer.  */
599   subfile->producer = NULL;
600
601   /* If the filename of this subfile ends in .C, then change the
602      language of any pending subfiles from C to C++.  We also accept
603      any other C++ suffixes accepted by deduce_language_from_filename.  */
604   /* Likewise for f2c.  */
605
606   if (subfile->name)
607     {
608       struct subfile *s;
609       enum language sublang = deduce_language_from_filename (subfile->name);
610
611       if (sublang == language_cplus || sublang == language_fortran)
612         for (s = subfiles; s != NULL; s = s->next)
613           if (s->language == language_c)
614             s->language = sublang;
615     }
616
617   /* And patch up this file if necessary.  */
618   if (subfile->language == language_c
619       && subfile->next != NULL
620       && (subfile->next->language == language_cplus
621           || subfile->next->language == language_fortran))
622     {
623       subfile->language = subfile->next->language;
624     }
625 }
626
627 /* For stabs readers, the first N_SO symbol is assumed to be the
628    source file name, and the subfile struct is initialized using that
629    assumption.  If another N_SO symbol is later seen, immediately
630    following the first one, then the first one is assumed to be the
631    directory name and the second one is really the source file name.
632
633    So we have to patch up the subfile struct by moving the old name
634    value to dirname and remembering the new name.  Some sanity
635    checking is performed to ensure that the state of the subfile
636    struct is reasonable and that the old name we are assuming to be a
637    directory name actually is (by checking for a trailing '/').  */
638
639 void
640 patch_subfile_names (struct subfile *subfile, char *name)
641 {
642   if (subfile != NULL && subfile->dirname == NULL && subfile->name != NULL
643       && IS_DIR_SEPARATOR (subfile->name[strlen (subfile->name) - 1]))
644     {
645       subfile->dirname = subfile->name;
646       subfile->name = xstrdup (name);
647       last_source_file = name;
648
649       /* Default the source language to whatever can be deduced from
650          the filename.  If nothing can be deduced (such as for a C/C++
651          include file with a ".h" extension), then inherit whatever
652          language the previous subfile had.  This kludgery is
653          necessary because there is no standard way in some object
654          formats to record the source language.  Also, when symtabs
655          are allocated we try to deduce a language then as well, but
656          it is too late for us to use that information while reading
657          symbols, since symtabs aren't allocated until after all the
658          symbols have been processed for a given source file.  */
659
660       subfile->language = deduce_language_from_filename (subfile->name);
661       if (subfile->language == language_unknown
662           && subfile->next != NULL)
663         {
664           subfile->language = subfile->next->language;
665         }
666     }
667 }
668 \f
669 /* Handle the N_BINCL and N_EINCL symbol types that act like N_SOL for
670    switching source files (different subfiles, as we call them) within
671    one object file, but using a stack rather than in an arbitrary
672    order.  */
673
674 void
675 push_subfile (void)
676 {
677   struct subfile_stack *tem
678     = (struct subfile_stack *) xmalloc (sizeof (struct subfile_stack));
679
680   tem->next = subfile_stack;
681   subfile_stack = tem;
682   if (current_subfile == NULL || current_subfile->name == NULL)
683     {
684       internal_error (__FILE__, __LINE__, 
685                       _("failed internal consistency check"));
686     }
687   tem->name = current_subfile->name;
688 }
689
690 char *
691 pop_subfile (void)
692 {
693   char *name;
694   struct subfile_stack *link = subfile_stack;
695
696   if (link == NULL)
697     {
698       internal_error (__FILE__, __LINE__,
699                       _("failed internal consistency check"));
700     }
701   name = link->name;
702   subfile_stack = link->next;
703   xfree ((void *) link);
704   return (name);
705 }
706 \f
707 /* Add a linetable entry for line number LINE and address PC to the
708    line vector for SUBFILE.  */
709
710 void
711 record_line (struct subfile *subfile, int line, CORE_ADDR pc)
712 {
713   struct linetable_entry *e;
714
715   /* Ignore the dummy line number in libg.o */
716   if (line == 0xffff)
717     {
718       return;
719     }
720
721   /* Make sure line vector exists and is big enough.  */
722   if (!subfile->line_vector)
723     {
724       subfile->line_vector_length = INITIAL_LINE_VECTOR_LENGTH;
725       subfile->line_vector = (struct linetable *)
726         xmalloc (sizeof (struct linetable)
727            + subfile->line_vector_length * sizeof (struct linetable_entry));
728       subfile->line_vector->nitems = 0;
729       have_line_numbers = 1;
730     }
731
732   if (subfile->line_vector->nitems + 1 >= subfile->line_vector_length)
733     {
734       subfile->line_vector_length *= 2;
735       subfile->line_vector = (struct linetable *)
736         xrealloc ((char *) subfile->line_vector,
737                   (sizeof (struct linetable)
738                    + (subfile->line_vector_length
739                       * sizeof (struct linetable_entry))));
740     }
741
742   /* Normally, we treat lines as unsorted.  But the end of sequence
743      marker is special.  We sort line markers at the same PC by line
744      number, so end of sequence markers (which have line == 0) appear
745      first.  This is right if the marker ends the previous function,
746      and there is no padding before the next function.  But it is
747      wrong if the previous line was empty and we are now marking a
748      switch to a different subfile.  We must leave the end of sequence
749      marker at the end of this group of lines, not sort the empty line
750      to after the marker.  The easiest way to accomplish this is to
751      delete any empty lines from our table, if they are followed by
752      end of sequence markers.  All we lose is the ability to set
753      breakpoints at some lines which contain no instructions
754      anyway.  */
755   if (line == 0 && subfile->line_vector->nitems > 0)
756     {
757       e = subfile->line_vector->item + subfile->line_vector->nitems - 1;
758       while (subfile->line_vector->nitems > 0 && e->pc == pc)
759         {
760           e--;
761           subfile->line_vector->nitems--;
762         }
763     }
764
765   e = subfile->line_vector->item + subfile->line_vector->nitems++;
766   e->line = line;
767   e->pc = pc;
768 }
769
770 /* Needed in order to sort line tables from IBM xcoff files.  Sigh!  */
771
772 static int
773 compare_line_numbers (const void *ln1p, const void *ln2p)
774 {
775   struct linetable_entry *ln1 = (struct linetable_entry *) ln1p;
776   struct linetable_entry *ln2 = (struct linetable_entry *) ln2p;
777
778   /* Note: this code does not assume that CORE_ADDRs can fit in ints.
779      Please keep it that way.  */
780   if (ln1->pc < ln2->pc)
781     return -1;
782
783   if (ln1->pc > ln2->pc)
784     return 1;
785
786   /* If pc equal, sort by line.  I'm not sure whether this is optimum
787      behavior (see comment at struct linetable in symtab.h).  */
788   return ln1->line - ln2->line;
789 }
790 \f
791 /* Start a new symtab for a new source file.  Called, for example,
792    when a stabs symbol of type N_SO is seen, or when a DWARF
793    TAG_compile_unit DIE is seen.  It indicates the start of data for
794    one original source file.
795
796    NAME is the name of the file (cannot be NULL).  DIRNAME is the directory in
797    which the file was compiled (or NULL if not known).  START_ADDR is the
798    lowest address of objects in the file (or 0 if not known).  */
799
800 void
801 start_symtab (char *name, char *dirname, CORE_ADDR start_addr)
802 {
803   last_source_file = name;
804   last_source_start_addr = start_addr;
805   file_symbols = NULL;
806   global_symbols = NULL;
807   within_function = 0;
808   have_line_numbers = 0;
809
810   /* Context stack is initially empty.  Allocate first one with room
811      for 10 levels; reuse it forever afterward.  */
812   if (context_stack == NULL)
813     {
814       context_stack_size = INITIAL_CONTEXT_STACK_SIZE;
815       context_stack = (struct context_stack *)
816         xmalloc (context_stack_size * sizeof (struct context_stack));
817     }
818   context_stack_depth = 0;
819
820   /* We shouldn't have any address map at this point.  */
821   gdb_assert (! pending_addrmap);
822
823   /* Initialize the list of sub source files with one entry for this
824      file (the top-level source file).  */
825
826   subfiles = NULL;
827   current_subfile = NULL;
828   start_subfile (name, dirname);
829 }
830
831 /* Subroutine of end_symtab to simplify it.  Look for a subfile that
832    matches the main source file's basename.  If there is only one, and
833    if the main source file doesn't have any symbol or line number
834    information, then copy this file's symtab and line_vector to the
835    main source file's subfile and discard the other subfile.  This can
836    happen because of a compiler bug or from the user playing games
837    with #line or from things like a distributed build system that
838    manipulates the debug info.  */
839
840 static void
841 watch_main_source_file_lossage (void)
842 {
843   struct subfile *mainsub, *subfile;
844
845   /* Find the main source file.
846      This loop could be eliminated if start_symtab saved it for us.  */
847   mainsub = NULL;
848   for (subfile = subfiles; subfile; subfile = subfile->next)
849     {
850       /* The main subfile is guaranteed to be the last one.  */
851       if (subfile->next == NULL)
852         mainsub = subfile;
853     }
854
855   /* If the main source file doesn't have any line number or symbol
856      info, look for an alias in another subfile.
857
858      We have to watch for mainsub == NULL here.  It's a quirk of
859      end_symtab, it can return NULL so there may not be a main
860      subfile.  */
861
862   if (mainsub
863       && mainsub->line_vector == NULL
864       && mainsub->symtab == NULL)
865     {
866       const char *mainbase = lbasename (mainsub->name);
867       int nr_matches = 0;
868       struct subfile *prevsub;
869       struct subfile *mainsub_alias = NULL;
870       struct subfile *prev_mainsub_alias = NULL;
871
872       prevsub = NULL;
873       for (subfile = subfiles;
874            /* Stop before we get to the last one.  */
875            subfile->next;
876            subfile = subfile->next)
877         {
878           if (filename_cmp (lbasename (subfile->name), mainbase) == 0)
879             {
880               ++nr_matches;
881               mainsub_alias = subfile;
882               prev_mainsub_alias = prevsub;
883             }
884           prevsub = subfile;
885         }
886
887       if (nr_matches == 1)
888         {
889           gdb_assert (mainsub_alias != NULL && mainsub_alias != mainsub);
890
891           /* Found a match for the main source file.
892              Copy its line_vector and symtab to the main subfile
893              and then discard it.  */
894
895           mainsub->line_vector = mainsub_alias->line_vector;
896           mainsub->line_vector_length = mainsub_alias->line_vector_length;
897           mainsub->symtab = mainsub_alias->symtab;
898
899           if (prev_mainsub_alias == NULL)
900             subfiles = mainsub_alias->next;
901           else
902             prev_mainsub_alias->next = mainsub_alias->next;
903           xfree (mainsub_alias);
904         }
905     }
906 }
907
908 /* Helper function for qsort.  Parametes are `struct block *' pointers,
909    function sorts them in descending order by their BLOCK_START.  */
910
911 static int
912 block_compar (const void *ap, const void *bp)
913 {
914   const struct block *a = *(const struct block **) ap;
915   const struct block *b = *(const struct block **) bp;
916
917   return ((BLOCK_START (b) > BLOCK_START (a))
918           - (BLOCK_START (b) < BLOCK_START (a)));
919 }
920
921 /* Finish the symbol definitions for one main source file, close off
922    all the lexical contexts for that file (creating struct block's for
923    them), then make the struct symtab for that file and put it in the
924    list of all such.
925
926    END_ADDR is the address of the end of the file's text.  SECTION is
927    the section number (in objfile->section_offsets) of the blockvector
928    and linetable.
929
930    Note that it is possible for end_symtab() to return NULL.  In
931    particular, for the DWARF case at least, it will return NULL when
932    it finds a compilation unit that has exactly one DIE, a
933    TAG_compile_unit DIE.  This can happen when we link in an object
934    file that was compiled from an empty source file.  Returning NULL
935    is probably not the correct thing to do, because then gdb will
936    never know about this empty file (FIXME).  */
937
938 struct symtab *
939 end_symtab (CORE_ADDR end_addr, struct objfile *objfile, int section)
940 {
941   struct symtab *symtab = NULL;
942   struct blockvector *blockvector;
943   struct subfile *subfile;
944   struct context_stack *cstk;
945   struct subfile *nextsub;
946
947   /* Finish the lexical context of the last function in the file; pop
948      the context stack.  */
949
950   if (context_stack_depth > 0)
951     {
952       cstk = pop_context ();
953       /* Make a block for the local symbols within.  */
954       finish_block (cstk->name, &local_symbols, cstk->old_blocks,
955                     cstk->start_addr, end_addr, objfile);
956
957       if (context_stack_depth > 0)
958         {
959           /* This is said to happen with SCO.  The old coffread.c
960              code simply emptied the context stack, so we do the
961              same.  FIXME: Find out why it is happening.  This is not
962              believed to happen in most cases (even for coffread.c);
963              it used to be an abort().  */
964           complaint (&symfile_complaints,
965                      _("Context stack not empty in end_symtab"));
966           context_stack_depth = 0;
967         }
968     }
969
970   /* Reordered executables may have out of order pending blocks; if
971      OBJF_REORDERED is true, then sort the pending blocks.  */
972   if ((objfile->flags & OBJF_REORDERED) && pending_blocks)
973     {
974       unsigned count = 0;
975       struct pending_block *pb;
976       struct block **barray, **bp;
977       struct cleanup *back_to;
978
979       for (pb = pending_blocks; pb != NULL; pb = pb->next)
980         count++;
981
982       barray = xmalloc (sizeof (*barray) * count);
983       back_to = make_cleanup (xfree, barray);
984
985       bp = barray;
986       for (pb = pending_blocks; pb != NULL; pb = pb->next)
987         *bp++ = pb->block;
988
989       qsort (barray, count, sizeof (*barray), block_compar);
990
991       bp = barray;
992       for (pb = pending_blocks; pb != NULL; pb = pb->next)
993         pb->block = *bp++;
994
995       do_cleanups (back_to);
996     }
997
998   /* Cleanup any undefined types that have been left hanging around
999      (this needs to be done before the finish_blocks so that
1000      file_symbols is still good).
1001
1002      Both cleanup_undefined_types and finish_global_stabs are stabs
1003      specific, but harmless for other symbol readers, since on gdb
1004      startup or when finished reading stabs, the state is set so these
1005      are no-ops.  FIXME: Is this handled right in case of QUIT?  Can
1006      we make this cleaner?  */
1007
1008   cleanup_undefined_types (objfile);
1009   finish_global_stabs (objfile);
1010
1011   if (pending_blocks == NULL
1012       && file_symbols == NULL
1013       && global_symbols == NULL
1014       && have_line_numbers == 0
1015       && pending_macros == NULL)
1016     {
1017       /* Ignore symtabs that have no functions with real debugging
1018          info.  */
1019       blockvector = NULL;
1020     }
1021   else
1022     {
1023       /* Define the STATIC_BLOCK & GLOBAL_BLOCK, and build the
1024          blockvector.  */
1025       finish_block (0, &file_symbols, 0, last_source_start_addr,
1026                     end_addr, objfile);
1027       finish_block (0, &global_symbols, 0, last_source_start_addr,
1028                     end_addr, objfile);
1029       blockvector = make_blockvector (objfile);
1030     }
1031
1032   /* Read the line table if it has to be read separately.  */
1033   if (objfile->sf->sym_read_linetable != NULL)
1034     objfile->sf->sym_read_linetable ();
1035
1036   /* Handle the case where the debug info specifies a different path
1037      for the main source file.  It can cause us to lose track of its
1038      line number information.  */
1039   watch_main_source_file_lossage ();
1040
1041   /* Now create the symtab objects proper, one for each subfile.  */
1042   /* (The main file is the last one on the chain.)  */
1043
1044   for (subfile = subfiles; subfile; subfile = nextsub)
1045     {
1046       int linetablesize = 0;
1047       symtab = NULL;
1048
1049       /* If we have blocks of symbols, make a symtab.  Otherwise, just
1050          ignore this file and any line number info in it.  */
1051       if (blockvector)
1052         {
1053           if (subfile->line_vector)
1054             {
1055               linetablesize = sizeof (struct linetable) +
1056                 subfile->line_vector->nitems * sizeof (struct linetable_entry);
1057
1058               /* Like the pending blocks, the line table may be
1059                  scrambled in reordered executables.  Sort it if
1060                  OBJF_REORDERED is true.  */
1061               if (objfile->flags & OBJF_REORDERED)
1062                 qsort (subfile->line_vector->item,
1063                        subfile->line_vector->nitems,
1064                      sizeof (struct linetable_entry), compare_line_numbers);
1065             }
1066
1067           /* Now, allocate a symbol table.  */
1068           if (subfile->symtab == NULL)
1069             symtab = allocate_symtab (subfile->name, objfile);
1070           else
1071             symtab = subfile->symtab;
1072
1073           /* Fill in its components.  */
1074           symtab->blockvector = blockvector;
1075           symtab->macro_table = pending_macros;
1076           if (subfile->line_vector)
1077             {
1078               /* Reallocate the line table on the symbol obstack.  */
1079               symtab->linetable = (struct linetable *)
1080                 obstack_alloc (&objfile->objfile_obstack, linetablesize);
1081               memcpy (symtab->linetable, subfile->line_vector, linetablesize);
1082             }
1083           else
1084             {
1085               symtab->linetable = NULL;
1086             }
1087           symtab->block_line_section = section;
1088           if (subfile->dirname)
1089             {
1090               /* Reallocate the dirname on the symbol obstack.  */
1091               symtab->dirname = (char *)
1092                 obstack_alloc (&objfile->objfile_obstack,
1093                                strlen (subfile->dirname) + 1);
1094               strcpy (symtab->dirname, subfile->dirname);
1095             }
1096           else
1097             {
1098               symtab->dirname = NULL;
1099             }
1100
1101           /* Use whatever language we have been using for this
1102              subfile, not the one that was deduced in allocate_symtab
1103              from the filename.  We already did our own deducing when
1104              we created the subfile, and we may have altered our
1105              opinion of what language it is from things we found in
1106              the symbols.  */
1107           symtab->language = subfile->language;
1108
1109           /* Save the debug format string (if any) in the symtab.  */
1110           symtab->debugformat = subfile->debugformat;
1111
1112           /* Similarly for the producer.  */
1113           symtab->producer = subfile->producer;
1114
1115           /* All symtabs for the main file and the subfiles share a
1116              blockvector, so we need to clear primary for everything
1117              but the main file.  */
1118
1119           symtab->primary = 0;
1120         }
1121       else
1122         {
1123           if (subfile->symtab)
1124             {
1125               /* Since we are ignoring that subfile, we also need
1126                  to unlink the associated empty symtab that we created.
1127                  Otherwise, we can into trouble because various parts
1128                  such as the block-vector are uninitialized whereas
1129                  the rest of the code assumes that they are.
1130                  
1131                  We can only unlink the symtab because it was allocated
1132                  on the objfile obstack.  */
1133               struct symtab *s;
1134
1135               if (objfile->symtabs == subfile->symtab)
1136                 objfile->symtabs = objfile->symtabs->next;
1137               else
1138                 ALL_OBJFILE_SYMTABS (objfile, s)
1139                   if (s->next == subfile->symtab)
1140                     {
1141                       s->next = s->next->next;
1142                       break;
1143                     }
1144               subfile->symtab = NULL;
1145             }
1146         }
1147       if (subfile->name != NULL)
1148         {
1149           xfree ((void *) subfile->name);
1150         }
1151       if (subfile->dirname != NULL)
1152         {
1153           xfree ((void *) subfile->dirname);
1154         }
1155       if (subfile->line_vector != NULL)
1156         {
1157           xfree ((void *) subfile->line_vector);
1158         }
1159
1160       nextsub = subfile->next;
1161       xfree ((void *) subfile);
1162     }
1163
1164   /* Set this for the main source file.  */
1165   if (symtab)
1166     {
1167       symtab->primary = 1;
1168     }
1169
1170   /* Default any symbols without a specified symtab to the primary
1171      symtab.  */
1172   if (blockvector)
1173     {
1174       int block_i;
1175
1176       for (block_i = 0; block_i < BLOCKVECTOR_NBLOCKS (blockvector); block_i++)
1177         {
1178           struct block *block = BLOCKVECTOR_BLOCK (blockvector, block_i);
1179           struct symbol *sym;
1180           struct dict_iterator iter;
1181
1182           /* Inlined functions may have symbols not in the global or
1183              static symbol lists.  */
1184           if (BLOCK_FUNCTION (block) != NULL)
1185             if (SYMBOL_SYMTAB (BLOCK_FUNCTION (block)) == NULL)
1186               SYMBOL_SYMTAB (BLOCK_FUNCTION (block)) = symtab;
1187
1188           for (sym = dict_iterator_first (BLOCK_DICT (block), &iter);
1189                sym != NULL;
1190                sym = dict_iterator_next (&iter))
1191             if (SYMBOL_SYMTAB (sym) == NULL)
1192               SYMBOL_SYMTAB (sym) = symtab;
1193         }
1194     }
1195
1196   last_source_file = NULL;
1197   current_subfile = NULL;
1198   pending_macros = NULL;
1199   if (pending_addrmap)
1200     {
1201       obstack_free (&pending_addrmap_obstack, NULL);
1202       pending_addrmap = NULL;
1203     }
1204
1205   return symtab;
1206 }
1207
1208 /* Push a context block.  Args are an identifying nesting level
1209    (checkable when you pop it), and the starting PC address of this
1210    context.  */
1211
1212 struct context_stack *
1213 push_context (int desc, CORE_ADDR valu)
1214 {
1215   struct context_stack *new;
1216
1217   if (context_stack_depth == context_stack_size)
1218     {
1219       context_stack_size *= 2;
1220       context_stack = (struct context_stack *)
1221         xrealloc ((char *) context_stack,
1222                   (context_stack_size * sizeof (struct context_stack)));
1223     }
1224
1225   new = &context_stack[context_stack_depth++];
1226   new->depth = desc;
1227   new->locals = local_symbols;
1228   new->params = param_symbols;
1229   new->old_blocks = pending_blocks;
1230   new->start_addr = valu;
1231   new->using_directives = using_directives;
1232   new->name = NULL;
1233
1234   local_symbols = NULL;
1235   param_symbols = NULL;
1236   using_directives = NULL;
1237
1238   return new;
1239 }
1240
1241 /* Pop a context block.  Returns the address of the context block just
1242    popped.  */
1243
1244 struct context_stack *
1245 pop_context (void)
1246 {
1247   gdb_assert (context_stack_depth > 0);
1248   return (&context_stack[--context_stack_depth]);
1249 }
1250
1251 \f
1252
1253 /* Compute a small integer hash code for the given name.  */
1254
1255 int
1256 hashname (char *name)
1257 {
1258     return (hash(name,strlen(name)) % HASHSIZE);
1259 }
1260 \f
1261
1262 void
1263 record_debugformat (const char *format)
1264 {
1265   current_subfile->debugformat = format;
1266 }
1267
1268 void
1269 record_producer (const char *producer)
1270 {
1271   current_subfile->producer = producer;
1272 }
1273
1274 /* Merge the first symbol list SRCLIST into the second symbol list
1275    TARGETLIST by repeated calls to add_symbol_to_list().  This
1276    procedure "frees" each link of SRCLIST by adding it to the
1277    free_pendings list.  Caller must set SRCLIST to a null list after
1278    calling this function.
1279
1280    Void return.  */
1281
1282 void
1283 merge_symbol_lists (struct pending **srclist, struct pending **targetlist)
1284 {
1285   int i;
1286
1287   if (!srclist || !*srclist)
1288     return;
1289
1290   /* Merge in elements from current link.  */
1291   for (i = 0; i < (*srclist)->nsyms; i++)
1292     add_symbol_to_list ((*srclist)->symbol[i], targetlist);
1293
1294   /* Recurse on next.  */
1295   merge_symbol_lists (&(*srclist)->next, targetlist);
1296
1297   /* "Free" the current link.  */
1298   (*srclist)->next = free_pendings;
1299   free_pendings = (*srclist);
1300 }
1301 \f
1302 /* Initialize anything that needs initializing when starting to read a
1303    fresh piece of a symbol file, e.g. reading in the stuff
1304    corresponding to a psymtab.  */
1305
1306 void
1307 buildsym_init (void)
1308 {
1309   free_pendings = NULL;
1310   file_symbols = NULL;
1311   global_symbols = NULL;
1312   pending_blocks = NULL;
1313   pending_macros = NULL;
1314
1315   /* We shouldn't have any address map at this point.  */
1316   gdb_assert (! pending_addrmap);
1317   pending_addrmap_interesting = 0;
1318 }
1319
1320 /* Initialize anything that needs initializing when a completely new
1321    symbol file is specified (not just adding some symbols from another
1322    file, e.g. a shared library).  */
1323
1324 void
1325 buildsym_new_init (void)
1326 {
1327   buildsym_init ();
1328 }