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