OSDN Git Service

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