DWARF: handle non-local references in nested functions
[external/binutils.git] / gdb / buildsym.c
1 /* Support routines for building symbol tables in GDB's internal format.
2    Copyright (C) 1986-2015 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /* This module provides subroutines used for creating and adding to
20    the symbol table.  These routines are called from various symbol-
21    file-reading routines.
22
23    Routines to support specific debugging information formats (stabs,
24    DWARF, etc) belong somewhere else.
25
26    The basic way this module is used is as follows:
27
28    buildsym_init ();
29    cleanups = make_cleanup (really_free_pendings, NULL);
30    cust = start_symtab (...);
31    ... read debug info ...
32    cust = end_symtab (...);
33    do_cleanups (cleanups);
34
35    The compunit symtab pointer ("cust") is returned from both start_symtab
36    and end_symtab to simplify the debug info readers.
37
38    There are minor variations on this, e.g., dwarf2read.c splits end_symtab
39    into two calls: end_symtab_get_static_block, end_symtab_from_static_block,
40    but all debug info readers follow this basic flow.
41
42    Reading DWARF Type Units is another variation:
43
44    buildsym_init ();
45    cleanups = make_cleanup (really_free_pendings, NULL);
46    cust = start_symtab (...);
47    ... read debug info ...
48    cust = end_expandable_symtab (...);
49    do_cleanups (cleanups);
50
51    And then reading subsequent Type Units within the containing "Comp Unit"
52    will use a second flow:
53
54    buildsym_init ();
55    cleanups = make_cleanup (really_free_pendings, NULL);
56    cust = restart_symtab (...);
57    ... read debug info ...
58    cust = augment_type_symtab (...);
59    do_cleanups (cleanups);
60
61    dbxread.c and xcoffread.c use another variation:
62
63    buildsym_init ();
64    cleanups = make_cleanup (really_free_pendings, NULL);
65    cust = start_symtab (...);
66    ... read debug info ...
67    cust = end_symtab (...);
68    ... start_symtab + read + end_symtab repeated ...
69    do_cleanups (cleanups);
70 */
71
72 #include "defs.h"
73 #include "bfd.h"
74 #include "gdb_obstack.h"
75 #include "symtab.h"
76 #include "symfile.h"
77 #include "objfiles.h"
78 #include "gdbtypes.h"
79 #include "complaints.h"
80 #include "expression.h"         /* For "enum exp_opcode" used by...  */
81 #include "bcache.h"
82 #include "filenames.h"          /* For DOSish file names.  */
83 #include "macrotab.h"
84 #include "demangle.h"           /* Needed by SYMBOL_INIT_DEMANGLED_NAME.  */
85 #include "block.h"
86 #include "cp-support.h"
87 #include "dictionary.h"
88 #include "addrmap.h"
89
90 /* Ask buildsym.h to define the vars it normally declares `extern'.  */
91 #define EXTERN
92 /**/
93 #include "buildsym.h"           /* Our own declarations.  */
94 #undef  EXTERN
95
96 /* For cleanup_undefined_stabs_types and finish_global_stabs (somewhat
97    questionable--see comment where we call them).  */
98
99 #include "stabsread.h"
100
101 /* Buildsym's counterpart to struct compunit_symtab.
102    TODO(dje): Move all related global state into here.  */
103
104 struct buildsym_compunit
105 {
106   /* The objfile we're reading debug info from.  */
107   struct objfile *objfile;
108
109   /* List of subfiles (source files).
110      Files are added to the front of the list.
111      This is important mostly for the language determination hacks we use,
112      which iterate over previously added files.  */
113   struct subfile *subfiles;
114
115   /* The subfile of the main source file.  */
116   struct subfile *main_subfile;
117
118   /* E.g., DW_AT_comp_dir if DWARF.  Space for this is malloc'd.  */
119   char *comp_dir;
120
121   /* Space for this is not malloc'd, and is assumed to have at least
122      the same lifetime as objfile.  */
123   const char *producer;
124
125   /* Space for this is not malloc'd, and is assumed to have at least
126      the same lifetime as objfile.  */
127   const char *debugformat;
128
129   /* The compunit we are building.  */
130   struct compunit_symtab *compunit_symtab;
131 };
132
133 /* The work-in-progress of the compunit we are building.
134    This is created first, before any subfiles by start_symtab.  */
135
136 static struct buildsym_compunit *buildsym_compunit;
137
138 /* List of free `struct pending' structures for reuse.  */
139
140 static struct pending *free_pendings;
141
142 /* Non-zero if symtab has line number info.  This prevents an
143    otherwise empty symtab from being tossed.  */
144
145 static int have_line_numbers;
146
147 /* The mutable address map for the compilation unit whose symbols
148    we're currently reading.  The symtabs' shared blockvector will
149    point to a fixed copy of this.  */
150 static struct addrmap *pending_addrmap;
151
152 /* The obstack on which we allocate pending_addrmap.
153    If pending_addrmap is NULL, this is uninitialized; otherwise, it is
154    initialized (and holds pending_addrmap).  */
155 static struct obstack pending_addrmap_obstack;
156
157 /* Non-zero if we recorded any ranges in the addrmap that are
158    different from those in the blockvector already.  We set this to
159    zero when we start processing a symfile, and if it's still zero at
160    the end, then we just toss the addrmap.  */
161 static int pending_addrmap_interesting;
162
163 /* An obstack used for allocating pending blocks.  */
164
165 static struct obstack pending_block_obstack;
166
167 /* List of blocks already made (lexical contexts already closed).
168    This is used at the end to make the blockvector.  */
169
170 struct pending_block
171   {
172     struct pending_block *next;
173     struct block *block;
174   };
175
176 /* Pointer to the head of a linked list of symbol blocks which have
177    already been finalized (lexical contexts already closed) and which
178    are just waiting to be built into a blockvector when finalizing the
179    associated symtab.  */
180
181 static struct pending_block *pending_blocks;
182
183 struct subfile_stack
184   {
185     struct subfile_stack *next;
186     char *name;
187   };
188
189 static struct subfile_stack *subfile_stack;
190
191 /* The macro table for the compilation unit whose symbols we're
192    currently reading.  */
193 static struct macro_table *pending_macros;
194
195 static void free_buildsym_compunit (void);
196
197 static int compare_line_numbers (const void *ln1p, const void *ln2p);
198
199 static void record_pending_block (struct objfile *objfile,
200                                   struct block *block,
201                                   struct pending_block *opblock);
202
203 /* Initial sizes of data structures.  These are realloc'd larger if
204    needed, and realloc'd down to the size actually used, when
205    completed.  */
206
207 #define INITIAL_CONTEXT_STACK_SIZE      10
208 #define INITIAL_LINE_VECTOR_LENGTH      1000
209 \f
210
211 /* Maintain the lists of symbols and blocks.  */
212
213 /* Add a symbol to one of the lists of symbols.  */
214
215 void
216 add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
217 {
218   struct pending *link;
219
220   /* If this is an alias for another symbol, don't add it.  */
221   if (symbol->ginfo.name && symbol->ginfo.name[0] == '#')
222     return;
223
224   /* We keep PENDINGSIZE symbols in each link of the list.  If we
225      don't have a link with room in it, add a new link.  */
226   if (*listhead == NULL || (*listhead)->nsyms == PENDINGSIZE)
227     {
228       if (free_pendings)
229         {
230           link = free_pendings;
231           free_pendings = link->next;
232         }
233       else
234         {
235           link = (struct pending *) xmalloc (sizeof (struct pending));
236         }
237
238       link->next = *listhead;
239       *listhead = link;
240       link->nsyms = 0;
241     }
242
243   (*listhead)->symbol[(*listhead)->nsyms++] = symbol;
244 }
245
246 /* Find a symbol named NAME on a LIST.  NAME need not be
247    '\0'-terminated; LENGTH is the length of the name.  */
248
249 struct symbol *
250 find_symbol_in_list (struct pending *list, char *name, int length)
251 {
252   int j;
253   const char *pp;
254
255   while (list != NULL)
256     {
257       for (j = list->nsyms; --j >= 0;)
258         {
259           pp = SYMBOL_LINKAGE_NAME (list->symbol[j]);
260           if (*pp == *name && strncmp (pp, name, length) == 0
261               && pp[length] == '\0')
262             {
263               return (list->symbol[j]);
264             }
265         }
266       list = list->next;
267     }
268   return (NULL);
269 }
270
271 /* At end of reading syms, or in case of quit, ensure everything associated
272    with building symtabs is freed.  This is intended to be registered as a
273    cleanup before doing psymtab->symtab expansion.
274
275    N.B. This is *not* intended to be used when building psymtabs.  Some debug
276    info readers call this anyway, which is harmless if confusing.  */
277
278 void
279 really_free_pendings (void *dummy)
280 {
281   struct pending *next, *next1;
282
283   for (next = free_pendings; next; next = next1)
284     {
285       next1 = next->next;
286       xfree ((void *) next);
287     }
288   free_pendings = NULL;
289
290   free_pending_blocks ();
291
292   for (next = file_symbols; next != NULL; next = next1)
293     {
294       next1 = next->next;
295       xfree ((void *) next);
296     }
297   file_symbols = NULL;
298
299   for (next = global_symbols; next != NULL; next = next1)
300     {
301       next1 = next->next;
302       xfree ((void *) next);
303     }
304   global_symbols = NULL;
305
306   if (pending_macros)
307     free_macro_table (pending_macros);
308   pending_macros = NULL;
309
310   if (pending_addrmap)
311     obstack_free (&pending_addrmap_obstack, NULL);
312   pending_addrmap = NULL;
313
314   free_buildsym_compunit ();
315 }
316
317 /* This function is called to discard any pending blocks.  */
318
319 void
320 free_pending_blocks (void)
321 {
322   if (pending_blocks != NULL)
323     {
324       obstack_free (&pending_block_obstack, NULL);
325       pending_blocks = NULL;
326     }
327 }
328
329 /* Take one of the lists of symbols and make a block from it.  Keep
330    the order the symbols have in the list (reversed from the input
331    file).  Put the block on the list of pending blocks.  */
332
333 static struct block *
334 finish_block_internal (struct symbol *symbol,
335                        struct pending **listhead,
336                        struct pending_block *old_blocks,
337                        const struct dynamic_prop *static_link,
338                        CORE_ADDR start, CORE_ADDR end,
339                        int is_global, int expandable)
340 {
341   struct objfile *objfile = buildsym_compunit->objfile;
342   struct gdbarch *gdbarch = get_objfile_arch (objfile);
343   struct pending *next, *next1;
344   struct block *block;
345   struct pending_block *pblock;
346   struct pending_block *opblock;
347
348   block = (is_global
349            ? allocate_global_block (&objfile->objfile_obstack)
350            : allocate_block (&objfile->objfile_obstack));
351
352   if (symbol)
353     {
354       BLOCK_DICT (block) = dict_create_linear (&objfile->objfile_obstack,
355                                                *listhead);
356     }
357   else
358     {
359       if (expandable)
360         {
361           BLOCK_DICT (block) = dict_create_hashed_expandable ();
362           dict_add_pending (BLOCK_DICT (block), *listhead);
363         }
364       else
365         {
366           BLOCK_DICT (block) =
367             dict_create_hashed (&objfile->objfile_obstack, *listhead);
368         }
369     }
370
371   BLOCK_START (block) = start;
372   BLOCK_END (block) = end;
373
374   /* Put the block in as the value of the symbol that names it.  */
375
376   if (symbol)
377     {
378       struct type *ftype = SYMBOL_TYPE (symbol);
379       struct dict_iterator iter;
380       SYMBOL_BLOCK_VALUE (symbol) = block;
381       BLOCK_FUNCTION (block) = symbol;
382
383       if (TYPE_NFIELDS (ftype) <= 0)
384         {
385           /* No parameter type information is recorded with the
386              function's type.  Set that from the type of the
387              parameter symbols.  */
388           int nparams = 0, iparams;
389           struct symbol *sym;
390
391           /* Here we want to directly access the dictionary, because
392              we haven't fully initialized the block yet.  */
393           ALL_DICT_SYMBOLS (BLOCK_DICT (block), iter, sym)
394             {
395               if (SYMBOL_IS_ARGUMENT (sym))
396                 nparams++;
397             }
398           if (nparams > 0)
399             {
400               TYPE_NFIELDS (ftype) = nparams;
401               TYPE_FIELDS (ftype) = (struct field *)
402                 TYPE_ALLOC (ftype, nparams * sizeof (struct field));
403
404               iparams = 0;
405               /* Here we want to directly access the dictionary, because
406                  we haven't fully initialized the block yet.  */
407               ALL_DICT_SYMBOLS (BLOCK_DICT (block), iter, sym)
408                 {
409                   if (iparams == nparams)
410                     break;
411
412                   if (SYMBOL_IS_ARGUMENT (sym))
413                     {
414                       TYPE_FIELD_TYPE (ftype, iparams) = SYMBOL_TYPE (sym);
415                       TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
416                       iparams++;
417                     }
418                 }
419             }
420         }
421     }
422   else
423     {
424       BLOCK_FUNCTION (block) = NULL;
425     }
426
427   if (static_link != NULL)
428     objfile_register_static_link (objfile, block, static_link);
429
430   /* Now "free" the links of the list, and empty the list.  */
431
432   for (next = *listhead; next; next = next1)
433     {
434       next1 = next->next;
435       next->next = free_pendings;
436       free_pendings = next;
437     }
438   *listhead = NULL;
439
440   /* Check to be sure that the blocks have an end address that is
441      greater than starting address.  */
442
443   if (BLOCK_END (block) < BLOCK_START (block))
444     {
445       if (symbol)
446         {
447           complaint (&symfile_complaints,
448                      _("block end address less than block "
449                        "start address in %s (patched it)"),
450                      SYMBOL_PRINT_NAME (symbol));
451         }
452       else
453         {
454           complaint (&symfile_complaints,
455                      _("block end address %s less than block "
456                        "start address %s (patched it)"),
457                      paddress (gdbarch, BLOCK_END (block)),
458                      paddress (gdbarch, BLOCK_START (block)));
459         }
460       /* Better than nothing.  */
461       BLOCK_END (block) = BLOCK_START (block);
462     }
463
464   /* Install this block as the superblock of all blocks made since the
465      start of this scope that don't have superblocks yet.  */
466
467   opblock = NULL;
468   for (pblock = pending_blocks; 
469        pblock && pblock != old_blocks; 
470        pblock = pblock->next)
471     {
472       if (BLOCK_SUPERBLOCK (pblock->block) == NULL)
473         {
474           /* Check to be sure the blocks are nested as we receive
475              them.  If the compiler/assembler/linker work, this just
476              burns a small amount of time.
477
478              Skip blocks which correspond to a function; they're not
479              physically nested inside this other blocks, only
480              lexically nested.  */
481           if (BLOCK_FUNCTION (pblock->block) == NULL
482               && (BLOCK_START (pblock->block) < BLOCK_START (block)
483                   || BLOCK_END (pblock->block) > BLOCK_END (block)))
484             {
485               if (symbol)
486                 {
487                   complaint (&symfile_complaints,
488                              _("inner block not inside outer block in %s"),
489                              SYMBOL_PRINT_NAME (symbol));
490                 }
491               else
492                 {
493                   complaint (&symfile_complaints,
494                              _("inner block (%s-%s) not "
495                                "inside outer block (%s-%s)"),
496                              paddress (gdbarch, BLOCK_START (pblock->block)),
497                              paddress (gdbarch, BLOCK_END (pblock->block)),
498                              paddress (gdbarch, BLOCK_START (block)),
499                              paddress (gdbarch, BLOCK_END (block)));
500                 }
501               if (BLOCK_START (pblock->block) < BLOCK_START (block))
502                 BLOCK_START (pblock->block) = BLOCK_START (block);
503               if (BLOCK_END (pblock->block) > BLOCK_END (block))
504                 BLOCK_END (pblock->block) = BLOCK_END (block);
505             }
506           BLOCK_SUPERBLOCK (pblock->block) = block;
507         }
508       opblock = pblock;
509     }
510
511   block_set_using (block,
512                    (is_global
513                     ? global_using_directives
514                     : local_using_directives),
515                    &objfile->objfile_obstack);
516   if (is_global)
517     global_using_directives = NULL;
518   else
519     local_using_directives = NULL;
520
521   record_pending_block (objfile, block, opblock);
522
523   return block;
524 }
525
526 struct block *
527 finish_block (struct symbol *symbol,
528               struct pending **listhead,
529               struct pending_block *old_blocks,
530               const struct dynamic_prop *static_link,
531               CORE_ADDR start, CORE_ADDR end)
532 {
533   return finish_block_internal (symbol, listhead, old_blocks, static_link,
534                                 start, end, 0, 0);
535 }
536
537 /* Record BLOCK on the list of all blocks in the file.  Put it after
538    OPBLOCK, or at the beginning if opblock is NULL.  This puts the
539    block in the list after all its subblocks.
540
541    Allocate the pending block struct in the objfile_obstack to save
542    time.  This wastes a little space.  FIXME: Is it worth it?  */
543
544 static void
545 record_pending_block (struct objfile *objfile, struct block *block,
546                       struct pending_block *opblock)
547 {
548   struct pending_block *pblock;
549
550   if (pending_blocks == NULL)
551     obstack_init (&pending_block_obstack);
552
553   pblock = (struct pending_block *)
554     obstack_alloc (&pending_block_obstack, sizeof (struct pending_block));
555   pblock->block = block;
556   if (opblock)
557     {
558       pblock->next = opblock->next;
559       opblock->next = pblock;
560     }
561   else
562     {
563       pblock->next = pending_blocks;
564       pending_blocks = pblock;
565     }
566 }
567
568
569 /* Record that the range of addresses from START to END_INCLUSIVE
570    (inclusive, like it says) belongs to BLOCK.  BLOCK's start and end
571    addresses must be set already.  You must apply this function to all
572    BLOCK's children before applying it to BLOCK.
573
574    If a call to this function complicates the picture beyond that
575    already provided by BLOCK_START and BLOCK_END, then we create an
576    address map for the block.  */
577 void
578 record_block_range (struct block *block,
579                     CORE_ADDR start, CORE_ADDR end_inclusive)
580 {
581   /* If this is any different from the range recorded in the block's
582      own BLOCK_START and BLOCK_END, then note that the address map has
583      become interesting.  Note that even if this block doesn't have
584      any "interesting" ranges, some later block might, so we still
585      need to record this block in the addrmap.  */
586   if (start != BLOCK_START (block)
587       || end_inclusive + 1 != BLOCK_END (block))
588     pending_addrmap_interesting = 1;
589
590   if (! pending_addrmap)
591     {
592       obstack_init (&pending_addrmap_obstack);
593       pending_addrmap = addrmap_create_mutable (&pending_addrmap_obstack);
594     }
595
596   addrmap_set_empty (pending_addrmap, start, end_inclusive, block);
597 }
598
599 static struct blockvector *
600 make_blockvector (void)
601 {
602   struct objfile *objfile = buildsym_compunit->objfile;
603   struct pending_block *next;
604   struct blockvector *blockvector;
605   int i;
606
607   /* Count the length of the list of blocks.  */
608
609   for (next = pending_blocks, i = 0; next; next = next->next, i++)
610     {;
611     }
612
613   blockvector = (struct blockvector *)
614     obstack_alloc (&objfile->objfile_obstack,
615                    (sizeof (struct blockvector)
616                     + (i - 1) * sizeof (struct block *)));
617
618   /* Copy the blocks into the blockvector.  This is done in reverse
619      order, which happens to put the blocks into the proper order
620      (ascending starting address).  finish_block has hair to insert
621      each block into the list after its subblocks in order to make
622      sure this is true.  */
623
624   BLOCKVECTOR_NBLOCKS (blockvector) = i;
625   for (next = pending_blocks; next; next = next->next)
626     {
627       BLOCKVECTOR_BLOCK (blockvector, --i) = next->block;
628     }
629
630   free_pending_blocks ();
631
632   /* If we needed an address map for this symtab, record it in the
633      blockvector.  */
634   if (pending_addrmap && pending_addrmap_interesting)
635     BLOCKVECTOR_MAP (blockvector)
636       = addrmap_create_fixed (pending_addrmap, &objfile->objfile_obstack);
637   else
638     BLOCKVECTOR_MAP (blockvector) = 0;
639
640   /* Some compilers output blocks in the wrong order, but we depend on
641      their being in the right order so we can binary search.  Check the
642      order and moan about it.
643      Note: Remember that the first two blocks are the global and static
644      blocks.  We could special case that fact and begin checking at block 2.
645      To avoid making that assumption we do not.  */
646   if (BLOCKVECTOR_NBLOCKS (blockvector) > 1)
647     {
648       for (i = 1; i < BLOCKVECTOR_NBLOCKS (blockvector); i++)
649         {
650           if (BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i - 1))
651               > BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i)))
652             {
653               CORE_ADDR start
654                 = BLOCK_START (BLOCKVECTOR_BLOCK (blockvector, i));
655
656               complaint (&symfile_complaints, _("block at %s out of order"),
657                          hex_string ((LONGEST) start));
658             }
659         }
660     }
661
662   return (blockvector);
663 }
664 \f
665 /* Start recording information about source code that came from an
666    included (or otherwise merged-in) source file with a different
667    name.  NAME is the name of the file (cannot be NULL).  */
668
669 void
670 start_subfile (const char *name)
671 {
672   const char *subfile_dirname;
673   struct subfile *subfile;
674
675   gdb_assert (buildsym_compunit != NULL);
676
677   subfile_dirname = buildsym_compunit->comp_dir;
678
679   /* See if this subfile is already registered.  */
680
681   for (subfile = buildsym_compunit->subfiles; subfile; subfile = subfile->next)
682     {
683       char *subfile_name;
684
685       /* If NAME is an absolute path, and this subfile is not, then
686          attempt to create an absolute path to compare.  */
687       if (IS_ABSOLUTE_PATH (name)
688           && !IS_ABSOLUTE_PATH (subfile->name)
689           && subfile_dirname != NULL)
690         subfile_name = concat (subfile_dirname, SLASH_STRING,
691                                subfile->name, (char *) NULL);
692       else
693         subfile_name = subfile->name;
694
695       if (FILENAME_CMP (subfile_name, name) == 0)
696         {
697           current_subfile = subfile;
698           if (subfile_name != subfile->name)
699             xfree (subfile_name);
700           return;
701         }
702       if (subfile_name != subfile->name)
703         xfree (subfile_name);
704     }
705
706   /* This subfile is not known.  Add an entry for it.  */
707
708   subfile = (struct subfile *) xmalloc (sizeof (struct subfile));
709   memset (subfile, 0, sizeof (struct subfile));
710   subfile->buildsym_compunit = buildsym_compunit;
711
712   subfile->next = buildsym_compunit->subfiles;
713   buildsym_compunit->subfiles = subfile;
714
715   current_subfile = subfile;
716
717   subfile->name = xstrdup (name);
718
719   /* Initialize line-number recording for this subfile.  */
720   subfile->line_vector = NULL;
721
722   /* Default the source language to whatever can be deduced from the
723      filename.  If nothing can be deduced (such as for a C/C++ include
724      file with a ".h" extension), then inherit whatever language the
725      previous subfile had.  This kludgery is necessary because there
726      is no standard way in some object formats to record the source
727      language.  Also, when symtabs are allocated we try to deduce a
728      language then as well, but it is too late for us to use that
729      information while reading symbols, since symtabs aren't allocated
730      until after all the symbols have been processed for a given
731      source file.  */
732
733   subfile->language = deduce_language_from_filename (subfile->name);
734   if (subfile->language == language_unknown
735       && subfile->next != NULL)
736     {
737       subfile->language = subfile->next->language;
738     }
739
740   /* If the filename of this subfile ends in .C, then change the
741      language of any pending subfiles from C to C++.  We also accept
742      any other C++ suffixes accepted by deduce_language_from_filename.  */
743   /* Likewise for f2c.  */
744
745   if (subfile->name)
746     {
747       struct subfile *s;
748       enum language sublang = deduce_language_from_filename (subfile->name);
749
750       if (sublang == language_cplus || sublang == language_fortran)
751         for (s = buildsym_compunit->subfiles; s != NULL; s = s->next)
752           if (s->language == language_c)
753             s->language = sublang;
754     }
755
756   /* And patch up this file if necessary.  */
757   if (subfile->language == language_c
758       && subfile->next != NULL
759       && (subfile->next->language == language_cplus
760           || subfile->next->language == language_fortran))
761     {
762       subfile->language = subfile->next->language;
763     }
764 }
765
766 /* Start recording information about a primary source file (IOW, not an
767    included source file).
768    COMP_DIR is the directory in which the compilation unit was compiled
769    (or NULL if not known).  */
770
771 static struct buildsym_compunit *
772 start_buildsym_compunit (struct objfile *objfile, const char *comp_dir)
773 {
774   struct buildsym_compunit *bscu;
775
776   bscu = (struct buildsym_compunit *)
777     xmalloc (sizeof (struct buildsym_compunit));
778   memset (bscu, 0, sizeof (struct buildsym_compunit));
779
780   bscu->objfile = objfile;
781   bscu->comp_dir = (comp_dir == NULL) ? NULL : xstrdup (comp_dir);
782
783   /* Initialize the debug format string to NULL.  We may supply it
784      later via a call to record_debugformat.  */
785   bscu->debugformat = NULL;
786
787   /* Similarly for the producer.  */
788   bscu->producer = NULL;
789
790   return bscu;
791 }
792
793 /* Delete the buildsym compunit.  */
794
795 static void
796 free_buildsym_compunit (void)
797 {
798   struct subfile *subfile, *nextsub;
799
800   if (buildsym_compunit == NULL)
801     return;
802   for (subfile = buildsym_compunit->subfiles;
803        subfile != NULL;
804        subfile = nextsub)
805     {
806       nextsub = subfile->next;
807       xfree (subfile->name);
808       xfree (subfile->line_vector);
809       xfree (subfile);
810     }
811   xfree (buildsym_compunit->comp_dir);
812   xfree (buildsym_compunit);
813   buildsym_compunit = NULL;
814   current_subfile = NULL;
815 }
816
817 /* For stabs readers, the first N_SO symbol is assumed to be the
818    source file name, and the subfile struct is initialized using that
819    assumption.  If another N_SO symbol is later seen, immediately
820    following the first one, then the first one is assumed to be the
821    directory name and the second one is really the source file name.
822
823    So we have to patch up the subfile struct by moving the old name
824    value to dirname and remembering the new name.  Some sanity
825    checking is performed to ensure that the state of the subfile
826    struct is reasonable and that the old name we are assuming to be a
827    directory name actually is (by checking for a trailing '/').  */
828
829 void
830 patch_subfile_names (struct subfile *subfile, char *name)
831 {
832   if (subfile != NULL
833       && buildsym_compunit->comp_dir == NULL
834       && subfile->name != NULL
835       && IS_DIR_SEPARATOR (subfile->name[strlen (subfile->name) - 1]))
836     {
837       buildsym_compunit->comp_dir = subfile->name;
838       subfile->name = xstrdup (name);
839       set_last_source_file (name);
840
841       /* Default the source language to whatever can be deduced from
842          the filename.  If nothing can be deduced (such as for a C/C++
843          include file with a ".h" extension), then inherit whatever
844          language the previous subfile had.  This kludgery is
845          necessary because there is no standard way in some object
846          formats to record the source language.  Also, when symtabs
847          are allocated we try to deduce a language then as well, but
848          it is too late for us to use that information while reading
849          symbols, since symtabs aren't allocated until after all the
850          symbols have been processed for a given source file.  */
851
852       subfile->language = deduce_language_from_filename (subfile->name);
853       if (subfile->language == language_unknown
854           && subfile->next != NULL)
855         {
856           subfile->language = subfile->next->language;
857         }
858     }
859 }
860 \f
861 /* Handle the N_BINCL and N_EINCL symbol types that act like N_SOL for
862    switching source files (different subfiles, as we call them) within
863    one object file, but using a stack rather than in an arbitrary
864    order.  */
865
866 void
867 push_subfile (void)
868 {
869   struct subfile_stack *tem
870     = (struct subfile_stack *) xmalloc (sizeof (struct subfile_stack));
871
872   tem->next = subfile_stack;
873   subfile_stack = tem;
874   if (current_subfile == NULL || current_subfile->name == NULL)
875     {
876       internal_error (__FILE__, __LINE__, 
877                       _("failed internal consistency check"));
878     }
879   tem->name = current_subfile->name;
880 }
881
882 char *
883 pop_subfile (void)
884 {
885   char *name;
886   struct subfile_stack *link = subfile_stack;
887
888   if (link == NULL)
889     {
890       internal_error (__FILE__, __LINE__,
891                       _("failed internal consistency check"));
892     }
893   name = link->name;
894   subfile_stack = link->next;
895   xfree ((void *) link);
896   return (name);
897 }
898 \f
899 /* Add a linetable entry for line number LINE and address PC to the
900    line vector for SUBFILE.  */
901
902 void
903 record_line (struct subfile *subfile, int line, CORE_ADDR pc)
904 {
905   struct linetable_entry *e;
906
907   /* Ignore the dummy line number in libg.o */
908   if (line == 0xffff)
909     {
910       return;
911     }
912
913   /* Make sure line vector exists and is big enough.  */
914   if (!subfile->line_vector)
915     {
916       subfile->line_vector_length = INITIAL_LINE_VECTOR_LENGTH;
917       subfile->line_vector = (struct linetable *)
918         xmalloc (sizeof (struct linetable)
919            + subfile->line_vector_length * sizeof (struct linetable_entry));
920       subfile->line_vector->nitems = 0;
921       have_line_numbers = 1;
922     }
923
924   if (subfile->line_vector->nitems + 1 >= subfile->line_vector_length)
925     {
926       subfile->line_vector_length *= 2;
927       subfile->line_vector = (struct linetable *)
928         xrealloc ((char *) subfile->line_vector,
929                   (sizeof (struct linetable)
930                    + (subfile->line_vector_length
931                       * sizeof (struct linetable_entry))));
932     }
933
934   /* Normally, we treat lines as unsorted.  But the end of sequence
935      marker is special.  We sort line markers at the same PC by line
936      number, so end of sequence markers (which have line == 0) appear
937      first.  This is right if the marker ends the previous function,
938      and there is no padding before the next function.  But it is
939      wrong if the previous line was empty and we are now marking a
940      switch to a different subfile.  We must leave the end of sequence
941      marker at the end of this group of lines, not sort the empty line
942      to after the marker.  The easiest way to accomplish this is to
943      delete any empty lines from our table, if they are followed by
944      end of sequence markers.  All we lose is the ability to set
945      breakpoints at some lines which contain no instructions
946      anyway.  */
947   if (line == 0 && subfile->line_vector->nitems > 0)
948     {
949       e = subfile->line_vector->item + subfile->line_vector->nitems - 1;
950       while (subfile->line_vector->nitems > 0 && e->pc == pc)
951         {
952           e--;
953           subfile->line_vector->nitems--;
954         }
955     }
956
957   e = subfile->line_vector->item + subfile->line_vector->nitems++;
958   e->line = line;
959   e->pc = pc;
960 }
961
962 /* Needed in order to sort line tables from IBM xcoff files.  Sigh!  */
963
964 static int
965 compare_line_numbers (const void *ln1p, const void *ln2p)
966 {
967   struct linetable_entry *ln1 = (struct linetable_entry *) ln1p;
968   struct linetable_entry *ln2 = (struct linetable_entry *) ln2p;
969
970   /* Note: this code does not assume that CORE_ADDRs can fit in ints.
971      Please keep it that way.  */
972   if (ln1->pc < ln2->pc)
973     return -1;
974
975   if (ln1->pc > ln2->pc)
976     return 1;
977
978   /* If pc equal, sort by line.  I'm not sure whether this is optimum
979      behavior (see comment at struct linetable in symtab.h).  */
980   return ln1->line - ln2->line;
981 }
982 \f
983 /* See buildsym.h.  */
984
985 struct compunit_symtab *
986 buildsym_compunit_symtab (void)
987 {
988   gdb_assert (buildsym_compunit != NULL);
989
990   return buildsym_compunit->compunit_symtab;
991 }
992
993 /* See buildsym.h.  */
994
995 struct macro_table *
996 get_macro_table (void)
997 {
998   struct objfile *objfile;
999
1000   gdb_assert (buildsym_compunit != NULL);
1001
1002   objfile = buildsym_compunit->objfile;
1003
1004   if (! pending_macros)
1005     {
1006       pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
1007                                         objfile->per_bfd->macro_cache,
1008                                         buildsym_compunit->compunit_symtab);
1009     }
1010
1011   return pending_macros;
1012 }
1013 \f
1014 /* Init state to prepare for building a symtab.
1015    Note: This can't be done in buildsym_init because dbxread.c and xcoffread.c
1016    can call start_symtab+end_symtab multiple times after one call to
1017    buildsym_init.  */
1018
1019 static void
1020 prepare_for_building (const char *name, CORE_ADDR start_addr)
1021 {
1022   set_last_source_file (name);
1023   last_source_start_addr = start_addr;
1024
1025   local_symbols = NULL;
1026   local_using_directives = NULL;
1027   within_function = 0;
1028   have_line_numbers = 0;
1029
1030   context_stack_depth = 0;
1031
1032   /* These should have been reset either by successful completion of building
1033      a symtab, or by the really_free_pendings cleanup.  */
1034   gdb_assert (file_symbols == NULL);
1035   gdb_assert (global_symbols == NULL);
1036   gdb_assert (global_using_directives == NULL);
1037   gdb_assert (pending_macros == NULL);
1038   gdb_assert (pending_addrmap == NULL);
1039   gdb_assert (current_subfile == NULL);
1040 }
1041
1042 /* Start a new symtab for a new source file in OBJFILE.  Called, for example,
1043    when a stabs symbol of type N_SO is seen, or when a DWARF
1044    TAG_compile_unit DIE is seen.  It indicates the start of data for
1045    one original source file.
1046
1047    NAME is the name of the file (cannot be NULL).  COMP_DIR is the directory in
1048    which the file was compiled (or NULL if not known).  START_ADDR is the
1049    lowest address of objects in the file (or 0 if not known).  */
1050
1051 struct compunit_symtab *
1052 start_symtab (struct objfile *objfile, const char *name, const char *comp_dir,
1053               CORE_ADDR start_addr)
1054 {
1055   prepare_for_building (name, start_addr);
1056
1057   buildsym_compunit = start_buildsym_compunit (objfile, comp_dir);
1058
1059   /* Allocate the compunit symtab now.  The caller needs it to allocate
1060      non-primary symtabs.  It is also needed by get_macro_table.  */
1061   buildsym_compunit->compunit_symtab = allocate_compunit_symtab (objfile,
1062                                                                  name);
1063
1064   /* Build the subfile for NAME (the main source file) so that we can record
1065      a pointer to it for later.
1066      IMPORTANT: Do not allocate a struct symtab for NAME here.
1067      It can happen that the debug info provides a different path to NAME than
1068      DIRNAME,NAME.  We cope with this in watch_main_source_file_lossage but
1069      that only works if the main_subfile doesn't have a symtab yet.  */
1070   start_subfile (name);
1071   /* Save this so that we don't have to go looking for it at the end
1072      of the subfiles list.  */
1073   buildsym_compunit->main_subfile = current_subfile;
1074
1075   return buildsym_compunit->compunit_symtab;
1076 }
1077
1078 /* Restart compilation for a symtab.
1079    CUST is the result of end_expandable_symtab.
1080    NAME, START_ADDR are the source file we are resuming with.
1081
1082    This is used when a symtab is built from multiple sources.
1083    The symtab is first built with start_symtab/end_expandable_symtab
1084    and then for each additional piece call restart_symtab/augment_*_symtab.
1085    Note: At the moment there is only augment_type_symtab.  */
1086
1087 void
1088 restart_symtab (struct compunit_symtab *cust,
1089                 const char *name, CORE_ADDR start_addr)
1090 {
1091   prepare_for_building (name, start_addr);
1092
1093   buildsym_compunit = start_buildsym_compunit (COMPUNIT_OBJFILE (cust),
1094                                                COMPUNIT_DIRNAME (cust));
1095   buildsym_compunit->compunit_symtab = cust;
1096 }
1097
1098 /* Subroutine of end_symtab to simplify it.  Look for a subfile that
1099    matches the main source file's basename.  If there is only one, and
1100    if the main source file doesn't have any symbol or line number
1101    information, then copy this file's symtab and line_vector to the
1102    main source file's subfile and discard the other subfile.  This can
1103    happen because of a compiler bug or from the user playing games
1104    with #line or from things like a distributed build system that
1105    manipulates the debug info.  This can also happen from an innocent
1106    symlink in the paths, we don't canonicalize paths here.  */
1107
1108 static void
1109 watch_main_source_file_lossage (void)
1110 {
1111   struct subfile *mainsub, *subfile;
1112
1113   /* We have to watch for buildsym_compunit == NULL here.  It's a quirk of
1114      end_symtab, it can return NULL so there may not be a main subfile.  */
1115   if (buildsym_compunit == NULL)
1116     return;
1117
1118   /* Get the main source file.  */
1119   mainsub = buildsym_compunit->main_subfile;
1120
1121   /* If the main source file doesn't have any line number or symbol
1122      info, look for an alias in another subfile.  */
1123
1124   if (mainsub->line_vector == NULL
1125       && mainsub->symtab == NULL)
1126     {
1127       const char *mainbase = lbasename (mainsub->name);
1128       int nr_matches = 0;
1129       struct subfile *prevsub;
1130       struct subfile *mainsub_alias = NULL;
1131       struct subfile *prev_mainsub_alias = NULL;
1132
1133       prevsub = NULL;
1134       for (subfile = buildsym_compunit->subfiles;
1135            subfile != NULL;
1136            subfile = subfile->next)
1137         {
1138           if (subfile == mainsub)
1139             continue;
1140           if (filename_cmp (lbasename (subfile->name), mainbase) == 0)
1141             {
1142               ++nr_matches;
1143               mainsub_alias = subfile;
1144               prev_mainsub_alias = prevsub;
1145             }
1146           prevsub = subfile;
1147         }
1148
1149       if (nr_matches == 1)
1150         {
1151           gdb_assert (mainsub_alias != NULL && mainsub_alias != mainsub);
1152
1153           /* Found a match for the main source file.
1154              Copy its line_vector and symtab to the main subfile
1155              and then discard it.  */
1156
1157           mainsub->line_vector = mainsub_alias->line_vector;
1158           mainsub->line_vector_length = mainsub_alias->line_vector_length;
1159           mainsub->symtab = mainsub_alias->symtab;
1160
1161           if (prev_mainsub_alias == NULL)
1162             buildsym_compunit->subfiles = mainsub_alias->next;
1163           else
1164             prev_mainsub_alias->next = mainsub_alias->next;
1165           xfree (mainsub_alias->name);
1166           xfree (mainsub_alias);
1167         }
1168     }
1169 }
1170
1171 /* Helper function for qsort.  Parameters are `struct block *' pointers,
1172    function sorts them in descending order by their BLOCK_START.  */
1173
1174 static int
1175 block_compar (const void *ap, const void *bp)
1176 {
1177   const struct block *a = *(const struct block **) ap;
1178   const struct block *b = *(const struct block **) bp;
1179
1180   return ((BLOCK_START (b) > BLOCK_START (a))
1181           - (BLOCK_START (b) < BLOCK_START (a)));
1182 }
1183
1184 /* Reset state after a successful building of a symtab.
1185    This exists because dbxread.c and xcoffread.c can call
1186    start_symtab+end_symtab multiple times after one call to buildsym_init,
1187    and before the really_free_pendings cleanup is called.
1188    We keep the free_pendings list around for dbx/xcoff sake.  */
1189
1190 static void
1191 reset_symtab_globals (void)
1192 {
1193   set_last_source_file (NULL);
1194
1195   local_symbols = NULL;
1196   local_using_directives = NULL;
1197   file_symbols = NULL;
1198   global_symbols = NULL;
1199   global_using_directives = NULL;
1200
1201   /* We don't free pending_macros here because if the symtab was successfully
1202      built then ownership was transferred to the symtab.  */
1203   pending_macros = NULL;
1204
1205   if (pending_addrmap)
1206     obstack_free (&pending_addrmap_obstack, NULL);
1207   pending_addrmap = NULL;
1208
1209   free_buildsym_compunit ();
1210 }
1211
1212 /* Implementation of the first part of end_symtab.  It allows modifying
1213    STATIC_BLOCK before it gets finalized by end_symtab_from_static_block.
1214    If the returned value is NULL there is no blockvector created for
1215    this symtab (you still must call end_symtab_from_static_block).
1216
1217    END_ADDR is the same as for end_symtab: the address of the end of the
1218    file's text.
1219
1220    If EXPANDABLE is non-zero the STATIC_BLOCK dictionary is made
1221    expandable.
1222
1223    If REQUIRED is non-zero, then a symtab is created even if it does
1224    not contain any symbols.  */
1225
1226 struct block *
1227 end_symtab_get_static_block (CORE_ADDR end_addr, int expandable, int required)
1228 {
1229   struct objfile *objfile = buildsym_compunit->objfile;
1230
1231   /* Finish the lexical context of the last function in the file; pop
1232      the context stack.  */
1233
1234   if (context_stack_depth > 0)
1235     {
1236       struct context_stack *cstk = pop_context ();
1237
1238       /* Make a block for the local symbols within.  */
1239       finish_block (cstk->name, &local_symbols, cstk->old_blocks, NULL,
1240                     cstk->start_addr, end_addr);
1241
1242       if (context_stack_depth > 0)
1243         {
1244           /* This is said to happen with SCO.  The old coffread.c
1245              code simply emptied the context stack, so we do the
1246              same.  FIXME: Find out why it is happening.  This is not
1247              believed to happen in most cases (even for coffread.c);
1248              it used to be an abort().  */
1249           complaint (&symfile_complaints,
1250                      _("Context stack not empty in end_symtab"));
1251           context_stack_depth = 0;
1252         }
1253     }
1254
1255   /* Reordered executables may have out of order pending blocks; if
1256      OBJF_REORDERED is true, then sort the pending blocks.  */
1257
1258   if ((objfile->flags & OBJF_REORDERED) && pending_blocks)
1259     {
1260       unsigned count = 0;
1261       struct pending_block *pb;
1262       struct block **barray, **bp;
1263       struct cleanup *back_to;
1264
1265       for (pb = pending_blocks; pb != NULL; pb = pb->next)
1266         count++;
1267
1268       barray = xmalloc (sizeof (*barray) * count);
1269       back_to = make_cleanup (xfree, barray);
1270
1271       bp = barray;
1272       for (pb = pending_blocks; pb != NULL; pb = pb->next)
1273         *bp++ = pb->block;
1274
1275       qsort (barray, count, sizeof (*barray), block_compar);
1276
1277       bp = barray;
1278       for (pb = pending_blocks; pb != NULL; pb = pb->next)
1279         pb->block = *bp++;
1280
1281       do_cleanups (back_to);
1282     }
1283
1284   /* Cleanup any undefined types that have been left hanging around
1285      (this needs to be done before the finish_blocks so that
1286      file_symbols is still good).
1287
1288      Both cleanup_undefined_stabs_types and finish_global_stabs are stabs
1289      specific, but harmless for other symbol readers, since on gdb
1290      startup or when finished reading stabs, the state is set so these
1291      are no-ops.  FIXME: Is this handled right in case of QUIT?  Can
1292      we make this cleaner?  */
1293
1294   cleanup_undefined_stabs_types (objfile);
1295   finish_global_stabs (objfile);
1296
1297   if (!required
1298       && pending_blocks == NULL
1299       && file_symbols == NULL
1300       && global_symbols == NULL
1301       && have_line_numbers == 0
1302       && pending_macros == NULL
1303       && global_using_directives == NULL)
1304     {
1305       /* Ignore symtabs that have no functions with real debugging info.  */
1306       return NULL;
1307     }
1308   else
1309     {
1310       /* Define the STATIC_BLOCK.  */
1311       return finish_block_internal (NULL, &file_symbols, NULL, NULL,
1312                                     last_source_start_addr, end_addr,
1313                                     0, expandable);
1314     }
1315 }
1316
1317 /* Subroutine of end_symtab_from_static_block to simplify it.
1318    Handle the "have blockvector" case.
1319    See end_symtab_from_static_block for a description of the arguments.  */
1320
1321 static struct compunit_symtab *
1322 end_symtab_with_blockvector (struct block *static_block,
1323                              int section, int expandable)
1324 {
1325   struct objfile *objfile = buildsym_compunit->objfile;
1326   struct compunit_symtab *cu = buildsym_compunit->compunit_symtab;
1327   struct symtab *symtab;
1328   struct blockvector *blockvector;
1329   struct subfile *subfile;
1330   CORE_ADDR end_addr;
1331
1332   gdb_assert (static_block != NULL);
1333   gdb_assert (buildsym_compunit != NULL);
1334   gdb_assert (buildsym_compunit->subfiles != NULL);
1335
1336   end_addr = BLOCK_END (static_block);
1337
1338   /* Create the GLOBAL_BLOCK and build the blockvector.  */
1339   finish_block_internal (NULL, &global_symbols, NULL, NULL,
1340                          last_source_start_addr, end_addr,
1341                          1, expandable);
1342   blockvector = make_blockvector ();
1343
1344   /* Read the line table if it has to be read separately.
1345      This is only used by xcoffread.c.  */
1346   if (objfile->sf->sym_read_linetable != NULL)
1347     objfile->sf->sym_read_linetable (objfile);
1348
1349   /* Handle the case where the debug info specifies a different path
1350      for the main source file.  It can cause us to lose track of its
1351      line number information.  */
1352   watch_main_source_file_lossage ();
1353
1354   /* Now create the symtab objects proper, if not already done,
1355      one for each subfile.  */
1356
1357   for (subfile = buildsym_compunit->subfiles;
1358        subfile != NULL;
1359        subfile = subfile->next)
1360     {
1361       int linetablesize = 0;
1362
1363       if (subfile->line_vector)
1364         {
1365           linetablesize = sizeof (struct linetable) +
1366             subfile->line_vector->nitems * sizeof (struct linetable_entry);
1367
1368           /* Like the pending blocks, the line table may be
1369              scrambled in reordered executables.  Sort it if
1370              OBJF_REORDERED is true.  */
1371           if (objfile->flags & OBJF_REORDERED)
1372             qsort (subfile->line_vector->item,
1373                    subfile->line_vector->nitems,
1374                    sizeof (struct linetable_entry), compare_line_numbers);
1375         }
1376
1377       /* Allocate a symbol table if necessary.  */
1378       if (subfile->symtab == NULL)
1379         subfile->symtab = allocate_symtab (cu, subfile->name);
1380       symtab = subfile->symtab;
1381
1382       /* Fill in its components.  */
1383
1384       if (subfile->line_vector)
1385         {
1386           /* Reallocate the line table on the symbol obstack.  */
1387           SYMTAB_LINETABLE (symtab) = (struct linetable *)
1388             obstack_alloc (&objfile->objfile_obstack, linetablesize);
1389           memcpy (SYMTAB_LINETABLE (symtab), subfile->line_vector,
1390                   linetablesize);
1391         }
1392       else
1393         {
1394           SYMTAB_LINETABLE (symtab) = NULL;
1395         }
1396
1397       /* Use whatever language we have been using for this
1398          subfile, not the one that was deduced in allocate_symtab
1399          from the filename.  We already did our own deducing when
1400          we created the subfile, and we may have altered our
1401          opinion of what language it is from things we found in
1402          the symbols.  */
1403       symtab->language = subfile->language;
1404     }
1405
1406   /* Make sure the symtab of main_subfile is the first in its list.  */
1407   {
1408     struct symtab *main_symtab, *prev_symtab;
1409
1410     main_symtab = buildsym_compunit->main_subfile->symtab;
1411     prev_symtab = NULL;
1412     ALL_COMPUNIT_FILETABS (cu, symtab)
1413       {
1414         if (symtab == main_symtab)
1415           {
1416             if (prev_symtab != NULL)
1417               {
1418                 prev_symtab->next = main_symtab->next;
1419                 main_symtab->next = COMPUNIT_FILETABS (cu);
1420                 COMPUNIT_FILETABS (cu) = main_symtab;
1421               }
1422             break;
1423           }
1424         prev_symtab = symtab;
1425       }
1426     gdb_assert (main_symtab == COMPUNIT_FILETABS (cu));
1427   }
1428
1429   /* Fill out the compunit symtab.  */
1430
1431   if (buildsym_compunit->comp_dir != NULL)
1432     {
1433       /* Reallocate the dirname on the symbol obstack.  */
1434       COMPUNIT_DIRNAME (cu)
1435         = obstack_copy0 (&objfile->objfile_obstack,
1436                          buildsym_compunit->comp_dir,
1437                          strlen (buildsym_compunit->comp_dir));
1438     }
1439
1440   /* Save the debug format string (if any) in the symtab.  */
1441   COMPUNIT_DEBUGFORMAT (cu) = buildsym_compunit->debugformat;
1442
1443   /* Similarly for the producer.  */
1444   COMPUNIT_PRODUCER (cu) = buildsym_compunit->producer;
1445
1446   COMPUNIT_BLOCKVECTOR (cu) = blockvector;
1447   {
1448     struct block *b = BLOCKVECTOR_BLOCK (blockvector, GLOBAL_BLOCK);
1449
1450     set_block_compunit_symtab (b, cu);
1451   }
1452
1453   COMPUNIT_BLOCK_LINE_SECTION (cu) = section;
1454
1455   COMPUNIT_MACRO_TABLE (cu) = pending_macros;
1456
1457   /* Default any symbols without a specified symtab to the primary symtab.  */
1458   {
1459     int block_i;
1460
1461     /* The main source file's symtab.  */
1462     symtab = COMPUNIT_FILETABS (cu);
1463
1464     for (block_i = 0; block_i < BLOCKVECTOR_NBLOCKS (blockvector); block_i++)
1465       {
1466         struct block *block = BLOCKVECTOR_BLOCK (blockvector, block_i);
1467         struct symbol *sym;
1468         struct dict_iterator iter;
1469
1470         /* Inlined functions may have symbols not in the global or
1471            static symbol lists.  */
1472         if (BLOCK_FUNCTION (block) != NULL)
1473           if (symbol_symtab (BLOCK_FUNCTION (block)) == NULL)
1474             symbol_set_symtab (BLOCK_FUNCTION (block), symtab);
1475
1476         /* Note that we only want to fix up symbols from the local
1477            blocks, not blocks coming from included symtabs.  That is why
1478            we use ALL_DICT_SYMBOLS here and not ALL_BLOCK_SYMBOLS.  */
1479         ALL_DICT_SYMBOLS (BLOCK_DICT (block), iter, sym)
1480           if (symbol_symtab (sym) == NULL)
1481             symbol_set_symtab (sym, symtab);
1482       }
1483   }
1484
1485   add_compunit_symtab_to_objfile (cu);
1486
1487   return cu;
1488 }
1489
1490 /* Implementation of the second part of end_symtab.  Pass STATIC_BLOCK
1491    as value returned by end_symtab_get_static_block.
1492
1493    SECTION is the same as for end_symtab: the section number
1494    (in objfile->section_offsets) of the blockvector and linetable.
1495
1496    If EXPANDABLE is non-zero the GLOBAL_BLOCK dictionary is made
1497    expandable.  */
1498
1499 struct compunit_symtab *
1500 end_symtab_from_static_block (struct block *static_block,
1501                               int section, int expandable)
1502 {
1503   struct compunit_symtab *cu;
1504
1505   if (static_block == NULL)
1506     {
1507       /* Handle the "no blockvector" case.
1508          When this happens there is nothing to record, so there's nothing
1509          to do: memory will be freed up later.
1510
1511          Note: We won't be adding a compunit to the objfile's list of
1512          compunits, so there's nothing to unchain.  However, since each symtab
1513          is added to the objfile's obstack we can't free that space.
1514          We could do better, but this is believed to be a sufficiently rare
1515          event.  */
1516       cu = NULL;
1517     }
1518   else
1519     cu = end_symtab_with_blockvector (static_block, section, expandable);
1520
1521   reset_symtab_globals ();
1522
1523   return cu;
1524 }
1525
1526 /* Finish the symbol definitions for one main source file, close off
1527    all the lexical contexts for that file (creating struct block's for
1528    them), then make the struct symtab for that file and put it in the
1529    list of all such.
1530
1531    END_ADDR is the address of the end of the file's text.  SECTION is
1532    the section number (in objfile->section_offsets) of the blockvector
1533    and linetable.
1534
1535    Note that it is possible for end_symtab() to return NULL.  In
1536    particular, for the DWARF case at least, it will return NULL when
1537    it finds a compilation unit that has exactly one DIE, a
1538    TAG_compile_unit DIE.  This can happen when we link in an object
1539    file that was compiled from an empty source file.  Returning NULL
1540    is probably not the correct thing to do, because then gdb will
1541    never know about this empty file (FIXME).
1542
1543    If you need to modify STATIC_BLOCK before it is finalized you should
1544    call end_symtab_get_static_block and end_symtab_from_static_block
1545    yourself.  */
1546
1547 struct compunit_symtab *
1548 end_symtab (CORE_ADDR end_addr, int section)
1549 {
1550   struct block *static_block;
1551
1552   static_block = end_symtab_get_static_block (end_addr, 0, 0);
1553   return end_symtab_from_static_block (static_block, section, 0);
1554 }
1555
1556 /* Same as end_symtab except create a symtab that can be later added to.  */
1557
1558 struct compunit_symtab *
1559 end_expandable_symtab (CORE_ADDR end_addr, int section)
1560 {
1561   struct block *static_block;
1562
1563   static_block = end_symtab_get_static_block (end_addr, 1, 0);
1564   return end_symtab_from_static_block (static_block, section, 1);
1565 }
1566
1567 /* Subroutine of augment_type_symtab to simplify it.
1568    Attach the main source file's symtab to all symbols in PENDING_LIST that
1569    don't have one.  */
1570
1571 static void
1572 set_missing_symtab (struct pending *pending_list,
1573                     struct compunit_symtab *cu)
1574 {
1575   struct pending *pending;
1576   int i;
1577
1578   for (pending = pending_list; pending != NULL; pending = pending->next)
1579     {
1580       for (i = 0; i < pending->nsyms; ++i)
1581         {
1582           if (symbol_symtab (pending->symbol[i]) == NULL)
1583             symbol_set_symtab (pending->symbol[i], COMPUNIT_FILETABS (cu));
1584         }
1585     }
1586 }
1587
1588 /* Same as end_symtab, but for the case where we're adding more symbols
1589    to an existing symtab that is known to contain only type information.
1590    This is the case for DWARF4 Type Units.  */
1591
1592 void
1593 augment_type_symtab (void)
1594 {
1595   struct compunit_symtab *cust = buildsym_compunit->compunit_symtab;
1596   const struct blockvector *blockvector = COMPUNIT_BLOCKVECTOR (cust);
1597
1598   if (context_stack_depth > 0)
1599     {
1600       complaint (&symfile_complaints,
1601                  _("Context stack not empty in augment_type_symtab"));
1602       context_stack_depth = 0;
1603     }
1604   if (pending_blocks != NULL)
1605     complaint (&symfile_complaints, _("Blocks in a type symtab"));
1606   if (pending_macros != NULL)
1607     complaint (&symfile_complaints, _("Macro in a type symtab"));
1608   if (have_line_numbers)
1609     complaint (&symfile_complaints,
1610                _("Line numbers recorded in a type symtab"));
1611
1612   if (file_symbols != NULL)
1613     {
1614       struct block *block = BLOCKVECTOR_BLOCK (blockvector, STATIC_BLOCK);
1615
1616       /* First mark any symbols without a specified symtab as belonging
1617          to the primary symtab.  */
1618       set_missing_symtab (file_symbols, cust);
1619
1620       dict_add_pending (BLOCK_DICT (block), file_symbols);
1621     }
1622
1623   if (global_symbols != NULL)
1624     {
1625       struct block *block = BLOCKVECTOR_BLOCK (blockvector, GLOBAL_BLOCK);
1626
1627       /* First mark any symbols without a specified symtab as belonging
1628          to the primary symtab.  */
1629       set_missing_symtab (global_symbols, cust);
1630
1631       dict_add_pending (BLOCK_DICT (block), global_symbols);
1632     }
1633
1634   reset_symtab_globals ();
1635 }
1636
1637 /* Push a context block.  Args are an identifying nesting level
1638    (checkable when you pop it), and the starting PC address of this
1639    context.  */
1640
1641 struct context_stack *
1642 push_context (int desc, CORE_ADDR valu)
1643 {
1644   struct context_stack *newobj;
1645
1646   if (context_stack_depth == context_stack_size)
1647     {
1648       context_stack_size *= 2;
1649       context_stack = (struct context_stack *)
1650         xrealloc ((char *) context_stack,
1651                   (context_stack_size * sizeof (struct context_stack)));
1652     }
1653
1654   newobj = &context_stack[context_stack_depth++];
1655   newobj->depth = desc;
1656   newobj->locals = local_symbols;
1657   newobj->old_blocks = pending_blocks;
1658   newobj->start_addr = valu;
1659   newobj->local_using_directives = local_using_directives;
1660   newobj->name = NULL;
1661
1662   local_symbols = NULL;
1663   local_using_directives = NULL;
1664
1665   return newobj;
1666 }
1667
1668 /* Pop a context block.  Returns the address of the context block just
1669    popped.  */
1670
1671 struct context_stack *
1672 pop_context (void)
1673 {
1674   gdb_assert (context_stack_depth > 0);
1675   return (&context_stack[--context_stack_depth]);
1676 }
1677
1678 \f
1679
1680 /* Compute a small integer hash code for the given name.  */
1681
1682 int
1683 hashname (const char *name)
1684 {
1685     return (hash(name,strlen(name)) % HASHSIZE);
1686 }
1687 \f
1688
1689 void
1690 record_debugformat (const char *format)
1691 {
1692   buildsym_compunit->debugformat = format;
1693 }
1694
1695 void
1696 record_producer (const char *producer)
1697 {
1698   buildsym_compunit->producer = producer;
1699 }
1700
1701 /* Merge the first symbol list SRCLIST into the second symbol list
1702    TARGETLIST by repeated calls to add_symbol_to_list().  This
1703    procedure "frees" each link of SRCLIST by adding it to the
1704    free_pendings list.  Caller must set SRCLIST to a null list after
1705    calling this function.
1706
1707    Void return.  */
1708
1709 void
1710 merge_symbol_lists (struct pending **srclist, struct pending **targetlist)
1711 {
1712   int i;
1713
1714   if (!srclist || !*srclist)
1715     return;
1716
1717   /* Merge in elements from current link.  */
1718   for (i = 0; i < (*srclist)->nsyms; i++)
1719     add_symbol_to_list ((*srclist)->symbol[i], targetlist);
1720
1721   /* Recurse on next.  */
1722   merge_symbol_lists (&(*srclist)->next, targetlist);
1723
1724   /* "Free" the current link.  */
1725   (*srclist)->next = free_pendings;
1726   free_pendings = (*srclist);
1727 }
1728 \f
1729
1730 /* Name of source file whose symbol data we are now processing.  This
1731    comes from a symbol of type N_SO for stabs.  For Dwarf it comes
1732    from the DW_AT_name attribute of a DW_TAG_compile_unit DIE.  */
1733
1734 static char *last_source_file;
1735
1736 /* See buildsym.h.  */
1737
1738 void
1739 set_last_source_file (const char *name)
1740 {
1741   xfree (last_source_file);
1742   last_source_file = name == NULL ? NULL : xstrdup (name);
1743 }
1744
1745 /* See buildsym.h.  */
1746
1747 const char *
1748 get_last_source_file (void)
1749 {
1750   return last_source_file;
1751 }
1752
1753 \f
1754
1755 /* Initialize anything that needs initializing when starting to read a
1756    fresh piece of a symbol file, e.g. reading in the stuff
1757    corresponding to a psymtab.  */
1758
1759 void
1760 buildsym_init (void)
1761 {
1762   subfile_stack = NULL;
1763
1764   pending_addrmap_interesting = 0;
1765
1766   /* Context stack is initially empty.  Allocate first one with room
1767      for a few levels; reuse it forever afterward.  */
1768   if (context_stack == NULL)
1769     {
1770       context_stack_size = INITIAL_CONTEXT_STACK_SIZE;
1771       context_stack = (struct context_stack *)
1772         xmalloc (context_stack_size * sizeof (struct context_stack));
1773     }
1774
1775   /* Ensure the really_free_pendings cleanup was called after
1776      the last time.  */
1777   gdb_assert (free_pendings == NULL);
1778   gdb_assert (pending_blocks == NULL);
1779   gdb_assert (file_symbols == NULL);
1780   gdb_assert (global_symbols == NULL);
1781   gdb_assert (global_using_directives == NULL);
1782   gdb_assert (pending_macros == NULL);
1783   gdb_assert (pending_addrmap == NULL);
1784   gdb_assert (buildsym_compunit == NULL);
1785 }
1786
1787 /* Initialize anything that needs initializing when a completely new
1788    symbol file is specified (not just adding some symbols from another
1789    file, e.g. a shared library).  */
1790
1791 void
1792 buildsym_new_init (void)
1793 {
1794   buildsym_init ();
1795 }