gdb/
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70
71 #include <fcntl.h>
72 #include "gdb_string.h"
73 #include "gdb_assert.h"
74 #include <sys/types.h>
75
76 typedef struct symbol *symbolp;
77 DEF_VEC_P (symbolp);
78
79 /* When non-zero, print basic high level tracing messages.
80    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
81 static int dwarf2_read_debug = 0;
82
83 /* When non-zero, dump DIEs after they are read in.  */
84 static unsigned int dwarf2_die_debug = 0;
85
86 /* When non-zero, cross-check physname against demangler.  */
87 static int check_physname = 0;
88
89 /* When non-zero, do not reject deprecated .gdb_index sections.  */
90 static int use_deprecated_index_sections = 0;
91
92 static const struct objfile_data *dwarf2_objfile_data_key;
93
94 struct dwarf2_section_info
95 {
96   asection *asection;
97   gdb_byte *buffer;
98   bfd_size_type size;
99   /* True if we have tried to read this section.  */
100   int readin;
101 };
102
103 typedef struct dwarf2_section_info dwarf2_section_info_def;
104 DEF_VEC_O (dwarf2_section_info_def);
105
106 /* All offsets in the index are of this type.  It must be
107    architecture-independent.  */
108 typedef uint32_t offset_type;
109
110 DEF_VEC_I (offset_type);
111
112 /* Ensure only legit values are used.  */
113 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
114   do { \
115     gdb_assert ((unsigned int) (value) <= 1); \
116     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
117   } while (0)
118
119 /* Ensure only legit values are used.  */
120 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
121   do { \
122     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
123                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
124     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
125   } while (0)
126
127 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
128 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
129   do { \
130     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
131     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
132   } while (0)
133
134 /* A description of the mapped index.  The file format is described in
135    a comment by the code that writes the index.  */
136 struct mapped_index
137 {
138   /* Index data format version.  */
139   int version;
140
141   /* The total length of the buffer.  */
142   off_t total_size;
143
144   /* A pointer to the address table data.  */
145   const gdb_byte *address_table;
146
147   /* Size of the address table data in bytes.  */
148   offset_type address_table_size;
149
150   /* The symbol table, implemented as a hash table.  */
151   const offset_type *symbol_table;
152
153   /* Size in slots, each slot is 2 offset_types.  */
154   offset_type symbol_table_slots;
155
156   /* A pointer to the constant pool.  */
157   const char *constant_pool;
158 };
159
160 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
161 DEF_VEC_P (dwarf2_per_cu_ptr);
162
163 /* Collection of data recorded per objfile.
164    This hangs off of dwarf2_objfile_data_key.  */
165
166 struct dwarf2_per_objfile
167 {
168   struct dwarf2_section_info info;
169   struct dwarf2_section_info abbrev;
170   struct dwarf2_section_info line;
171   struct dwarf2_section_info loc;
172   struct dwarf2_section_info macinfo;
173   struct dwarf2_section_info macro;
174   struct dwarf2_section_info str;
175   struct dwarf2_section_info ranges;
176   struct dwarf2_section_info addr;
177   struct dwarf2_section_info frame;
178   struct dwarf2_section_info eh_frame;
179   struct dwarf2_section_info gdb_index;
180
181   VEC (dwarf2_section_info_def) *types;
182
183   /* Back link.  */
184   struct objfile *objfile;
185
186   /* Table of all the compilation units.  This is used to locate
187      the target compilation unit of a particular reference.  */
188   struct dwarf2_per_cu_data **all_comp_units;
189
190   /* The number of compilation units in ALL_COMP_UNITS.  */
191   int n_comp_units;
192
193   /* The number of .debug_types-related CUs.  */
194   int n_type_units;
195
196   /* The .debug_types-related CUs (TUs).  */
197   struct signatured_type **all_type_units;
198
199   /* The number of entries in all_type_unit_groups.  */
200   int n_type_unit_groups;
201
202   /* Table of type unit groups.
203      This exists to make it easy to iterate over all CUs and TU groups.  */
204   struct type_unit_group **all_type_unit_groups;
205
206   /* Table of struct type_unit_group objects.
207      The hash key is the DW_AT_stmt_list value.  */
208   htab_t type_unit_groups;
209
210   /* A table mapping .debug_types signatures to its signatured_type entry.
211      This is NULL if the .debug_types section hasn't been read in yet.  */
212   htab_t signatured_types;
213
214   /* Type unit statistics, to see how well the scaling improvements
215      are doing.  */
216   struct tu_stats
217   {
218     int nr_uniq_abbrev_tables;
219     int nr_symtabs;
220     int nr_symtab_sharers;
221     int nr_stmt_less_type_units;
222   } tu_stats;
223
224   /* A chain of compilation units that are currently read in, so that
225      they can be freed later.  */
226   struct dwarf2_per_cu_data *read_in_chain;
227
228   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
229      This is NULL if the table hasn't been allocated yet.  */
230   htab_t dwo_files;
231
232   /* Non-zero if we've check for whether there is a DWP file.  */
233   int dwp_checked;
234
235   /* The DWP file if there is one, or NULL.  */
236   struct dwp_file *dwp_file;
237
238   /* The shared '.dwz' file, if one exists.  This is used when the
239      original data was compressed using 'dwz -m'.  */
240   struct dwz_file *dwz_file;
241
242   /* A flag indicating wether this objfile has a section loaded at a
243      VMA of 0.  */
244   int has_section_at_zero;
245
246   /* True if we are using the mapped index,
247      or we are faking it for OBJF_READNOW's sake.  */
248   unsigned char using_index;
249
250   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
251   struct mapped_index *index_table;
252
253   /* When using index_table, this keeps track of all quick_file_names entries.
254      TUs typically share line table entries with a CU, so we maintain a
255      separate table of all line table entries to support the sharing.
256      Note that while there can be way more TUs than CUs, we've already
257      sorted all the TUs into "type unit groups", grouped by their
258      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
259      CU and its associated TU group if there is one.  */
260   htab_t quick_file_names_table;
261
262   /* Set during partial symbol reading, to prevent queueing of full
263      symbols.  */
264   int reading_partial_symbols;
265
266   /* Table mapping type DIEs to their struct type *.
267      This is NULL if not allocated yet.
268      The mapping is done via (CU/TU signature + DIE offset) -> type.  */
269   htab_t die_type_hash;
270
271   /* The CUs we recently read.  */
272   VEC (dwarf2_per_cu_ptr) *just_read_cus;
273 };
274
275 static struct dwarf2_per_objfile *dwarf2_per_objfile;
276
277 /* Default names of the debugging sections.  */
278
279 /* Note that if the debugging section has been compressed, it might
280    have a name like .zdebug_info.  */
281
282 static const struct dwarf2_debug_sections dwarf2_elf_names =
283 {
284   { ".debug_info", ".zdebug_info" },
285   { ".debug_abbrev", ".zdebug_abbrev" },
286   { ".debug_line", ".zdebug_line" },
287   { ".debug_loc", ".zdebug_loc" },
288   { ".debug_macinfo", ".zdebug_macinfo" },
289   { ".debug_macro", ".zdebug_macro" },
290   { ".debug_str", ".zdebug_str" },
291   { ".debug_ranges", ".zdebug_ranges" },
292   { ".debug_types", ".zdebug_types" },
293   { ".debug_addr", ".zdebug_addr" },
294   { ".debug_frame", ".zdebug_frame" },
295   { ".eh_frame", NULL },
296   { ".gdb_index", ".zgdb_index" },
297   23
298 };
299
300 /* List of DWO/DWP sections.  */
301
302 static const struct dwop_section_names
303 {
304   struct dwarf2_section_names abbrev_dwo;
305   struct dwarf2_section_names info_dwo;
306   struct dwarf2_section_names line_dwo;
307   struct dwarf2_section_names loc_dwo;
308   struct dwarf2_section_names macinfo_dwo;
309   struct dwarf2_section_names macro_dwo;
310   struct dwarf2_section_names str_dwo;
311   struct dwarf2_section_names str_offsets_dwo;
312   struct dwarf2_section_names types_dwo;
313   struct dwarf2_section_names cu_index;
314   struct dwarf2_section_names tu_index;
315 }
316 dwop_section_names =
317 {
318   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
319   { ".debug_info.dwo", ".zdebug_info.dwo" },
320   { ".debug_line.dwo", ".zdebug_line.dwo" },
321   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
322   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
323   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
324   { ".debug_str.dwo", ".zdebug_str.dwo" },
325   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
326   { ".debug_types.dwo", ".zdebug_types.dwo" },
327   { ".debug_cu_index", ".zdebug_cu_index" },
328   { ".debug_tu_index", ".zdebug_tu_index" },
329 };
330
331 /* local data types */
332
333 /* The data in a compilation unit header, after target2host
334    translation, looks like this.  */
335 struct comp_unit_head
336 {
337   unsigned int length;
338   short version;
339   unsigned char addr_size;
340   unsigned char signed_addr_p;
341   sect_offset abbrev_offset;
342
343   /* Size of file offsets; either 4 or 8.  */
344   unsigned int offset_size;
345
346   /* Size of the length field; either 4 or 12.  */
347   unsigned int initial_length_size;
348
349   /* Offset to the first byte of this compilation unit header in the
350      .debug_info section, for resolving relative reference dies.  */
351   sect_offset offset;
352
353   /* Offset to first die in this cu from the start of the cu.
354      This will be the first byte following the compilation unit header.  */
355   cu_offset first_die_offset;
356 };
357
358 /* Type used for delaying computation of method physnames.
359    See comments for compute_delayed_physnames.  */
360 struct delayed_method_info
361 {
362   /* The type to which the method is attached, i.e., its parent class.  */
363   struct type *type;
364
365   /* The index of the method in the type's function fieldlists.  */
366   int fnfield_index;
367
368   /* The index of the method in the fieldlist.  */
369   int index;
370
371   /* The name of the DIE.  */
372   const char *name;
373
374   /*  The DIE associated with this method.  */
375   struct die_info *die;
376 };
377
378 typedef struct delayed_method_info delayed_method_info;
379 DEF_VEC_O (delayed_method_info);
380
381 /* Internal state when decoding a particular compilation unit.  */
382 struct dwarf2_cu
383 {
384   /* The objfile containing this compilation unit.  */
385   struct objfile *objfile;
386
387   /* The header of the compilation unit.  */
388   struct comp_unit_head header;
389
390   /* Base address of this compilation unit.  */
391   CORE_ADDR base_address;
392
393   /* Non-zero if base_address has been set.  */
394   int base_known;
395
396   /* The language we are debugging.  */
397   enum language language;
398   const struct language_defn *language_defn;
399
400   const char *producer;
401
402   /* The generic symbol table building routines have separate lists for
403      file scope symbols and all all other scopes (local scopes).  So
404      we need to select the right one to pass to add_symbol_to_list().
405      We do it by keeping a pointer to the correct list in list_in_scope.
406
407      FIXME: The original dwarf code just treated the file scope as the
408      first local scope, and all other local scopes as nested local
409      scopes, and worked fine.  Check to see if we really need to
410      distinguish these in buildsym.c.  */
411   struct pending **list_in_scope;
412
413   /* The abbrev table for this CU.
414      Normally this points to the abbrev table in the objfile.
415      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
416   struct abbrev_table *abbrev_table;
417
418   /* Hash table holding all the loaded partial DIEs
419      with partial_die->offset.SECT_OFF as hash.  */
420   htab_t partial_dies;
421
422   /* Storage for things with the same lifetime as this read-in compilation
423      unit, including partial DIEs.  */
424   struct obstack comp_unit_obstack;
425
426   /* When multiple dwarf2_cu structures are living in memory, this field
427      chains them all together, so that they can be released efficiently.
428      We will probably also want a generation counter so that most-recently-used
429      compilation units are cached...  */
430   struct dwarf2_per_cu_data *read_in_chain;
431
432   /* Backchain to our per_cu entry if the tree has been built.  */
433   struct dwarf2_per_cu_data *per_cu;
434
435   /* How many compilation units ago was this CU last referenced?  */
436   int last_used;
437
438   /* A hash table of DIE cu_offset for following references with
439      die_info->offset.sect_off as hash.  */
440   htab_t die_hash;
441
442   /* Full DIEs if read in.  */
443   struct die_info *dies;
444
445   /* A set of pointers to dwarf2_per_cu_data objects for compilation
446      units referenced by this one.  Only set during full symbol processing;
447      partial symbol tables do not have dependencies.  */
448   htab_t dependencies;
449
450   /* Header data from the line table, during full symbol processing.  */
451   struct line_header *line_header;
452
453   /* A list of methods which need to have physnames computed
454      after all type information has been read.  */
455   VEC (delayed_method_info) *method_list;
456
457   /* To be copied to symtab->call_site_htab.  */
458   htab_t call_site_htab;
459
460   /* Non-NULL if this CU came from a DWO file.
461      There is an invariant here that is important to remember:
462      Except for attributes copied from the top level DIE in the "main"
463      (or "stub") file in preparation for reading the DWO file
464      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
465      Either there isn't a DWO file (in which case this is NULL and the point
466      is moot), or there is and either we're not going to read it (in which
467      case this is NULL) or there is and we are reading it (in which case this
468      is non-NULL).  */
469   struct dwo_unit *dwo_unit;
470
471   /* The DW_AT_addr_base attribute if present, zero otherwise
472      (zero is a valid value though).
473      Note this value comes from the stub CU/TU's DIE.  */
474   ULONGEST addr_base;
475
476   /* The DW_AT_ranges_base attribute if present, zero otherwise
477      (zero is a valid value though).
478      Note this value comes from the stub CU/TU's DIE.
479      Also note that the value is zero in the non-DWO case so this value can
480      be used without needing to know whether DWO files are in use or not.
481      N.B. This does not apply to DW_AT_ranges appearing in
482      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
483      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
484      DW_AT_ranges_base *would* have to be applied, and we'd have to care
485      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
486   ULONGEST ranges_base;
487
488   /* Mark used when releasing cached dies.  */
489   unsigned int mark : 1;
490
491   /* This CU references .debug_loc.  See the symtab->locations_valid field.
492      This test is imperfect as there may exist optimized debug code not using
493      any location list and still facing inlining issues if handled as
494      unoptimized code.  For a future better test see GCC PR other/32998.  */
495   unsigned int has_loclist : 1;
496
497   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
498      if all the producer_is_* fields are valid.  This information is cached
499      because profiling CU expansion showed excessive time spent in
500      producer_is_gxx_lt_4_6.  */
501   unsigned int checked_producer : 1;
502   unsigned int producer_is_gxx_lt_4_6 : 1;
503   unsigned int producer_is_gcc_lt_4_3 : 1;
504   unsigned int producer_is_icc : 1;
505
506   /* When set, the file that we're processing is known to have
507      debugging info for C++ namespaces.  GCC 3.3.x did not produce
508      this information, but later versions do.  */
509
510   unsigned int processing_has_namespace_info : 1;
511 };
512
513 /* Persistent data held for a compilation unit, even when not
514    processing it.  We put a pointer to this structure in the
515    read_symtab_private field of the psymtab.  */
516
517 struct dwarf2_per_cu_data
518 {
519   /* The start offset and length of this compilation unit.
520      NOTE: Unlike comp_unit_head.length, this length includes
521      initial_length_size.
522      If the DIE refers to a DWO file, this is always of the original die,
523      not the DWO file.  */
524   sect_offset offset;
525   unsigned int length;
526
527   /* Flag indicating this compilation unit will be read in before
528      any of the current compilation units are processed.  */
529   unsigned int queued : 1;
530
531   /* This flag will be set when reading partial DIEs if we need to load
532      absolutely all DIEs for this compilation unit, instead of just the ones
533      we think are interesting.  It gets set if we look for a DIE in the
534      hash table and don't find it.  */
535   unsigned int load_all_dies : 1;
536
537   /* Non-zero if this CU is from .debug_types.  */
538   unsigned int is_debug_types : 1;
539
540   /* Non-zero if this CU is from the .dwz file.  */
541   unsigned int is_dwz : 1;
542
543   /* The section this CU/TU lives in.
544      If the DIE refers to a DWO file, this is always the original die,
545      not the DWO file.  */
546   struct dwarf2_section_info *info_or_types_section;
547
548   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
549      of the CU cache it gets reset to NULL again.  */
550   struct dwarf2_cu *cu;
551
552   /* The corresponding objfile.
553      Normally we can get the objfile from dwarf2_per_objfile.
554      However we can enter this file with just a "per_cu" handle.  */
555   struct objfile *objfile;
556
557   /* When using partial symbol tables, the 'psymtab' field is active.
558      Otherwise the 'quick' field is active.  */
559   union
560   {
561     /* The partial symbol table associated with this compilation unit,
562        or NULL for unread partial units.  */
563     struct partial_symtab *psymtab;
564
565     /* Data needed by the "quick" functions.  */
566     struct dwarf2_per_cu_quick_data *quick;
567   } v;
568
569   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
570      while reading psymtabs, used to compute the psymtab dependencies,
571      and then cleared.  Then it is filled in again while reading full
572      symbols, and only deleted when the objfile is destroyed.
573
574      This is also used to work around a difference between the way gold
575      generates .gdb_index version <=7 and the way gdb does.  Arguably this
576      is a gold bug.  For symbols coming from TUs, gold records in the index
577      the CU that includes the TU instead of the TU itself.  This breaks
578      dw2_lookup_symbol: It assumes that if the index says symbol X lives
579      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
580      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
581      we need to look in TU Z to find X.  Fortunately, this is akin to
582      DW_TAG_imported_unit, so we just use the same mechanism: For
583      .gdb_index version <=7 this also records the TUs that the CU referred
584      to.  Concurrently with this change gdb was modified to emit version 8
585      indices so we only pay a price for gold generated indices.  */
586   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
587
588   /* Type units are grouped by their DW_AT_stmt_list entry so that they
589      can share them.  If this is a TU, this points to the containing
590      symtab.  */
591   struct type_unit_group *type_unit_group;
592 };
593
594 /* Entry in the signatured_types hash table.  */
595
596 struct signatured_type
597 {
598   /* The "per_cu" object of this type.
599      N.B.: This is the first member so that it's easy to convert pointers
600      between them.  */
601   struct dwarf2_per_cu_data per_cu;
602
603   /* The type's signature.  */
604   ULONGEST signature;
605
606   /* Offset in the TU of the type's DIE, as read from the TU header.
607      If the definition lives in a DWO file, this value is unusable.  */
608   cu_offset type_offset_in_tu;
609
610   /* Offset in the section of the type's DIE.
611      If the definition lives in a DWO file, this is the offset in the
612      .debug_types.dwo section.
613      The value is zero until the actual value is known.
614      Zero is otherwise not a valid section offset.  */
615   sect_offset type_offset_in_section;
616 };
617
618 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
619    This includes type_unit_group and quick_file_names.  */
620
621 struct stmt_list_hash
622 {
623   /* The DWO unit this table is from or NULL if there is none.  */
624   struct dwo_unit *dwo_unit;
625
626   /* Offset in .debug_line or .debug_line.dwo.  */
627   sect_offset line_offset;
628 };
629
630 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
631    an object of this type.  */
632
633 struct type_unit_group
634 {
635   /* dwarf2read.c's main "handle" on the symtab.
636      To simplify things we create an artificial CU that "includes" all the
637      type units using this stmt_list so that the rest of the code still has
638      a "per_cu" handle on the symtab.
639      This PER_CU is recognized by having no section.  */
640 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->info_or_types_section == NULL)
641   struct dwarf2_per_cu_data per_cu;
642
643   union
644   {
645     /* The TUs that share this DW_AT_stmt_list entry.
646        This is added to while parsing type units to build partial symtabs,
647        and is deleted afterwards and not used again.  */
648     VEC (dwarf2_per_cu_ptr) *tus;
649
650     /* When reading the line table in "quick" functions, we need a real TU.
651        Any will do, we know they all share the same DW_AT_stmt_list entry.
652        For simplicity's sake, we pick the first one.  */
653     struct dwarf2_per_cu_data *first_tu;
654   } t;
655
656   /* The primary symtab.
657      Type units in a group needn't all be defined in the same source file,
658      so we create an essentially anonymous symtab as the primary symtab.  */
659   struct symtab *primary_symtab;
660
661   /* The data used to construct the hash key.  */
662   struct stmt_list_hash hash;
663
664   /* The number of symtabs from the line header.
665      The value here must match line_header.num_file_names.  */
666   unsigned int num_symtabs;
667
668   /* The symbol tables for this TU (obtained from the files listed in
669      DW_AT_stmt_list).
670      WARNING: The order of entries here must match the order of entries
671      in the line header.  After the first TU using this type_unit_group, the
672      line header for the subsequent TUs is recreated from this.  This is done
673      because we need to use the same symtabs for each TU using the same
674      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
675      there's no guarantee the line header doesn't have duplicate entries.  */
676   struct symtab **symtabs;
677 };
678
679 /* These sections are what may appear in a DWO file.  */
680
681 struct dwo_sections
682 {
683   struct dwarf2_section_info abbrev;
684   struct dwarf2_section_info line;
685   struct dwarf2_section_info loc;
686   struct dwarf2_section_info macinfo;
687   struct dwarf2_section_info macro;
688   struct dwarf2_section_info str;
689   struct dwarf2_section_info str_offsets;
690   /* In the case of a virtual DWO file, these two are unused.  */
691   struct dwarf2_section_info info;
692   VEC (dwarf2_section_info_def) *types;
693 };
694
695 /* Common bits of DWO CUs/TUs.  */
696
697 struct dwo_unit
698 {
699   /* Backlink to the containing struct dwo_file.  */
700   struct dwo_file *dwo_file;
701
702   /* The "id" that distinguishes this CU/TU.
703      .debug_info calls this "dwo_id", .debug_types calls this "signature".
704      Since signatures came first, we stick with it for consistency.  */
705   ULONGEST signature;
706
707   /* The section this CU/TU lives in, in the DWO file.  */
708   struct dwarf2_section_info *info_or_types_section;
709
710   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
711   sect_offset offset;
712   unsigned int length;
713
714   /* For types, offset in the type's DIE of the type defined by this TU.  */
715   cu_offset type_offset_in_tu;
716 };
717
718 /* Data for one DWO file.
719    This includes virtual DWO files that have been packaged into a
720    DWP file.  */
721
722 struct dwo_file
723 {
724   /* The DW_AT_GNU_dwo_name attribute.  This is the hash key.
725      For virtual DWO files the name is constructed from the section offsets
726      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
727      from related CU+TUs.  */
728   const char *name;
729
730   /* The bfd, when the file is open.  Otherwise this is NULL.
731      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
732   bfd *dbfd;
733
734   /* Section info for this file.  */
735   struct dwo_sections sections;
736
737   /* Table of CUs in the file.
738      Each element is a struct dwo_unit.  */
739   htab_t cus;
740
741   /* Table of TUs in the file.
742      Each element is a struct dwo_unit.  */
743   htab_t tus;
744 };
745
746 /* These sections are what may appear in a DWP file.  */
747
748 struct dwp_sections
749 {
750   struct dwarf2_section_info str;
751   struct dwarf2_section_info cu_index;
752   struct dwarf2_section_info tu_index;
753   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
754      by section number.  We don't need to record them here.  */
755 };
756
757 /* These sections are what may appear in a virtual DWO file.  */
758
759 struct virtual_dwo_sections
760 {
761   struct dwarf2_section_info abbrev;
762   struct dwarf2_section_info line;
763   struct dwarf2_section_info loc;
764   struct dwarf2_section_info macinfo;
765   struct dwarf2_section_info macro;
766   struct dwarf2_section_info str_offsets;
767   /* Each DWP hash table entry records one CU or one TU.
768      That is recorded here, and copied to dwo_unit.info_or_types_section.  */
769   struct dwarf2_section_info info_or_types;
770 };
771
772 /* Contents of DWP hash tables.  */
773
774 struct dwp_hash_table
775 {
776   uint32_t nr_units, nr_slots;
777   const gdb_byte *hash_table, *unit_table, *section_pool;
778 };
779
780 /* Data for one DWP file.  */
781
782 struct dwp_file
783 {
784   /* Name of the file.  */
785   const char *name;
786
787   /* The bfd, when the file is open.  Otherwise this is NULL.  */
788   bfd *dbfd;
789
790   /* Section info for this file.  */
791   struct dwp_sections sections;
792
793   /* Table of CUs in the file. */
794   const struct dwp_hash_table *cus;
795
796   /* Table of TUs in the file.  */
797   const struct dwp_hash_table *tus;
798
799   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
800   htab_t loaded_cutus;
801
802   /* Table to map ELF section numbers to their sections.  */
803   unsigned int num_sections;
804   asection **elf_sections;
805 };
806
807 /* This represents a '.dwz' file.  */
808
809 struct dwz_file
810 {
811   /* A dwz file can only contain a few sections.  */
812   struct dwarf2_section_info abbrev;
813   struct dwarf2_section_info info;
814   struct dwarf2_section_info str;
815   struct dwarf2_section_info line;
816   struct dwarf2_section_info macro;
817   struct dwarf2_section_info gdb_index;
818
819   /* The dwz's BFD.  */
820   bfd *dwz_bfd;
821 };
822
823 /* Struct used to pass misc. parameters to read_die_and_children, et
824    al.  which are used for both .debug_info and .debug_types dies.
825    All parameters here are unchanging for the life of the call.  This
826    struct exists to abstract away the constant parameters of die reading.  */
827
828 struct die_reader_specs
829 {
830   /* die_section->asection->owner.  */
831   bfd* abfd;
832
833   /* The CU of the DIE we are parsing.  */
834   struct dwarf2_cu *cu;
835
836   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
837   struct dwo_file *dwo_file;
838
839   /* The section the die comes from.
840      This is either .debug_info or .debug_types, or the .dwo variants.  */
841   struct dwarf2_section_info *die_section;
842
843   /* die_section->buffer.  */
844   gdb_byte *buffer;
845
846   /* The end of the buffer.  */
847   const gdb_byte *buffer_end;
848 };
849
850 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
851 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
852                                       gdb_byte *info_ptr,
853                                       struct die_info *comp_unit_die,
854                                       int has_children,
855                                       void *data);
856
857 /* The line number information for a compilation unit (found in the
858    .debug_line section) begins with a "statement program header",
859    which contains the following information.  */
860 struct line_header
861 {
862   unsigned int total_length;
863   unsigned short version;
864   unsigned int header_length;
865   unsigned char minimum_instruction_length;
866   unsigned char maximum_ops_per_instruction;
867   unsigned char default_is_stmt;
868   int line_base;
869   unsigned char line_range;
870   unsigned char opcode_base;
871
872   /* standard_opcode_lengths[i] is the number of operands for the
873      standard opcode whose value is i.  This means that
874      standard_opcode_lengths[0] is unused, and the last meaningful
875      element is standard_opcode_lengths[opcode_base - 1].  */
876   unsigned char *standard_opcode_lengths;
877
878   /* The include_directories table.  NOTE!  These strings are not
879      allocated with xmalloc; instead, they are pointers into
880      debug_line_buffer.  If you try to free them, `free' will get
881      indigestion.  */
882   unsigned int num_include_dirs, include_dirs_size;
883   char **include_dirs;
884
885   /* The file_names table.  NOTE!  These strings are not allocated
886      with xmalloc; instead, they are pointers into debug_line_buffer.
887      Don't try to free them directly.  */
888   unsigned int num_file_names, file_names_size;
889   struct file_entry
890   {
891     char *name;
892     unsigned int dir_index;
893     unsigned int mod_time;
894     unsigned int length;
895     int included_p; /* Non-zero if referenced by the Line Number Program.  */
896     struct symtab *symtab; /* The associated symbol table, if any.  */
897   } *file_names;
898
899   /* The start and end of the statement program following this
900      header.  These point into dwarf2_per_objfile->line_buffer.  */
901   gdb_byte *statement_program_start, *statement_program_end;
902 };
903
904 /* When we construct a partial symbol table entry we only
905    need this much information.  */
906 struct partial_die_info
907   {
908     /* Offset of this DIE.  */
909     sect_offset offset;
910
911     /* DWARF-2 tag for this DIE.  */
912     ENUM_BITFIELD(dwarf_tag) tag : 16;
913
914     /* Assorted flags describing the data found in this DIE.  */
915     unsigned int has_children : 1;
916     unsigned int is_external : 1;
917     unsigned int is_declaration : 1;
918     unsigned int has_type : 1;
919     unsigned int has_specification : 1;
920     unsigned int has_pc_info : 1;
921     unsigned int may_be_inlined : 1;
922
923     /* Flag set if the SCOPE field of this structure has been
924        computed.  */
925     unsigned int scope_set : 1;
926
927     /* Flag set if the DIE has a byte_size attribute.  */
928     unsigned int has_byte_size : 1;
929
930     /* Flag set if any of the DIE's children are template arguments.  */
931     unsigned int has_template_arguments : 1;
932
933     /* Flag set if fixup_partial_die has been called on this die.  */
934     unsigned int fixup_called : 1;
935
936     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
937     unsigned int is_dwz : 1;
938
939     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
940     unsigned int spec_is_dwz : 1;
941
942     /* The name of this DIE.  Normally the value of DW_AT_name, but
943        sometimes a default name for unnamed DIEs.  */
944     const char *name;
945
946     /* The linkage name, if present.  */
947     const char *linkage_name;
948
949     /* The scope to prepend to our children.  This is generally
950        allocated on the comp_unit_obstack, so will disappear
951        when this compilation unit leaves the cache.  */
952     const char *scope;
953
954     /* Some data associated with the partial DIE.  The tag determines
955        which field is live.  */
956     union
957     {
958       /* The location description associated with this DIE, if any.  */
959       struct dwarf_block *locdesc;
960       /* The offset of an import, for DW_TAG_imported_unit.  */
961       sect_offset offset;
962     } d;
963
964     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
965     CORE_ADDR lowpc;
966     CORE_ADDR highpc;
967
968     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
969        DW_AT_sibling, if any.  */
970     /* NOTE: This member isn't strictly necessary, read_partial_die could
971        return DW_AT_sibling values to its caller load_partial_dies.  */
972     gdb_byte *sibling;
973
974     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
975        DW_AT_specification (or DW_AT_abstract_origin or
976        DW_AT_extension).  */
977     sect_offset spec_offset;
978
979     /* Pointers to this DIE's parent, first child, and next sibling,
980        if any.  */
981     struct partial_die_info *die_parent, *die_child, *die_sibling;
982   };
983
984 /* This data structure holds the information of an abbrev.  */
985 struct abbrev_info
986   {
987     unsigned int number;        /* number identifying abbrev */
988     enum dwarf_tag tag;         /* dwarf tag */
989     unsigned short has_children;                /* boolean */
990     unsigned short num_attrs;   /* number of attributes */
991     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
992     struct abbrev_info *next;   /* next in chain */
993   };
994
995 struct attr_abbrev
996   {
997     ENUM_BITFIELD(dwarf_attribute) name : 16;
998     ENUM_BITFIELD(dwarf_form) form : 16;
999   };
1000
1001 /* Size of abbrev_table.abbrev_hash_table.  */
1002 #define ABBREV_HASH_SIZE 121
1003
1004 /* Top level data structure to contain an abbreviation table.  */
1005
1006 struct abbrev_table
1007 {
1008   /* Where the abbrev table came from.
1009      This is used as a sanity check when the table is used.  */
1010   sect_offset offset;
1011
1012   /* Storage for the abbrev table.  */
1013   struct obstack abbrev_obstack;
1014
1015   /* Hash table of abbrevs.
1016      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1017      It could be statically allocated, but the previous code didn't so we
1018      don't either.  */
1019   struct abbrev_info **abbrevs;
1020 };
1021
1022 /* Attributes have a name and a value.  */
1023 struct attribute
1024   {
1025     ENUM_BITFIELD(dwarf_attribute) name : 16;
1026     ENUM_BITFIELD(dwarf_form) form : 15;
1027
1028     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1029        field should be in u.str (existing only for DW_STRING) but it is kept
1030        here for better struct attribute alignment.  */
1031     unsigned int string_is_canonical : 1;
1032
1033     union
1034       {
1035         const char *str;
1036         struct dwarf_block *blk;
1037         ULONGEST unsnd;
1038         LONGEST snd;
1039         CORE_ADDR addr;
1040         struct signatured_type *signatured_type;
1041       }
1042     u;
1043   };
1044
1045 /* This data structure holds a complete die structure.  */
1046 struct die_info
1047   {
1048     /* DWARF-2 tag for this DIE.  */
1049     ENUM_BITFIELD(dwarf_tag) tag : 16;
1050
1051     /* Number of attributes */
1052     unsigned char num_attrs;
1053
1054     /* True if we're presently building the full type name for the
1055        type derived from this DIE.  */
1056     unsigned char building_fullname : 1;
1057
1058     /* Abbrev number */
1059     unsigned int abbrev;
1060
1061     /* Offset in .debug_info or .debug_types section.  */
1062     sect_offset offset;
1063
1064     /* The dies in a compilation unit form an n-ary tree.  PARENT
1065        points to this die's parent; CHILD points to the first child of
1066        this node; and all the children of a given node are chained
1067        together via their SIBLING fields.  */
1068     struct die_info *child;     /* Its first child, if any.  */
1069     struct die_info *sibling;   /* Its next sibling, if any.  */
1070     struct die_info *parent;    /* Its parent, if any.  */
1071
1072     /* An array of attributes, with NUM_ATTRS elements.  There may be
1073        zero, but it's not common and zero-sized arrays are not
1074        sufficiently portable C.  */
1075     struct attribute attrs[1];
1076   };
1077
1078 /* Get at parts of an attribute structure.  */
1079
1080 #define DW_STRING(attr)    ((attr)->u.str)
1081 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1082 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1083 #define DW_BLOCK(attr)     ((attr)->u.blk)
1084 #define DW_SND(attr)       ((attr)->u.snd)
1085 #define DW_ADDR(attr)      ((attr)->u.addr)
1086 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
1087
1088 /* Blocks are a bunch of untyped bytes.  */
1089 struct dwarf_block
1090   {
1091     size_t size;
1092
1093     /* Valid only if SIZE is not zero.  */
1094     gdb_byte *data;
1095   };
1096
1097 #ifndef ATTR_ALLOC_CHUNK
1098 #define ATTR_ALLOC_CHUNK 4
1099 #endif
1100
1101 /* Allocate fields for structs, unions and enums in this size.  */
1102 #ifndef DW_FIELD_ALLOC_CHUNK
1103 #define DW_FIELD_ALLOC_CHUNK 4
1104 #endif
1105
1106 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1107    but this would require a corresponding change in unpack_field_as_long
1108    and friends.  */
1109 static int bits_per_byte = 8;
1110
1111 /* The routines that read and process dies for a C struct or C++ class
1112    pass lists of data member fields and lists of member function fields
1113    in an instance of a field_info structure, as defined below.  */
1114 struct field_info
1115   {
1116     /* List of data member and baseclasses fields.  */
1117     struct nextfield
1118       {
1119         struct nextfield *next;
1120         int accessibility;
1121         int virtuality;
1122         struct field field;
1123       }
1124      *fields, *baseclasses;
1125
1126     /* Number of fields (including baseclasses).  */
1127     int nfields;
1128
1129     /* Number of baseclasses.  */
1130     int nbaseclasses;
1131
1132     /* Set if the accesibility of one of the fields is not public.  */
1133     int non_public_fields;
1134
1135     /* Member function fields array, entries are allocated in the order they
1136        are encountered in the object file.  */
1137     struct nextfnfield
1138       {
1139         struct nextfnfield *next;
1140         struct fn_field fnfield;
1141       }
1142      *fnfields;
1143
1144     /* Member function fieldlist array, contains name of possibly overloaded
1145        member function, number of overloaded member functions and a pointer
1146        to the head of the member function field chain.  */
1147     struct fnfieldlist
1148       {
1149         const char *name;
1150         int length;
1151         struct nextfnfield *head;
1152       }
1153      *fnfieldlists;
1154
1155     /* Number of entries in the fnfieldlists array.  */
1156     int nfnfields;
1157
1158     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1159        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1160     struct typedef_field_list
1161       {
1162         struct typedef_field field;
1163         struct typedef_field_list *next;
1164       }
1165     *typedef_field_list;
1166     unsigned typedef_field_list_count;
1167   };
1168
1169 /* One item on the queue of compilation units to read in full symbols
1170    for.  */
1171 struct dwarf2_queue_item
1172 {
1173   struct dwarf2_per_cu_data *per_cu;
1174   enum language pretend_language;
1175   struct dwarf2_queue_item *next;
1176 };
1177
1178 /* The current queue.  */
1179 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1180
1181 /* Loaded secondary compilation units are kept in memory until they
1182    have not been referenced for the processing of this many
1183    compilation units.  Set this to zero to disable caching.  Cache
1184    sizes of up to at least twenty will improve startup time for
1185    typical inter-CU-reference binaries, at an obvious memory cost.  */
1186 static int dwarf2_max_cache_age = 5;
1187 static void
1188 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1189                            struct cmd_list_element *c, const char *value)
1190 {
1191   fprintf_filtered (file, _("The upper bound on the age of cached "
1192                             "dwarf2 compilation units is %s.\n"),
1193                     value);
1194 }
1195
1196
1197 /* Various complaints about symbol reading that don't abort the process.  */
1198
1199 static void
1200 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1201 {
1202   complaint (&symfile_complaints,
1203              _("statement list doesn't fit in .debug_line section"));
1204 }
1205
1206 static void
1207 dwarf2_debug_line_missing_file_complaint (void)
1208 {
1209   complaint (&symfile_complaints,
1210              _(".debug_line section has line data without a file"));
1211 }
1212
1213 static void
1214 dwarf2_debug_line_missing_end_sequence_complaint (void)
1215 {
1216   complaint (&symfile_complaints,
1217              _(".debug_line section has line "
1218                "program sequence without an end"));
1219 }
1220
1221 static void
1222 dwarf2_complex_location_expr_complaint (void)
1223 {
1224   complaint (&symfile_complaints, _("location expression too complex"));
1225 }
1226
1227 static void
1228 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1229                                               int arg3)
1230 {
1231   complaint (&symfile_complaints,
1232              _("const value length mismatch for '%s', got %d, expected %d"),
1233              arg1, arg2, arg3);
1234 }
1235
1236 static void
1237 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1238 {
1239   complaint (&symfile_complaints,
1240              _("debug info runs off end of %s section"
1241                " [in module %s]"),
1242              section->asection->name,
1243              bfd_get_filename (section->asection->owner));
1244 }
1245
1246 static void
1247 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1248 {
1249   complaint (&symfile_complaints,
1250              _("macro debug info contains a "
1251                "malformed macro definition:\n`%s'"),
1252              arg1);
1253 }
1254
1255 static void
1256 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1257 {
1258   complaint (&symfile_complaints,
1259              _("invalid attribute class or form for '%s' in '%s'"),
1260              arg1, arg2);
1261 }
1262
1263 /* local function prototypes */
1264
1265 static void dwarf2_locate_sections (bfd *, asection *, void *);
1266
1267 static void dwarf2_create_include_psymtab (char *, struct partial_symtab *,
1268                                            struct objfile *);
1269
1270 static void dwarf2_find_base_address (struct die_info *die,
1271                                       struct dwarf2_cu *cu);
1272
1273 static void dwarf2_build_psymtabs_hard (struct objfile *);
1274
1275 static void scan_partial_symbols (struct partial_die_info *,
1276                                   CORE_ADDR *, CORE_ADDR *,
1277                                   int, struct dwarf2_cu *);
1278
1279 static void add_partial_symbol (struct partial_die_info *,
1280                                 struct dwarf2_cu *);
1281
1282 static void add_partial_namespace (struct partial_die_info *pdi,
1283                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1284                                    int need_pc, struct dwarf2_cu *cu);
1285
1286 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1287                                 CORE_ADDR *highpc, int need_pc,
1288                                 struct dwarf2_cu *cu);
1289
1290 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1291                                      struct dwarf2_cu *cu);
1292
1293 static void add_partial_subprogram (struct partial_die_info *pdi,
1294                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1295                                     int need_pc, struct dwarf2_cu *cu);
1296
1297 static void dwarf2_read_symtab (struct partial_symtab *,
1298                                 struct objfile *);
1299
1300 static void psymtab_to_symtab_1 (struct partial_symtab *);
1301
1302 static struct abbrev_info *abbrev_table_lookup_abbrev
1303   (const struct abbrev_table *, unsigned int);
1304
1305 static struct abbrev_table *abbrev_table_read_table
1306   (struct dwarf2_section_info *, sect_offset);
1307
1308 static void abbrev_table_free (struct abbrev_table *);
1309
1310 static void abbrev_table_free_cleanup (void *);
1311
1312 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1313                                  struct dwarf2_section_info *);
1314
1315 static void dwarf2_free_abbrev_table (void *);
1316
1317 static unsigned int peek_abbrev_code (bfd *, gdb_byte *);
1318
1319 static struct partial_die_info *load_partial_dies
1320   (const struct die_reader_specs *, gdb_byte *, int);
1321
1322 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1323                                    struct partial_die_info *,
1324                                    struct abbrev_info *,
1325                                    unsigned int,
1326                                    gdb_byte *);
1327
1328 static struct partial_die_info *find_partial_die (sect_offset, int,
1329                                                   struct dwarf2_cu *);
1330
1331 static void fixup_partial_die (struct partial_die_info *,
1332                                struct dwarf2_cu *);
1333
1334 static gdb_byte *read_attribute (const struct die_reader_specs *,
1335                                  struct attribute *, struct attr_abbrev *,
1336                                  gdb_byte *);
1337
1338 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1339
1340 static int read_1_signed_byte (bfd *, const gdb_byte *);
1341
1342 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1343
1344 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1345
1346 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1347
1348 static CORE_ADDR read_address (bfd *, gdb_byte *ptr, struct dwarf2_cu *,
1349                                unsigned int *);
1350
1351 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1352
1353 static LONGEST read_checked_initial_length_and_offset
1354   (bfd *, gdb_byte *, const struct comp_unit_head *,
1355    unsigned int *, unsigned int *);
1356
1357 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1358                             unsigned int *);
1359
1360 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1361
1362 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1363                                        sect_offset);
1364
1365 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1366
1367 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1368
1369 static char *read_indirect_string (bfd *, gdb_byte *,
1370                                    const struct comp_unit_head *,
1371                                    unsigned int *);
1372
1373 static char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1374
1375 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1376
1377 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1378
1379 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1380                                               unsigned int *);
1381
1382 static char *read_str_index (const struct die_reader_specs *reader,
1383                              struct dwarf2_cu *cu, ULONGEST str_index);
1384
1385 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1386
1387 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1388                                       struct dwarf2_cu *);
1389
1390 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1391                                                 unsigned int);
1392
1393 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1394                                struct dwarf2_cu *cu);
1395
1396 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1397
1398 static struct die_info *die_specification (struct die_info *die,
1399                                            struct dwarf2_cu **);
1400
1401 static void free_line_header (struct line_header *lh);
1402
1403 static void add_file_name (struct line_header *, char *, unsigned int,
1404                            unsigned int, unsigned int);
1405
1406 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1407                                                      struct dwarf2_cu *cu);
1408
1409 static void dwarf_decode_lines (struct line_header *, const char *,
1410                                 struct dwarf2_cu *, struct partial_symtab *,
1411                                 int);
1412
1413 static void dwarf2_start_subfile (char *, const char *, const char *);
1414
1415 static void dwarf2_start_symtab (struct dwarf2_cu *,
1416                                  const char *, const char *, CORE_ADDR);
1417
1418 static struct symbol *new_symbol (struct die_info *, struct type *,
1419                                   struct dwarf2_cu *);
1420
1421 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1422                                        struct dwarf2_cu *, struct symbol *);
1423
1424 static void dwarf2_const_value (struct attribute *, struct symbol *,
1425                                 struct dwarf2_cu *);
1426
1427 static void dwarf2_const_value_attr (struct attribute *attr,
1428                                      struct type *type,
1429                                      const char *name,
1430                                      struct obstack *obstack,
1431                                      struct dwarf2_cu *cu, LONGEST *value,
1432                                      gdb_byte **bytes,
1433                                      struct dwarf2_locexpr_baton **baton);
1434
1435 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1436
1437 static int need_gnat_info (struct dwarf2_cu *);
1438
1439 static struct type *die_descriptive_type (struct die_info *,
1440                                           struct dwarf2_cu *);
1441
1442 static void set_descriptive_type (struct type *, struct die_info *,
1443                                   struct dwarf2_cu *);
1444
1445 static struct type *die_containing_type (struct die_info *,
1446                                          struct dwarf2_cu *);
1447
1448 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1449                                      struct dwarf2_cu *);
1450
1451 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1452
1453 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1454
1455 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1456
1457 static char *typename_concat (struct obstack *obs, const char *prefix,
1458                               const char *suffix, int physname,
1459                               struct dwarf2_cu *cu);
1460
1461 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1462
1463 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1464
1465 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1466
1467 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1468
1469 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1470
1471 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1472                                struct dwarf2_cu *, struct partial_symtab *);
1473
1474 static int dwarf2_get_pc_bounds (struct die_info *,
1475                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1476                                  struct partial_symtab *);
1477
1478 static void get_scope_pc_bounds (struct die_info *,
1479                                  CORE_ADDR *, CORE_ADDR *,
1480                                  struct dwarf2_cu *);
1481
1482 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1483                                         CORE_ADDR, struct dwarf2_cu *);
1484
1485 static void dwarf2_add_field (struct field_info *, struct die_info *,
1486                               struct dwarf2_cu *);
1487
1488 static void dwarf2_attach_fields_to_type (struct field_info *,
1489                                           struct type *, struct dwarf2_cu *);
1490
1491 static void dwarf2_add_member_fn (struct field_info *,
1492                                   struct die_info *, struct type *,
1493                                   struct dwarf2_cu *);
1494
1495 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1496                                              struct type *,
1497                                              struct dwarf2_cu *);
1498
1499 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1500
1501 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1502
1503 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1504
1505 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1506
1507 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1508
1509 static struct type *read_module_type (struct die_info *die,
1510                                       struct dwarf2_cu *cu);
1511
1512 static const char *namespace_name (struct die_info *die,
1513                                    int *is_anonymous, struct dwarf2_cu *);
1514
1515 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1516
1517 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1518
1519 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1520                                                        struct dwarf2_cu *);
1521
1522 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1523                                                gdb_byte *info_ptr,
1524                                                gdb_byte **new_info_ptr,
1525                                                struct die_info *parent);
1526
1527 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1528                                                gdb_byte *info_ptr,
1529                                                gdb_byte **new_info_ptr,
1530                                                struct die_info *parent);
1531
1532 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1533                                   struct die_info **, gdb_byte *, int *, int);
1534
1535 static gdb_byte *read_full_die (const struct die_reader_specs *,
1536                                 struct die_info **, gdb_byte *, int *);
1537
1538 static void process_die (struct die_info *, struct dwarf2_cu *);
1539
1540 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1541                                              struct obstack *);
1542
1543 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1544
1545 static const char *dwarf2_full_name (const char *name,
1546                                      struct die_info *die,
1547                                      struct dwarf2_cu *cu);
1548
1549 static struct die_info *dwarf2_extension (struct die_info *die,
1550                                           struct dwarf2_cu **);
1551
1552 static const char *dwarf_tag_name (unsigned int);
1553
1554 static const char *dwarf_attr_name (unsigned int);
1555
1556 static const char *dwarf_form_name (unsigned int);
1557
1558 static char *dwarf_bool_name (unsigned int);
1559
1560 static const char *dwarf_type_encoding_name (unsigned int);
1561
1562 static struct die_info *sibling_die (struct die_info *);
1563
1564 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1565
1566 static void dump_die_for_error (struct die_info *);
1567
1568 static void dump_die_1 (struct ui_file *, int level, int max_level,
1569                         struct die_info *);
1570
1571 /*static*/ void dump_die (struct die_info *, int max_level);
1572
1573 static void store_in_ref_table (struct die_info *,
1574                                 struct dwarf2_cu *);
1575
1576 static int is_ref_attr (struct attribute *);
1577
1578 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1579
1580 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1581
1582 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1583                                                struct attribute *,
1584                                                struct dwarf2_cu **);
1585
1586 static struct die_info *follow_die_ref (struct die_info *,
1587                                         struct attribute *,
1588                                         struct dwarf2_cu **);
1589
1590 static struct die_info *follow_die_sig (struct die_info *,
1591                                         struct attribute *,
1592                                         struct dwarf2_cu **);
1593
1594 static struct signatured_type *lookup_signatured_type_at_offset
1595     (struct objfile *objfile,
1596      struct dwarf2_section_info *section, sect_offset offset);
1597
1598 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1599
1600 static void read_signatured_type (struct signatured_type *);
1601
1602 static struct type_unit_group *get_type_unit_group
1603     (struct dwarf2_cu *, struct attribute *);
1604
1605 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1606
1607 /* memory allocation interface */
1608
1609 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1610
1611 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1612
1613 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1614                                  const char *, int);
1615
1616 static int attr_form_is_block (struct attribute *);
1617
1618 static int attr_form_is_section_offset (struct attribute *);
1619
1620 static int attr_form_is_constant (struct attribute *);
1621
1622 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1623                                    struct dwarf2_loclist_baton *baton,
1624                                    struct attribute *attr);
1625
1626 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1627                                          struct symbol *sym,
1628                                          struct dwarf2_cu *cu);
1629
1630 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1631                                gdb_byte *info_ptr,
1632                                struct abbrev_info *abbrev);
1633
1634 static void free_stack_comp_unit (void *);
1635
1636 static hashval_t partial_die_hash (const void *item);
1637
1638 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1639
1640 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1641   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1642
1643 static void init_one_comp_unit (struct dwarf2_cu *cu,
1644                                 struct dwarf2_per_cu_data *per_cu);
1645
1646 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1647                                    struct die_info *comp_unit_die,
1648                                    enum language pretend_language);
1649
1650 static void free_heap_comp_unit (void *);
1651
1652 static void free_cached_comp_units (void *);
1653
1654 static void age_cached_comp_units (void);
1655
1656 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1657
1658 static struct type *set_die_type (struct die_info *, struct type *,
1659                                   struct dwarf2_cu *);
1660
1661 static void create_all_comp_units (struct objfile *);
1662
1663 static int create_all_type_units (struct objfile *);
1664
1665 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1666                                  enum language);
1667
1668 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1669                                     enum language);
1670
1671 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1672                                     enum language);
1673
1674 static void dwarf2_add_dependence (struct dwarf2_cu *,
1675                                    struct dwarf2_per_cu_data *);
1676
1677 static void dwarf2_mark (struct dwarf2_cu *);
1678
1679 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1680
1681 static struct type *get_die_type_at_offset (sect_offset,
1682                                             struct dwarf2_per_cu_data *per_cu);
1683
1684 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1685
1686 static void dwarf2_release_queue (void *dummy);
1687
1688 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1689                              enum language pretend_language);
1690
1691 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1692                                   struct dwarf2_per_cu_data *per_cu,
1693                                   enum language pretend_language);
1694
1695 static void process_queue (void);
1696
1697 static void find_file_and_directory (struct die_info *die,
1698                                      struct dwarf2_cu *cu,
1699                                      const char **name, const char **comp_dir);
1700
1701 static char *file_full_name (int file, struct line_header *lh,
1702                              const char *comp_dir);
1703
1704 static gdb_byte *read_and_check_comp_unit_head
1705   (struct comp_unit_head *header,
1706    struct dwarf2_section_info *section,
1707    struct dwarf2_section_info *abbrev_section, gdb_byte *info_ptr,
1708    int is_debug_types_section);
1709
1710 static void init_cutu_and_read_dies
1711   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1712    int use_existing_cu, int keep,
1713    die_reader_func_ftype *die_reader_func, void *data);
1714
1715 static void init_cutu_and_read_dies_simple
1716   (struct dwarf2_per_cu_data *this_cu,
1717    die_reader_func_ftype *die_reader_func, void *data);
1718
1719 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1720
1721 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1722
1723 static struct dwo_unit *lookup_dwo_comp_unit
1724   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1725
1726 static struct dwo_unit *lookup_dwo_type_unit
1727   (struct signatured_type *, const char *, const char *);
1728
1729 static void free_dwo_file_cleanup (void *);
1730
1731 static void process_cu_includes (void);
1732
1733 static void check_producer (struct dwarf2_cu *cu);
1734
1735 #if WORDS_BIGENDIAN
1736
1737 /* Convert VALUE between big- and little-endian.  */
1738 static offset_type
1739 byte_swap (offset_type value)
1740 {
1741   offset_type result;
1742
1743   result = (value & 0xff) << 24;
1744   result |= (value & 0xff00) << 8;
1745   result |= (value & 0xff0000) >> 8;
1746   result |= (value & 0xff000000) >> 24;
1747   return result;
1748 }
1749
1750 #define MAYBE_SWAP(V)  byte_swap (V)
1751
1752 #else
1753 #define MAYBE_SWAP(V) (V)
1754 #endif /* WORDS_BIGENDIAN */
1755
1756 /* The suffix for an index file.  */
1757 #define INDEX_SUFFIX ".gdb-index"
1758
1759 static const char *dwarf2_physname (const char *name, struct die_info *die,
1760                                     struct dwarf2_cu *cu);
1761
1762 /* Try to locate the sections we need for DWARF 2 debugging
1763    information and return true if we have enough to do something.
1764    NAMES points to the dwarf2 section names, or is NULL if the standard
1765    ELF names are used.  */
1766
1767 int
1768 dwarf2_has_info (struct objfile *objfile,
1769                  const struct dwarf2_debug_sections *names)
1770 {
1771   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1772   if (!dwarf2_per_objfile)
1773     {
1774       /* Initialize per-objfile state.  */
1775       struct dwarf2_per_objfile *data
1776         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1777
1778       memset (data, 0, sizeof (*data));
1779       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1780       dwarf2_per_objfile = data;
1781
1782       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1783                              (void *) names);
1784       dwarf2_per_objfile->objfile = objfile;
1785     }
1786   return (dwarf2_per_objfile->info.asection != NULL
1787           && dwarf2_per_objfile->abbrev.asection != NULL);
1788 }
1789
1790 /* When loading sections, we look either for uncompressed section or for
1791    compressed section names.  */
1792
1793 static int
1794 section_is_p (const char *section_name,
1795               const struct dwarf2_section_names *names)
1796 {
1797   if (names->normal != NULL
1798       && strcmp (section_name, names->normal) == 0)
1799     return 1;
1800   if (names->compressed != NULL
1801       && strcmp (section_name, names->compressed) == 0)
1802     return 1;
1803   return 0;
1804 }
1805
1806 /* This function is mapped across the sections and remembers the
1807    offset and size of each of the debugging sections we are interested
1808    in.  */
1809
1810 static void
1811 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1812 {
1813   const struct dwarf2_debug_sections *names;
1814   flagword aflag = bfd_get_section_flags (abfd, sectp);
1815
1816   if (vnames == NULL)
1817     names = &dwarf2_elf_names;
1818   else
1819     names = (const struct dwarf2_debug_sections *) vnames;
1820
1821   if ((aflag & SEC_HAS_CONTENTS) == 0)
1822     {
1823     }
1824   else if (section_is_p (sectp->name, &names->info))
1825     {
1826       dwarf2_per_objfile->info.asection = sectp;
1827       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1828     }
1829   else if (section_is_p (sectp->name, &names->abbrev))
1830     {
1831       dwarf2_per_objfile->abbrev.asection = sectp;
1832       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1833     }
1834   else if (section_is_p (sectp->name, &names->line))
1835     {
1836       dwarf2_per_objfile->line.asection = sectp;
1837       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1838     }
1839   else if (section_is_p (sectp->name, &names->loc))
1840     {
1841       dwarf2_per_objfile->loc.asection = sectp;
1842       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1843     }
1844   else if (section_is_p (sectp->name, &names->macinfo))
1845     {
1846       dwarf2_per_objfile->macinfo.asection = sectp;
1847       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1848     }
1849   else if (section_is_p (sectp->name, &names->macro))
1850     {
1851       dwarf2_per_objfile->macro.asection = sectp;
1852       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1853     }
1854   else if (section_is_p (sectp->name, &names->str))
1855     {
1856       dwarf2_per_objfile->str.asection = sectp;
1857       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1858     }
1859   else if (section_is_p (sectp->name, &names->addr))
1860     {
1861       dwarf2_per_objfile->addr.asection = sectp;
1862       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1863     }
1864   else if (section_is_p (sectp->name, &names->frame))
1865     {
1866       dwarf2_per_objfile->frame.asection = sectp;
1867       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1868     }
1869   else if (section_is_p (sectp->name, &names->eh_frame))
1870     {
1871       dwarf2_per_objfile->eh_frame.asection = sectp;
1872       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1873     }
1874   else if (section_is_p (sectp->name, &names->ranges))
1875     {
1876       dwarf2_per_objfile->ranges.asection = sectp;
1877       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1878     }
1879   else if (section_is_p (sectp->name, &names->types))
1880     {
1881       struct dwarf2_section_info type_section;
1882
1883       memset (&type_section, 0, sizeof (type_section));
1884       type_section.asection = sectp;
1885       type_section.size = bfd_get_section_size (sectp);
1886
1887       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1888                      &type_section);
1889     }
1890   else if (section_is_p (sectp->name, &names->gdb_index))
1891     {
1892       dwarf2_per_objfile->gdb_index.asection = sectp;
1893       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1894     }
1895
1896   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1897       && bfd_section_vma (abfd, sectp) == 0)
1898     dwarf2_per_objfile->has_section_at_zero = 1;
1899 }
1900
1901 /* A helper function that decides whether a section is empty,
1902    or not present.  */
1903
1904 static int
1905 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1906 {
1907   return info->asection == NULL || info->size == 0;
1908 }
1909
1910 /* Read the contents of the section INFO.
1911    OBJFILE is the main object file, but not necessarily the file where
1912    the section comes from.  E.g., for DWO files INFO->asection->owner
1913    is the bfd of the DWO file.
1914    If the section is compressed, uncompress it before returning.  */
1915
1916 static void
1917 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1918 {
1919   asection *sectp = info->asection;
1920   bfd *abfd;
1921   gdb_byte *buf, *retbuf;
1922   unsigned char header[4];
1923
1924   if (info->readin)
1925     return;
1926   info->buffer = NULL;
1927   info->readin = 1;
1928
1929   if (dwarf2_section_empty_p (info))
1930     return;
1931
1932   abfd = sectp->owner;
1933
1934   /* If the section has relocations, we must read it ourselves.
1935      Otherwise we attach it to the BFD.  */
1936   if ((sectp->flags & SEC_RELOC) == 0)
1937     {
1938       const gdb_byte *bytes = gdb_bfd_map_section (sectp, &info->size);
1939
1940       /* We have to cast away const here for historical reasons.
1941          Fixing dwarf2read to be const-correct would be quite nice.  */
1942       info->buffer = (gdb_byte *) bytes;
1943       return;
1944     }
1945
1946   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1947   info->buffer = buf;
1948
1949   /* When debugging .o files, we may need to apply relocations; see
1950      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1951      We never compress sections in .o files, so we only need to
1952      try this when the section is not compressed.  */
1953   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1954   if (retbuf != NULL)
1955     {
1956       info->buffer = retbuf;
1957       return;
1958     }
1959
1960   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1961       || bfd_bread (buf, info->size, abfd) != info->size)
1962     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1963            bfd_get_filename (abfd));
1964 }
1965
1966 /* A helper function that returns the size of a section in a safe way.
1967    If you are positive that the section has been read before using the
1968    size, then it is safe to refer to the dwarf2_section_info object's
1969    "size" field directly.  In other cases, you must call this
1970    function, because for compressed sections the size field is not set
1971    correctly until the section has been read.  */
1972
1973 static bfd_size_type
1974 dwarf2_section_size (struct objfile *objfile,
1975                      struct dwarf2_section_info *info)
1976 {
1977   if (!info->readin)
1978     dwarf2_read_section (objfile, info);
1979   return info->size;
1980 }
1981
1982 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1983    SECTION_NAME.  */
1984
1985 void
1986 dwarf2_get_section_info (struct objfile *objfile,
1987                          enum dwarf2_section_enum sect,
1988                          asection **sectp, gdb_byte **bufp,
1989                          bfd_size_type *sizep)
1990 {
1991   struct dwarf2_per_objfile *data
1992     = objfile_data (objfile, dwarf2_objfile_data_key);
1993   struct dwarf2_section_info *info;
1994
1995   /* We may see an objfile without any DWARF, in which case we just
1996      return nothing.  */
1997   if (data == NULL)
1998     {
1999       *sectp = NULL;
2000       *bufp = NULL;
2001       *sizep = 0;
2002       return;
2003     }
2004   switch (sect)
2005     {
2006     case DWARF2_DEBUG_FRAME:
2007       info = &data->frame;
2008       break;
2009     case DWARF2_EH_FRAME:
2010       info = &data->eh_frame;
2011       break;
2012     default:
2013       gdb_assert_not_reached ("unexpected section");
2014     }
2015
2016   dwarf2_read_section (objfile, info);
2017
2018   *sectp = info->asection;
2019   *bufp = info->buffer;
2020   *sizep = info->size;
2021 }
2022
2023 /* A helper function to find the sections for a .dwz file.  */
2024
2025 static void
2026 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2027 {
2028   struct dwz_file *dwz_file = arg;
2029
2030   /* Note that we only support the standard ELF names, because .dwz
2031      is ELF-only (at the time of writing).  */
2032   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2033     {
2034       dwz_file->abbrev.asection = sectp;
2035       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2036     }
2037   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2038     {
2039       dwz_file->info.asection = sectp;
2040       dwz_file->info.size = bfd_get_section_size (sectp);
2041     }
2042   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2043     {
2044       dwz_file->str.asection = sectp;
2045       dwz_file->str.size = bfd_get_section_size (sectp);
2046     }
2047   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2048     {
2049       dwz_file->line.asection = sectp;
2050       dwz_file->line.size = bfd_get_section_size (sectp);
2051     }
2052   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2053     {
2054       dwz_file->macro.asection = sectp;
2055       dwz_file->macro.size = bfd_get_section_size (sectp);
2056     }
2057   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2058     {
2059       dwz_file->gdb_index.asection = sectp;
2060       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2061     }
2062 }
2063
2064 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2065    cannot be found.  */
2066
2067 static struct dwz_file *
2068 dwarf2_get_dwz_file (void)
2069 {
2070   bfd *abfd, *dwz_bfd;
2071   asection *section;
2072   gdb_byte *data;
2073   struct cleanup *cleanup;
2074   const char *filename;
2075   struct dwz_file *result;
2076
2077   if (dwarf2_per_objfile->dwz_file != NULL)
2078     return dwarf2_per_objfile->dwz_file;
2079
2080   abfd = dwarf2_per_objfile->objfile->obfd;
2081   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2082   if (section == NULL)
2083     error (_("could not find '.gnu_debugaltlink' section"));
2084   if (!bfd_malloc_and_get_section (abfd, section, &data))
2085     error (_("could not read '.gnu_debugaltlink' section: %s"),
2086            bfd_errmsg (bfd_get_error ()));
2087   cleanup = make_cleanup (xfree, data);
2088
2089   filename = data;
2090   if (!IS_ABSOLUTE_PATH (filename))
2091     {
2092       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2093       char *rel;
2094
2095       make_cleanup (xfree, abs);
2096       abs = ldirname (abs);
2097       make_cleanup (xfree, abs);
2098
2099       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2100       make_cleanup (xfree, rel);
2101       filename = rel;
2102     }
2103
2104   /* The format is just a NUL-terminated file name, followed by the
2105      build-id.  For now, though, we ignore the build-id.  */
2106   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2107   if (dwz_bfd == NULL)
2108     error (_("could not read '%s': %s"), filename,
2109            bfd_errmsg (bfd_get_error ()));
2110
2111   if (!bfd_check_format (dwz_bfd, bfd_object))
2112     {
2113       gdb_bfd_unref (dwz_bfd);
2114       error (_("file '%s' was not usable: %s"), filename,
2115              bfd_errmsg (bfd_get_error ()));
2116     }
2117
2118   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2119                            struct dwz_file);
2120   result->dwz_bfd = dwz_bfd;
2121
2122   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2123
2124   do_cleanups (cleanup);
2125
2126   dwarf2_per_objfile->dwz_file = result;
2127   return result;
2128 }
2129 \f
2130 /* DWARF quick_symbols_functions support.  */
2131
2132 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2133    unique line tables, so we maintain a separate table of all .debug_line
2134    derived entries to support the sharing.
2135    All the quick functions need is the list of file names.  We discard the
2136    line_header when we're done and don't need to record it here.  */
2137 struct quick_file_names
2138 {
2139   /* The data used to construct the hash key.  */
2140   struct stmt_list_hash hash;
2141
2142   /* The number of entries in file_names, real_names.  */
2143   unsigned int num_file_names;
2144
2145   /* The file names from the line table, after being run through
2146      file_full_name.  */
2147   const char **file_names;
2148
2149   /* The file names from the line table after being run through
2150      gdb_realpath.  These are computed lazily.  */
2151   const char **real_names;
2152 };
2153
2154 /* When using the index (and thus not using psymtabs), each CU has an
2155    object of this type.  This is used to hold information needed by
2156    the various "quick" methods.  */
2157 struct dwarf2_per_cu_quick_data
2158 {
2159   /* The file table.  This can be NULL if there was no file table
2160      or it's currently not read in.
2161      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2162   struct quick_file_names *file_names;
2163
2164   /* The corresponding symbol table.  This is NULL if symbols for this
2165      CU have not yet been read.  */
2166   struct symtab *symtab;
2167
2168   /* A temporary mark bit used when iterating over all CUs in
2169      expand_symtabs_matching.  */
2170   unsigned int mark : 1;
2171
2172   /* True if we've tried to read the file table and found there isn't one.
2173      There will be no point in trying to read it again next time.  */
2174   unsigned int no_file_data : 1;
2175 };
2176
2177 /* Utility hash function for a stmt_list_hash.  */
2178
2179 static hashval_t
2180 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2181 {
2182   hashval_t v = 0;
2183
2184   if (stmt_list_hash->dwo_unit != NULL)
2185     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2186   v += stmt_list_hash->line_offset.sect_off;
2187   return v;
2188 }
2189
2190 /* Utility equality function for a stmt_list_hash.  */
2191
2192 static int
2193 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2194                     const struct stmt_list_hash *rhs)
2195 {
2196   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2197     return 0;
2198   if (lhs->dwo_unit != NULL
2199       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2200     return 0;
2201
2202   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2203 }
2204
2205 /* Hash function for a quick_file_names.  */
2206
2207 static hashval_t
2208 hash_file_name_entry (const void *e)
2209 {
2210   const struct quick_file_names *file_data = e;
2211
2212   return hash_stmt_list_entry (&file_data->hash);
2213 }
2214
2215 /* Equality function for a quick_file_names.  */
2216
2217 static int
2218 eq_file_name_entry (const void *a, const void *b)
2219 {
2220   const struct quick_file_names *ea = a;
2221   const struct quick_file_names *eb = b;
2222
2223   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2224 }
2225
2226 /* Delete function for a quick_file_names.  */
2227
2228 static void
2229 delete_file_name_entry (void *e)
2230 {
2231   struct quick_file_names *file_data = e;
2232   int i;
2233
2234   for (i = 0; i < file_data->num_file_names; ++i)
2235     {
2236       xfree ((void*) file_data->file_names[i]);
2237       if (file_data->real_names)
2238         xfree ((void*) file_data->real_names[i]);
2239     }
2240
2241   /* The space for the struct itself lives on objfile_obstack,
2242      so we don't free it here.  */
2243 }
2244
2245 /* Create a quick_file_names hash table.  */
2246
2247 static htab_t
2248 create_quick_file_names_table (unsigned int nr_initial_entries)
2249 {
2250   return htab_create_alloc (nr_initial_entries,
2251                             hash_file_name_entry, eq_file_name_entry,
2252                             delete_file_name_entry, xcalloc, xfree);
2253 }
2254
2255 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2256    have to be created afterwards.  You should call age_cached_comp_units after
2257    processing PER_CU->CU.  dw2_setup must have been already called.  */
2258
2259 static void
2260 load_cu (struct dwarf2_per_cu_data *per_cu)
2261 {
2262   if (per_cu->is_debug_types)
2263     load_full_type_unit (per_cu);
2264   else
2265     load_full_comp_unit (per_cu, language_minimal);
2266
2267   gdb_assert (per_cu->cu != NULL);
2268
2269   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2270 }
2271
2272 /* Read in the symbols for PER_CU.  */
2273
2274 static void
2275 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2276 {
2277   struct cleanup *back_to;
2278
2279   /* Skip type_unit_groups, reading the type units they contain
2280      is handled elsewhere.  */
2281   if (IS_TYPE_UNIT_GROUP (per_cu))
2282     return;
2283
2284   back_to = make_cleanup (dwarf2_release_queue, NULL);
2285
2286   if (dwarf2_per_objfile->using_index
2287       ? per_cu->v.quick->symtab == NULL
2288       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2289     {
2290       queue_comp_unit (per_cu, language_minimal);
2291       load_cu (per_cu);
2292     }
2293
2294   process_queue ();
2295
2296   /* Age the cache, releasing compilation units that have not
2297      been used recently.  */
2298   age_cached_comp_units ();
2299
2300   do_cleanups (back_to);
2301 }
2302
2303 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2304    the objfile from which this CU came.  Returns the resulting symbol
2305    table.  */
2306
2307 static struct symtab *
2308 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2309 {
2310   gdb_assert (dwarf2_per_objfile->using_index);
2311   if (!per_cu->v.quick->symtab)
2312     {
2313       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2314       increment_reading_symtab ();
2315       dw2_do_instantiate_symtab (per_cu);
2316       process_cu_includes ();
2317       do_cleanups (back_to);
2318     }
2319   return per_cu->v.quick->symtab;
2320 }
2321
2322 /* Return the CU given its index.
2323
2324    This is intended for loops like:
2325
2326    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2327                     + dwarf2_per_objfile->n_type_units); ++i)
2328      {
2329        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2330
2331        ...;
2332      }
2333 */
2334
2335 static struct dwarf2_per_cu_data *
2336 dw2_get_cu (int index)
2337 {
2338   if (index >= dwarf2_per_objfile->n_comp_units)
2339     {
2340       index -= dwarf2_per_objfile->n_comp_units;
2341       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2342       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2343     }
2344
2345   return dwarf2_per_objfile->all_comp_units[index];
2346 }
2347
2348 /* Return the primary CU given its index.
2349    The difference between this function and dw2_get_cu is in the handling
2350    of type units (TUs).  Here we return the type_unit_group object.
2351
2352    This is intended for loops like:
2353
2354    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2355                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2356      {
2357        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2358
2359        ...;
2360      }
2361 */
2362
2363 static struct dwarf2_per_cu_data *
2364 dw2_get_primary_cu (int index)
2365 {
2366   if (index >= dwarf2_per_objfile->n_comp_units)
2367     {
2368       index -= dwarf2_per_objfile->n_comp_units;
2369       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2370       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2371     }
2372
2373   return dwarf2_per_objfile->all_comp_units[index];
2374 }
2375
2376 /* A helper for create_cus_from_index that handles a given list of
2377    CUs.  */
2378
2379 static void
2380 create_cus_from_index_list (struct objfile *objfile,
2381                             const gdb_byte *cu_list, offset_type n_elements,
2382                             struct dwarf2_section_info *section,
2383                             int is_dwz,
2384                             int base_offset)
2385 {
2386   offset_type i;
2387
2388   for (i = 0; i < n_elements; i += 2)
2389     {
2390       struct dwarf2_per_cu_data *the_cu;
2391       ULONGEST offset, length;
2392
2393       gdb_static_assert (sizeof (ULONGEST) >= 8);
2394       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2395       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2396       cu_list += 2 * 8;
2397
2398       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2399                                struct dwarf2_per_cu_data);
2400       the_cu->offset.sect_off = offset;
2401       the_cu->length = length;
2402       the_cu->objfile = objfile;
2403       the_cu->info_or_types_section = section;
2404       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2405                                         struct dwarf2_per_cu_quick_data);
2406       the_cu->is_dwz = is_dwz;
2407       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2408     }
2409 }
2410
2411 /* Read the CU list from the mapped index, and use it to create all
2412    the CU objects for this objfile.  */
2413
2414 static void
2415 create_cus_from_index (struct objfile *objfile,
2416                        const gdb_byte *cu_list, offset_type cu_list_elements,
2417                        const gdb_byte *dwz_list, offset_type dwz_elements)
2418 {
2419   struct dwz_file *dwz;
2420
2421   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2422   dwarf2_per_objfile->all_comp_units
2423     = obstack_alloc (&objfile->objfile_obstack,
2424                      dwarf2_per_objfile->n_comp_units
2425                      * sizeof (struct dwarf2_per_cu_data *));
2426
2427   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2428                               &dwarf2_per_objfile->info, 0, 0);
2429
2430   if (dwz_elements == 0)
2431     return;
2432
2433   dwz = dwarf2_get_dwz_file ();
2434   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2435                               cu_list_elements / 2);
2436 }
2437
2438 /* Create the signatured type hash table from the index.  */
2439
2440 static void
2441 create_signatured_type_table_from_index (struct objfile *objfile,
2442                                          struct dwarf2_section_info *section,
2443                                          const gdb_byte *bytes,
2444                                          offset_type elements)
2445 {
2446   offset_type i;
2447   htab_t sig_types_hash;
2448
2449   dwarf2_per_objfile->n_type_units = elements / 3;
2450   dwarf2_per_objfile->all_type_units
2451     = obstack_alloc (&objfile->objfile_obstack,
2452                      dwarf2_per_objfile->n_type_units
2453                      * sizeof (struct signatured_type *));
2454
2455   sig_types_hash = allocate_signatured_type_table (objfile);
2456
2457   for (i = 0; i < elements; i += 3)
2458     {
2459       struct signatured_type *sig_type;
2460       ULONGEST offset, type_offset_in_tu, signature;
2461       void **slot;
2462
2463       gdb_static_assert (sizeof (ULONGEST) >= 8);
2464       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2465       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2466                                                     BFD_ENDIAN_LITTLE);
2467       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2468       bytes += 3 * 8;
2469
2470       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2471                                  struct signatured_type);
2472       sig_type->signature = signature;
2473       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2474       sig_type->per_cu.is_debug_types = 1;
2475       sig_type->per_cu.info_or_types_section = section;
2476       sig_type->per_cu.offset.sect_off = offset;
2477       sig_type->per_cu.objfile = objfile;
2478       sig_type->per_cu.v.quick
2479         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2480                           struct dwarf2_per_cu_quick_data);
2481
2482       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2483       *slot = sig_type;
2484
2485       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2486     }
2487
2488   dwarf2_per_objfile->signatured_types = sig_types_hash;
2489 }
2490
2491 /* Read the address map data from the mapped index, and use it to
2492    populate the objfile's psymtabs_addrmap.  */
2493
2494 static void
2495 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2496 {
2497   const gdb_byte *iter, *end;
2498   struct obstack temp_obstack;
2499   struct addrmap *mutable_map;
2500   struct cleanup *cleanup;
2501   CORE_ADDR baseaddr;
2502
2503   obstack_init (&temp_obstack);
2504   cleanup = make_cleanup_obstack_free (&temp_obstack);
2505   mutable_map = addrmap_create_mutable (&temp_obstack);
2506
2507   iter = index->address_table;
2508   end = iter + index->address_table_size;
2509
2510   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2511
2512   while (iter < end)
2513     {
2514       ULONGEST hi, lo, cu_index;
2515       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2516       iter += 8;
2517       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2518       iter += 8;
2519       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2520       iter += 4;
2521       
2522       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2523                          dw2_get_cu (cu_index));
2524     }
2525
2526   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2527                                                     &objfile->objfile_obstack);
2528   do_cleanups (cleanup);
2529 }
2530
2531 /* The hash function for strings in the mapped index.  This is the same as
2532    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2533    implementation.  This is necessary because the hash function is tied to the
2534    format of the mapped index file.  The hash values do not have to match with
2535    SYMBOL_HASH_NEXT.
2536    
2537    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2538
2539 static hashval_t
2540 mapped_index_string_hash (int index_version, const void *p)
2541 {
2542   const unsigned char *str = (const unsigned char *) p;
2543   hashval_t r = 0;
2544   unsigned char c;
2545
2546   while ((c = *str++) != 0)
2547     {
2548       if (index_version >= 5)
2549         c = tolower (c);
2550       r = r * 67 + c - 113;
2551     }
2552
2553   return r;
2554 }
2555
2556 /* Find a slot in the mapped index INDEX for the object named NAME.
2557    If NAME is found, set *VEC_OUT to point to the CU vector in the
2558    constant pool and return 1.  If NAME cannot be found, return 0.  */
2559
2560 static int
2561 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2562                           offset_type **vec_out)
2563 {
2564   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2565   offset_type hash;
2566   offset_type slot, step;
2567   int (*cmp) (const char *, const char *);
2568
2569   if (current_language->la_language == language_cplus
2570       || current_language->la_language == language_java
2571       || current_language->la_language == language_fortran)
2572     {
2573       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2574          not contain any.  */
2575       const char *paren = strchr (name, '(');
2576
2577       if (paren)
2578         {
2579           char *dup;
2580
2581           dup = xmalloc (paren - name + 1);
2582           memcpy (dup, name, paren - name);
2583           dup[paren - name] = 0;
2584
2585           make_cleanup (xfree, dup);
2586           name = dup;
2587         }
2588     }
2589
2590   /* Index version 4 did not support case insensitive searches.  But the
2591      indices for case insensitive languages are built in lowercase, therefore
2592      simulate our NAME being searched is also lowercased.  */
2593   hash = mapped_index_string_hash ((index->version == 4
2594                                     && case_sensitivity == case_sensitive_off
2595                                     ? 5 : index->version),
2596                                    name);
2597
2598   slot = hash & (index->symbol_table_slots - 1);
2599   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2600   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2601
2602   for (;;)
2603     {
2604       /* Convert a slot number to an offset into the table.  */
2605       offset_type i = 2 * slot;
2606       const char *str;
2607       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2608         {
2609           do_cleanups (back_to);
2610           return 0;
2611         }
2612
2613       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2614       if (!cmp (name, str))
2615         {
2616           *vec_out = (offset_type *) (index->constant_pool
2617                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2618           do_cleanups (back_to);
2619           return 1;
2620         }
2621
2622       slot = (slot + step) & (index->symbol_table_slots - 1);
2623     }
2624 }
2625
2626 /* A helper function that reads the .gdb_index from SECTION and fills
2627    in MAP.  FILENAME is the name of the file containing the section;
2628    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2629    ok to use deprecated sections.
2630
2631    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2632    out parameters that are filled in with information about the CU and
2633    TU lists in the section.
2634
2635    Returns 1 if all went well, 0 otherwise.  */
2636
2637 static int
2638 read_index_from_section (struct objfile *objfile,
2639                          const char *filename,
2640                          int deprecated_ok,
2641                          struct dwarf2_section_info *section,
2642                          struct mapped_index *map,
2643                          const gdb_byte **cu_list,
2644                          offset_type *cu_list_elements,
2645                          const gdb_byte **types_list,
2646                          offset_type *types_list_elements)
2647 {
2648   char *addr;
2649   offset_type version;
2650   offset_type *metadata;
2651   int i;
2652
2653   if (dwarf2_section_empty_p (section))
2654     return 0;
2655
2656   /* Older elfutils strip versions could keep the section in the main
2657      executable while splitting it for the separate debug info file.  */
2658   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2659     return 0;
2660
2661   dwarf2_read_section (objfile, section);
2662
2663   addr = section->buffer;
2664   /* Version check.  */
2665   version = MAYBE_SWAP (*(offset_type *) addr);
2666   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2667      causes the index to behave very poorly for certain requests.  Version 3
2668      contained incomplete addrmap.  So, it seems better to just ignore such
2669      indices.  */
2670   if (version < 4)
2671     {
2672       static int warning_printed = 0;
2673       if (!warning_printed)
2674         {
2675           warning (_("Skipping obsolete .gdb_index section in %s."),
2676                    filename);
2677           warning_printed = 1;
2678         }
2679       return 0;
2680     }
2681   /* Index version 4 uses a different hash function than index version
2682      5 and later.
2683
2684      Versions earlier than 6 did not emit psymbols for inlined
2685      functions.  Using these files will cause GDB not to be able to
2686      set breakpoints on inlined functions by name, so we ignore these
2687      indices unless the user has done
2688      "set use-deprecated-index-sections on".  */
2689   if (version < 6 && !deprecated_ok)
2690     {
2691       static int warning_printed = 0;
2692       if (!warning_printed)
2693         {
2694           warning (_("\
2695 Skipping deprecated .gdb_index section in %s.\n\
2696 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2697 to use the section anyway."),
2698                    filename);
2699           warning_printed = 1;
2700         }
2701       return 0;
2702     }
2703   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2704      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2705      we can't distinguish gdb-generated indices from gold-generated ones, so
2706      nothing to do here.  */
2707
2708   /* Indexes with higher version than the one supported by GDB may be no
2709      longer backward compatible.  */
2710   if (version > 8)
2711     return 0;
2712
2713   map->version = version;
2714   map->total_size = section->size;
2715
2716   metadata = (offset_type *) (addr + sizeof (offset_type));
2717
2718   i = 0;
2719   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2720   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2721                        / 8);
2722   ++i;
2723
2724   *types_list = addr + MAYBE_SWAP (metadata[i]);
2725   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2726                            - MAYBE_SWAP (metadata[i]))
2727                           / 8);
2728   ++i;
2729
2730   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2731   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2732                              - MAYBE_SWAP (metadata[i]));
2733   ++i;
2734
2735   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2736   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2737                               - MAYBE_SWAP (metadata[i]))
2738                              / (2 * sizeof (offset_type)));
2739   ++i;
2740
2741   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2742
2743   return 1;
2744 }
2745
2746
2747 /* Read the index file.  If everything went ok, initialize the "quick"
2748    elements of all the CUs and return 1.  Otherwise, return 0.  */
2749
2750 static int
2751 dwarf2_read_index (struct objfile *objfile)
2752 {
2753   struct mapped_index local_map, *map;
2754   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2755   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2756
2757   if (!read_index_from_section (objfile, objfile->name,
2758                                 use_deprecated_index_sections,
2759                                 &dwarf2_per_objfile->gdb_index, &local_map,
2760                                 &cu_list, &cu_list_elements,
2761                                 &types_list, &types_list_elements))
2762     return 0;
2763
2764   /* Don't use the index if it's empty.  */
2765   if (local_map.symbol_table_slots == 0)
2766     return 0;
2767
2768   /* If there is a .dwz file, read it so we can get its CU list as
2769      well.  */
2770   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2771     {
2772       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2773       struct mapped_index dwz_map;
2774       const gdb_byte *dwz_types_ignore;
2775       offset_type dwz_types_elements_ignore;
2776
2777       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2778                                     1,
2779                                     &dwz->gdb_index, &dwz_map,
2780                                     &dwz_list, &dwz_list_elements,
2781                                     &dwz_types_ignore,
2782                                     &dwz_types_elements_ignore))
2783         {
2784           warning (_("could not read '.gdb_index' section from %s; skipping"),
2785                    bfd_get_filename (dwz->dwz_bfd));
2786           return 0;
2787         }
2788     }
2789
2790   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2791                          dwz_list_elements);
2792
2793   if (types_list_elements)
2794     {
2795       struct dwarf2_section_info *section;
2796
2797       /* We can only handle a single .debug_types when we have an
2798          index.  */
2799       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2800         return 0;
2801
2802       section = VEC_index (dwarf2_section_info_def,
2803                            dwarf2_per_objfile->types, 0);
2804
2805       create_signatured_type_table_from_index (objfile, section, types_list,
2806                                                types_list_elements);
2807     }
2808
2809   create_addrmap_from_index (objfile, &local_map);
2810
2811   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2812   *map = local_map;
2813
2814   dwarf2_per_objfile->index_table = map;
2815   dwarf2_per_objfile->using_index = 1;
2816   dwarf2_per_objfile->quick_file_names_table =
2817     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2818
2819   return 1;
2820 }
2821
2822 /* A helper for the "quick" functions which sets the global
2823    dwarf2_per_objfile according to OBJFILE.  */
2824
2825 static void
2826 dw2_setup (struct objfile *objfile)
2827 {
2828   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2829   gdb_assert (dwarf2_per_objfile);
2830 }
2831
2832 /* die_reader_func for dw2_get_file_names.  */
2833
2834 static void
2835 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2836                            gdb_byte *info_ptr,
2837                            struct die_info *comp_unit_die,
2838                            int has_children,
2839                            void *data)
2840 {
2841   struct dwarf2_cu *cu = reader->cu;
2842   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2843   struct objfile *objfile = dwarf2_per_objfile->objfile;
2844   struct dwarf2_per_cu_data *lh_cu;
2845   struct line_header *lh;
2846   struct attribute *attr;
2847   int i;
2848   const char *name, *comp_dir;
2849   void **slot;
2850   struct quick_file_names *qfn;
2851   unsigned int line_offset;
2852
2853   /* Our callers never want to match partial units -- instead they
2854      will match the enclosing full CU.  */
2855   if (comp_unit_die->tag == DW_TAG_partial_unit)
2856     {
2857       this_cu->v.quick->no_file_data = 1;
2858       return;
2859     }
2860
2861   /* If we're reading the line header for TUs, store it in the "per_cu"
2862      for tu_group.  */
2863   if (this_cu->is_debug_types)
2864     {
2865       struct type_unit_group *tu_group = data;
2866
2867       gdb_assert (tu_group != NULL);
2868       lh_cu = &tu_group->per_cu;
2869     }
2870   else
2871     lh_cu = this_cu;
2872
2873   lh = NULL;
2874   slot = NULL;
2875   line_offset = 0;
2876
2877   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2878   if (attr)
2879     {
2880       struct quick_file_names find_entry;
2881
2882       line_offset = DW_UNSND (attr);
2883
2884       /* We may have already read in this line header (TU line header sharing).
2885          If we have we're done.  */
2886       find_entry.hash.dwo_unit = cu->dwo_unit;
2887       find_entry.hash.line_offset.sect_off = line_offset;
2888       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2889                              &find_entry, INSERT);
2890       if (*slot != NULL)
2891         {
2892           lh_cu->v.quick->file_names = *slot;
2893           return;
2894         }
2895
2896       lh = dwarf_decode_line_header (line_offset, cu);
2897     }
2898   if (lh == NULL)
2899     {
2900       lh_cu->v.quick->no_file_data = 1;
2901       return;
2902     }
2903
2904   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2905   qfn->hash.dwo_unit = cu->dwo_unit;
2906   qfn->hash.line_offset.sect_off = line_offset;
2907   gdb_assert (slot != NULL);
2908   *slot = qfn;
2909
2910   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2911
2912   qfn->num_file_names = lh->num_file_names;
2913   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2914                                    lh->num_file_names * sizeof (char *));
2915   for (i = 0; i < lh->num_file_names; ++i)
2916     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2917   qfn->real_names = NULL;
2918
2919   free_line_header (lh);
2920
2921   lh_cu->v.quick->file_names = qfn;
2922 }
2923
2924 /* A helper for the "quick" functions which attempts to read the line
2925    table for THIS_CU.  */
2926
2927 static struct quick_file_names *
2928 dw2_get_file_names (struct objfile *objfile,
2929                     struct dwarf2_per_cu_data *this_cu)
2930 {
2931   /* For TUs this should only be called on the parent group.  */
2932   if (this_cu->is_debug_types)
2933     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2934
2935   if (this_cu->v.quick->file_names != NULL)
2936     return this_cu->v.quick->file_names;
2937   /* If we know there is no line data, no point in looking again.  */
2938   if (this_cu->v.quick->no_file_data)
2939     return NULL;
2940
2941   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2942      in the stub for CUs, there's is no need to lookup the DWO file.
2943      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2944      DWO file.  */
2945   if (this_cu->is_debug_types)
2946     {
2947       struct type_unit_group *tu_group = this_cu->type_unit_group;
2948
2949       init_cutu_and_read_dies (tu_group->t.first_tu, NULL, 0, 0,
2950                                dw2_get_file_names_reader, tu_group);
2951     }
2952   else
2953     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2954
2955   if (this_cu->v.quick->no_file_data)
2956     return NULL;
2957   return this_cu->v.quick->file_names;
2958 }
2959
2960 /* A helper for the "quick" functions which computes and caches the
2961    real path for a given file name from the line table.  */
2962
2963 static const char *
2964 dw2_get_real_path (struct objfile *objfile,
2965                    struct quick_file_names *qfn, int index)
2966 {
2967   if (qfn->real_names == NULL)
2968     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2969                                       qfn->num_file_names, sizeof (char *));
2970
2971   if (qfn->real_names[index] == NULL)
2972     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2973
2974   return qfn->real_names[index];
2975 }
2976
2977 static struct symtab *
2978 dw2_find_last_source_symtab (struct objfile *objfile)
2979 {
2980   int index;
2981
2982   dw2_setup (objfile);
2983   index = dwarf2_per_objfile->n_comp_units - 1;
2984   return dw2_instantiate_symtab (dw2_get_cu (index));
2985 }
2986
2987 /* Traversal function for dw2_forget_cached_source_info.  */
2988
2989 static int
2990 dw2_free_cached_file_names (void **slot, void *info)
2991 {
2992   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2993
2994   if (file_data->real_names)
2995     {
2996       int i;
2997
2998       for (i = 0; i < file_data->num_file_names; ++i)
2999         {
3000           xfree ((void*) file_data->real_names[i]);
3001           file_data->real_names[i] = NULL;
3002         }
3003     }
3004
3005   return 1;
3006 }
3007
3008 static void
3009 dw2_forget_cached_source_info (struct objfile *objfile)
3010 {
3011   dw2_setup (objfile);
3012
3013   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3014                           dw2_free_cached_file_names, NULL);
3015 }
3016
3017 /* Helper function for dw2_map_symtabs_matching_filename that expands
3018    the symtabs and calls the iterator.  */
3019
3020 static int
3021 dw2_map_expand_apply (struct objfile *objfile,
3022                       struct dwarf2_per_cu_data *per_cu,
3023                       const char *name, const char *real_path,
3024                       int (*callback) (struct symtab *, void *),
3025                       void *data)
3026 {
3027   struct symtab *last_made = objfile->symtabs;
3028
3029   /* Don't visit already-expanded CUs.  */
3030   if (per_cu->v.quick->symtab)
3031     return 0;
3032
3033   /* This may expand more than one symtab, and we want to iterate over
3034      all of them.  */
3035   dw2_instantiate_symtab (per_cu);
3036
3037   return iterate_over_some_symtabs (name, real_path, callback, data,
3038                                     objfile->symtabs, last_made);
3039 }
3040
3041 /* Implementation of the map_symtabs_matching_filename method.  */
3042
3043 static int
3044 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3045                                    const char *real_path,
3046                                    int (*callback) (struct symtab *, void *),
3047                                    void *data)
3048 {
3049   int i;
3050   const char *name_basename = lbasename (name);
3051
3052   dw2_setup (objfile);
3053
3054   /* The rule is CUs specify all the files, including those used by
3055      any TU, so there's no need to scan TUs here.  */
3056
3057   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3058     {
3059       int j;
3060       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3061       struct quick_file_names *file_data;
3062
3063       /* We only need to look at symtabs not already expanded.  */
3064       if (per_cu->v.quick->symtab)
3065         continue;
3066
3067       file_data = dw2_get_file_names (objfile, per_cu);
3068       if (file_data == NULL)
3069         continue;
3070
3071       for (j = 0; j < file_data->num_file_names; ++j)
3072         {
3073           const char *this_name = file_data->file_names[j];
3074
3075           if (compare_filenames_for_search (this_name, name))
3076             {
3077               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3078                                         callback, data))
3079                 return 1;
3080             }
3081
3082           /* Before we invoke realpath, which can get expensive when many
3083              files are involved, do a quick comparison of the basenames.  */
3084           if (! basenames_may_differ
3085               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3086             continue;
3087
3088           if (real_path != NULL)
3089             {
3090               const char *this_real_name = dw2_get_real_path (objfile,
3091                                                               file_data, j);
3092
3093               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3094               gdb_assert (IS_ABSOLUTE_PATH (name));
3095               if (this_real_name != NULL
3096                   && FILENAME_CMP (real_path, this_real_name) == 0)
3097                 {
3098                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3099                                             callback, data))
3100                     return 1;
3101                 }
3102             }
3103         }
3104     }
3105
3106   return 0;
3107 }
3108
3109 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3110
3111 struct dw2_symtab_iterator
3112 {
3113   /* The internalized form of .gdb_index.  */
3114   struct mapped_index *index;
3115   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3116   int want_specific_block;
3117   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3118      Unused if !WANT_SPECIFIC_BLOCK.  */
3119   int block_index;
3120   /* The kind of symbol we're looking for.  */
3121   domain_enum domain;
3122   /* The list of CUs from the index entry of the symbol,
3123      or NULL if not found.  */
3124   offset_type *vec;
3125   /* The next element in VEC to look at.  */
3126   int next;
3127   /* The number of elements in VEC, or zero if there is no match.  */
3128   int length;
3129 };
3130
3131 /* Initialize the index symtab iterator ITER.
3132    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3133    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3134
3135 static void
3136 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3137                       struct mapped_index *index,
3138                       int want_specific_block,
3139                       int block_index,
3140                       domain_enum domain,
3141                       const char *name)
3142 {
3143   iter->index = index;
3144   iter->want_specific_block = want_specific_block;
3145   iter->block_index = block_index;
3146   iter->domain = domain;
3147   iter->next = 0;
3148
3149   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3150     iter->length = MAYBE_SWAP (*iter->vec);
3151   else
3152     {
3153       iter->vec = NULL;
3154       iter->length = 0;
3155     }
3156 }
3157
3158 /* Return the next matching CU or NULL if there are no more.  */
3159
3160 static struct dwarf2_per_cu_data *
3161 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3162 {
3163   for ( ; iter->next < iter->length; ++iter->next)
3164     {
3165       offset_type cu_index_and_attrs =
3166         MAYBE_SWAP (iter->vec[iter->next + 1]);
3167       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3168       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3169       int want_static = iter->block_index != GLOBAL_BLOCK;
3170       /* This value is only valid for index versions >= 7.  */
3171       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3172       gdb_index_symbol_kind symbol_kind =
3173         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3174       /* Only check the symbol attributes if they're present.
3175          Indices prior to version 7 don't record them,
3176          and indices >= 7 may elide them for certain symbols
3177          (gold does this).  */
3178       int attrs_valid =
3179         (iter->index->version >= 7
3180          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3181
3182       /* Skip if already read in.  */
3183       if (per_cu->v.quick->symtab)
3184         continue;
3185
3186       if (attrs_valid
3187           && iter->want_specific_block
3188           && want_static != is_static)
3189         continue;
3190
3191       /* Only check the symbol's kind if it has one.  */
3192       if (attrs_valid)
3193         {
3194           switch (iter->domain)
3195             {
3196             case VAR_DOMAIN:
3197               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3198                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3199                   /* Some types are also in VAR_DOMAIN.  */
3200                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3201                 continue;
3202               break;
3203             case STRUCT_DOMAIN:
3204               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3205                 continue;
3206               break;
3207             case LABEL_DOMAIN:
3208               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3209                 continue;
3210               break;
3211             default:
3212               break;
3213             }
3214         }
3215
3216       ++iter->next;
3217       return per_cu;
3218     }
3219
3220   return NULL;
3221 }
3222
3223 static struct symtab *
3224 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3225                    const char *name, domain_enum domain)
3226 {
3227   struct symtab *stab_best = NULL;
3228   struct mapped_index *index;
3229
3230   dw2_setup (objfile);
3231
3232   index = dwarf2_per_objfile->index_table;
3233
3234   /* index is NULL if OBJF_READNOW.  */
3235   if (index)
3236     {
3237       struct dw2_symtab_iterator iter;
3238       struct dwarf2_per_cu_data *per_cu;
3239
3240       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3241
3242       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3243         {
3244           struct symbol *sym = NULL;
3245           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3246
3247           /* Some caution must be observed with overloaded functions
3248              and methods, since the index will not contain any overload
3249              information (but NAME might contain it).  */
3250           if (stab->primary)
3251             {
3252               struct blockvector *bv = BLOCKVECTOR (stab);
3253               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3254
3255               sym = lookup_block_symbol (block, name, domain);
3256             }
3257
3258           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3259             {
3260               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3261                 return stab;
3262
3263               stab_best = stab;
3264             }
3265
3266           /* Keep looking through other CUs.  */
3267         }
3268     }
3269
3270   return stab_best;
3271 }
3272
3273 static void
3274 dw2_print_stats (struct objfile *objfile)
3275 {
3276   int i, count;
3277
3278   dw2_setup (objfile);
3279   count = 0;
3280   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3281                    + dwarf2_per_objfile->n_type_units); ++i)
3282     {
3283       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3284
3285       if (!per_cu->v.quick->symtab)
3286         ++count;
3287     }
3288   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3289 }
3290
3291 static void
3292 dw2_dump (struct objfile *objfile)
3293 {
3294   /* Nothing worth printing.  */
3295 }
3296
3297 static void
3298 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3299               struct section_offsets *delta)
3300 {
3301   /* There's nothing to relocate here.  */
3302 }
3303
3304 static void
3305 dw2_expand_symtabs_for_function (struct objfile *objfile,
3306                                  const char *func_name)
3307 {
3308   struct mapped_index *index;
3309
3310   dw2_setup (objfile);
3311
3312   index = dwarf2_per_objfile->index_table;
3313
3314   /* index is NULL if OBJF_READNOW.  */
3315   if (index)
3316     {
3317       struct dw2_symtab_iterator iter;
3318       struct dwarf2_per_cu_data *per_cu;
3319
3320       /* Note: It doesn't matter what we pass for block_index here.  */
3321       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3322                             func_name);
3323
3324       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3325         dw2_instantiate_symtab (per_cu);
3326     }
3327 }
3328
3329 static void
3330 dw2_expand_all_symtabs (struct objfile *objfile)
3331 {
3332   int i;
3333
3334   dw2_setup (objfile);
3335
3336   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3337                    + dwarf2_per_objfile->n_type_units); ++i)
3338     {
3339       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3340
3341       dw2_instantiate_symtab (per_cu);
3342     }
3343 }
3344
3345 static void
3346 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3347                                   const char *fullname)
3348 {
3349   int i;
3350
3351   dw2_setup (objfile);
3352
3353   /* We don't need to consider type units here.
3354      This is only called for examining code, e.g. expand_line_sal.
3355      There can be an order of magnitude (or more) more type units
3356      than comp units, and we avoid them if we can.  */
3357
3358   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3359     {
3360       int j;
3361       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3362       struct quick_file_names *file_data;
3363
3364       /* We only need to look at symtabs not already expanded.  */
3365       if (per_cu->v.quick->symtab)
3366         continue;
3367
3368       file_data = dw2_get_file_names (objfile, per_cu);
3369       if (file_data == NULL)
3370         continue;
3371
3372       for (j = 0; j < file_data->num_file_names; ++j)
3373         {
3374           const char *this_fullname = file_data->file_names[j];
3375
3376           if (filename_cmp (this_fullname, fullname) == 0)
3377             {
3378               dw2_instantiate_symtab (per_cu);
3379               break;
3380             }
3381         }
3382     }
3383 }
3384
3385 /* A helper function for dw2_find_symbol_file that finds the primary
3386    file name for a given CU.  This is a die_reader_func.  */
3387
3388 static void
3389 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3390                                  gdb_byte *info_ptr,
3391                                  struct die_info *comp_unit_die,
3392                                  int has_children,
3393                                  void *data)
3394 {
3395   const char **result_ptr = data;
3396   struct dwarf2_cu *cu = reader->cu;
3397   struct attribute *attr;
3398
3399   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3400   if (attr == NULL)
3401     *result_ptr = NULL;
3402   else
3403     *result_ptr = DW_STRING (attr);
3404 }
3405
3406 static const char *
3407 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3408 {
3409   struct dwarf2_per_cu_data *per_cu;
3410   offset_type *vec;
3411   const char *filename;
3412
3413   dw2_setup (objfile);
3414
3415   /* index_table is NULL if OBJF_READNOW.  */
3416   if (!dwarf2_per_objfile->index_table)
3417     {
3418       struct symtab *s;
3419
3420       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3421         {
3422           struct blockvector *bv = BLOCKVECTOR (s);
3423           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3424           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3425
3426           if (sym)
3427             {
3428               /* Only file extension of returned filename is recognized.  */
3429               return SYMBOL_SYMTAB (sym)->filename;
3430             }
3431         }
3432       return NULL;
3433     }
3434
3435   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3436                                  name, &vec))
3437     return NULL;
3438
3439   /* Note that this just looks at the very first one named NAME -- but
3440      actually we are looking for a function.  find_main_filename
3441      should be rewritten so that it doesn't require a custom hook.  It
3442      could just use the ordinary symbol tables.  */
3443   /* vec[0] is the length, which must always be >0.  */
3444   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3445
3446   if (per_cu->v.quick->symtab != NULL)
3447     {
3448       /* Only file extension of returned filename is recognized.  */
3449       return per_cu->v.quick->symtab->filename;
3450     }
3451
3452   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3453                            dw2_get_primary_filename_reader, &filename);
3454
3455   /* Only file extension of returned filename is recognized.  */
3456   return filename;
3457 }
3458
3459 static void
3460 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3461                           struct objfile *objfile, int global,
3462                           int (*callback) (struct block *,
3463                                            struct symbol *, void *),
3464                           void *data, symbol_compare_ftype *match,
3465                           symbol_compare_ftype *ordered_compare)
3466 {
3467   /* Currently unimplemented; used for Ada.  The function can be called if the
3468      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3469      does not look for non-Ada symbols this function should just return.  */
3470 }
3471
3472 static void
3473 dw2_expand_symtabs_matching
3474   (struct objfile *objfile,
3475    int (*file_matcher) (const char *, void *),
3476    int (*name_matcher) (const char *, void *),
3477    enum search_domain kind,
3478    void *data)
3479 {
3480   int i;
3481   offset_type iter;
3482   struct mapped_index *index;
3483
3484   dw2_setup (objfile);
3485
3486   /* index_table is NULL if OBJF_READNOW.  */
3487   if (!dwarf2_per_objfile->index_table)
3488     return;
3489   index = dwarf2_per_objfile->index_table;
3490
3491   if (file_matcher != NULL)
3492     {
3493       struct cleanup *cleanup;
3494       htab_t visited_found, visited_not_found;
3495
3496       visited_found = htab_create_alloc (10,
3497                                          htab_hash_pointer, htab_eq_pointer,
3498                                          NULL, xcalloc, xfree);
3499       cleanup = make_cleanup_htab_delete (visited_found);
3500       visited_not_found = htab_create_alloc (10,
3501                                              htab_hash_pointer, htab_eq_pointer,
3502                                              NULL, xcalloc, xfree);
3503       make_cleanup_htab_delete (visited_not_found);
3504
3505       /* The rule is CUs specify all the files, including those used by
3506          any TU, so there's no need to scan TUs here.  */
3507
3508       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3509         {
3510           int j;
3511           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3512           struct quick_file_names *file_data;
3513           void **slot;
3514
3515           per_cu->v.quick->mark = 0;
3516
3517           /* We only need to look at symtabs not already expanded.  */
3518           if (per_cu->v.quick->symtab)
3519             continue;
3520
3521           file_data = dw2_get_file_names (objfile, per_cu);
3522           if (file_data == NULL)
3523             continue;
3524
3525           if (htab_find (visited_not_found, file_data) != NULL)
3526             continue;
3527           else if (htab_find (visited_found, file_data) != NULL)
3528             {
3529               per_cu->v.quick->mark = 1;
3530               continue;
3531             }
3532
3533           for (j = 0; j < file_data->num_file_names; ++j)
3534             {
3535               if (file_matcher (file_data->file_names[j], data))
3536                 {
3537                   per_cu->v.quick->mark = 1;
3538                   break;
3539                 }
3540             }
3541
3542           slot = htab_find_slot (per_cu->v.quick->mark
3543                                  ? visited_found
3544                                  : visited_not_found,
3545                                  file_data, INSERT);
3546           *slot = file_data;
3547         }
3548
3549       do_cleanups (cleanup);
3550     }
3551
3552   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3553     {
3554       offset_type idx = 2 * iter;
3555       const char *name;
3556       offset_type *vec, vec_len, vec_idx;
3557
3558       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3559         continue;
3560
3561       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3562
3563       if (! (*name_matcher) (name, data))
3564         continue;
3565
3566       /* The name was matched, now expand corresponding CUs that were
3567          marked.  */
3568       vec = (offset_type *) (index->constant_pool
3569                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3570       vec_len = MAYBE_SWAP (vec[0]);
3571       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3572         {
3573           struct dwarf2_per_cu_data *per_cu;
3574           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3575           gdb_index_symbol_kind symbol_kind =
3576             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3577           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3578
3579           /* Don't crash on bad data.  */
3580           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3581                            + dwarf2_per_objfile->n_type_units))
3582             continue;
3583
3584           /* Only check the symbol's kind if it has one.
3585              Indices prior to version 7 don't record it.  */
3586           if (index->version >= 7)
3587             {
3588               switch (kind)
3589                 {
3590                 case VARIABLES_DOMAIN:
3591                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3592                     continue;
3593                   break;
3594                 case FUNCTIONS_DOMAIN:
3595                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3596                     continue;
3597                   break;
3598                 case TYPES_DOMAIN:
3599                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3600                     continue;
3601                   break;
3602                 default:
3603                   break;
3604                 }
3605             }
3606
3607           per_cu = dw2_get_cu (cu_index);
3608           if (file_matcher == NULL || per_cu->v.quick->mark)
3609             dw2_instantiate_symtab (per_cu);
3610         }
3611     }
3612 }
3613
3614 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3615    symtab.  */
3616
3617 static struct symtab *
3618 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3619 {
3620   int i;
3621
3622   if (BLOCKVECTOR (symtab) != NULL
3623       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3624     return symtab;
3625
3626   if (symtab->includes == NULL)
3627     return NULL;
3628
3629   for (i = 0; symtab->includes[i]; ++i)
3630     {
3631       struct symtab *s = symtab->includes[i];
3632
3633       s = recursively_find_pc_sect_symtab (s, pc);
3634       if (s != NULL)
3635         return s;
3636     }
3637
3638   return NULL;
3639 }
3640
3641 static struct symtab *
3642 dw2_find_pc_sect_symtab (struct objfile *objfile,
3643                          struct minimal_symbol *msymbol,
3644                          CORE_ADDR pc,
3645                          struct obj_section *section,
3646                          int warn_if_readin)
3647 {
3648   struct dwarf2_per_cu_data *data;
3649   struct symtab *result;
3650
3651   dw2_setup (objfile);
3652
3653   if (!objfile->psymtabs_addrmap)
3654     return NULL;
3655
3656   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3657   if (!data)
3658     return NULL;
3659
3660   if (warn_if_readin && data->v.quick->symtab)
3661     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3662              paddress (get_objfile_arch (objfile), pc));
3663
3664   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3665   gdb_assert (result != NULL);
3666   return result;
3667 }
3668
3669 static void
3670 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3671                           void *data, int need_fullname)
3672 {
3673   int i;
3674   struct cleanup *cleanup;
3675   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3676                                       NULL, xcalloc, xfree);
3677
3678   cleanup = make_cleanup_htab_delete (visited);
3679   dw2_setup (objfile);
3680
3681   /* The rule is CUs specify all the files, including those used by
3682      any TU, so there's no need to scan TUs here.
3683      We can ignore file names coming from already-expanded CUs.  */
3684
3685   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3686     {
3687       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3688
3689       if (per_cu->v.quick->symtab)
3690         {
3691           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3692                                         INSERT);
3693
3694           *slot = per_cu->v.quick->file_names;
3695         }
3696     }
3697
3698   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3699     {
3700       int j;
3701       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3702       struct quick_file_names *file_data;
3703       void **slot;
3704
3705       /* We only need to look at symtabs not already expanded.  */
3706       if (per_cu->v.quick->symtab)
3707         continue;
3708
3709       file_data = dw2_get_file_names (objfile, per_cu);
3710       if (file_data == NULL)
3711         continue;
3712
3713       slot = htab_find_slot (visited, file_data, INSERT);
3714       if (*slot)
3715         {
3716           /* Already visited.  */
3717           continue;
3718         }
3719       *slot = file_data;
3720
3721       for (j = 0; j < file_data->num_file_names; ++j)
3722         {
3723           const char *this_real_name;
3724
3725           if (need_fullname)
3726             this_real_name = dw2_get_real_path (objfile, file_data, j);
3727           else
3728             this_real_name = NULL;
3729           (*fun) (file_data->file_names[j], this_real_name, data);
3730         }
3731     }
3732
3733   do_cleanups (cleanup);
3734 }
3735
3736 static int
3737 dw2_has_symbols (struct objfile *objfile)
3738 {
3739   return 1;
3740 }
3741
3742 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3743 {
3744   dw2_has_symbols,
3745   dw2_find_last_source_symtab,
3746   dw2_forget_cached_source_info,
3747   dw2_map_symtabs_matching_filename,
3748   dw2_lookup_symbol,
3749   dw2_print_stats,
3750   dw2_dump,
3751   dw2_relocate,
3752   dw2_expand_symtabs_for_function,
3753   dw2_expand_all_symtabs,
3754   dw2_expand_symtabs_with_fullname,
3755   dw2_find_symbol_file,
3756   dw2_map_matching_symbols,
3757   dw2_expand_symtabs_matching,
3758   dw2_find_pc_sect_symtab,
3759   dw2_map_symbol_filenames
3760 };
3761
3762 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3763    file will use psymtabs, or 1 if using the GNU index.  */
3764
3765 int
3766 dwarf2_initialize_objfile (struct objfile *objfile)
3767 {
3768   /* If we're about to read full symbols, don't bother with the
3769      indices.  In this case we also don't care if some other debug
3770      format is making psymtabs, because they are all about to be
3771      expanded anyway.  */
3772   if ((objfile->flags & OBJF_READNOW))
3773     {
3774       int i;
3775
3776       dwarf2_per_objfile->using_index = 1;
3777       create_all_comp_units (objfile);
3778       create_all_type_units (objfile);
3779       dwarf2_per_objfile->quick_file_names_table =
3780         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3781
3782       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3783                        + dwarf2_per_objfile->n_type_units); ++i)
3784         {
3785           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3786
3787           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3788                                             struct dwarf2_per_cu_quick_data);
3789         }
3790
3791       /* Return 1 so that gdb sees the "quick" functions.  However,
3792          these functions will be no-ops because we will have expanded
3793          all symtabs.  */
3794       return 1;
3795     }
3796
3797   if (dwarf2_read_index (objfile))
3798     return 1;
3799
3800   return 0;
3801 }
3802
3803 \f
3804
3805 /* Build a partial symbol table.  */
3806
3807 void
3808 dwarf2_build_psymtabs (struct objfile *objfile)
3809 {
3810   volatile struct gdb_exception except;
3811
3812   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3813     {
3814       init_psymbol_list (objfile, 1024);
3815     }
3816
3817   TRY_CATCH (except, RETURN_MASK_ERROR)
3818     {
3819       /* This isn't really ideal: all the data we allocate on the
3820          objfile's obstack is still uselessly kept around.  However,
3821          freeing it seems unsafe.  */
3822       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3823
3824       dwarf2_build_psymtabs_hard (objfile);
3825       discard_cleanups (cleanups);
3826     }
3827   if (except.reason < 0)
3828     exception_print (gdb_stderr, except);
3829 }
3830
3831 /* Return the total length of the CU described by HEADER.  */
3832
3833 static unsigned int
3834 get_cu_length (const struct comp_unit_head *header)
3835 {
3836   return header->initial_length_size + header->length;
3837 }
3838
3839 /* Return TRUE if OFFSET is within CU_HEADER.  */
3840
3841 static inline int
3842 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3843 {
3844   sect_offset bottom = { cu_header->offset.sect_off };
3845   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3846
3847   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3848 }
3849
3850 /* Find the base address of the compilation unit for range lists and
3851    location lists.  It will normally be specified by DW_AT_low_pc.
3852    In DWARF-3 draft 4, the base address could be overridden by
3853    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3854    compilation units with discontinuous ranges.  */
3855
3856 static void
3857 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3858 {
3859   struct attribute *attr;
3860
3861   cu->base_known = 0;
3862   cu->base_address = 0;
3863
3864   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3865   if (attr)
3866     {
3867       cu->base_address = DW_ADDR (attr);
3868       cu->base_known = 1;
3869     }
3870   else
3871     {
3872       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3873       if (attr)
3874         {
3875           cu->base_address = DW_ADDR (attr);
3876           cu->base_known = 1;
3877         }
3878     }
3879 }
3880
3881 /* Read in the comp unit header information from the debug_info at info_ptr.
3882    NOTE: This leaves members offset, first_die_offset to be filled in
3883    by the caller.  */
3884
3885 static gdb_byte *
3886 read_comp_unit_head (struct comp_unit_head *cu_header,
3887                      gdb_byte *info_ptr, bfd *abfd)
3888 {
3889   int signed_addr;
3890   unsigned int bytes_read;
3891
3892   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3893   cu_header->initial_length_size = bytes_read;
3894   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3895   info_ptr += bytes_read;
3896   cu_header->version = read_2_bytes (abfd, info_ptr);
3897   info_ptr += 2;
3898   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3899                                              &bytes_read);
3900   info_ptr += bytes_read;
3901   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3902   info_ptr += 1;
3903   signed_addr = bfd_get_sign_extend_vma (abfd);
3904   if (signed_addr < 0)
3905     internal_error (__FILE__, __LINE__,
3906                     _("read_comp_unit_head: dwarf from non elf file"));
3907   cu_header->signed_addr_p = signed_addr;
3908
3909   return info_ptr;
3910 }
3911
3912 /* Helper function that returns the proper abbrev section for
3913    THIS_CU.  */
3914
3915 static struct dwarf2_section_info *
3916 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3917 {
3918   struct dwarf2_section_info *abbrev;
3919
3920   if (this_cu->is_dwz)
3921     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3922   else
3923     abbrev = &dwarf2_per_objfile->abbrev;
3924
3925   return abbrev;
3926 }
3927
3928 /* Subroutine of read_and_check_comp_unit_head and
3929    read_and_check_type_unit_head to simplify them.
3930    Perform various error checking on the header.  */
3931
3932 static void
3933 error_check_comp_unit_head (struct comp_unit_head *header,
3934                             struct dwarf2_section_info *section,
3935                             struct dwarf2_section_info *abbrev_section)
3936 {
3937   bfd *abfd = section->asection->owner;
3938   const char *filename = bfd_get_filename (abfd);
3939
3940   if (header->version != 2 && header->version != 3 && header->version != 4)
3941     error (_("Dwarf Error: wrong version in compilation unit header "
3942            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3943            filename);
3944
3945   if (header->abbrev_offset.sect_off
3946       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3947     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3948            "(offset 0x%lx + 6) [in module %s]"),
3949            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3950            filename);
3951
3952   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3953      avoid potential 32-bit overflow.  */
3954   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3955       > section->size)
3956     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3957            "(offset 0x%lx + 0) [in module %s]"),
3958            (long) header->length, (long) header->offset.sect_off,
3959            filename);
3960 }
3961
3962 /* Read in a CU/TU header and perform some basic error checking.
3963    The contents of the header are stored in HEADER.
3964    The result is a pointer to the start of the first DIE.  */
3965
3966 static gdb_byte *
3967 read_and_check_comp_unit_head (struct comp_unit_head *header,
3968                                struct dwarf2_section_info *section,
3969                                struct dwarf2_section_info *abbrev_section,
3970                                gdb_byte *info_ptr,
3971                                int is_debug_types_section)
3972 {
3973   gdb_byte *beg_of_comp_unit = info_ptr;
3974   bfd *abfd = section->asection->owner;
3975
3976   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3977
3978   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3979
3980   /* If we're reading a type unit, skip over the signature and
3981      type_offset fields.  */
3982   if (is_debug_types_section)
3983     info_ptr += 8 /*signature*/ + header->offset_size;
3984
3985   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3986
3987   error_check_comp_unit_head (header, section, abbrev_section);
3988
3989   return info_ptr;
3990 }
3991
3992 /* Read in the types comp unit header information from .debug_types entry at
3993    types_ptr.  The result is a pointer to one past the end of the header.  */
3994
3995 static gdb_byte *
3996 read_and_check_type_unit_head (struct comp_unit_head *header,
3997                                struct dwarf2_section_info *section,
3998                                struct dwarf2_section_info *abbrev_section,
3999                                gdb_byte *info_ptr,
4000                                ULONGEST *signature,
4001                                cu_offset *type_offset_in_tu)
4002 {
4003   gdb_byte *beg_of_comp_unit = info_ptr;
4004   bfd *abfd = section->asection->owner;
4005
4006   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4007
4008   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4009
4010   /* If we're reading a type unit, skip over the signature and
4011      type_offset fields.  */
4012   if (signature != NULL)
4013     *signature = read_8_bytes (abfd, info_ptr);
4014   info_ptr += 8;
4015   if (type_offset_in_tu != NULL)
4016     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4017                                                header->offset_size);
4018   info_ptr += header->offset_size;
4019
4020   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4021
4022   error_check_comp_unit_head (header, section, abbrev_section);
4023
4024   return info_ptr;
4025 }
4026
4027 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4028
4029 static sect_offset
4030 read_abbrev_offset (struct dwarf2_section_info *section,
4031                     sect_offset offset)
4032 {
4033   bfd *abfd = section->asection->owner;
4034   gdb_byte *info_ptr;
4035   unsigned int length, initial_length_size, offset_size;
4036   sect_offset abbrev_offset;
4037
4038   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4039   info_ptr = section->buffer + offset.sect_off;
4040   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4041   offset_size = initial_length_size == 4 ? 4 : 8;
4042   info_ptr += initial_length_size + 2 /*version*/;
4043   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4044   return abbrev_offset;
4045 }
4046
4047 /* Allocate a new partial symtab for file named NAME and mark this new
4048    partial symtab as being an include of PST.  */
4049
4050 static void
4051 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
4052                                struct objfile *objfile)
4053 {
4054   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4055
4056   subpst->section_offsets = pst->section_offsets;
4057   subpst->textlow = 0;
4058   subpst->texthigh = 0;
4059
4060   subpst->dependencies = (struct partial_symtab **)
4061     obstack_alloc (&objfile->objfile_obstack,
4062                    sizeof (struct partial_symtab *));
4063   subpst->dependencies[0] = pst;
4064   subpst->number_of_dependencies = 1;
4065
4066   subpst->globals_offset = 0;
4067   subpst->n_global_syms = 0;
4068   subpst->statics_offset = 0;
4069   subpst->n_static_syms = 0;
4070   subpst->symtab = NULL;
4071   subpst->read_symtab = pst->read_symtab;
4072   subpst->readin = 0;
4073
4074   /* No private part is necessary for include psymtabs.  This property
4075      can be used to differentiate between such include psymtabs and
4076      the regular ones.  */
4077   subpst->read_symtab_private = NULL;
4078 }
4079
4080 /* Read the Line Number Program data and extract the list of files
4081    included by the source file represented by PST.  Build an include
4082    partial symtab for each of these included files.  */
4083
4084 static void
4085 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4086                                struct die_info *die,
4087                                struct partial_symtab *pst)
4088 {
4089   struct line_header *lh = NULL;
4090   struct attribute *attr;
4091
4092   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4093   if (attr)
4094     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4095   if (lh == NULL)
4096     return;  /* No linetable, so no includes.  */
4097
4098   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4099   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4100
4101   free_line_header (lh);
4102 }
4103
4104 static hashval_t
4105 hash_signatured_type (const void *item)
4106 {
4107   const struct signatured_type *sig_type = item;
4108
4109   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4110   return sig_type->signature;
4111 }
4112
4113 static int
4114 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4115 {
4116   const struct signatured_type *lhs = item_lhs;
4117   const struct signatured_type *rhs = item_rhs;
4118
4119   return lhs->signature == rhs->signature;
4120 }
4121
4122 /* Allocate a hash table for signatured types.  */
4123
4124 static htab_t
4125 allocate_signatured_type_table (struct objfile *objfile)
4126 {
4127   return htab_create_alloc_ex (41,
4128                                hash_signatured_type,
4129                                eq_signatured_type,
4130                                NULL,
4131                                &objfile->objfile_obstack,
4132                                hashtab_obstack_allocate,
4133                                dummy_obstack_deallocate);
4134 }
4135
4136 /* A helper function to add a signatured type CU to a table.  */
4137
4138 static int
4139 add_signatured_type_cu_to_table (void **slot, void *datum)
4140 {
4141   struct signatured_type *sigt = *slot;
4142   struct signatured_type ***datap = datum;
4143
4144   **datap = sigt;
4145   ++*datap;
4146
4147   return 1;
4148 }
4149
4150 /* Create the hash table of all entries in the .debug_types section.
4151    DWO_FILE is a pointer to the DWO file for .debug_types.dwo,
4152    NULL otherwise.
4153    Note: This function processes DWO files only, not DWP files.
4154    The result is a pointer to the hash table or NULL if there are
4155    no types.  */
4156
4157 static htab_t
4158 create_debug_types_hash_table (struct dwo_file *dwo_file,
4159                                VEC (dwarf2_section_info_def) *types)
4160 {
4161   struct objfile *objfile = dwarf2_per_objfile->objfile;
4162   htab_t types_htab = NULL;
4163   int ix;
4164   struct dwarf2_section_info *section;
4165   struct dwarf2_section_info *abbrev_section;
4166
4167   if (VEC_empty (dwarf2_section_info_def, types))
4168     return NULL;
4169
4170   abbrev_section = (dwo_file != NULL
4171                     ? &dwo_file->sections.abbrev
4172                     : &dwarf2_per_objfile->abbrev);
4173
4174   if (dwarf2_read_debug)
4175     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4176                         dwo_file ? ".dwo" : "",
4177                         bfd_get_filename (abbrev_section->asection->owner));
4178
4179   for (ix = 0;
4180        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4181        ++ix)
4182     {
4183       bfd *abfd;
4184       gdb_byte *info_ptr, *end_ptr;
4185       struct dwarf2_section_info *abbrev_section;
4186
4187       dwarf2_read_section (objfile, section);
4188       info_ptr = section->buffer;
4189
4190       if (info_ptr == NULL)
4191         continue;
4192
4193       /* We can't set abfd until now because the section may be empty or
4194          not present, in which case section->asection will be NULL.  */
4195       abfd = section->asection->owner;
4196
4197       if (dwo_file)
4198         abbrev_section = &dwo_file->sections.abbrev;
4199       else
4200         abbrev_section = &dwarf2_per_objfile->abbrev;
4201
4202       if (types_htab == NULL)
4203         {
4204           if (dwo_file)
4205             types_htab = allocate_dwo_unit_table (objfile);
4206           else
4207             types_htab = allocate_signatured_type_table (objfile);
4208         }
4209
4210       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4211          because we don't need to read any dies: the signature is in the
4212          header.  */
4213
4214       end_ptr = info_ptr + section->size;
4215       while (info_ptr < end_ptr)
4216         {
4217           sect_offset offset;
4218           cu_offset type_offset_in_tu;
4219           ULONGEST signature;
4220           struct signatured_type *sig_type;
4221           struct dwo_unit *dwo_tu;
4222           void **slot;
4223           gdb_byte *ptr = info_ptr;
4224           struct comp_unit_head header;
4225           unsigned int length;
4226
4227           offset.sect_off = ptr - section->buffer;
4228
4229           /* We need to read the type's signature in order to build the hash
4230              table, but we don't need anything else just yet.  */
4231
4232           ptr = read_and_check_type_unit_head (&header, section,
4233                                                abbrev_section, ptr,
4234                                                &signature, &type_offset_in_tu);
4235
4236           length = get_cu_length (&header);
4237
4238           /* Skip dummy type units.  */
4239           if (ptr >= info_ptr + length
4240               || peek_abbrev_code (abfd, ptr) == 0)
4241             {
4242               info_ptr += length;
4243               continue;
4244             }
4245
4246           if (dwo_file)
4247             {
4248               sig_type = NULL;
4249               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4250                                        struct dwo_unit);
4251               dwo_tu->dwo_file = dwo_file;
4252               dwo_tu->signature = signature;
4253               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4254               dwo_tu->info_or_types_section = section;
4255               dwo_tu->offset = offset;
4256               dwo_tu->length = length;
4257             }
4258           else
4259             {
4260               /* N.B.: type_offset is not usable if this type uses a DWO file.
4261                  The real type_offset is in the DWO file.  */
4262               dwo_tu = NULL;
4263               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4264                                          struct signatured_type);
4265               sig_type->signature = signature;
4266               sig_type->type_offset_in_tu = type_offset_in_tu;
4267               sig_type->per_cu.objfile = objfile;
4268               sig_type->per_cu.is_debug_types = 1;
4269               sig_type->per_cu.info_or_types_section = section;
4270               sig_type->per_cu.offset = offset;
4271               sig_type->per_cu.length = length;
4272             }
4273
4274           slot = htab_find_slot (types_htab,
4275                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4276                                  INSERT);
4277           gdb_assert (slot != NULL);
4278           if (*slot != NULL)
4279             {
4280               sect_offset dup_offset;
4281
4282               if (dwo_file)
4283                 {
4284                   const struct dwo_unit *dup_tu = *slot;
4285
4286                   dup_offset = dup_tu->offset;
4287                 }
4288               else
4289                 {
4290                   const struct signatured_type *dup_tu = *slot;
4291
4292                   dup_offset = dup_tu->per_cu.offset;
4293                 }
4294
4295               complaint (&symfile_complaints,
4296                          _("debug type entry at offset 0x%x is duplicate to the "
4297                            "entry at offset 0x%x, signature 0x%s"),
4298                          offset.sect_off, dup_offset.sect_off,
4299                          phex (signature, sizeof (signature)));
4300             }
4301           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4302
4303           if (dwarf2_read_debug)
4304             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4305                                 offset.sect_off,
4306                                 phex (signature, sizeof (signature)));
4307
4308           info_ptr += length;
4309         }
4310     }
4311
4312   return types_htab;
4313 }
4314
4315 /* Create the hash table of all entries in the .debug_types section,
4316    and initialize all_type_units.
4317    The result is zero if there is an error (e.g. missing .debug_types section),
4318    otherwise non-zero.  */
4319
4320 static int
4321 create_all_type_units (struct objfile *objfile)
4322 {
4323   htab_t types_htab;
4324   struct signatured_type **iter;
4325
4326   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4327   if (types_htab == NULL)
4328     {
4329       dwarf2_per_objfile->signatured_types = NULL;
4330       return 0;
4331     }
4332
4333   dwarf2_per_objfile->signatured_types = types_htab;
4334
4335   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4336   dwarf2_per_objfile->all_type_units
4337     = obstack_alloc (&objfile->objfile_obstack,
4338                      dwarf2_per_objfile->n_type_units
4339                      * sizeof (struct signatured_type *));
4340   iter = &dwarf2_per_objfile->all_type_units[0];
4341   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4342   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4343               == dwarf2_per_objfile->n_type_units);
4344
4345   return 1;
4346 }
4347
4348 /* Lookup a signature based type for DW_FORM_ref_sig8.
4349    Returns NULL if signature SIG is not present in the table.  */
4350
4351 static struct signatured_type *
4352 lookup_signatured_type (ULONGEST sig)
4353 {
4354   struct signatured_type find_entry, *entry;
4355
4356   if (dwarf2_per_objfile->signatured_types == NULL)
4357     {
4358       complaint (&symfile_complaints,
4359                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4360       return NULL;
4361     }
4362
4363   find_entry.signature = sig;
4364   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4365   return entry;
4366 }
4367 \f
4368 /* Low level DIE reading support.  */
4369
4370 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4371
4372 static void
4373 init_cu_die_reader (struct die_reader_specs *reader,
4374                     struct dwarf2_cu *cu,
4375                     struct dwarf2_section_info *section,
4376                     struct dwo_file *dwo_file)
4377 {
4378   gdb_assert (section->readin && section->buffer != NULL);
4379   reader->abfd = section->asection->owner;
4380   reader->cu = cu;
4381   reader->dwo_file = dwo_file;
4382   reader->die_section = section;
4383   reader->buffer = section->buffer;
4384   reader->buffer_end = section->buffer + section->size;
4385 }
4386
4387 /* Initialize a CU (or TU) and read its DIEs.
4388    If the CU defers to a DWO file, read the DWO file as well.
4389
4390    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4391    Otherwise the table specified in the comp unit header is read in and used.
4392    This is an optimization for when we already have the abbrev table.
4393
4394    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4395    Otherwise, a new CU is allocated with xmalloc.
4396
4397    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4398    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4399
4400    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4401    linker) then DIE_READER_FUNC will not get called.  */
4402
4403 static void
4404 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4405                          struct abbrev_table *abbrev_table,
4406                          int use_existing_cu, int keep,
4407                          die_reader_func_ftype *die_reader_func,
4408                          void *data)
4409 {
4410   struct objfile *objfile = dwarf2_per_objfile->objfile;
4411   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4412   bfd *abfd = section->asection->owner;
4413   struct dwarf2_cu *cu;
4414   gdb_byte *begin_info_ptr, *info_ptr;
4415   struct die_reader_specs reader;
4416   struct die_info *comp_unit_die;
4417   int has_children;
4418   struct attribute *attr;
4419   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4420   struct signatured_type *sig_type = NULL;
4421   struct dwarf2_section_info *abbrev_section;
4422   /* Non-zero if CU currently points to a DWO file and we need to
4423      reread it.  When this happens we need to reread the skeleton die
4424      before we can reread the DWO file.  */
4425   int rereading_dwo_cu = 0;
4426
4427   if (dwarf2_die_debug)
4428     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4429                         this_cu->is_debug_types ? "type" : "comp",
4430                         this_cu->offset.sect_off);
4431
4432   if (use_existing_cu)
4433     gdb_assert (keep);
4434
4435   cleanups = make_cleanup (null_cleanup, NULL);
4436
4437   /* This is cheap if the section is already read in.  */
4438   dwarf2_read_section (objfile, section);
4439
4440   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4441
4442   abbrev_section = get_abbrev_section_for_cu (this_cu);
4443
4444   if (use_existing_cu && this_cu->cu != NULL)
4445     {
4446       cu = this_cu->cu;
4447
4448       /* If this CU is from a DWO file we need to start over, we need to
4449          refetch the attributes from the skeleton CU.
4450          This could be optimized by retrieving those attributes from when we
4451          were here the first time: the previous comp_unit_die was stored in
4452          comp_unit_obstack.  But there's no data yet that we need this
4453          optimization.  */
4454       if (cu->dwo_unit != NULL)
4455         rereading_dwo_cu = 1;
4456     }
4457   else
4458     {
4459       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4460       gdb_assert (this_cu->cu == NULL);
4461
4462       cu = xmalloc (sizeof (*cu));
4463       init_one_comp_unit (cu, this_cu);
4464
4465       /* If an error occurs while loading, release our storage.  */
4466       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4467     }
4468
4469   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4470     {
4471       /* We already have the header, there's no need to read it in again.  */
4472       info_ptr += cu->header.first_die_offset.cu_off;
4473     }
4474   else
4475     {
4476       if (this_cu->is_debug_types)
4477         {
4478           ULONGEST signature;
4479           cu_offset type_offset_in_tu;
4480
4481           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4482                                                     abbrev_section, info_ptr,
4483                                                     &signature,
4484                                                     &type_offset_in_tu);
4485
4486           /* Since per_cu is the first member of struct signatured_type,
4487              we can go from a pointer to one to a pointer to the other.  */
4488           sig_type = (struct signatured_type *) this_cu;
4489           gdb_assert (sig_type->signature == signature);
4490           gdb_assert (sig_type->type_offset_in_tu.cu_off
4491                       == type_offset_in_tu.cu_off);
4492           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4493
4494           /* LENGTH has not been set yet for type units if we're
4495              using .gdb_index.  */
4496           this_cu->length = get_cu_length (&cu->header);
4497
4498           /* Establish the type offset that can be used to lookup the type.  */
4499           sig_type->type_offset_in_section.sect_off =
4500             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4501         }
4502       else
4503         {
4504           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4505                                                     abbrev_section,
4506                                                     info_ptr, 0);
4507
4508           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4509           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4510         }
4511     }
4512
4513   /* Skip dummy compilation units.  */
4514   if (info_ptr >= begin_info_ptr + this_cu->length
4515       || peek_abbrev_code (abfd, info_ptr) == 0)
4516     {
4517       do_cleanups (cleanups);
4518       return;
4519     }
4520
4521   /* If we don't have them yet, read the abbrevs for this compilation unit.
4522      And if we need to read them now, make sure they're freed when we're
4523      done.  Note that it's important that if the CU had an abbrev table
4524      on entry we don't free it when we're done: Somewhere up the call stack
4525      it may be in use.  */
4526   if (abbrev_table != NULL)
4527     {
4528       gdb_assert (cu->abbrev_table == NULL);
4529       gdb_assert (cu->header.abbrev_offset.sect_off
4530                   == abbrev_table->offset.sect_off);
4531       cu->abbrev_table = abbrev_table;
4532     }
4533   else if (cu->abbrev_table == NULL)
4534     {
4535       dwarf2_read_abbrevs (cu, abbrev_section);
4536       make_cleanup (dwarf2_free_abbrev_table, cu);
4537     }
4538   else if (rereading_dwo_cu)
4539     {
4540       dwarf2_free_abbrev_table (cu);
4541       dwarf2_read_abbrevs (cu, abbrev_section);
4542     }
4543
4544   /* Read the top level CU/TU die.  */
4545   init_cu_die_reader (&reader, cu, section, NULL);
4546   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4547
4548   /* If we have a DWO stub, process it and then read in the DWO file.
4549      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4550      a DWO CU, that this test will fail.  */
4551   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4552   if (attr)
4553     {
4554       const char *dwo_name = DW_STRING (attr);
4555       const char *comp_dir_string;
4556       struct dwo_unit *dwo_unit;
4557       ULONGEST signature; /* Or dwo_id.  */
4558       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4559       int i,num_extra_attrs;
4560       struct dwarf2_section_info *dwo_abbrev_section;
4561
4562       if (has_children)
4563         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4564                  " has children (offset 0x%x) [in module %s]"),
4565                this_cu->offset.sect_off, bfd_get_filename (abfd));
4566
4567       /* These attributes aren't processed until later:
4568          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4569          However, the attribute is found in the stub which we won't have later.
4570          In order to not impose this complication on the rest of the code,
4571          we read them here and copy them to the DWO CU/TU die.  */
4572
4573       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4574          DWO file.  */
4575       stmt_list = NULL;
4576       if (! this_cu->is_debug_types)
4577         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4578       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4579       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4580       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4581       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4582
4583       /* There should be a DW_AT_addr_base attribute here (if needed).
4584          We need the value before we can process DW_FORM_GNU_addr_index.  */
4585       cu->addr_base = 0;
4586       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4587       if (attr)
4588         cu->addr_base = DW_UNSND (attr);
4589
4590       /* There should be a DW_AT_ranges_base attribute here (if needed).
4591          We need the value before we can process DW_AT_ranges.  */
4592       cu->ranges_base = 0;
4593       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4594       if (attr)
4595         cu->ranges_base = DW_UNSND (attr);
4596
4597       if (this_cu->is_debug_types)
4598         {
4599           gdb_assert (sig_type != NULL);
4600           signature = sig_type->signature;
4601         }
4602       else
4603         {
4604           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4605           if (! attr)
4606             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4607                    dwo_name);
4608           signature = DW_UNSND (attr);
4609         }
4610
4611       /* We may need the comp_dir in order to find the DWO file.  */
4612       comp_dir_string = NULL;
4613       if (comp_dir)
4614         comp_dir_string = DW_STRING (comp_dir);
4615
4616       if (this_cu->is_debug_types)
4617         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4618       else
4619         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4620                                          signature);
4621
4622       if (dwo_unit == NULL)
4623         {
4624           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4625                    " with ID %s [in module %s]"),
4626                  this_cu->offset.sect_off,
4627                  phex (signature, sizeof (signature)),
4628                  objfile->name);
4629         }
4630
4631       /* Set up for reading the DWO CU/TU.  */
4632       cu->dwo_unit = dwo_unit;
4633       section = dwo_unit->info_or_types_section;
4634       dwarf2_read_section (objfile, section);
4635       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4636       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4637       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4638
4639       if (this_cu->is_debug_types)
4640         {
4641           ULONGEST signature;
4642           cu_offset type_offset_in_tu;
4643
4644           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4645                                                     dwo_abbrev_section,
4646                                                     info_ptr,
4647                                                     &signature,
4648                                                     &type_offset_in_tu);
4649           gdb_assert (sig_type->signature == signature);
4650           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4651           /* For DWOs coming from DWP files, we don't know the CU length
4652              nor the type's offset in the TU until now.  */
4653           dwo_unit->length = get_cu_length (&cu->header);
4654           dwo_unit->type_offset_in_tu = type_offset_in_tu;
4655
4656           /* Establish the type offset that can be used to lookup the type.
4657              For DWO files, we don't know it until now.  */
4658           sig_type->type_offset_in_section.sect_off =
4659             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4660         }
4661       else
4662         {
4663           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4664                                                     dwo_abbrev_section,
4665                                                     info_ptr, 0);
4666           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4667           /* For DWOs coming from DWP files, we don't know the CU length
4668              until now.  */
4669           dwo_unit->length = get_cu_length (&cu->header);
4670         }
4671
4672       /* Discard the original CU's abbrev table, and read the DWO's.  */
4673       if (abbrev_table == NULL)
4674         {
4675           dwarf2_free_abbrev_table (cu);
4676           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4677         }
4678       else
4679         {
4680           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4681           make_cleanup (dwarf2_free_abbrev_table, cu);
4682         }
4683
4684       /* Read in the die, but leave space to copy over the attributes
4685          from the stub.  This has the benefit of simplifying the rest of
4686          the code - all the real work is done here.  */
4687       num_extra_attrs = ((stmt_list != NULL)
4688                          + (low_pc != NULL)
4689                          + (high_pc != NULL)
4690                          + (ranges != NULL)
4691                          + (comp_dir != NULL));
4692       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4693                                   &has_children, num_extra_attrs);
4694
4695       /* Copy over the attributes from the stub to the DWO die.  */
4696       i = comp_unit_die->num_attrs;
4697       if (stmt_list != NULL)
4698         comp_unit_die->attrs[i++] = *stmt_list;
4699       if (low_pc != NULL)
4700         comp_unit_die->attrs[i++] = *low_pc;
4701       if (high_pc != NULL)
4702         comp_unit_die->attrs[i++] = *high_pc;
4703       if (ranges != NULL)
4704         comp_unit_die->attrs[i++] = *ranges;
4705       if (comp_dir != NULL)
4706         comp_unit_die->attrs[i++] = *comp_dir;
4707       comp_unit_die->num_attrs += num_extra_attrs;
4708
4709       /* Skip dummy compilation units.  */
4710       if (info_ptr >= begin_info_ptr + dwo_unit->length
4711           || peek_abbrev_code (abfd, info_ptr) == 0)
4712         {
4713           do_cleanups (cleanups);
4714           return;
4715         }
4716     }
4717
4718   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4719
4720   if (free_cu_cleanup != NULL)
4721     {
4722       if (keep)
4723         {
4724           /* We've successfully allocated this compilation unit.  Let our
4725              caller clean it up when finished with it.  */
4726           discard_cleanups (free_cu_cleanup);
4727
4728           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4729              So we have to manually free the abbrev table.  */
4730           dwarf2_free_abbrev_table (cu);
4731
4732           /* Link this CU into read_in_chain.  */
4733           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4734           dwarf2_per_objfile->read_in_chain = this_cu;
4735         }
4736       else
4737         do_cleanups (free_cu_cleanup);
4738     }
4739
4740   do_cleanups (cleanups);
4741 }
4742
4743 /* Read CU/TU THIS_CU in section SECTION,
4744    but do not follow DW_AT_GNU_dwo_name if present.
4745    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4746    to have already done the lookup to find the DWO/DWP file).
4747
4748    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4749    THIS_CU->is_debug_types, but nothing else.
4750
4751    We fill in THIS_CU->length.
4752
4753    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4754    linker) then DIE_READER_FUNC will not get called.
4755
4756    THIS_CU->cu is always freed when done.
4757    This is done in order to not leave THIS_CU->cu in a state where we have
4758    to care whether it refers to the "main" CU or the DWO CU.  */
4759
4760 static void
4761 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4762                                    struct dwarf2_section_info *abbrev_section,
4763                                    struct dwo_file *dwo_file,
4764                                    die_reader_func_ftype *die_reader_func,
4765                                    void *data)
4766 {
4767   struct objfile *objfile = dwarf2_per_objfile->objfile;
4768   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4769   bfd *abfd = section->asection->owner;
4770   struct dwarf2_cu cu;
4771   gdb_byte *begin_info_ptr, *info_ptr;
4772   struct die_reader_specs reader;
4773   struct cleanup *cleanups;
4774   struct die_info *comp_unit_die;
4775   int has_children;
4776
4777   if (dwarf2_die_debug)
4778     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4779                         this_cu->is_debug_types ? "type" : "comp",
4780                         this_cu->offset.sect_off);
4781
4782   gdb_assert (this_cu->cu == NULL);
4783
4784   /* This is cheap if the section is already read in.  */
4785   dwarf2_read_section (objfile, section);
4786
4787   init_one_comp_unit (&cu, this_cu);
4788
4789   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4790
4791   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4792   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4793                                             abbrev_section, info_ptr,
4794                                             this_cu->is_debug_types);
4795
4796   this_cu->length = get_cu_length (&cu.header);
4797
4798   /* Skip dummy compilation units.  */
4799   if (info_ptr >= begin_info_ptr + this_cu->length
4800       || peek_abbrev_code (abfd, info_ptr) == 0)
4801     {
4802       do_cleanups (cleanups);
4803       return;
4804     }
4805
4806   dwarf2_read_abbrevs (&cu, abbrev_section);
4807   make_cleanup (dwarf2_free_abbrev_table, &cu);
4808
4809   init_cu_die_reader (&reader, &cu, section, dwo_file);
4810   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4811
4812   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4813
4814   do_cleanups (cleanups);
4815 }
4816
4817 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4818    does not lookup the specified DWO file.
4819    This cannot be used to read DWO files.
4820
4821    THIS_CU->cu is always freed when done.
4822    This is done in order to not leave THIS_CU->cu in a state where we have
4823    to care whether it refers to the "main" CU or the DWO CU.
4824    We can revisit this if the data shows there's a performance issue.  */
4825
4826 static void
4827 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4828                                 die_reader_func_ftype *die_reader_func,
4829                                 void *data)
4830 {
4831   init_cutu_and_read_dies_no_follow (this_cu,
4832                                      get_abbrev_section_for_cu (this_cu),
4833                                      NULL,
4834                                      die_reader_func, data);
4835 }
4836
4837 /* Create a psymtab named NAME and assign it to PER_CU.
4838
4839    The caller must fill in the following details:
4840    dirname, textlow, texthigh.  */
4841
4842 static struct partial_symtab *
4843 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4844 {
4845   struct objfile *objfile = per_cu->objfile;
4846   struct partial_symtab *pst;
4847
4848   pst = start_psymtab_common (objfile, objfile->section_offsets,
4849                               name, 0,
4850                               objfile->global_psymbols.next,
4851                               objfile->static_psymbols.next);
4852
4853   pst->psymtabs_addrmap_supported = 1;
4854
4855   /* This is the glue that links PST into GDB's symbol API.  */
4856   pst->read_symtab_private = per_cu;
4857   pst->read_symtab = dwarf2_read_symtab;
4858   per_cu->v.psymtab = pst;
4859
4860   return pst;
4861 }
4862
4863 /* die_reader_func for process_psymtab_comp_unit.  */
4864
4865 static void
4866 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4867                                   gdb_byte *info_ptr,
4868                                   struct die_info *comp_unit_die,
4869                                   int has_children,
4870                                   void *data)
4871 {
4872   struct dwarf2_cu *cu = reader->cu;
4873   struct objfile *objfile = cu->objfile;
4874   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4875   struct attribute *attr;
4876   CORE_ADDR baseaddr;
4877   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4878   struct partial_symtab *pst;
4879   int has_pc_info;
4880   const char *filename;
4881   int *want_partial_unit_ptr = data;
4882
4883   if (comp_unit_die->tag == DW_TAG_partial_unit
4884       && (want_partial_unit_ptr == NULL
4885           || !*want_partial_unit_ptr))
4886     return;
4887
4888   gdb_assert (! per_cu->is_debug_types);
4889
4890   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4891
4892   cu->list_in_scope = &file_symbols;
4893
4894   /* Allocate a new partial symbol table structure.  */
4895   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4896   if (attr == NULL || !DW_STRING (attr))
4897     filename = "";
4898   else
4899     filename = DW_STRING (attr);
4900
4901   pst = create_partial_symtab (per_cu, filename);
4902
4903   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4904   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4905   if (attr != NULL)
4906     pst->dirname = DW_STRING (attr);
4907
4908   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4909
4910   dwarf2_find_base_address (comp_unit_die, cu);
4911
4912   /* Possibly set the default values of LOWPC and HIGHPC from
4913      `DW_AT_ranges'.  */
4914   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4915                                       &best_highpc, cu, pst);
4916   if (has_pc_info == 1 && best_lowpc < best_highpc)
4917     /* Store the contiguous range if it is not empty; it can be empty for
4918        CUs with no code.  */
4919     addrmap_set_empty (objfile->psymtabs_addrmap,
4920                        best_lowpc + baseaddr,
4921                        best_highpc + baseaddr - 1, pst);
4922
4923   /* Check if comp unit has_children.
4924      If so, read the rest of the partial symbols from this comp unit.
4925      If not, there's no more debug_info for this comp unit.  */
4926   if (has_children)
4927     {
4928       struct partial_die_info *first_die;
4929       CORE_ADDR lowpc, highpc;
4930
4931       lowpc = ((CORE_ADDR) -1);
4932       highpc = ((CORE_ADDR) 0);
4933
4934       first_die = load_partial_dies (reader, info_ptr, 1);
4935
4936       scan_partial_symbols (first_die, &lowpc, &highpc,
4937                             ! has_pc_info, cu);
4938
4939       /* If we didn't find a lowpc, set it to highpc to avoid
4940          complaints from `maint check'.  */
4941       if (lowpc == ((CORE_ADDR) -1))
4942         lowpc = highpc;
4943
4944       /* If the compilation unit didn't have an explicit address range,
4945          then use the information extracted from its child dies.  */
4946       if (! has_pc_info)
4947         {
4948           best_lowpc = lowpc;
4949           best_highpc = highpc;
4950         }
4951     }
4952   pst->textlow = best_lowpc + baseaddr;
4953   pst->texthigh = best_highpc + baseaddr;
4954
4955   pst->n_global_syms = objfile->global_psymbols.next -
4956     (objfile->global_psymbols.list + pst->globals_offset);
4957   pst->n_static_syms = objfile->static_psymbols.next -
4958     (objfile->static_psymbols.list + pst->statics_offset);
4959   sort_pst_symbols (objfile, pst);
4960
4961   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
4962     {
4963       int i;
4964       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4965       struct dwarf2_per_cu_data *iter;
4966
4967       /* Fill in 'dependencies' here; we fill in 'users' in a
4968          post-pass.  */
4969       pst->number_of_dependencies = len;
4970       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4971                                          len * sizeof (struct symtab *));
4972       for (i = 0;
4973            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4974                         i, iter);
4975            ++i)
4976         pst->dependencies[i] = iter->v.psymtab;
4977
4978       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4979     }
4980
4981   /* Get the list of files included in the current compilation unit,
4982      and build a psymtab for each of them.  */
4983   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4984
4985   if (dwarf2_read_debug)
4986     {
4987       struct gdbarch *gdbarch = get_objfile_arch (objfile);
4988
4989       fprintf_unfiltered (gdb_stdlog,
4990                           "Psymtab for %s unit @0x%x: %s - %s"
4991                           ", %d global, %d static syms\n",
4992                           per_cu->is_debug_types ? "type" : "comp",
4993                           per_cu->offset.sect_off,
4994                           paddress (gdbarch, pst->textlow),
4995                           paddress (gdbarch, pst->texthigh),
4996                           pst->n_global_syms, pst->n_static_syms);
4997     }
4998 }
4999
5000 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5001    Process compilation unit THIS_CU for a psymtab.  */
5002
5003 static void
5004 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5005                            int want_partial_unit)
5006 {
5007   /* If this compilation unit was already read in, free the
5008      cached copy in order to read it in again.  This is
5009      necessary because we skipped some symbols when we first
5010      read in the compilation unit (see load_partial_dies).
5011      This problem could be avoided, but the benefit is unclear.  */
5012   if (this_cu->cu != NULL)
5013     free_one_cached_comp_unit (this_cu);
5014
5015   gdb_assert (! this_cu->is_debug_types);
5016   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5017                            process_psymtab_comp_unit_reader,
5018                            &want_partial_unit);
5019
5020   /* Age out any secondary CUs.  */
5021   age_cached_comp_units ();
5022 }
5023
5024 static hashval_t
5025 hash_type_unit_group (const void *item)
5026 {
5027   const struct type_unit_group *tu_group = item;
5028
5029   return hash_stmt_list_entry (&tu_group->hash);
5030 }
5031
5032 static int
5033 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5034 {
5035   const struct type_unit_group *lhs = item_lhs;
5036   const struct type_unit_group *rhs = item_rhs;
5037
5038   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5039 }
5040
5041 /* Allocate a hash table for type unit groups.  */
5042
5043 static htab_t
5044 allocate_type_unit_groups_table (void)
5045 {
5046   return htab_create_alloc_ex (3,
5047                                hash_type_unit_group,
5048                                eq_type_unit_group,
5049                                NULL,
5050                                &dwarf2_per_objfile->objfile->objfile_obstack,
5051                                hashtab_obstack_allocate,
5052                                dummy_obstack_deallocate);
5053 }
5054
5055 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5056    partial symtabs.  We combine several TUs per psymtab to not let the size
5057    of any one psymtab grow too big.  */
5058 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5059 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5060
5061 /* Helper routine for get_type_unit_group.
5062    Create the type_unit_group object used to hold one or more TUs.  */
5063
5064 static struct type_unit_group *
5065 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5066 {
5067   struct objfile *objfile = dwarf2_per_objfile->objfile;
5068   struct dwarf2_per_cu_data *per_cu;
5069   struct type_unit_group *tu_group;
5070
5071   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5072                              struct type_unit_group);
5073   per_cu = &tu_group->per_cu;
5074   per_cu->objfile = objfile;
5075   per_cu->is_debug_types = 1;
5076   per_cu->type_unit_group = tu_group;
5077
5078   if (dwarf2_per_objfile->using_index)
5079     {
5080       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5081                                         struct dwarf2_per_cu_quick_data);
5082       tu_group->t.first_tu = cu->per_cu;
5083     }
5084   else
5085     {
5086       unsigned int line_offset = line_offset_struct.sect_off;
5087       struct partial_symtab *pst;
5088       char *name;
5089
5090       /* Give the symtab a useful name for debug purposes.  */
5091       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5092         name = xstrprintf ("<type_units_%d>",
5093                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5094       else
5095         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5096
5097       pst = create_partial_symtab (per_cu, name);
5098       pst->anonymous = 1;
5099
5100       xfree (name);
5101     }
5102
5103   tu_group->hash.dwo_unit = cu->dwo_unit;
5104   tu_group->hash.line_offset = line_offset_struct;
5105
5106   return tu_group;
5107 }
5108
5109 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5110    STMT_LIST is a DW_AT_stmt_list attribute.  */
5111
5112 static struct type_unit_group *
5113 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5114 {
5115   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5116   struct type_unit_group *tu_group;
5117   void **slot;
5118   unsigned int line_offset;
5119   struct type_unit_group type_unit_group_for_lookup;
5120
5121   if (dwarf2_per_objfile->type_unit_groups == NULL)
5122     {
5123       dwarf2_per_objfile->type_unit_groups =
5124         allocate_type_unit_groups_table ();
5125     }
5126
5127   /* Do we need to create a new group, or can we use an existing one?  */
5128
5129   if (stmt_list)
5130     {
5131       line_offset = DW_UNSND (stmt_list);
5132       ++tu_stats->nr_symtab_sharers;
5133     }
5134   else
5135     {
5136       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5137          We can do various things here like create one group per TU or
5138          spread them over multiple groups to split up the expansion work.
5139          To avoid worst case scenarios (too many groups or too large groups)
5140          we, umm, group them in bunches.  */
5141       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5142                      | (tu_stats->nr_stmt_less_type_units
5143                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5144       ++tu_stats->nr_stmt_less_type_units;
5145     }
5146
5147   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5148   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5149   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5150                          &type_unit_group_for_lookup, INSERT);
5151   if (*slot != NULL)
5152     {
5153       tu_group = *slot;
5154       gdb_assert (tu_group != NULL);
5155     }
5156   else
5157     {
5158       sect_offset line_offset_struct;
5159
5160       line_offset_struct.sect_off = line_offset;
5161       tu_group = create_type_unit_group (cu, line_offset_struct);
5162       *slot = tu_group;
5163       ++tu_stats->nr_symtabs;
5164     }
5165
5166   return tu_group;
5167 }
5168
5169 /* Struct used to sort TUs by their abbreviation table offset.  */
5170
5171 struct tu_abbrev_offset
5172 {
5173   struct signatured_type *sig_type;
5174   sect_offset abbrev_offset;
5175 };
5176
5177 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5178
5179 static int
5180 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5181 {
5182   const struct tu_abbrev_offset * const *a = ap;
5183   const struct tu_abbrev_offset * const *b = bp;
5184   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5185   unsigned int boff = (*b)->abbrev_offset.sect_off;
5186
5187   return (aoff > boff) - (aoff < boff);
5188 }
5189
5190 /* A helper function to add a type_unit_group to a table.  */
5191
5192 static int
5193 add_type_unit_group_to_table (void **slot, void *datum)
5194 {
5195   struct type_unit_group *tu_group = *slot;
5196   struct type_unit_group ***datap = datum;
5197
5198   **datap = tu_group;
5199   ++*datap;
5200
5201   return 1;
5202 }
5203
5204 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5205    each one passing FUNC,DATA.
5206
5207    The efficiency is because we sort TUs by the abbrev table they use and
5208    only read each abbrev table once.  In one program there are 200K TUs
5209    sharing 8K abbrev tables.
5210
5211    The main purpose of this function is to support building the
5212    dwarf2_per_objfile->type_unit_groups table.
5213    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5214    can collapse the search space by grouping them by stmt_list.
5215    The savings can be significant, in the same program from above the 200K TUs
5216    share 8K stmt_list tables.
5217
5218    FUNC is expected to call get_type_unit_group, which will create the
5219    struct type_unit_group if necessary and add it to
5220    dwarf2_per_objfile->type_unit_groups.  */
5221
5222 static void
5223 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5224 {
5225   struct objfile *objfile = dwarf2_per_objfile->objfile;
5226   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5227   struct cleanup *cleanups;
5228   struct abbrev_table *abbrev_table;
5229   sect_offset abbrev_offset;
5230   struct tu_abbrev_offset *sorted_by_abbrev;
5231   struct type_unit_group **iter;
5232   int i;
5233
5234   /* It's up to the caller to not call us multiple times.  */
5235   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5236
5237   if (dwarf2_per_objfile->n_type_units == 0)
5238     return;
5239
5240   /* TUs typically share abbrev tables, and there can be way more TUs than
5241      abbrev tables.  Sort by abbrev table to reduce the number of times we
5242      read each abbrev table in.
5243      Alternatives are to punt or to maintain a cache of abbrev tables.
5244      This is simpler and efficient enough for now.
5245
5246      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5247      symtab to use).  Typically TUs with the same abbrev offset have the same
5248      stmt_list value too so in practice this should work well.
5249
5250      The basic algorithm here is:
5251
5252       sort TUs by abbrev table
5253       for each TU with same abbrev table:
5254         read abbrev table if first user
5255         read TU top level DIE
5256           [IWBN if DWO skeletons had DW_AT_stmt_list]
5257         call FUNC  */
5258
5259   if (dwarf2_read_debug)
5260     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5261
5262   /* Sort in a separate table to maintain the order of all_type_units
5263      for .gdb_index: TU indices directly index all_type_units.  */
5264   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5265                               dwarf2_per_objfile->n_type_units);
5266   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5267     {
5268       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5269
5270       sorted_by_abbrev[i].sig_type = sig_type;
5271       sorted_by_abbrev[i].abbrev_offset =
5272         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
5273                             sig_type->per_cu.offset);
5274     }
5275   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5276   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5277          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5278
5279   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5280      called any number of times, so we don't reset tu_stats here.  */
5281
5282   abbrev_offset.sect_off = ~(unsigned) 0;
5283   abbrev_table = NULL;
5284   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5285
5286   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5287     {
5288       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5289
5290       /* Switch to the next abbrev table if necessary.  */
5291       if (abbrev_table == NULL
5292           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5293         {
5294           if (abbrev_table != NULL)
5295             {
5296               abbrev_table_free (abbrev_table);
5297               /* Reset to NULL in case abbrev_table_read_table throws
5298                  an error: abbrev_table_free_cleanup will get called.  */
5299               abbrev_table = NULL;
5300             }
5301           abbrev_offset = tu->abbrev_offset;
5302           abbrev_table =
5303             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5304                                      abbrev_offset);
5305           ++tu_stats->nr_uniq_abbrev_tables;
5306         }
5307
5308       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5309                                func, data);
5310     }
5311
5312   /* Create a vector of pointers to primary type units to make it easy to
5313      iterate over them and CUs.  See dw2_get_primary_cu.  */
5314   dwarf2_per_objfile->n_type_unit_groups =
5315     htab_elements (dwarf2_per_objfile->type_unit_groups);
5316   dwarf2_per_objfile->all_type_unit_groups =
5317     obstack_alloc (&objfile->objfile_obstack,
5318                    dwarf2_per_objfile->n_type_unit_groups
5319                    * sizeof (struct type_unit_group *));
5320   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5321   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5322                           add_type_unit_group_to_table, &iter);
5323   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5324               == dwarf2_per_objfile->n_type_unit_groups);
5325
5326   do_cleanups (cleanups);
5327
5328   if (dwarf2_read_debug)
5329     {
5330       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5331       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5332                           dwarf2_per_objfile->n_type_units);
5333       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5334                           tu_stats->nr_uniq_abbrev_tables);
5335       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5336                           tu_stats->nr_symtabs);
5337       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5338                           tu_stats->nr_symtab_sharers);
5339       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5340                           tu_stats->nr_stmt_less_type_units);
5341     }
5342 }
5343
5344 /* Reader function for build_type_psymtabs.  */
5345
5346 static void
5347 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5348                             gdb_byte *info_ptr,
5349                             struct die_info *type_unit_die,
5350                             int has_children,
5351                             void *data)
5352 {
5353   struct objfile *objfile = dwarf2_per_objfile->objfile;
5354   struct dwarf2_cu *cu = reader->cu;
5355   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5356   struct type_unit_group *tu_group;
5357   struct attribute *attr;
5358   struct partial_die_info *first_die;
5359   CORE_ADDR lowpc, highpc;
5360   struct partial_symtab *pst;
5361
5362   gdb_assert (data == NULL);
5363
5364   if (! has_children)
5365     return;
5366
5367   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5368   tu_group = get_type_unit_group (cu, attr);
5369
5370   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5371
5372   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5373   cu->list_in_scope = &file_symbols;
5374   pst = create_partial_symtab (per_cu, "");
5375   pst->anonymous = 1;
5376
5377   first_die = load_partial_dies (reader, info_ptr, 1);
5378
5379   lowpc = (CORE_ADDR) -1;
5380   highpc = (CORE_ADDR) 0;
5381   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5382
5383   pst->n_global_syms = objfile->global_psymbols.next -
5384     (objfile->global_psymbols.list + pst->globals_offset);
5385   pst->n_static_syms = objfile->static_psymbols.next -
5386     (objfile->static_psymbols.list + pst->statics_offset);
5387   sort_pst_symbols (objfile, pst);
5388 }
5389
5390 /* Traversal function for build_type_psymtabs.  */
5391
5392 static int
5393 build_type_psymtab_dependencies (void **slot, void *info)
5394 {
5395   struct objfile *objfile = dwarf2_per_objfile->objfile;
5396   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5397   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5398   struct partial_symtab *pst = per_cu->v.psymtab;
5399   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5400   struct dwarf2_per_cu_data *iter;
5401   int i;
5402
5403   gdb_assert (len > 0);
5404
5405   pst->number_of_dependencies = len;
5406   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5407                                      len * sizeof (struct psymtab *));
5408   for (i = 0;
5409        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5410        ++i)
5411     {
5412       pst->dependencies[i] = iter->v.psymtab;
5413       iter->type_unit_group = tu_group;
5414     }
5415
5416   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5417
5418   return 1;
5419 }
5420
5421 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5422    Build partial symbol tables for the .debug_types comp-units.  */
5423
5424 static void
5425 build_type_psymtabs (struct objfile *objfile)
5426 {
5427   if (! create_all_type_units (objfile))
5428     return;
5429
5430   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5431
5432   /* Now that all TUs have been processed we can fill in the dependencies.  */
5433   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5434                           build_type_psymtab_dependencies, NULL);
5435 }
5436
5437 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5438
5439 static void
5440 psymtabs_addrmap_cleanup (void *o)
5441 {
5442   struct objfile *objfile = o;
5443
5444   objfile->psymtabs_addrmap = NULL;
5445 }
5446
5447 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5448
5449 static void
5450 set_partial_user (struct objfile *objfile)
5451 {
5452   int i;
5453
5454   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5455     {
5456       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5457       struct partial_symtab *pst = per_cu->v.psymtab;
5458       int j;
5459
5460       if (pst == NULL)
5461         continue;
5462
5463       for (j = 0; j < pst->number_of_dependencies; ++j)
5464         {
5465           /* Set the 'user' field only if it is not already set.  */
5466           if (pst->dependencies[j]->user == NULL)
5467             pst->dependencies[j]->user = pst;
5468         }
5469     }
5470 }
5471
5472 /* Build the partial symbol table by doing a quick pass through the
5473    .debug_info and .debug_abbrev sections.  */
5474
5475 static void
5476 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5477 {
5478   struct cleanup *back_to, *addrmap_cleanup;
5479   struct obstack temp_obstack;
5480   int i;
5481
5482   if (dwarf2_read_debug)
5483     {
5484       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5485                           objfile->name);
5486     }
5487
5488   dwarf2_per_objfile->reading_partial_symbols = 1;
5489
5490   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5491
5492   /* Any cached compilation units will be linked by the per-objfile
5493      read_in_chain.  Make sure to free them when we're done.  */
5494   back_to = make_cleanup (free_cached_comp_units, NULL);
5495
5496   build_type_psymtabs (objfile);
5497
5498   create_all_comp_units (objfile);
5499
5500   /* Create a temporary address map on a temporary obstack.  We later
5501      copy this to the final obstack.  */
5502   obstack_init (&temp_obstack);
5503   make_cleanup_obstack_free (&temp_obstack);
5504   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5505   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5506
5507   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5508     {
5509       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5510
5511       process_psymtab_comp_unit (per_cu, 0);
5512     }
5513
5514   set_partial_user (objfile);
5515
5516   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5517                                                     &objfile->objfile_obstack);
5518   discard_cleanups (addrmap_cleanup);
5519
5520   do_cleanups (back_to);
5521
5522   if (dwarf2_read_debug)
5523     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5524                         objfile->name);
5525 }
5526
5527 /* die_reader_func for load_partial_comp_unit.  */
5528
5529 static void
5530 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5531                                gdb_byte *info_ptr,
5532                                struct die_info *comp_unit_die,
5533                                int has_children,
5534                                void *data)
5535 {
5536   struct dwarf2_cu *cu = reader->cu;
5537
5538   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5539
5540   /* Check if comp unit has_children.
5541      If so, read the rest of the partial symbols from this comp unit.
5542      If not, there's no more debug_info for this comp unit.  */
5543   if (has_children)
5544     load_partial_dies (reader, info_ptr, 0);
5545 }
5546
5547 /* Load the partial DIEs for a secondary CU into memory.
5548    This is also used when rereading a primary CU with load_all_dies.  */
5549
5550 static void
5551 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5552 {
5553   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5554                            load_partial_comp_unit_reader, NULL);
5555 }
5556
5557 static void
5558 read_comp_units_from_section (struct objfile *objfile,
5559                               struct dwarf2_section_info *section,
5560                               unsigned int is_dwz,
5561                               int *n_allocated,
5562                               int *n_comp_units,
5563                               struct dwarf2_per_cu_data ***all_comp_units)
5564 {
5565   gdb_byte *info_ptr;
5566   bfd *abfd = section->asection->owner;
5567
5568   dwarf2_read_section (objfile, section);
5569
5570   info_ptr = section->buffer;
5571
5572   while (info_ptr < section->buffer + section->size)
5573     {
5574       unsigned int length, initial_length_size;
5575       struct dwarf2_per_cu_data *this_cu;
5576       sect_offset offset;
5577
5578       offset.sect_off = info_ptr - section->buffer;
5579
5580       /* Read just enough information to find out where the next
5581          compilation unit is.  */
5582       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5583
5584       /* Save the compilation unit for later lookup.  */
5585       this_cu = obstack_alloc (&objfile->objfile_obstack,
5586                                sizeof (struct dwarf2_per_cu_data));
5587       memset (this_cu, 0, sizeof (*this_cu));
5588       this_cu->offset = offset;
5589       this_cu->length = length + initial_length_size;
5590       this_cu->is_dwz = is_dwz;
5591       this_cu->objfile = objfile;
5592       this_cu->info_or_types_section = section;
5593
5594       if (*n_comp_units == *n_allocated)
5595         {
5596           *n_allocated *= 2;
5597           *all_comp_units = xrealloc (*all_comp_units,
5598                                       *n_allocated
5599                                       * sizeof (struct dwarf2_per_cu_data *));
5600         }
5601       (*all_comp_units)[*n_comp_units] = this_cu;
5602       ++*n_comp_units;
5603
5604       info_ptr = info_ptr + this_cu->length;
5605     }
5606 }
5607
5608 /* Create a list of all compilation units in OBJFILE.
5609    This is only done for -readnow and building partial symtabs.  */
5610
5611 static void
5612 create_all_comp_units (struct objfile *objfile)
5613 {
5614   int n_allocated;
5615   int n_comp_units;
5616   struct dwarf2_per_cu_data **all_comp_units;
5617
5618   n_comp_units = 0;
5619   n_allocated = 10;
5620   all_comp_units = xmalloc (n_allocated
5621                             * sizeof (struct dwarf2_per_cu_data *));
5622
5623   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5624                                 &n_allocated, &n_comp_units, &all_comp_units);
5625
5626   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5627     {
5628       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5629
5630       read_comp_units_from_section (objfile, &dwz->info, 1,
5631                                     &n_allocated, &n_comp_units,
5632                                     &all_comp_units);
5633     }
5634
5635   dwarf2_per_objfile->all_comp_units
5636     = obstack_alloc (&objfile->objfile_obstack,
5637                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5638   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5639           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5640   xfree (all_comp_units);
5641   dwarf2_per_objfile->n_comp_units = n_comp_units;
5642 }
5643
5644 /* Process all loaded DIEs for compilation unit CU, starting at
5645    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5646    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5647    DW_AT_ranges).  If NEED_PC is set, then this function will set
5648    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5649    and record the covered ranges in the addrmap.  */
5650
5651 static void
5652 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5653                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5654 {
5655   struct partial_die_info *pdi;
5656
5657   /* Now, march along the PDI's, descending into ones which have
5658      interesting children but skipping the children of the other ones,
5659      until we reach the end of the compilation unit.  */
5660
5661   pdi = first_die;
5662
5663   while (pdi != NULL)
5664     {
5665       fixup_partial_die (pdi, cu);
5666
5667       /* Anonymous namespaces or modules have no name but have interesting
5668          children, so we need to look at them.  Ditto for anonymous
5669          enums.  */
5670
5671       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5672           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5673           || pdi->tag == DW_TAG_imported_unit)
5674         {
5675           switch (pdi->tag)
5676             {
5677             case DW_TAG_subprogram:
5678               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5679               break;
5680             case DW_TAG_constant:
5681             case DW_TAG_variable:
5682             case DW_TAG_typedef:
5683             case DW_TAG_union_type:
5684               if (!pdi->is_declaration)
5685                 {
5686                   add_partial_symbol (pdi, cu);
5687                 }
5688               break;
5689             case DW_TAG_class_type:
5690             case DW_TAG_interface_type:
5691             case DW_TAG_structure_type:
5692               if (!pdi->is_declaration)
5693                 {
5694                   add_partial_symbol (pdi, cu);
5695                 }
5696               break;
5697             case DW_TAG_enumeration_type:
5698               if (!pdi->is_declaration)
5699                 add_partial_enumeration (pdi, cu);
5700               break;
5701             case DW_TAG_base_type:
5702             case DW_TAG_subrange_type:
5703               /* File scope base type definitions are added to the partial
5704                  symbol table.  */
5705               add_partial_symbol (pdi, cu);
5706               break;
5707             case DW_TAG_namespace:
5708               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5709               break;
5710             case DW_TAG_module:
5711               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5712               break;
5713             case DW_TAG_imported_unit:
5714               {
5715                 struct dwarf2_per_cu_data *per_cu;
5716
5717                 /* For now we don't handle imported units in type units.  */
5718                 if (cu->per_cu->is_debug_types)
5719                   {
5720                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5721                              " supported in type units [in module %s]"),
5722                            cu->objfile->name);
5723                   }
5724
5725                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5726                                                            pdi->is_dwz,
5727                                                            cu->objfile);
5728
5729                 /* Go read the partial unit, if needed.  */
5730                 if (per_cu->v.psymtab == NULL)
5731                   process_psymtab_comp_unit (per_cu, 1);
5732
5733                 VEC_safe_push (dwarf2_per_cu_ptr,
5734                                cu->per_cu->imported_symtabs, per_cu);
5735               }
5736               break;
5737             default:
5738               break;
5739             }
5740         }
5741
5742       /* If the die has a sibling, skip to the sibling.  */
5743
5744       pdi = pdi->die_sibling;
5745     }
5746 }
5747
5748 /* Functions used to compute the fully scoped name of a partial DIE.
5749
5750    Normally, this is simple.  For C++, the parent DIE's fully scoped
5751    name is concatenated with "::" and the partial DIE's name.  For
5752    Java, the same thing occurs except that "." is used instead of "::".
5753    Enumerators are an exception; they use the scope of their parent
5754    enumeration type, i.e. the name of the enumeration type is not
5755    prepended to the enumerator.
5756
5757    There are two complexities.  One is DW_AT_specification; in this
5758    case "parent" means the parent of the target of the specification,
5759    instead of the direct parent of the DIE.  The other is compilers
5760    which do not emit DW_TAG_namespace; in this case we try to guess
5761    the fully qualified name of structure types from their members'
5762    linkage names.  This must be done using the DIE's children rather
5763    than the children of any DW_AT_specification target.  We only need
5764    to do this for structures at the top level, i.e. if the target of
5765    any DW_AT_specification (if any; otherwise the DIE itself) does not
5766    have a parent.  */
5767
5768 /* Compute the scope prefix associated with PDI's parent, in
5769    compilation unit CU.  The result will be allocated on CU's
5770    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5771    field.  NULL is returned if no prefix is necessary.  */
5772 static const char *
5773 partial_die_parent_scope (struct partial_die_info *pdi,
5774                           struct dwarf2_cu *cu)
5775 {
5776   const char *grandparent_scope;
5777   struct partial_die_info *parent, *real_pdi;
5778
5779   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5780      then this means the parent of the specification DIE.  */
5781
5782   real_pdi = pdi;
5783   while (real_pdi->has_specification)
5784     real_pdi = find_partial_die (real_pdi->spec_offset,
5785                                  real_pdi->spec_is_dwz, cu);
5786
5787   parent = real_pdi->die_parent;
5788   if (parent == NULL)
5789     return NULL;
5790
5791   if (parent->scope_set)
5792     return parent->scope;
5793
5794   fixup_partial_die (parent, cu);
5795
5796   grandparent_scope = partial_die_parent_scope (parent, cu);
5797
5798   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5799      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5800      Work around this problem here.  */
5801   if (cu->language == language_cplus
5802       && parent->tag == DW_TAG_namespace
5803       && strcmp (parent->name, "::") == 0
5804       && grandparent_scope == NULL)
5805     {
5806       parent->scope = NULL;
5807       parent->scope_set = 1;
5808       return NULL;
5809     }
5810
5811   if (pdi->tag == DW_TAG_enumerator)
5812     /* Enumerators should not get the name of the enumeration as a prefix.  */
5813     parent->scope = grandparent_scope;
5814   else if (parent->tag == DW_TAG_namespace
5815       || parent->tag == DW_TAG_module
5816       || parent->tag == DW_TAG_structure_type
5817       || parent->tag == DW_TAG_class_type
5818       || parent->tag == DW_TAG_interface_type
5819       || parent->tag == DW_TAG_union_type
5820       || parent->tag == DW_TAG_enumeration_type)
5821     {
5822       if (grandparent_scope == NULL)
5823         parent->scope = parent->name;
5824       else
5825         parent->scope = typename_concat (&cu->comp_unit_obstack,
5826                                          grandparent_scope,
5827                                          parent->name, 0, cu);
5828     }
5829   else
5830     {
5831       /* FIXME drow/2004-04-01: What should we be doing with
5832          function-local names?  For partial symbols, we should probably be
5833          ignoring them.  */
5834       complaint (&symfile_complaints,
5835                  _("unhandled containing DIE tag %d for DIE at %d"),
5836                  parent->tag, pdi->offset.sect_off);
5837       parent->scope = grandparent_scope;
5838     }
5839
5840   parent->scope_set = 1;
5841   return parent->scope;
5842 }
5843
5844 /* Return the fully scoped name associated with PDI, from compilation unit
5845    CU.  The result will be allocated with malloc.  */
5846
5847 static char *
5848 partial_die_full_name (struct partial_die_info *pdi,
5849                        struct dwarf2_cu *cu)
5850 {
5851   const char *parent_scope;
5852
5853   /* If this is a template instantiation, we can not work out the
5854      template arguments from partial DIEs.  So, unfortunately, we have
5855      to go through the full DIEs.  At least any work we do building
5856      types here will be reused if full symbols are loaded later.  */
5857   if (pdi->has_template_arguments)
5858     {
5859       fixup_partial_die (pdi, cu);
5860
5861       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5862         {
5863           struct die_info *die;
5864           struct attribute attr;
5865           struct dwarf2_cu *ref_cu = cu;
5866
5867           /* DW_FORM_ref_addr is using section offset.  */
5868           attr.name = 0;
5869           attr.form = DW_FORM_ref_addr;
5870           attr.u.unsnd = pdi->offset.sect_off;
5871           die = follow_die_ref (NULL, &attr, &ref_cu);
5872
5873           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5874         }
5875     }
5876
5877   parent_scope = partial_die_parent_scope (pdi, cu);
5878   if (parent_scope == NULL)
5879     return NULL;
5880   else
5881     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5882 }
5883
5884 static void
5885 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5886 {
5887   struct objfile *objfile = cu->objfile;
5888   CORE_ADDR addr = 0;
5889   const char *actual_name = NULL;
5890   CORE_ADDR baseaddr;
5891   char *built_actual_name;
5892
5893   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5894
5895   built_actual_name = partial_die_full_name (pdi, cu);
5896   if (built_actual_name != NULL)
5897     actual_name = built_actual_name;
5898
5899   if (actual_name == NULL)
5900     actual_name = pdi->name;
5901
5902   switch (pdi->tag)
5903     {
5904     case DW_TAG_subprogram:
5905       if (pdi->is_external || cu->language == language_ada)
5906         {
5907           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5908              of the global scope.  But in Ada, we want to be able to access
5909              nested procedures globally.  So all Ada subprograms are stored
5910              in the global scope.  */
5911           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5912              mst_text, objfile); */
5913           add_psymbol_to_list (actual_name, strlen (actual_name),
5914                                built_actual_name != NULL,
5915                                VAR_DOMAIN, LOC_BLOCK,
5916                                &objfile->global_psymbols,
5917                                0, pdi->lowpc + baseaddr,
5918                                cu->language, objfile);
5919         }
5920       else
5921         {
5922           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5923              mst_file_text, objfile); */
5924           add_psymbol_to_list (actual_name, strlen (actual_name),
5925                                built_actual_name != NULL,
5926                                VAR_DOMAIN, LOC_BLOCK,
5927                                &objfile->static_psymbols,
5928                                0, pdi->lowpc + baseaddr,
5929                                cu->language, objfile);
5930         }
5931       break;
5932     case DW_TAG_constant:
5933       {
5934         struct psymbol_allocation_list *list;
5935
5936         if (pdi->is_external)
5937           list = &objfile->global_psymbols;
5938         else
5939           list = &objfile->static_psymbols;
5940         add_psymbol_to_list (actual_name, strlen (actual_name),
5941                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
5942                              list, 0, 0, cu->language, objfile);
5943       }
5944       break;
5945     case DW_TAG_variable:
5946       if (pdi->d.locdesc)
5947         addr = decode_locdesc (pdi->d.locdesc, cu);
5948
5949       if (pdi->d.locdesc
5950           && addr == 0
5951           && !dwarf2_per_objfile->has_section_at_zero)
5952         {
5953           /* A global or static variable may also have been stripped
5954              out by the linker if unused, in which case its address
5955              will be nullified; do not add such variables into partial
5956              symbol table then.  */
5957         }
5958       else if (pdi->is_external)
5959         {
5960           /* Global Variable.
5961              Don't enter into the minimal symbol tables as there is
5962              a minimal symbol table entry from the ELF symbols already.
5963              Enter into partial symbol table if it has a location
5964              descriptor or a type.
5965              If the location descriptor is missing, new_symbol will create
5966              a LOC_UNRESOLVED symbol, the address of the variable will then
5967              be determined from the minimal symbol table whenever the variable
5968              is referenced.
5969              The address for the partial symbol table entry is not
5970              used by GDB, but it comes in handy for debugging partial symbol
5971              table building.  */
5972
5973           if (pdi->d.locdesc || pdi->has_type)
5974             add_psymbol_to_list (actual_name, strlen (actual_name),
5975                                  built_actual_name != NULL,
5976                                  VAR_DOMAIN, LOC_STATIC,
5977                                  &objfile->global_psymbols,
5978                                  0, addr + baseaddr,
5979                                  cu->language, objfile);
5980         }
5981       else
5982         {
5983           /* Static Variable.  Skip symbols without location descriptors.  */
5984           if (pdi->d.locdesc == NULL)
5985             {
5986               xfree (built_actual_name);
5987               return;
5988             }
5989           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
5990              mst_file_data, objfile); */
5991           add_psymbol_to_list (actual_name, strlen (actual_name),
5992                                built_actual_name != NULL,
5993                                VAR_DOMAIN, LOC_STATIC,
5994                                &objfile->static_psymbols,
5995                                0, addr + baseaddr,
5996                                cu->language, objfile);
5997         }
5998       break;
5999     case DW_TAG_typedef:
6000     case DW_TAG_base_type:
6001     case DW_TAG_subrange_type:
6002       add_psymbol_to_list (actual_name, strlen (actual_name),
6003                            built_actual_name != NULL,
6004                            VAR_DOMAIN, LOC_TYPEDEF,
6005                            &objfile->static_psymbols,
6006                            0, (CORE_ADDR) 0, cu->language, objfile);
6007       break;
6008     case DW_TAG_namespace:
6009       add_psymbol_to_list (actual_name, strlen (actual_name),
6010                            built_actual_name != NULL,
6011                            VAR_DOMAIN, LOC_TYPEDEF,
6012                            &objfile->global_psymbols,
6013                            0, (CORE_ADDR) 0, cu->language, objfile);
6014       break;
6015     case DW_TAG_class_type:
6016     case DW_TAG_interface_type:
6017     case DW_TAG_structure_type:
6018     case DW_TAG_union_type:
6019     case DW_TAG_enumeration_type:
6020       /* Skip external references.  The DWARF standard says in the section
6021          about "Structure, Union, and Class Type Entries": "An incomplete
6022          structure, union or class type is represented by a structure,
6023          union or class entry that does not have a byte size attribute
6024          and that has a DW_AT_declaration attribute."  */
6025       if (!pdi->has_byte_size && pdi->is_declaration)
6026         {
6027           xfree (built_actual_name);
6028           return;
6029         }
6030
6031       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6032          static vs. global.  */
6033       add_psymbol_to_list (actual_name, strlen (actual_name),
6034                            built_actual_name != NULL,
6035                            STRUCT_DOMAIN, LOC_TYPEDEF,
6036                            (cu->language == language_cplus
6037                             || cu->language == language_java)
6038                            ? &objfile->global_psymbols
6039                            : &objfile->static_psymbols,
6040                            0, (CORE_ADDR) 0, cu->language, objfile);
6041
6042       break;
6043     case DW_TAG_enumerator:
6044       add_psymbol_to_list (actual_name, strlen (actual_name),
6045                            built_actual_name != NULL,
6046                            VAR_DOMAIN, LOC_CONST,
6047                            (cu->language == language_cplus
6048                             || cu->language == language_java)
6049                            ? &objfile->global_psymbols
6050                            : &objfile->static_psymbols,
6051                            0, (CORE_ADDR) 0, cu->language, objfile);
6052       break;
6053     default:
6054       break;
6055     }
6056
6057   xfree (built_actual_name);
6058 }
6059
6060 /* Read a partial die corresponding to a namespace; also, add a symbol
6061    corresponding to that namespace to the symbol table.  NAMESPACE is
6062    the name of the enclosing namespace.  */
6063
6064 static void
6065 add_partial_namespace (struct partial_die_info *pdi,
6066                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6067                        int need_pc, struct dwarf2_cu *cu)
6068 {
6069   /* Add a symbol for the namespace.  */
6070
6071   add_partial_symbol (pdi, cu);
6072
6073   /* Now scan partial symbols in that namespace.  */
6074
6075   if (pdi->has_children)
6076     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6077 }
6078
6079 /* Read a partial die corresponding to a Fortran module.  */
6080
6081 static void
6082 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6083                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6084 {
6085   /* Now scan partial symbols in that module.  */
6086
6087   if (pdi->has_children)
6088     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6089 }
6090
6091 /* Read a partial die corresponding to a subprogram and create a partial
6092    symbol for that subprogram.  When the CU language allows it, this
6093    routine also defines a partial symbol for each nested subprogram
6094    that this subprogram contains.
6095
6096    DIE my also be a lexical block, in which case we simply search
6097    recursively for suprograms defined inside that lexical block.
6098    Again, this is only performed when the CU language allows this
6099    type of definitions.  */
6100
6101 static void
6102 add_partial_subprogram (struct partial_die_info *pdi,
6103                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6104                         int need_pc, struct dwarf2_cu *cu)
6105 {
6106   if (pdi->tag == DW_TAG_subprogram)
6107     {
6108       if (pdi->has_pc_info)
6109         {
6110           if (pdi->lowpc < *lowpc)
6111             *lowpc = pdi->lowpc;
6112           if (pdi->highpc > *highpc)
6113             *highpc = pdi->highpc;
6114           if (need_pc)
6115             {
6116               CORE_ADDR baseaddr;
6117               struct objfile *objfile = cu->objfile;
6118
6119               baseaddr = ANOFFSET (objfile->section_offsets,
6120                                    SECT_OFF_TEXT (objfile));
6121               addrmap_set_empty (objfile->psymtabs_addrmap,
6122                                  pdi->lowpc + baseaddr,
6123                                  pdi->highpc - 1 + baseaddr,
6124                                  cu->per_cu->v.psymtab);
6125             }
6126         }
6127
6128       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6129         {
6130           if (!pdi->is_declaration)
6131             /* Ignore subprogram DIEs that do not have a name, they are
6132                illegal.  Do not emit a complaint at this point, we will
6133                do so when we convert this psymtab into a symtab.  */
6134             if (pdi->name)
6135               add_partial_symbol (pdi, cu);
6136         }
6137     }
6138
6139   if (! pdi->has_children)
6140     return;
6141
6142   if (cu->language == language_ada)
6143     {
6144       pdi = pdi->die_child;
6145       while (pdi != NULL)
6146         {
6147           fixup_partial_die (pdi, cu);
6148           if (pdi->tag == DW_TAG_subprogram
6149               || pdi->tag == DW_TAG_lexical_block)
6150             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6151           pdi = pdi->die_sibling;
6152         }
6153     }
6154 }
6155
6156 /* Read a partial die corresponding to an enumeration type.  */
6157
6158 static void
6159 add_partial_enumeration (struct partial_die_info *enum_pdi,
6160                          struct dwarf2_cu *cu)
6161 {
6162   struct partial_die_info *pdi;
6163
6164   if (enum_pdi->name != NULL)
6165     add_partial_symbol (enum_pdi, cu);
6166
6167   pdi = enum_pdi->die_child;
6168   while (pdi)
6169     {
6170       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6171         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6172       else
6173         add_partial_symbol (pdi, cu);
6174       pdi = pdi->die_sibling;
6175     }
6176 }
6177
6178 /* Return the initial uleb128 in the die at INFO_PTR.  */
6179
6180 static unsigned int
6181 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
6182 {
6183   unsigned int bytes_read;
6184
6185   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6186 }
6187
6188 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6189    Return the corresponding abbrev, or NULL if the number is zero (indicating
6190    an empty DIE).  In either case *BYTES_READ will be set to the length of
6191    the initial number.  */
6192
6193 static struct abbrev_info *
6194 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
6195                  struct dwarf2_cu *cu)
6196 {
6197   bfd *abfd = cu->objfile->obfd;
6198   unsigned int abbrev_number;
6199   struct abbrev_info *abbrev;
6200
6201   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6202
6203   if (abbrev_number == 0)
6204     return NULL;
6205
6206   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6207   if (!abbrev)
6208     {
6209       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6210              abbrev_number, bfd_get_filename (abfd));
6211     }
6212
6213   return abbrev;
6214 }
6215
6216 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6217    Returns a pointer to the end of a series of DIEs, terminated by an empty
6218    DIE.  Any children of the skipped DIEs will also be skipped.  */
6219
6220 static gdb_byte *
6221 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
6222 {
6223   struct dwarf2_cu *cu = reader->cu;
6224   struct abbrev_info *abbrev;
6225   unsigned int bytes_read;
6226
6227   while (1)
6228     {
6229       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6230       if (abbrev == NULL)
6231         return info_ptr + bytes_read;
6232       else
6233         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6234     }
6235 }
6236
6237 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6238    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6239    abbrev corresponding to that skipped uleb128 should be passed in
6240    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6241    children.  */
6242
6243 static gdb_byte *
6244 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
6245               struct abbrev_info *abbrev)
6246 {
6247   unsigned int bytes_read;
6248   struct attribute attr;
6249   bfd *abfd = reader->abfd;
6250   struct dwarf2_cu *cu = reader->cu;
6251   gdb_byte *buffer = reader->buffer;
6252   const gdb_byte *buffer_end = reader->buffer_end;
6253   gdb_byte *start_info_ptr = info_ptr;
6254   unsigned int form, i;
6255
6256   for (i = 0; i < abbrev->num_attrs; i++)
6257     {
6258       /* The only abbrev we care about is DW_AT_sibling.  */
6259       if (abbrev->attrs[i].name == DW_AT_sibling)
6260         {
6261           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6262           if (attr.form == DW_FORM_ref_addr)
6263             complaint (&symfile_complaints,
6264                        _("ignoring absolute DW_AT_sibling"));
6265           else
6266             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6267         }
6268
6269       /* If it isn't DW_AT_sibling, skip this attribute.  */
6270       form = abbrev->attrs[i].form;
6271     skip_attribute:
6272       switch (form)
6273         {
6274         case DW_FORM_ref_addr:
6275           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6276              and later it is offset sized.  */
6277           if (cu->header.version == 2)
6278             info_ptr += cu->header.addr_size;
6279           else
6280             info_ptr += cu->header.offset_size;
6281           break;
6282         case DW_FORM_GNU_ref_alt:
6283           info_ptr += cu->header.offset_size;
6284           break;
6285         case DW_FORM_addr:
6286           info_ptr += cu->header.addr_size;
6287           break;
6288         case DW_FORM_data1:
6289         case DW_FORM_ref1:
6290         case DW_FORM_flag:
6291           info_ptr += 1;
6292           break;
6293         case DW_FORM_flag_present:
6294           break;
6295         case DW_FORM_data2:
6296         case DW_FORM_ref2:
6297           info_ptr += 2;
6298           break;
6299         case DW_FORM_data4:
6300         case DW_FORM_ref4:
6301           info_ptr += 4;
6302           break;
6303         case DW_FORM_data8:
6304         case DW_FORM_ref8:
6305         case DW_FORM_ref_sig8:
6306           info_ptr += 8;
6307           break;
6308         case DW_FORM_string:
6309           read_direct_string (abfd, info_ptr, &bytes_read);
6310           info_ptr += bytes_read;
6311           break;
6312         case DW_FORM_sec_offset:
6313         case DW_FORM_strp:
6314         case DW_FORM_GNU_strp_alt:
6315           info_ptr += cu->header.offset_size;
6316           break;
6317         case DW_FORM_exprloc:
6318         case DW_FORM_block:
6319           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6320           info_ptr += bytes_read;
6321           break;
6322         case DW_FORM_block1:
6323           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6324           break;
6325         case DW_FORM_block2:
6326           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6327           break;
6328         case DW_FORM_block4:
6329           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6330           break;
6331         case DW_FORM_sdata:
6332         case DW_FORM_udata:
6333         case DW_FORM_ref_udata:
6334         case DW_FORM_GNU_addr_index:
6335         case DW_FORM_GNU_str_index:
6336           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6337           break;
6338         case DW_FORM_indirect:
6339           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6340           info_ptr += bytes_read;
6341           /* We need to continue parsing from here, so just go back to
6342              the top.  */
6343           goto skip_attribute;
6344
6345         default:
6346           error (_("Dwarf Error: Cannot handle %s "
6347                    "in DWARF reader [in module %s]"),
6348                  dwarf_form_name (form),
6349                  bfd_get_filename (abfd));
6350         }
6351     }
6352
6353   if (abbrev->has_children)
6354     return skip_children (reader, info_ptr);
6355   else
6356     return info_ptr;
6357 }
6358
6359 /* Locate ORIG_PDI's sibling.
6360    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6361
6362 static gdb_byte *
6363 locate_pdi_sibling (const struct die_reader_specs *reader,
6364                     struct partial_die_info *orig_pdi,
6365                     gdb_byte *info_ptr)
6366 {
6367   /* Do we know the sibling already?  */
6368
6369   if (orig_pdi->sibling)
6370     return orig_pdi->sibling;
6371
6372   /* Are there any children to deal with?  */
6373
6374   if (!orig_pdi->has_children)
6375     return info_ptr;
6376
6377   /* Skip the children the long way.  */
6378
6379   return skip_children (reader, info_ptr);
6380 }
6381
6382 /* Expand this partial symbol table into a full symbol table.  SELF is
6383    not NULL.  */
6384
6385 static void
6386 dwarf2_read_symtab (struct partial_symtab *self,
6387                     struct objfile *objfile)
6388 {
6389   if (self->readin)
6390     {
6391       warning (_("bug: psymtab for %s is already read in."),
6392                self->filename);
6393     }
6394   else
6395     {
6396       if (info_verbose)
6397         {
6398           printf_filtered (_("Reading in symbols for %s..."),
6399                            self->filename);
6400           gdb_flush (gdb_stdout);
6401         }
6402
6403       /* Restore our global data.  */
6404       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6405
6406       /* If this psymtab is constructed from a debug-only objfile, the
6407          has_section_at_zero flag will not necessarily be correct.  We
6408          can get the correct value for this flag by looking at the data
6409          associated with the (presumably stripped) associated objfile.  */
6410       if (objfile->separate_debug_objfile_backlink)
6411         {
6412           struct dwarf2_per_objfile *dpo_backlink
6413             = objfile_data (objfile->separate_debug_objfile_backlink,
6414                             dwarf2_objfile_data_key);
6415
6416           dwarf2_per_objfile->has_section_at_zero
6417             = dpo_backlink->has_section_at_zero;
6418         }
6419
6420       dwarf2_per_objfile->reading_partial_symbols = 0;
6421
6422       psymtab_to_symtab_1 (self);
6423
6424       /* Finish up the debug error message.  */
6425       if (info_verbose)
6426         printf_filtered (_("done.\n"));
6427     }
6428
6429   process_cu_includes ();
6430 }
6431 \f
6432 /* Reading in full CUs.  */
6433
6434 /* Add PER_CU to the queue.  */
6435
6436 static void
6437 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6438                  enum language pretend_language)
6439 {
6440   struct dwarf2_queue_item *item;
6441
6442   per_cu->queued = 1;
6443   item = xmalloc (sizeof (*item));
6444   item->per_cu = per_cu;
6445   item->pretend_language = pretend_language;
6446   item->next = NULL;
6447
6448   if (dwarf2_queue == NULL)
6449     dwarf2_queue = item;
6450   else
6451     dwarf2_queue_tail->next = item;
6452
6453   dwarf2_queue_tail = item;
6454 }
6455
6456 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6457    unit and add it to our queue.
6458    The result is non-zero if PER_CU was queued, otherwise the result is zero
6459    meaning either PER_CU is already queued or it is already loaded.  */
6460
6461 static int
6462 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6463                        struct dwarf2_per_cu_data *per_cu,
6464                        enum language pretend_language)
6465 {
6466   /* We may arrive here during partial symbol reading, if we need full
6467      DIEs to process an unusual case (e.g. template arguments).  Do
6468      not queue PER_CU, just tell our caller to load its DIEs.  */
6469   if (dwarf2_per_objfile->reading_partial_symbols)
6470     {
6471       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6472         return 1;
6473       return 0;
6474     }
6475
6476   /* Mark the dependence relation so that we don't flush PER_CU
6477      too early.  */
6478   dwarf2_add_dependence (this_cu, per_cu);
6479
6480   /* If it's already on the queue, we have nothing to do.  */
6481   if (per_cu->queued)
6482     return 0;
6483
6484   /* If the compilation unit is already loaded, just mark it as
6485      used.  */
6486   if (per_cu->cu != NULL)
6487     {
6488       per_cu->cu->last_used = 0;
6489       return 0;
6490     }
6491
6492   /* Add it to the queue.  */
6493   queue_comp_unit (per_cu, pretend_language);
6494
6495   return 1;
6496 }
6497
6498 /* Process the queue.  */
6499
6500 static void
6501 process_queue (void)
6502 {
6503   struct dwarf2_queue_item *item, *next_item;
6504
6505   if (dwarf2_read_debug)
6506     {
6507       fprintf_unfiltered (gdb_stdlog,
6508                           "Expanding one or more symtabs of objfile %s ...\n",
6509                           dwarf2_per_objfile->objfile->name);
6510     }
6511
6512   /* The queue starts out with one item, but following a DIE reference
6513      may load a new CU, adding it to the end of the queue.  */
6514   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6515     {
6516       if (dwarf2_per_objfile->using_index
6517           ? !item->per_cu->v.quick->symtab
6518           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6519         {
6520           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6521
6522           if (dwarf2_read_debug)
6523             {
6524               fprintf_unfiltered (gdb_stdlog,
6525                                   "Expanding symtab of %s at offset 0x%x\n",
6526                                   per_cu->is_debug_types ? "TU" : "CU",
6527                                   per_cu->offset.sect_off);
6528             }
6529
6530           if (per_cu->is_debug_types)
6531             process_full_type_unit (per_cu, item->pretend_language);
6532           else
6533             process_full_comp_unit (per_cu, item->pretend_language);
6534
6535           if (dwarf2_read_debug)
6536             {
6537               fprintf_unfiltered (gdb_stdlog,
6538                                   "Done expanding %s at offset 0x%x\n",
6539                                   per_cu->is_debug_types ? "TU" : "CU",
6540                                   per_cu->offset.sect_off);
6541             }
6542         }
6543
6544       item->per_cu->queued = 0;
6545       next_item = item->next;
6546       xfree (item);
6547     }
6548
6549   dwarf2_queue_tail = NULL;
6550
6551   if (dwarf2_read_debug)
6552     {
6553       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6554                           dwarf2_per_objfile->objfile->name);
6555     }
6556 }
6557
6558 /* Free all allocated queue entries.  This function only releases anything if
6559    an error was thrown; if the queue was processed then it would have been
6560    freed as we went along.  */
6561
6562 static void
6563 dwarf2_release_queue (void *dummy)
6564 {
6565   struct dwarf2_queue_item *item, *last;
6566
6567   item = dwarf2_queue;
6568   while (item)
6569     {
6570       /* Anything still marked queued is likely to be in an
6571          inconsistent state, so discard it.  */
6572       if (item->per_cu->queued)
6573         {
6574           if (item->per_cu->cu != NULL)
6575             free_one_cached_comp_unit (item->per_cu);
6576           item->per_cu->queued = 0;
6577         }
6578
6579       last = item;
6580       item = item->next;
6581       xfree (last);
6582     }
6583
6584   dwarf2_queue = dwarf2_queue_tail = NULL;
6585 }
6586
6587 /* Read in full symbols for PST, and anything it depends on.  */
6588
6589 static void
6590 psymtab_to_symtab_1 (struct partial_symtab *pst)
6591 {
6592   struct dwarf2_per_cu_data *per_cu;
6593   int i;
6594
6595   if (pst->readin)
6596     return;
6597
6598   for (i = 0; i < pst->number_of_dependencies; i++)
6599     if (!pst->dependencies[i]->readin
6600         && pst->dependencies[i]->user == NULL)
6601       {
6602         /* Inform about additional files that need to be read in.  */
6603         if (info_verbose)
6604           {
6605             /* FIXME: i18n: Need to make this a single string.  */
6606             fputs_filtered (" ", gdb_stdout);
6607             wrap_here ("");
6608             fputs_filtered ("and ", gdb_stdout);
6609             wrap_here ("");
6610             printf_filtered ("%s...", pst->dependencies[i]->filename);
6611             wrap_here ("");     /* Flush output.  */
6612             gdb_flush (gdb_stdout);
6613           }
6614         psymtab_to_symtab_1 (pst->dependencies[i]);
6615       }
6616
6617   per_cu = pst->read_symtab_private;
6618
6619   if (per_cu == NULL)
6620     {
6621       /* It's an include file, no symbols to read for it.
6622          Everything is in the parent symtab.  */
6623       pst->readin = 1;
6624       return;
6625     }
6626
6627   dw2_do_instantiate_symtab (per_cu);
6628 }
6629
6630 /* Trivial hash function for die_info: the hash value of a DIE
6631    is its offset in .debug_info for this objfile.  */
6632
6633 static hashval_t
6634 die_hash (const void *item)
6635 {
6636   const struct die_info *die = item;
6637
6638   return die->offset.sect_off;
6639 }
6640
6641 /* Trivial comparison function for die_info structures: two DIEs
6642    are equal if they have the same offset.  */
6643
6644 static int
6645 die_eq (const void *item_lhs, const void *item_rhs)
6646 {
6647   const struct die_info *die_lhs = item_lhs;
6648   const struct die_info *die_rhs = item_rhs;
6649
6650   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6651 }
6652
6653 /* die_reader_func for load_full_comp_unit.
6654    This is identical to read_signatured_type_reader,
6655    but is kept separate for now.  */
6656
6657 static void
6658 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6659                             gdb_byte *info_ptr,
6660                             struct die_info *comp_unit_die,
6661                             int has_children,
6662                             void *data)
6663 {
6664   struct dwarf2_cu *cu = reader->cu;
6665   enum language *language_ptr = data;
6666
6667   gdb_assert (cu->die_hash == NULL);
6668   cu->die_hash =
6669     htab_create_alloc_ex (cu->header.length / 12,
6670                           die_hash,
6671                           die_eq,
6672                           NULL,
6673                           &cu->comp_unit_obstack,
6674                           hashtab_obstack_allocate,
6675                           dummy_obstack_deallocate);
6676
6677   if (has_children)
6678     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6679                                                   &info_ptr, comp_unit_die);
6680   cu->dies = comp_unit_die;
6681   /* comp_unit_die is not stored in die_hash, no need.  */
6682
6683   /* We try not to read any attributes in this function, because not
6684      all CUs needed for references have been loaded yet, and symbol
6685      table processing isn't initialized.  But we have to set the CU language,
6686      or we won't be able to build types correctly.
6687      Similarly, if we do not read the producer, we can not apply
6688      producer-specific interpretation.  */
6689   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6690 }
6691
6692 /* Load the DIEs associated with PER_CU into memory.  */
6693
6694 static void
6695 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6696                      enum language pretend_language)
6697 {
6698   gdb_assert (! this_cu->is_debug_types);
6699
6700   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6701                            load_full_comp_unit_reader, &pretend_language);
6702 }
6703
6704 /* Add a DIE to the delayed physname list.  */
6705
6706 static void
6707 add_to_method_list (struct type *type, int fnfield_index, int index,
6708                     const char *name, struct die_info *die,
6709                     struct dwarf2_cu *cu)
6710 {
6711   struct delayed_method_info mi;
6712   mi.type = type;
6713   mi.fnfield_index = fnfield_index;
6714   mi.index = index;
6715   mi.name = name;
6716   mi.die = die;
6717   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6718 }
6719
6720 /* A cleanup for freeing the delayed method list.  */
6721
6722 static void
6723 free_delayed_list (void *ptr)
6724 {
6725   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6726   if (cu->method_list != NULL)
6727     {
6728       VEC_free (delayed_method_info, cu->method_list);
6729       cu->method_list = NULL;
6730     }
6731 }
6732
6733 /* Compute the physnames of any methods on the CU's method list.
6734
6735    The computation of method physnames is delayed in order to avoid the
6736    (bad) condition that one of the method's formal parameters is of an as yet
6737    incomplete type.  */
6738
6739 static void
6740 compute_delayed_physnames (struct dwarf2_cu *cu)
6741 {
6742   int i;
6743   struct delayed_method_info *mi;
6744   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6745     {
6746       const char *physname;
6747       struct fn_fieldlist *fn_flp
6748         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6749       physname = dwarf2_physname (mi->name, mi->die, cu);
6750       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6751     }
6752 }
6753
6754 /* Go objects should be embedded in a DW_TAG_module DIE,
6755    and it's not clear if/how imported objects will appear.
6756    To keep Go support simple until that's worked out,
6757    go back through what we've read and create something usable.
6758    We could do this while processing each DIE, and feels kinda cleaner,
6759    but that way is more invasive.
6760    This is to, for example, allow the user to type "p var" or "b main"
6761    without having to specify the package name, and allow lookups
6762    of module.object to work in contexts that use the expression
6763    parser.  */
6764
6765 static void
6766 fixup_go_packaging (struct dwarf2_cu *cu)
6767 {
6768   char *package_name = NULL;
6769   struct pending *list;
6770   int i;
6771
6772   for (list = global_symbols; list != NULL; list = list->next)
6773     {
6774       for (i = 0; i < list->nsyms; ++i)
6775         {
6776           struct symbol *sym = list->symbol[i];
6777
6778           if (SYMBOL_LANGUAGE (sym) == language_go
6779               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6780             {
6781               char *this_package_name = go_symbol_package_name (sym);
6782
6783               if (this_package_name == NULL)
6784                 continue;
6785               if (package_name == NULL)
6786                 package_name = this_package_name;
6787               else
6788                 {
6789                   if (strcmp (package_name, this_package_name) != 0)
6790                     complaint (&symfile_complaints,
6791                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6792                                (SYMBOL_SYMTAB (sym)
6793                                 ? SYMBOL_SYMTAB (sym)->filename
6794                                 : cu->objfile->name),
6795                                this_package_name, package_name);
6796                   xfree (this_package_name);
6797                 }
6798             }
6799         }
6800     }
6801
6802   if (package_name != NULL)
6803     {
6804       struct objfile *objfile = cu->objfile;
6805       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6806                                                       package_name,
6807                                                       strlen (package_name));
6808       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6809                                      saved_package_name, objfile);
6810       struct symbol *sym;
6811
6812       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6813
6814       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6815       SYMBOL_SET_LANGUAGE (sym, language_go);
6816       SYMBOL_SET_NAMES (sym, saved_package_name,
6817                         strlen (saved_package_name), 0, objfile);
6818       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6819          e.g., "main" finds the "main" module and not C's main().  */
6820       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6821       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
6822       SYMBOL_TYPE (sym) = type;
6823
6824       add_symbol_to_list (sym, &global_symbols);
6825
6826       xfree (package_name);
6827     }
6828 }
6829
6830 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
6831
6832 /* Return the symtab for PER_CU.  This works properly regardless of
6833    whether we're using the index or psymtabs.  */
6834
6835 static struct symtab *
6836 get_symtab (struct dwarf2_per_cu_data *per_cu)
6837 {
6838   return (dwarf2_per_objfile->using_index
6839           ? per_cu->v.quick->symtab
6840           : per_cu->v.psymtab->symtab);
6841 }
6842
6843 /* A helper function for computing the list of all symbol tables
6844    included by PER_CU.  */
6845
6846 static void
6847 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6848                                 htab_t all_children,
6849                                 struct dwarf2_per_cu_data *per_cu)
6850 {
6851   void **slot;
6852   int ix;
6853   struct dwarf2_per_cu_data *iter;
6854
6855   slot = htab_find_slot (all_children, per_cu, INSERT);
6856   if (*slot != NULL)
6857     {
6858       /* This inclusion and its children have been processed.  */
6859       return;
6860     }
6861
6862   *slot = per_cu;
6863   /* Only add a CU if it has a symbol table.  */
6864   if (get_symtab (per_cu) != NULL)
6865     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6866
6867   for (ix = 0;
6868        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
6869        ++ix)
6870     recursively_compute_inclusions (result, all_children, iter);
6871 }
6872
6873 /* Compute the symtab 'includes' fields for the symtab related to
6874    PER_CU.  */
6875
6876 static void
6877 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6878 {
6879   gdb_assert (! per_cu->is_debug_types);
6880
6881   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
6882     {
6883       int ix, len;
6884       struct dwarf2_per_cu_data *iter;
6885       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6886       htab_t all_children;
6887       struct symtab *symtab = get_symtab (per_cu);
6888
6889       /* If we don't have a symtab, we can just skip this case.  */
6890       if (symtab == NULL)
6891         return;
6892
6893       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6894                                         NULL, xcalloc, xfree);
6895
6896       for (ix = 0;
6897            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
6898                         ix, iter);
6899            ++ix)
6900         recursively_compute_inclusions (&result_children, all_children, iter);
6901
6902       /* Now we have a transitive closure of all the included CUs, and
6903          for .gdb_index version 7 the included TUs, so we can convert it
6904          to a list of symtabs.  */
6905       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6906       symtab->includes
6907         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6908                          (len + 1) * sizeof (struct symtab *));
6909       for (ix = 0;
6910            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6911            ++ix)
6912         symtab->includes[ix] = get_symtab (iter);
6913       symtab->includes[len] = NULL;
6914
6915       VEC_free (dwarf2_per_cu_ptr, result_children);
6916       htab_delete (all_children);
6917     }
6918 }
6919
6920 /* Compute the 'includes' field for the symtabs of all the CUs we just
6921    read.  */
6922
6923 static void
6924 process_cu_includes (void)
6925 {
6926   int ix;
6927   struct dwarf2_per_cu_data *iter;
6928
6929   for (ix = 0;
6930        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6931                     ix, iter);
6932        ++ix)
6933     {
6934       if (! iter->is_debug_types)
6935         compute_symtab_includes (iter);
6936     }
6937
6938   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6939 }
6940
6941 /* Generate full symbol information for PER_CU, whose DIEs have
6942    already been loaded into memory.  */
6943
6944 static void
6945 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6946                         enum language pretend_language)
6947 {
6948   struct dwarf2_cu *cu = per_cu->cu;
6949   struct objfile *objfile = per_cu->objfile;
6950   CORE_ADDR lowpc, highpc;
6951   struct symtab *symtab;
6952   struct cleanup *back_to, *delayed_list_cleanup;
6953   CORE_ADDR baseaddr;
6954   struct block *static_block;
6955
6956   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6957
6958   buildsym_init ();
6959   back_to = make_cleanup (really_free_pendings, NULL);
6960   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6961
6962   cu->list_in_scope = &file_symbols;
6963
6964   cu->language = pretend_language;
6965   cu->language_defn = language_def (cu->language);
6966
6967   /* Do line number decoding in read_file_scope () */
6968   process_die (cu->dies, cu);
6969
6970   /* For now fudge the Go package.  */
6971   if (cu->language == language_go)
6972     fixup_go_packaging (cu);
6973
6974   /* Now that we have processed all the DIEs in the CU, all the types 
6975      should be complete, and it should now be safe to compute all of the
6976      physnames.  */
6977   compute_delayed_physnames (cu);
6978   do_cleanups (delayed_list_cleanup);
6979
6980   /* Some compilers don't define a DW_AT_high_pc attribute for the
6981      compilation unit.  If the DW_AT_high_pc is missing, synthesize
6982      it, by scanning the DIE's below the compilation unit.  */
6983   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
6984
6985   static_block
6986     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
6987                                    per_cu->imported_symtabs != NULL);
6988
6989   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
6990      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
6991      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
6992      addrmap to help ensure it has an accurate map of pc values belonging to
6993      this comp unit.  */
6994   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
6995
6996   symtab = end_symtab_from_static_block (static_block, objfile,
6997                                          SECT_OFF_TEXT (objfile), 0);
6998
6999   if (symtab != NULL)
7000     {
7001       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7002
7003       /* Set symtab language to language from DW_AT_language.  If the
7004          compilation is from a C file generated by language preprocessors, do
7005          not set the language if it was already deduced by start_subfile.  */
7006       if (!(cu->language == language_c && symtab->language != language_c))
7007         symtab->language = cu->language;
7008
7009       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7010          produce DW_AT_location with location lists but it can be possibly
7011          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7012          there were bugs in prologue debug info, fixed later in GCC-4.5
7013          by "unwind info for epilogues" patch (which is not directly related).
7014
7015          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7016          needed, it would be wrong due to missing DW_AT_producer there.
7017
7018          Still one can confuse GDB by using non-standard GCC compilation
7019          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7020          */ 
7021       if (cu->has_loclist && gcc_4_minor >= 5)
7022         symtab->locations_valid = 1;
7023
7024       if (gcc_4_minor >= 5)
7025         symtab->epilogue_unwind_valid = 1;
7026
7027       symtab->call_site_htab = cu->call_site_htab;
7028     }
7029
7030   if (dwarf2_per_objfile->using_index)
7031     per_cu->v.quick->symtab = symtab;
7032   else
7033     {
7034       struct partial_symtab *pst = per_cu->v.psymtab;
7035       pst->symtab = symtab;
7036       pst->readin = 1;
7037     }
7038
7039   /* Push it for inclusion processing later.  */
7040   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7041
7042   do_cleanups (back_to);
7043 }
7044
7045 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7046    already been loaded into memory.  */
7047
7048 static void
7049 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7050                         enum language pretend_language)
7051 {
7052   struct dwarf2_cu *cu = per_cu->cu;
7053   struct objfile *objfile = per_cu->objfile;
7054   struct symtab *symtab;
7055   struct cleanup *back_to, *delayed_list_cleanup;
7056
7057   buildsym_init ();
7058   back_to = make_cleanup (really_free_pendings, NULL);
7059   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7060
7061   cu->list_in_scope = &file_symbols;
7062
7063   cu->language = pretend_language;
7064   cu->language_defn = language_def (cu->language);
7065
7066   /* The symbol tables are set up in read_type_unit_scope.  */
7067   process_die (cu->dies, cu);
7068
7069   /* For now fudge the Go package.  */
7070   if (cu->language == language_go)
7071     fixup_go_packaging (cu);
7072
7073   /* Now that we have processed all the DIEs in the CU, all the types 
7074      should be complete, and it should now be safe to compute all of the
7075      physnames.  */
7076   compute_delayed_physnames (cu);
7077   do_cleanups (delayed_list_cleanup);
7078
7079   /* TUs share symbol tables.
7080      If this is the first TU to use this symtab, complete the construction
7081      of it with end_expandable_symtab.  Otherwise, complete the addition of
7082      this TU's symbols to the existing symtab.  */
7083   if (per_cu->type_unit_group->primary_symtab == NULL)
7084     {
7085       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7086       per_cu->type_unit_group->primary_symtab = symtab;
7087
7088       if (symtab != NULL)
7089         {
7090           /* Set symtab language to language from DW_AT_language.  If the
7091              compilation is from a C file generated by language preprocessors,
7092              do not set the language if it was already deduced by
7093              start_subfile.  */
7094           if (!(cu->language == language_c && symtab->language != language_c))
7095             symtab->language = cu->language;
7096         }
7097     }
7098   else
7099     {
7100       augment_type_symtab (objfile,
7101                            per_cu->type_unit_group->primary_symtab);
7102       symtab = per_cu->type_unit_group->primary_symtab;
7103     }
7104
7105   if (dwarf2_per_objfile->using_index)
7106     per_cu->v.quick->symtab = symtab;
7107   else
7108     {
7109       struct partial_symtab *pst = per_cu->v.psymtab;
7110       pst->symtab = symtab;
7111       pst->readin = 1;
7112     }
7113
7114   do_cleanups (back_to);
7115 }
7116
7117 /* Process an imported unit DIE.  */
7118
7119 static void
7120 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7121 {
7122   struct attribute *attr;
7123
7124   /* For now we don't handle imported units in type units.  */
7125   if (cu->per_cu->is_debug_types)
7126     {
7127       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7128                " supported in type units [in module %s]"),
7129              cu->objfile->name);
7130     }
7131
7132   attr = dwarf2_attr (die, DW_AT_import, cu);
7133   if (attr != NULL)
7134     {
7135       struct dwarf2_per_cu_data *per_cu;
7136       struct symtab *imported_symtab;
7137       sect_offset offset;
7138       int is_dwz;
7139
7140       offset = dwarf2_get_ref_die_offset (attr);
7141       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7142       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7143
7144       /* Queue the unit, if needed.  */
7145       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7146         load_full_comp_unit (per_cu, cu->language);
7147
7148       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7149                      per_cu);
7150     }
7151 }
7152
7153 /* Process a die and its children.  */
7154
7155 static void
7156 process_die (struct die_info *die, struct dwarf2_cu *cu)
7157 {
7158   switch (die->tag)
7159     {
7160     case DW_TAG_padding:
7161       break;
7162     case DW_TAG_compile_unit:
7163     case DW_TAG_partial_unit:
7164       read_file_scope (die, cu);
7165       break;
7166     case DW_TAG_type_unit:
7167       read_type_unit_scope (die, cu);
7168       break;
7169     case DW_TAG_subprogram:
7170     case DW_TAG_inlined_subroutine:
7171       read_func_scope (die, cu);
7172       break;
7173     case DW_TAG_lexical_block:
7174     case DW_TAG_try_block:
7175     case DW_TAG_catch_block:
7176       read_lexical_block_scope (die, cu);
7177       break;
7178     case DW_TAG_GNU_call_site:
7179       read_call_site_scope (die, cu);
7180       break;
7181     case DW_TAG_class_type:
7182     case DW_TAG_interface_type:
7183     case DW_TAG_structure_type:
7184     case DW_TAG_union_type:
7185       process_structure_scope (die, cu);
7186       break;
7187     case DW_TAG_enumeration_type:
7188       process_enumeration_scope (die, cu);
7189       break;
7190
7191     /* These dies have a type, but processing them does not create
7192        a symbol or recurse to process the children.  Therefore we can
7193        read them on-demand through read_type_die.  */
7194     case DW_TAG_subroutine_type:
7195     case DW_TAG_set_type:
7196     case DW_TAG_array_type:
7197     case DW_TAG_pointer_type:
7198     case DW_TAG_ptr_to_member_type:
7199     case DW_TAG_reference_type:
7200     case DW_TAG_string_type:
7201       break;
7202
7203     case DW_TAG_base_type:
7204     case DW_TAG_subrange_type:
7205     case DW_TAG_typedef:
7206       /* Add a typedef symbol for the type definition, if it has a
7207          DW_AT_name.  */
7208       new_symbol (die, read_type_die (die, cu), cu);
7209       break;
7210     case DW_TAG_common_block:
7211       read_common_block (die, cu);
7212       break;
7213     case DW_TAG_common_inclusion:
7214       break;
7215     case DW_TAG_namespace:
7216       cu->processing_has_namespace_info = 1;
7217       read_namespace (die, cu);
7218       break;
7219     case DW_TAG_module:
7220       cu->processing_has_namespace_info = 1;
7221       read_module (die, cu);
7222       break;
7223     case DW_TAG_imported_declaration:
7224     case DW_TAG_imported_module:
7225       cu->processing_has_namespace_info = 1;
7226       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7227                                  || cu->language != language_fortran))
7228         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7229                    dwarf_tag_name (die->tag));
7230       read_import_statement (die, cu);
7231       break;
7232
7233     case DW_TAG_imported_unit:
7234       process_imported_unit_die (die, cu);
7235       break;
7236
7237     default:
7238       new_symbol (die, NULL, cu);
7239       break;
7240     }
7241 }
7242
7243 /* A helper function for dwarf2_compute_name which determines whether DIE
7244    needs to have the name of the scope prepended to the name listed in the
7245    die.  */
7246
7247 static int
7248 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7249 {
7250   struct attribute *attr;
7251
7252   switch (die->tag)
7253     {
7254     case DW_TAG_namespace:
7255     case DW_TAG_typedef:
7256     case DW_TAG_class_type:
7257     case DW_TAG_interface_type:
7258     case DW_TAG_structure_type:
7259     case DW_TAG_union_type:
7260     case DW_TAG_enumeration_type:
7261     case DW_TAG_enumerator:
7262     case DW_TAG_subprogram:
7263     case DW_TAG_member:
7264       return 1;
7265
7266     case DW_TAG_variable:
7267     case DW_TAG_constant:
7268       /* We only need to prefix "globally" visible variables.  These include
7269          any variable marked with DW_AT_external or any variable that
7270          lives in a namespace.  [Variables in anonymous namespaces
7271          require prefixing, but they are not DW_AT_external.]  */
7272
7273       if (dwarf2_attr (die, DW_AT_specification, cu))
7274         {
7275           struct dwarf2_cu *spec_cu = cu;
7276
7277           return die_needs_namespace (die_specification (die, &spec_cu),
7278                                       spec_cu);
7279         }
7280
7281       attr = dwarf2_attr (die, DW_AT_external, cu);
7282       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7283           && die->parent->tag != DW_TAG_module)
7284         return 0;
7285       /* A variable in a lexical block of some kind does not need a
7286          namespace, even though in C++ such variables may be external
7287          and have a mangled name.  */
7288       if (die->parent->tag ==  DW_TAG_lexical_block
7289           || die->parent->tag ==  DW_TAG_try_block
7290           || die->parent->tag ==  DW_TAG_catch_block
7291           || die->parent->tag == DW_TAG_subprogram)
7292         return 0;
7293       return 1;
7294
7295     default:
7296       return 0;
7297     }
7298 }
7299
7300 /* Retrieve the last character from a mem_file.  */
7301
7302 static void
7303 do_ui_file_peek_last (void *object, const char *buffer, long length)
7304 {
7305   char *last_char_p = (char *) object;
7306
7307   if (length > 0)
7308     *last_char_p = buffer[length - 1];
7309 }
7310
7311 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7312    compute the physname for the object, which include a method's:
7313    - formal parameters (C++/Java),
7314    - receiver type (Go),
7315    - return type (Java).
7316
7317    The term "physname" is a bit confusing.
7318    For C++, for example, it is the demangled name.
7319    For Go, for example, it's the mangled name.
7320
7321    For Ada, return the DIE's linkage name rather than the fully qualified
7322    name.  PHYSNAME is ignored..
7323
7324    The result is allocated on the objfile_obstack and canonicalized.  */
7325
7326 static const char *
7327 dwarf2_compute_name (const char *name,
7328                      struct die_info *die, struct dwarf2_cu *cu,
7329                      int physname)
7330 {
7331   struct objfile *objfile = cu->objfile;
7332
7333   if (name == NULL)
7334     name = dwarf2_name (die, cu);
7335
7336   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7337      compute it by typename_concat inside GDB.  */
7338   if (cu->language == language_ada
7339       || (cu->language == language_fortran && physname))
7340     {
7341       /* For Ada unit, we prefer the linkage name over the name, as
7342          the former contains the exported name, which the user expects
7343          to be able to reference.  Ideally, we want the user to be able
7344          to reference this entity using either natural or linkage name,
7345          but we haven't started looking at this enhancement yet.  */
7346       struct attribute *attr;
7347
7348       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7349       if (attr == NULL)
7350         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7351       if (attr && DW_STRING (attr))
7352         return DW_STRING (attr);
7353     }
7354
7355   /* These are the only languages we know how to qualify names in.  */
7356   if (name != NULL
7357       && (cu->language == language_cplus || cu->language == language_java
7358           || cu->language == language_fortran))
7359     {
7360       if (die_needs_namespace (die, cu))
7361         {
7362           long length;
7363           const char *prefix;
7364           struct ui_file *buf;
7365
7366           prefix = determine_prefix (die, cu);
7367           buf = mem_fileopen ();
7368           if (*prefix != '\0')
7369             {
7370               char *prefixed_name = typename_concat (NULL, prefix, name,
7371                                                      physname, cu);
7372
7373               fputs_unfiltered (prefixed_name, buf);
7374               xfree (prefixed_name);
7375             }
7376           else
7377             fputs_unfiltered (name, buf);
7378
7379           /* Template parameters may be specified in the DIE's DW_AT_name, or
7380              as children with DW_TAG_template_type_param or
7381              DW_TAG_value_type_param.  If the latter, add them to the name
7382              here.  If the name already has template parameters, then
7383              skip this step; some versions of GCC emit both, and
7384              it is more efficient to use the pre-computed name.
7385
7386              Something to keep in mind about this process: it is very
7387              unlikely, or in some cases downright impossible, to produce
7388              something that will match the mangled name of a function.
7389              If the definition of the function has the same debug info,
7390              we should be able to match up with it anyway.  But fallbacks
7391              using the minimal symbol, for instance to find a method
7392              implemented in a stripped copy of libstdc++, will not work.
7393              If we do not have debug info for the definition, we will have to
7394              match them up some other way.
7395
7396              When we do name matching there is a related problem with function
7397              templates; two instantiated function templates are allowed to
7398              differ only by their return types, which we do not add here.  */
7399
7400           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7401             {
7402               struct attribute *attr;
7403               struct die_info *child;
7404               int first = 1;
7405
7406               die->building_fullname = 1;
7407
7408               for (child = die->child; child != NULL; child = child->sibling)
7409                 {
7410                   struct type *type;
7411                   LONGEST value;
7412                   gdb_byte *bytes;
7413                   struct dwarf2_locexpr_baton *baton;
7414                   struct value *v;
7415
7416                   if (child->tag != DW_TAG_template_type_param
7417                       && child->tag != DW_TAG_template_value_param)
7418                     continue;
7419
7420                   if (first)
7421                     {
7422                       fputs_unfiltered ("<", buf);
7423                       first = 0;
7424                     }
7425                   else
7426                     fputs_unfiltered (", ", buf);
7427
7428                   attr = dwarf2_attr (child, DW_AT_type, cu);
7429                   if (attr == NULL)
7430                     {
7431                       complaint (&symfile_complaints,
7432                                  _("template parameter missing DW_AT_type"));
7433                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7434                       continue;
7435                     }
7436                   type = die_type (child, cu);
7437
7438                   if (child->tag == DW_TAG_template_type_param)
7439                     {
7440                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7441                       continue;
7442                     }
7443
7444                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7445                   if (attr == NULL)
7446                     {
7447                       complaint (&symfile_complaints,
7448                                  _("template parameter missing "
7449                                    "DW_AT_const_value"));
7450                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7451                       continue;
7452                     }
7453
7454                   dwarf2_const_value_attr (attr, type, name,
7455                                            &cu->comp_unit_obstack, cu,
7456                                            &value, &bytes, &baton);
7457
7458                   if (TYPE_NOSIGN (type))
7459                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7460                        changed, this can use value_print instead.  */
7461                     c_printchar (value, type, buf);
7462                   else
7463                     {
7464                       struct value_print_options opts;
7465
7466                       if (baton != NULL)
7467                         v = dwarf2_evaluate_loc_desc (type, NULL,
7468                                                       baton->data,
7469                                                       baton->size,
7470                                                       baton->per_cu);
7471                       else if (bytes != NULL)
7472                         {
7473                           v = allocate_value (type);
7474                           memcpy (value_contents_writeable (v), bytes,
7475                                   TYPE_LENGTH (type));
7476                         }
7477                       else
7478                         v = value_from_longest (type, value);
7479
7480                       /* Specify decimal so that we do not depend on
7481                          the radix.  */
7482                       get_formatted_print_options (&opts, 'd');
7483                       opts.raw = 1;
7484                       value_print (v, buf, &opts);
7485                       release_value (v);
7486                       value_free (v);
7487                     }
7488                 }
7489
7490               die->building_fullname = 0;
7491
7492               if (!first)
7493                 {
7494                   /* Close the argument list, with a space if necessary
7495                      (nested templates).  */
7496                   char last_char = '\0';
7497                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7498                   if (last_char == '>')
7499                     fputs_unfiltered (" >", buf);
7500                   else
7501                     fputs_unfiltered (">", buf);
7502                 }
7503             }
7504
7505           /* For Java and C++ methods, append formal parameter type
7506              information, if PHYSNAME.  */
7507
7508           if (physname && die->tag == DW_TAG_subprogram
7509               && (cu->language == language_cplus
7510                   || cu->language == language_java))
7511             {
7512               struct type *type = read_type_die (die, cu);
7513
7514               c_type_print_args (type, buf, 1, cu->language,
7515                                  &type_print_raw_options);
7516
7517               if (cu->language == language_java)
7518                 {
7519                   /* For java, we must append the return type to method
7520                      names.  */
7521                   if (die->tag == DW_TAG_subprogram)
7522                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7523                                      0, 0, &type_print_raw_options);
7524                 }
7525               else if (cu->language == language_cplus)
7526                 {
7527                   /* Assume that an artificial first parameter is
7528                      "this", but do not crash if it is not.  RealView
7529                      marks unnamed (and thus unused) parameters as
7530                      artificial; there is no way to differentiate
7531                      the two cases.  */
7532                   if (TYPE_NFIELDS (type) > 0
7533                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7534                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7535                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7536                                                                         0))))
7537                     fputs_unfiltered (" const", buf);
7538                 }
7539             }
7540
7541           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7542                                        &length);
7543           ui_file_delete (buf);
7544
7545           if (cu->language == language_cplus)
7546             {
7547               const char *cname
7548                 = dwarf2_canonicalize_name (name, cu,
7549                                             &objfile->objfile_obstack);
7550
7551               if (cname != NULL)
7552                 name = cname;
7553             }
7554         }
7555     }
7556
7557   return name;
7558 }
7559
7560 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7561    If scope qualifiers are appropriate they will be added.  The result
7562    will be allocated on the objfile_obstack, or NULL if the DIE does
7563    not have a name.  NAME may either be from a previous call to
7564    dwarf2_name or NULL.
7565
7566    The output string will be canonicalized (if C++/Java).  */
7567
7568 static const char *
7569 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7570 {
7571   return dwarf2_compute_name (name, die, cu, 0);
7572 }
7573
7574 /* Construct a physname for the given DIE in CU.  NAME may either be
7575    from a previous call to dwarf2_name or NULL.  The result will be
7576    allocated on the objfile_objstack or NULL if the DIE does not have a
7577    name.
7578
7579    The output string will be canonicalized (if C++/Java).  */
7580
7581 static const char *
7582 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7583 {
7584   struct objfile *objfile = cu->objfile;
7585   struct attribute *attr;
7586   const char *retval, *mangled = NULL, *canon = NULL;
7587   struct cleanup *back_to;
7588   int need_copy = 1;
7589
7590   /* In this case dwarf2_compute_name is just a shortcut not building anything
7591      on its own.  */
7592   if (!die_needs_namespace (die, cu))
7593     return dwarf2_compute_name (name, die, cu, 1);
7594
7595   back_to = make_cleanup (null_cleanup, NULL);
7596
7597   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7598   if (!attr)
7599     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7600
7601   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7602      has computed.  */
7603   if (attr && DW_STRING (attr))
7604     {
7605       char *demangled;
7606
7607       mangled = DW_STRING (attr);
7608
7609       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7610          type.  It is easier for GDB users to search for such functions as
7611          `name(params)' than `long name(params)'.  In such case the minimal
7612          symbol names do not match the full symbol names but for template
7613          functions there is never a need to look up their definition from their
7614          declaration so the only disadvantage remains the minimal symbol
7615          variant `long name(params)' does not have the proper inferior type.
7616          */
7617
7618       if (cu->language == language_go)
7619         {
7620           /* This is a lie, but we already lie to the caller new_symbol_full.
7621              new_symbol_full assumes we return the mangled name.
7622              This just undoes that lie until things are cleaned up.  */
7623           demangled = NULL;
7624         }
7625       else
7626         {
7627           demangled = cplus_demangle (mangled,
7628                                       (DMGL_PARAMS | DMGL_ANSI
7629                                        | (cu->language == language_java
7630                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7631                                           : DMGL_RET_DROP)));
7632         }
7633       if (demangled)
7634         {
7635           make_cleanup (xfree, demangled);
7636           canon = demangled;
7637         }
7638       else
7639         {
7640           canon = mangled;
7641           need_copy = 0;
7642         }
7643     }
7644
7645   if (canon == NULL || check_physname)
7646     {
7647       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7648
7649       if (canon != NULL && strcmp (physname, canon) != 0)
7650         {
7651           /* It may not mean a bug in GDB.  The compiler could also
7652              compute DW_AT_linkage_name incorrectly.  But in such case
7653              GDB would need to be bug-to-bug compatible.  */
7654
7655           complaint (&symfile_complaints,
7656                      _("Computed physname <%s> does not match demangled <%s> "
7657                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7658                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7659
7660           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7661              is available here - over computed PHYSNAME.  It is safer
7662              against both buggy GDB and buggy compilers.  */
7663
7664           retval = canon;
7665         }
7666       else
7667         {
7668           retval = physname;
7669           need_copy = 0;
7670         }
7671     }
7672   else
7673     retval = canon;
7674
7675   if (need_copy)
7676     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7677
7678   do_cleanups (back_to);
7679   return retval;
7680 }
7681
7682 /* Read the import statement specified by the given die and record it.  */
7683
7684 static void
7685 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7686 {
7687   struct objfile *objfile = cu->objfile;
7688   struct attribute *import_attr;
7689   struct die_info *imported_die, *child_die;
7690   struct dwarf2_cu *imported_cu;
7691   const char *imported_name;
7692   const char *imported_name_prefix;
7693   const char *canonical_name;
7694   const char *import_alias;
7695   const char *imported_declaration = NULL;
7696   const char *import_prefix;
7697   VEC (const_char_ptr) *excludes = NULL;
7698   struct cleanup *cleanups;
7699
7700   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7701   if (import_attr == NULL)
7702     {
7703       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7704                  dwarf_tag_name (die->tag));
7705       return;
7706     }
7707
7708   imported_cu = cu;
7709   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7710   imported_name = dwarf2_name (imported_die, imported_cu);
7711   if (imported_name == NULL)
7712     {
7713       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7714
7715         The import in the following code:
7716         namespace A
7717           {
7718             typedef int B;
7719           }
7720
7721         int main ()
7722           {
7723             using A::B;
7724             B b;
7725             return b;
7726           }
7727
7728         ...
7729          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7730             <52>   DW_AT_decl_file   : 1
7731             <53>   DW_AT_decl_line   : 6
7732             <54>   DW_AT_import      : <0x75>
7733          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7734             <59>   DW_AT_name        : B
7735             <5b>   DW_AT_decl_file   : 1
7736             <5c>   DW_AT_decl_line   : 2
7737             <5d>   DW_AT_type        : <0x6e>
7738         ...
7739          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7740             <76>   DW_AT_byte_size   : 4
7741             <77>   DW_AT_encoding    : 5        (signed)
7742
7743         imports the wrong die ( 0x75 instead of 0x58 ).
7744         This case will be ignored until the gcc bug is fixed.  */
7745       return;
7746     }
7747
7748   /* Figure out the local name after import.  */
7749   import_alias = dwarf2_name (die, cu);
7750
7751   /* Figure out where the statement is being imported to.  */
7752   import_prefix = determine_prefix (die, cu);
7753
7754   /* Figure out what the scope of the imported die is and prepend it
7755      to the name of the imported die.  */
7756   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7757
7758   if (imported_die->tag != DW_TAG_namespace
7759       && imported_die->tag != DW_TAG_module)
7760     {
7761       imported_declaration = imported_name;
7762       canonical_name = imported_name_prefix;
7763     }
7764   else if (strlen (imported_name_prefix) > 0)
7765     canonical_name = obconcat (&objfile->objfile_obstack,
7766                                imported_name_prefix, "::", imported_name,
7767                                (char *) NULL);
7768   else
7769     canonical_name = imported_name;
7770
7771   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7772
7773   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7774     for (child_die = die->child; child_die && child_die->tag;
7775          child_die = sibling_die (child_die))
7776       {
7777         /* DWARF-4: A Fortran use statement with a “rename list” may be
7778            represented by an imported module entry with an import attribute
7779            referring to the module and owned entries corresponding to those
7780            entities that are renamed as part of being imported.  */
7781
7782         if (child_die->tag != DW_TAG_imported_declaration)
7783           {
7784             complaint (&symfile_complaints,
7785                        _("child DW_TAG_imported_declaration expected "
7786                          "- DIE at 0x%x [in module %s]"),
7787                        child_die->offset.sect_off, objfile->name);
7788             continue;
7789           }
7790
7791         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7792         if (import_attr == NULL)
7793           {
7794             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7795                        dwarf_tag_name (child_die->tag));
7796             continue;
7797           }
7798
7799         imported_cu = cu;
7800         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7801                                               &imported_cu);
7802         imported_name = dwarf2_name (imported_die, imported_cu);
7803         if (imported_name == NULL)
7804           {
7805             complaint (&symfile_complaints,
7806                        _("child DW_TAG_imported_declaration has unknown "
7807                          "imported name - DIE at 0x%x [in module %s]"),
7808                        child_die->offset.sect_off, objfile->name);
7809             continue;
7810           }
7811
7812         VEC_safe_push (const_char_ptr, excludes, imported_name);
7813
7814         process_die (child_die, cu);
7815       }
7816
7817   cp_add_using_directive (import_prefix,
7818                           canonical_name,
7819                           import_alias,
7820                           imported_declaration,
7821                           excludes,
7822                           0,
7823                           &objfile->objfile_obstack);
7824
7825   do_cleanups (cleanups);
7826 }
7827
7828 /* Cleanup function for handle_DW_AT_stmt_list.  */
7829
7830 static void
7831 free_cu_line_header (void *arg)
7832 {
7833   struct dwarf2_cu *cu = arg;
7834
7835   free_line_header (cu->line_header);
7836   cu->line_header = NULL;
7837 }
7838
7839 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7840    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7841    this, it was first present in GCC release 4.3.0.  */
7842
7843 static int
7844 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7845 {
7846   if (!cu->checked_producer)
7847     check_producer (cu);
7848
7849   return cu->producer_is_gcc_lt_4_3;
7850 }
7851
7852 static void
7853 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7854                          const char **name, const char **comp_dir)
7855 {
7856   struct attribute *attr;
7857
7858   *name = NULL;
7859   *comp_dir = NULL;
7860
7861   /* Find the filename.  Do not use dwarf2_name here, since the filename
7862      is not a source language identifier.  */
7863   attr = dwarf2_attr (die, DW_AT_name, cu);
7864   if (attr)
7865     {
7866       *name = DW_STRING (attr);
7867     }
7868
7869   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7870   if (attr)
7871     *comp_dir = DW_STRING (attr);
7872   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
7873            && IS_ABSOLUTE_PATH (*name))
7874     {
7875       char *d = ldirname (*name);
7876
7877       *comp_dir = d;
7878       if (d != NULL)
7879         make_cleanup (xfree, d);
7880     }
7881   if (*comp_dir != NULL)
7882     {
7883       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7884          directory, get rid of it.  */
7885       char *cp = strchr (*comp_dir, ':');
7886
7887       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7888         *comp_dir = cp + 1;
7889     }
7890
7891   if (*name == NULL)
7892     *name = "<unknown>";
7893 }
7894
7895 /* Handle DW_AT_stmt_list for a compilation unit.
7896    DIE is the DW_TAG_compile_unit die for CU.
7897    COMP_DIR is the compilation directory.
7898    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7899
7900 static void
7901 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7902                         const char *comp_dir)
7903 {
7904   struct attribute *attr;
7905
7906   gdb_assert (! cu->per_cu->is_debug_types);
7907
7908   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7909   if (attr)
7910     {
7911       unsigned int line_offset = DW_UNSND (attr);
7912       struct line_header *line_header
7913         = dwarf_decode_line_header (line_offset, cu);
7914
7915       if (line_header)
7916         {
7917           cu->line_header = line_header;
7918           make_cleanup (free_cu_line_header, cu);
7919           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7920         }
7921     }
7922 }
7923
7924 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7925
7926 static void
7927 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7928 {
7929   struct objfile *objfile = dwarf2_per_objfile->objfile;
7930   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7931   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7932   CORE_ADDR highpc = ((CORE_ADDR) 0);
7933   struct attribute *attr;
7934   const char *name = NULL;
7935   const char *comp_dir = NULL;
7936   struct die_info *child_die;
7937   bfd *abfd = objfile->obfd;
7938   CORE_ADDR baseaddr;
7939
7940   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7941
7942   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7943
7944   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7945      from finish_block.  */
7946   if (lowpc == ((CORE_ADDR) -1))
7947     lowpc = highpc;
7948   lowpc += baseaddr;
7949   highpc += baseaddr;
7950
7951   find_file_and_directory (die, cu, &name, &comp_dir);
7952
7953   prepare_one_comp_unit (cu, die, cu->language);
7954
7955   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7956      standardised yet.  As a workaround for the language detection we fall
7957      back to the DW_AT_producer string.  */
7958   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7959     cu->language = language_opencl;
7960
7961   /* Similar hack for Go.  */
7962   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
7963     set_cu_language (DW_LANG_Go, cu);
7964
7965   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
7966
7967   /* Decode line number information if present.  We do this before
7968      processing child DIEs, so that the line header table is available
7969      for DW_AT_decl_file.  */
7970   handle_DW_AT_stmt_list (die, cu, comp_dir);
7971
7972   /* Process all dies in compilation unit.  */
7973   if (die->child != NULL)
7974     {
7975       child_die = die->child;
7976       while (child_die && child_die->tag)
7977         {
7978           process_die (child_die, cu);
7979           child_die = sibling_die (child_die);
7980         }
7981     }
7982
7983   /* Decode macro information, if present.  Dwarf 2 macro information
7984      refers to information in the line number info statement program
7985      header, so we can only read it if we've read the header
7986      successfully.  */
7987   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
7988   if (attr && cu->line_header)
7989     {
7990       if (dwarf2_attr (die, DW_AT_macro_info, cu))
7991         complaint (&symfile_complaints,
7992                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
7993
7994       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
7995     }
7996   else
7997     {
7998       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
7999       if (attr && cu->line_header)
8000         {
8001           unsigned int macro_offset = DW_UNSND (attr);
8002
8003           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8004         }
8005     }
8006
8007   do_cleanups (back_to);
8008 }
8009
8010 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8011    Create the set of symtabs used by this TU, or if this TU is sharing
8012    symtabs with another TU and the symtabs have already been created
8013    then restore those symtabs in the line header.
8014    We don't need the pc/line-number mapping for type units.  */
8015
8016 static void
8017 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8018 {
8019   struct objfile *objfile = dwarf2_per_objfile->objfile;
8020   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8021   struct type_unit_group *tu_group;
8022   int first_time;
8023   struct line_header *lh;
8024   struct attribute *attr;
8025   unsigned int i, line_offset;
8026
8027   gdb_assert (per_cu->is_debug_types);
8028
8029   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8030
8031   /* If we're using .gdb_index (includes -readnow) then
8032      per_cu->s.type_unit_group may not have been set up yet.  */
8033   if (per_cu->type_unit_group == NULL)
8034     per_cu->type_unit_group = get_type_unit_group (cu, attr);
8035   tu_group = per_cu->type_unit_group;
8036
8037   /* If we've already processed this stmt_list there's no real need to
8038      do it again, we could fake it and just recreate the part we need
8039      (file name,index -> symtab mapping).  If data shows this optimization
8040      is useful we can do it then.  */
8041   first_time = tu_group->primary_symtab == NULL;
8042
8043   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8044      debug info.  */
8045   lh = NULL;
8046   if (attr != NULL)
8047     {
8048       line_offset = DW_UNSND (attr);
8049       lh = dwarf_decode_line_header (line_offset, cu);
8050     }
8051   if (lh == NULL)
8052     {
8053       if (first_time)
8054         dwarf2_start_symtab (cu, "", NULL, 0);
8055       else
8056         {
8057           gdb_assert (tu_group->symtabs == NULL);
8058           restart_symtab (0);
8059         }
8060       /* Note: The primary symtab will get allocated at the end.  */
8061       return;
8062     }
8063
8064   cu->line_header = lh;
8065   make_cleanup (free_cu_line_header, cu);
8066
8067   if (first_time)
8068     {
8069       dwarf2_start_symtab (cu, "", NULL, 0);
8070
8071       tu_group->num_symtabs = lh->num_file_names;
8072       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8073
8074       for (i = 0; i < lh->num_file_names; ++i)
8075         {
8076           char *dir = NULL;
8077           struct file_entry *fe = &lh->file_names[i];
8078
8079           if (fe->dir_index)
8080             dir = lh->include_dirs[fe->dir_index - 1];
8081           dwarf2_start_subfile (fe->name, dir, NULL);
8082
8083           /* Note: We don't have to watch for the main subfile here, type units
8084              don't have DW_AT_name.  */
8085
8086           if (current_subfile->symtab == NULL)
8087             {
8088               /* NOTE: start_subfile will recognize when it's been passed
8089                  a file it has already seen.  So we can't assume there's a
8090                  simple mapping from lh->file_names to subfiles,
8091                  lh->file_names may contain dups.  */
8092               current_subfile->symtab = allocate_symtab (current_subfile->name,
8093                                                          objfile);
8094             }
8095
8096           fe->symtab = current_subfile->symtab;
8097           tu_group->symtabs[i] = fe->symtab;
8098         }
8099     }
8100   else
8101     {
8102       restart_symtab (0);
8103
8104       for (i = 0; i < lh->num_file_names; ++i)
8105         {
8106           struct file_entry *fe = &lh->file_names[i];
8107
8108           fe->symtab = tu_group->symtabs[i];
8109         }
8110     }
8111
8112   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8113      so they don't have a "real" (so to speak) symtab anyway.
8114      There is later code that will assign the main symtab to all symbols
8115      that don't have one.  We need to handle the case of a symbol with a
8116      missing symtab (DW_AT_decl_file) anyway.  */
8117 }
8118
8119 /* Process DW_TAG_type_unit.
8120    For TUs we want to skip the first top level sibling if it's not the
8121    actual type being defined by this TU.  In this case the first top
8122    level sibling is there to provide context only.  */
8123
8124 static void
8125 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8126 {
8127   struct die_info *child_die;
8128
8129   prepare_one_comp_unit (cu, die, language_minimal);
8130
8131   /* Initialize (or reinitialize) the machinery for building symtabs.
8132      We do this before processing child DIEs, so that the line header table
8133      is available for DW_AT_decl_file.  */
8134   setup_type_unit_groups (die, cu);
8135
8136   if (die->child != NULL)
8137     {
8138       child_die = die->child;
8139       while (child_die && child_die->tag)
8140         {
8141           process_die (child_die, cu);
8142           child_die = sibling_die (child_die);
8143         }
8144     }
8145 }
8146 \f
8147 /* DWO/DWP files.
8148
8149    http://gcc.gnu.org/wiki/DebugFission
8150    http://gcc.gnu.org/wiki/DebugFissionDWP
8151
8152    To simplify handling of both DWO files ("object" files with the DWARF info)
8153    and DWP files (a file with the DWOs packaged up into one file), we treat
8154    DWP files as having a collection of virtual DWO files.  */
8155
8156 static hashval_t
8157 hash_dwo_file (const void *item)
8158 {
8159   const struct dwo_file *dwo_file = item;
8160
8161   return htab_hash_string (dwo_file->name);
8162 }
8163
8164 static int
8165 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8166 {
8167   const struct dwo_file *lhs = item_lhs;
8168   const struct dwo_file *rhs = item_rhs;
8169
8170   return strcmp (lhs->name, rhs->name) == 0;
8171 }
8172
8173 /* Allocate a hash table for DWO files.  */
8174
8175 static htab_t
8176 allocate_dwo_file_hash_table (void)
8177 {
8178   struct objfile *objfile = dwarf2_per_objfile->objfile;
8179
8180   return htab_create_alloc_ex (41,
8181                                hash_dwo_file,
8182                                eq_dwo_file,
8183                                NULL,
8184                                &objfile->objfile_obstack,
8185                                hashtab_obstack_allocate,
8186                                dummy_obstack_deallocate);
8187 }
8188
8189 /* Lookup DWO file DWO_NAME.  */
8190
8191 static void **
8192 lookup_dwo_file_slot (const char *dwo_name)
8193 {
8194   struct dwo_file find_entry;
8195   void **slot;
8196
8197   if (dwarf2_per_objfile->dwo_files == NULL)
8198     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8199
8200   memset (&find_entry, 0, sizeof (find_entry));
8201   find_entry.name = dwo_name;
8202   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8203
8204   return slot;
8205 }
8206
8207 static hashval_t
8208 hash_dwo_unit (const void *item)
8209 {
8210   const struct dwo_unit *dwo_unit = item;
8211
8212   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8213   return dwo_unit->signature;
8214 }
8215
8216 static int
8217 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8218 {
8219   const struct dwo_unit *lhs = item_lhs;
8220   const struct dwo_unit *rhs = item_rhs;
8221
8222   /* The signature is assumed to be unique within the DWO file.
8223      So while object file CU dwo_id's always have the value zero,
8224      that's OK, assuming each object file DWO file has only one CU,
8225      and that's the rule for now.  */
8226   return lhs->signature == rhs->signature;
8227 }
8228
8229 /* Allocate a hash table for DWO CUs,TUs.
8230    There is one of these tables for each of CUs,TUs for each DWO file.  */
8231
8232 static htab_t
8233 allocate_dwo_unit_table (struct objfile *objfile)
8234 {
8235   /* Start out with a pretty small number.
8236      Generally DWO files contain only one CU and maybe some TUs.  */
8237   return htab_create_alloc_ex (3,
8238                                hash_dwo_unit,
8239                                eq_dwo_unit,
8240                                NULL,
8241                                &objfile->objfile_obstack,
8242                                hashtab_obstack_allocate,
8243                                dummy_obstack_deallocate);
8244 }
8245
8246 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8247
8248 struct create_dwo_info_table_data
8249 {
8250   struct dwo_file *dwo_file;
8251   htab_t cu_htab;
8252 };
8253
8254 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8255
8256 static void
8257 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8258                                          gdb_byte *info_ptr,
8259                                          struct die_info *comp_unit_die,
8260                                          int has_children,
8261                                          void *datap)
8262 {
8263   struct dwarf2_cu *cu = reader->cu;
8264   struct objfile *objfile = dwarf2_per_objfile->objfile;
8265   sect_offset offset = cu->per_cu->offset;
8266   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
8267   struct create_dwo_info_table_data *data = datap;
8268   struct dwo_file *dwo_file = data->dwo_file;
8269   htab_t cu_htab = data->cu_htab;
8270   void **slot;
8271   struct attribute *attr;
8272   struct dwo_unit *dwo_unit;
8273
8274   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8275   if (attr == NULL)
8276     {
8277       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8278                " its dwo_id [in module %s]"),
8279              offset.sect_off, dwo_file->name);
8280       return;
8281     }
8282
8283   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8284   dwo_unit->dwo_file = dwo_file;
8285   dwo_unit->signature = DW_UNSND (attr);
8286   dwo_unit->info_or_types_section = section;
8287   dwo_unit->offset = offset;
8288   dwo_unit->length = cu->per_cu->length;
8289
8290   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8291   gdb_assert (slot != NULL);
8292   if (*slot != NULL)
8293     {
8294       const struct dwo_unit *dup_dwo_unit = *slot;
8295
8296       complaint (&symfile_complaints,
8297                  _("debug entry at offset 0x%x is duplicate to the entry at"
8298                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8299                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8300                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8301                  dwo_file->name);
8302     }
8303   else
8304     *slot = dwo_unit;
8305
8306   if (dwarf2_read_debug)
8307     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8308                         offset.sect_off,
8309                         phex (dwo_unit->signature,
8310                               sizeof (dwo_unit->signature)));
8311 }
8312
8313 /* Create a hash table to map DWO IDs to their CU entry in
8314    .debug_info.dwo in DWO_FILE.
8315    Note: This function processes DWO files only, not DWP files.  */
8316
8317 static htab_t
8318 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8319 {
8320   struct objfile *objfile = dwarf2_per_objfile->objfile;
8321   struct dwarf2_section_info *section = &dwo_file->sections.info;
8322   bfd *abfd;
8323   htab_t cu_htab;
8324   gdb_byte *info_ptr, *end_ptr;
8325   struct create_dwo_info_table_data create_dwo_info_table_data;
8326
8327   dwarf2_read_section (objfile, section);
8328   info_ptr = section->buffer;
8329
8330   if (info_ptr == NULL)
8331     return NULL;
8332
8333   /* We can't set abfd until now because the section may be empty or
8334      not present, in which case section->asection will be NULL.  */
8335   abfd = section->asection->owner;
8336
8337   if (dwarf2_read_debug)
8338     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8339                         bfd_get_filename (abfd));
8340
8341   cu_htab = allocate_dwo_unit_table (objfile);
8342
8343   create_dwo_info_table_data.dwo_file = dwo_file;
8344   create_dwo_info_table_data.cu_htab = cu_htab;
8345
8346   end_ptr = info_ptr + section->size;
8347   while (info_ptr < end_ptr)
8348     {
8349       struct dwarf2_per_cu_data per_cu;
8350
8351       memset (&per_cu, 0, sizeof (per_cu));
8352       per_cu.objfile = objfile;
8353       per_cu.is_debug_types = 0;
8354       per_cu.offset.sect_off = info_ptr - section->buffer;
8355       per_cu.info_or_types_section = section;
8356
8357       init_cutu_and_read_dies_no_follow (&per_cu,
8358                                          &dwo_file->sections.abbrev,
8359                                          dwo_file,
8360                                          create_dwo_debug_info_hash_table_reader,
8361                                          &create_dwo_info_table_data);
8362
8363       info_ptr += per_cu.length;
8364     }
8365
8366   return cu_htab;
8367 }
8368
8369 /* DWP file .debug_{cu,tu}_index section format:
8370    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8371
8372    Both index sections have the same format, and serve to map a 64-bit
8373    signature to a set of section numbers.  Each section begins with a header,
8374    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8375    indexes, and a pool of 32-bit section numbers.  The index sections will be
8376    aligned at 8-byte boundaries in the file.
8377
8378    The index section header contains two unsigned 32-bit values (using the
8379    byte order of the application binary):
8380
8381     N, the number of compilation units or type units in the index
8382     M, the number of slots in the hash table
8383
8384   (We assume that N and M will not exceed 2^32 - 1.)
8385
8386   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8387
8388   The hash table begins at offset 8 in the section, and consists of an array
8389   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8390   order of the application binary).  Unused slots in the hash table are 0.
8391   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8392
8393   The parallel table begins immediately after the hash table
8394   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8395   array of 32-bit indexes (using the byte order of the application binary),
8396   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8397   table contains a 32-bit index into the pool of section numbers.  For unused
8398   hash table slots, the corresponding entry in the parallel table will be 0.
8399
8400   Given a 64-bit compilation unit signature or a type signature S, an entry
8401   in the hash table is located as follows:
8402
8403   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8404      the low-order k bits all set to 1.
8405
8406   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8407
8408   3) If the hash table entry at index H matches the signature, use that
8409      entry.  If the hash table entry at index H is unused (all zeroes),
8410      terminate the search: the signature is not present in the table.
8411
8412   4) Let H = (H + H') modulo M. Repeat at Step 3.
8413
8414   Because M > N and H' and M are relatively prime, the search is guaranteed
8415   to stop at an unused slot or find the match.
8416
8417   The pool of section numbers begins immediately following the hash table
8418   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8419   section numbers consists of an array of 32-bit words (using the byte order
8420   of the application binary).  Each item in the array is indexed starting
8421   from 0.  The hash table entry provides the index of the first section
8422   number in the set.  Additional section numbers in the set follow, and the
8423   set is terminated by a 0 entry (section number 0 is not used in ELF).
8424
8425   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8426   section must be the first entry in the set, and the .debug_abbrev.dwo must
8427   be the second entry. Other members of the set may follow in any order.  */
8428
8429 /* Create a hash table to map DWO IDs to their CU/TU entry in
8430    .debug_{info,types}.dwo in DWP_FILE.
8431    Returns NULL if there isn't one.
8432    Note: This function processes DWP files only, not DWO files.  */
8433
8434 static struct dwp_hash_table *
8435 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8436 {
8437   struct objfile *objfile = dwarf2_per_objfile->objfile;
8438   bfd *dbfd = dwp_file->dbfd;
8439   char *index_ptr, *index_end;
8440   struct dwarf2_section_info *index;
8441   uint32_t version, nr_units, nr_slots;
8442   struct dwp_hash_table *htab;
8443
8444   if (is_debug_types)
8445     index = &dwp_file->sections.tu_index;
8446   else
8447     index = &dwp_file->sections.cu_index;
8448
8449   if (dwarf2_section_empty_p (index))
8450     return NULL;
8451   dwarf2_read_section (objfile, index);
8452
8453   index_ptr = index->buffer;
8454   index_end = index_ptr + index->size;
8455
8456   version = read_4_bytes (dbfd, index_ptr);
8457   index_ptr += 8; /* Skip the unused word.  */
8458   nr_units = read_4_bytes (dbfd, index_ptr);
8459   index_ptr += 4;
8460   nr_slots = read_4_bytes (dbfd, index_ptr);
8461   index_ptr += 4;
8462
8463   if (version != 1)
8464     {
8465       error (_("Dwarf Error: unsupported DWP file version (%u)"
8466                " [in module %s]"),
8467              version, dwp_file->name);
8468     }
8469   if (nr_slots != (nr_slots & -nr_slots))
8470     {
8471       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8472                " is not power of 2 [in module %s]"),
8473              nr_slots, dwp_file->name);
8474     }
8475
8476   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8477   htab->nr_units = nr_units;
8478   htab->nr_slots = nr_slots;
8479   htab->hash_table = index_ptr;
8480   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8481   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8482
8483   return htab;
8484 }
8485
8486 /* Update SECTIONS with the data from SECTP.
8487
8488    This function is like the other "locate" section routines that are
8489    passed to bfd_map_over_sections, but in this context the sections to
8490    read comes from the DWP hash table, not the full ELF section table.
8491
8492    The result is non-zero for success, or zero if an error was found.  */
8493
8494 static int
8495 locate_virtual_dwo_sections (asection *sectp,
8496                              struct virtual_dwo_sections *sections)
8497 {
8498   const struct dwop_section_names *names = &dwop_section_names;
8499
8500   if (section_is_p (sectp->name, &names->abbrev_dwo))
8501     {
8502       /* There can be only one.  */
8503       if (sections->abbrev.asection != NULL)
8504         return 0;
8505       sections->abbrev.asection = sectp;
8506       sections->abbrev.size = bfd_get_section_size (sectp);
8507     }
8508   else if (section_is_p (sectp->name, &names->info_dwo)
8509            || section_is_p (sectp->name, &names->types_dwo))
8510     {
8511       /* There can be only one.  */
8512       if (sections->info_or_types.asection != NULL)
8513         return 0;
8514       sections->info_or_types.asection = sectp;
8515       sections->info_or_types.size = bfd_get_section_size (sectp);
8516     }
8517   else if (section_is_p (sectp->name, &names->line_dwo))
8518     {
8519       /* There can be only one.  */
8520       if (sections->line.asection != NULL)
8521         return 0;
8522       sections->line.asection = sectp;
8523       sections->line.size = bfd_get_section_size (sectp);
8524     }
8525   else if (section_is_p (sectp->name, &names->loc_dwo))
8526     {
8527       /* There can be only one.  */
8528       if (sections->loc.asection != NULL)
8529         return 0;
8530       sections->loc.asection = sectp;
8531       sections->loc.size = bfd_get_section_size (sectp);
8532     }
8533   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8534     {
8535       /* There can be only one.  */
8536       if (sections->macinfo.asection != NULL)
8537         return 0;
8538       sections->macinfo.asection = sectp;
8539       sections->macinfo.size = bfd_get_section_size (sectp);
8540     }
8541   else if (section_is_p (sectp->name, &names->macro_dwo))
8542     {
8543       /* There can be only one.  */
8544       if (sections->macro.asection != NULL)
8545         return 0;
8546       sections->macro.asection = sectp;
8547       sections->macro.size = bfd_get_section_size (sectp);
8548     }
8549   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8550     {
8551       /* There can be only one.  */
8552       if (sections->str_offsets.asection != NULL)
8553         return 0;
8554       sections->str_offsets.asection = sectp;
8555       sections->str_offsets.size = bfd_get_section_size (sectp);
8556     }
8557   else
8558     {
8559       /* No other kind of section is valid.  */
8560       return 0;
8561     }
8562
8563   return 1;
8564 }
8565
8566 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8567    HTAB is the hash table from the DWP file.
8568    SECTION_INDEX is the index of the DWO in HTAB.  */
8569
8570 static struct dwo_unit *
8571 create_dwo_in_dwp (struct dwp_file *dwp_file,
8572                    const struct dwp_hash_table *htab,
8573                    uint32_t section_index,
8574                    ULONGEST signature, int is_debug_types)
8575 {
8576   struct objfile *objfile = dwarf2_per_objfile->objfile;
8577   bfd *dbfd = dwp_file->dbfd;
8578   const char *kind = is_debug_types ? "TU" : "CU";
8579   struct dwo_file *dwo_file;
8580   struct dwo_unit *dwo_unit;
8581   struct virtual_dwo_sections sections;
8582   void **dwo_file_slot;
8583   char *virtual_dwo_name;
8584   struct dwarf2_section_info *cutu;
8585   struct cleanup *cleanups;
8586   int i;
8587
8588   if (dwarf2_read_debug)
8589     {
8590       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8591                           kind,
8592                           section_index, phex (signature, sizeof (signature)),
8593                           dwp_file->name);
8594     }
8595
8596   /* Fetch the sections of this DWO.
8597      Put a limit on the number of sections we look for so that bad data
8598      doesn't cause us to loop forever.  */
8599
8600 #define MAX_NR_DWO_SECTIONS \
8601   (1 /* .debug_info or .debug_types */ \
8602    + 1 /* .debug_abbrev */ \
8603    + 1 /* .debug_line */ \
8604    + 1 /* .debug_loc */ \
8605    + 1 /* .debug_str_offsets */ \
8606    + 1 /* .debug_macro */ \
8607    + 1 /* .debug_macinfo */ \
8608    + 1 /* trailing zero */)
8609
8610   memset (&sections, 0, sizeof (sections));
8611   cleanups = make_cleanup (null_cleanup, 0);
8612
8613   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8614     {
8615       asection *sectp;
8616       uint32_t section_nr =
8617         read_4_bytes (dbfd,
8618                       htab->section_pool
8619                       + (section_index + i) * sizeof (uint32_t));
8620
8621       if (section_nr == 0)
8622         break;
8623       if (section_nr >= dwp_file->num_sections)
8624         {
8625           error (_("Dwarf Error: bad DWP hash table, section number too large"
8626                    " [in module %s]"),
8627                  dwp_file->name);
8628         }
8629
8630       sectp = dwp_file->elf_sections[section_nr];
8631       if (! locate_virtual_dwo_sections (sectp, &sections))
8632         {
8633           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8634                    " [in module %s]"),
8635                  dwp_file->name);
8636         }
8637     }
8638
8639   if (i < 2
8640       || sections.info_or_types.asection == NULL
8641       || sections.abbrev.asection == NULL)
8642     {
8643       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8644                " [in module %s]"),
8645              dwp_file->name);
8646     }
8647   if (i == MAX_NR_DWO_SECTIONS)
8648     {
8649       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8650                " [in module %s]"),
8651              dwp_file->name);
8652     }
8653
8654   /* It's easier for the rest of the code if we fake a struct dwo_file and
8655      have dwo_unit "live" in that.  At least for now.
8656
8657      The DWP file can be made up of a random collection of CUs and TUs.
8658      However, for each CU + set of TUs that came from the same original DWO
8659      file, we want to combine them back into a virtual DWO file to save space
8660      (fewer struct dwo_file objects to allocated).  Remember that for really
8661      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8662
8663   virtual_dwo_name =
8664     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8665                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8666                 sections.line.asection ? sections.line.asection->id : 0,
8667                 sections.loc.asection ? sections.loc.asection->id : 0,
8668                 (sections.str_offsets.asection
8669                 ? sections.str_offsets.asection->id
8670                 : 0));
8671   make_cleanup (xfree, virtual_dwo_name);
8672   /* Can we use an existing virtual DWO file?  */
8673   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name);
8674   /* Create one if necessary.  */
8675   if (*dwo_file_slot == NULL)
8676     {
8677       if (dwarf2_read_debug)
8678         {
8679           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8680                               virtual_dwo_name);
8681         }
8682       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8683       dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8684                                       virtual_dwo_name,
8685                                       strlen (virtual_dwo_name));
8686       dwo_file->sections.abbrev = sections.abbrev;
8687       dwo_file->sections.line = sections.line;
8688       dwo_file->sections.loc = sections.loc;
8689       dwo_file->sections.macinfo = sections.macinfo;
8690       dwo_file->sections.macro = sections.macro;
8691       dwo_file->sections.str_offsets = sections.str_offsets;
8692       /* The "str" section is global to the entire DWP file.  */
8693       dwo_file->sections.str = dwp_file->sections.str;
8694       /* The info or types section is assigned later to dwo_unit,
8695          there's no need to record it in dwo_file.
8696          Also, we can't simply record type sections in dwo_file because
8697          we record a pointer into the vector in dwo_unit.  As we collect more
8698          types we'll grow the vector and eventually have to reallocate space
8699          for it, invalidating all the pointers into the current copy.  */
8700       *dwo_file_slot = dwo_file;
8701     }
8702   else
8703     {
8704       if (dwarf2_read_debug)
8705         {
8706           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8707                               virtual_dwo_name);
8708         }
8709       dwo_file = *dwo_file_slot;
8710     }
8711   do_cleanups (cleanups);
8712
8713   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8714   dwo_unit->dwo_file = dwo_file;
8715   dwo_unit->signature = signature;
8716   dwo_unit->info_or_types_section =
8717     obstack_alloc (&objfile->objfile_obstack,
8718                    sizeof (struct dwarf2_section_info));
8719   *dwo_unit->info_or_types_section = sections.info_or_types;
8720   /* offset, length, type_offset_in_tu are set later.  */
8721
8722   return dwo_unit;
8723 }
8724
8725 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8726
8727 static struct dwo_unit *
8728 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8729                    const struct dwp_hash_table *htab,
8730                    ULONGEST signature, int is_debug_types)
8731 {
8732   bfd *dbfd = dwp_file->dbfd;
8733   uint32_t mask = htab->nr_slots - 1;
8734   uint32_t hash = signature & mask;
8735   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8736   unsigned int i;
8737   void **slot;
8738   struct dwo_unit find_dwo_cu, *dwo_cu;
8739
8740   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8741   find_dwo_cu.signature = signature;
8742   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8743
8744   if (*slot != NULL)
8745     return *slot;
8746
8747   /* Use a for loop so that we don't loop forever on bad debug info.  */
8748   for (i = 0; i < htab->nr_slots; ++i)
8749     {
8750       ULONGEST signature_in_table;
8751
8752       signature_in_table =
8753         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8754       if (signature_in_table == signature)
8755         {
8756           uint32_t section_index =
8757             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8758
8759           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8760                                      signature, is_debug_types);
8761           return *slot;
8762         }
8763       if (signature_in_table == 0)
8764         return NULL;
8765       hash = (hash + hash2) & mask;
8766     }
8767
8768   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8769            " [in module %s]"),
8770          dwp_file->name);
8771 }
8772
8773 /* Subroutine of open_dwop_file to simplify it.
8774    Open the file specified by FILE_NAME and hand it off to BFD for
8775    preliminary analysis.  Return a newly initialized bfd *, which
8776    includes a canonicalized copy of FILE_NAME.
8777    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8778    In case of trouble, return NULL.
8779    NOTE: This function is derived from symfile_bfd_open.  */
8780
8781 static bfd *
8782 try_open_dwop_file (const char *file_name, int is_dwp)
8783 {
8784   bfd *sym_bfd;
8785   int desc, flags;
8786   char *absolute_name;
8787
8788   flags = OPF_TRY_CWD_FIRST;
8789   if (is_dwp)
8790     flags |= OPF_SEARCH_IN_PATH;
8791   desc = openp (debug_file_directory, flags, file_name,
8792                 O_RDONLY | O_BINARY, &absolute_name);
8793   if (desc < 0)
8794     return NULL;
8795
8796   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8797   if (!sym_bfd)
8798     {
8799       xfree (absolute_name);
8800       return NULL;
8801     }
8802   xfree (absolute_name);
8803   bfd_set_cacheable (sym_bfd, 1);
8804
8805   if (!bfd_check_format (sym_bfd, bfd_object))
8806     {
8807       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8808       return NULL;
8809     }
8810
8811   return sym_bfd;
8812 }
8813
8814 /* Try to open DWO/DWP file FILE_NAME.
8815    COMP_DIR is the DW_AT_comp_dir attribute.
8816    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8817    The result is the bfd handle of the file.
8818    If there is a problem finding or opening the file, return NULL.
8819    Upon success, the canonicalized path of the file is stored in the bfd,
8820    same as symfile_bfd_open.  */
8821
8822 static bfd *
8823 open_dwop_file (const char *file_name, const char *comp_dir, int is_dwp)
8824 {
8825   bfd *abfd;
8826
8827   if (IS_ABSOLUTE_PATH (file_name))
8828     return try_open_dwop_file (file_name, is_dwp);
8829
8830   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8831
8832   if (comp_dir != NULL)
8833     {
8834       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8835
8836       /* NOTE: If comp_dir is a relative path, this will also try the
8837          search path, which seems useful.  */
8838       abfd = try_open_dwop_file (path_to_try, is_dwp);
8839       xfree (path_to_try);
8840       if (abfd != NULL)
8841         return abfd;
8842     }
8843
8844   /* That didn't work, try debug-file-directory, which, despite its name,
8845      is a list of paths.  */
8846
8847   if (*debug_file_directory == '\0')
8848     return NULL;
8849
8850   return try_open_dwop_file (file_name, is_dwp);
8851 }
8852
8853 /* This function is mapped across the sections and remembers the offset and
8854    size of each of the DWO debugging sections we are interested in.  */
8855
8856 static void
8857 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
8858 {
8859   struct dwo_sections *dwo_sections = dwo_sections_ptr;
8860   const struct dwop_section_names *names = &dwop_section_names;
8861
8862   if (section_is_p (sectp->name, &names->abbrev_dwo))
8863     {
8864       dwo_sections->abbrev.asection = sectp;
8865       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
8866     }
8867   else if (section_is_p (sectp->name, &names->info_dwo))
8868     {
8869       dwo_sections->info.asection = sectp;
8870       dwo_sections->info.size = bfd_get_section_size (sectp);
8871     }
8872   else if (section_is_p (sectp->name, &names->line_dwo))
8873     {
8874       dwo_sections->line.asection = sectp;
8875       dwo_sections->line.size = bfd_get_section_size (sectp);
8876     }
8877   else if (section_is_p (sectp->name, &names->loc_dwo))
8878     {
8879       dwo_sections->loc.asection = sectp;
8880       dwo_sections->loc.size = bfd_get_section_size (sectp);
8881     }
8882   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8883     {
8884       dwo_sections->macinfo.asection = sectp;
8885       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
8886     }
8887   else if (section_is_p (sectp->name, &names->macro_dwo))
8888     {
8889       dwo_sections->macro.asection = sectp;
8890       dwo_sections->macro.size = bfd_get_section_size (sectp);
8891     }
8892   else if (section_is_p (sectp->name, &names->str_dwo))
8893     {
8894       dwo_sections->str.asection = sectp;
8895       dwo_sections->str.size = bfd_get_section_size (sectp);
8896     }
8897   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8898     {
8899       dwo_sections->str_offsets.asection = sectp;
8900       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
8901     }
8902   else if (section_is_p (sectp->name, &names->types_dwo))
8903     {
8904       struct dwarf2_section_info type_section;
8905
8906       memset (&type_section, 0, sizeof (type_section));
8907       type_section.asection = sectp;
8908       type_section.size = bfd_get_section_size (sectp);
8909       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
8910                      &type_section);
8911     }
8912 }
8913
8914 /* Initialize the use of the DWO file specified by DWO_NAME.
8915    The result is NULL if DWO_NAME can't be found.  */
8916
8917 static struct dwo_file *
8918 open_and_init_dwo_file (const char *dwo_name, const char *comp_dir)
8919 {
8920   struct objfile *objfile = dwarf2_per_objfile->objfile;
8921   struct dwo_file *dwo_file;
8922   bfd *dbfd;
8923   struct cleanup *cleanups;
8924
8925   dbfd = open_dwop_file (dwo_name, comp_dir, 0);
8926   if (dbfd == NULL)
8927     {
8928       if (dwarf2_read_debug)
8929         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
8930       return NULL;
8931     }
8932   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8933   dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8934                                   dwo_name, strlen (dwo_name));
8935   dwo_file->dbfd = dbfd;
8936
8937   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8938
8939   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
8940
8941   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
8942
8943   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8944                                                  dwo_file->sections.types);
8945
8946   discard_cleanups (cleanups);
8947
8948   if (dwarf2_read_debug)
8949     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
8950
8951   return dwo_file;
8952 }
8953
8954 /* This function is mapped across the sections and remembers the offset and
8955    size of each of the DWP debugging sections we are interested in.  */
8956
8957 static void
8958 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
8959 {
8960   struct dwp_file *dwp_file = dwp_file_ptr;
8961   const struct dwop_section_names *names = &dwop_section_names;
8962   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
8963
8964   /* Record the ELF section number for later lookup: this is what the
8965      .debug_cu_index,.debug_tu_index tables use.  */
8966   gdb_assert (elf_section_nr < dwp_file->num_sections);
8967   dwp_file->elf_sections[elf_section_nr] = sectp;
8968
8969   /* Look for specific sections that we need.  */
8970   if (section_is_p (sectp->name, &names->str_dwo))
8971     {
8972       dwp_file->sections.str.asection = sectp;
8973       dwp_file->sections.str.size = bfd_get_section_size (sectp);
8974     }
8975   else if (section_is_p (sectp->name, &names->cu_index))
8976     {
8977       dwp_file->sections.cu_index.asection = sectp;
8978       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
8979     }
8980   else if (section_is_p (sectp->name, &names->tu_index))
8981     {
8982       dwp_file->sections.tu_index.asection = sectp;
8983       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
8984     }
8985 }
8986
8987 /* Hash function for dwp_file loaded CUs/TUs.  */
8988
8989 static hashval_t
8990 hash_dwp_loaded_cutus (const void *item)
8991 {
8992   const struct dwo_unit *dwo_unit = item;
8993
8994   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
8995   return dwo_unit->signature;
8996 }
8997
8998 /* Equality function for dwp_file loaded CUs/TUs.  */
8999
9000 static int
9001 eq_dwp_loaded_cutus (const void *a, const void *b)
9002 {
9003   const struct dwo_unit *dua = a;
9004   const struct dwo_unit *dub = b;
9005
9006   return dua->signature == dub->signature;
9007 }
9008
9009 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9010
9011 static htab_t
9012 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9013 {
9014   return htab_create_alloc_ex (3,
9015                                hash_dwp_loaded_cutus,
9016                                eq_dwp_loaded_cutus,
9017                                NULL,
9018                                &objfile->objfile_obstack,
9019                                hashtab_obstack_allocate,
9020                                dummy_obstack_deallocate);
9021 }
9022
9023 /* Initialize the use of the DWP file for the current objfile.
9024    By convention the name of the DWP file is ${objfile}.dwp.
9025    The result is NULL if it can't be found.  */
9026
9027 static struct dwp_file *
9028 open_and_init_dwp_file (const char *comp_dir)
9029 {
9030   struct objfile *objfile = dwarf2_per_objfile->objfile;
9031   struct dwp_file *dwp_file;
9032   char *dwp_name;
9033   bfd *dbfd;
9034   struct cleanup *cleanups;
9035
9036   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9037   cleanups = make_cleanup (xfree, dwp_name);
9038
9039   dbfd = open_dwop_file (dwp_name, comp_dir, 1);
9040   if (dbfd == NULL)
9041     {
9042       if (dwarf2_read_debug)
9043         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9044       do_cleanups (cleanups);
9045       return NULL;
9046     }
9047   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9048   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9049                                   dwp_name, strlen (dwp_name));
9050   dwp_file->dbfd = dbfd;
9051   do_cleanups (cleanups);
9052
9053   cleanups = make_cleanup (free_dwo_file_cleanup, dwp_file);
9054
9055   /* +1: section 0 is unused */
9056   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9057   dwp_file->elf_sections =
9058     OBSTACK_CALLOC (&objfile->objfile_obstack,
9059                     dwp_file->num_sections, asection *);
9060
9061   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9062
9063   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9064
9065   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9066
9067   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9068
9069   discard_cleanups (cleanups);
9070
9071   if (dwarf2_read_debug)
9072     {
9073       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9074       fprintf_unfiltered (gdb_stdlog,
9075                           "    %u CUs, %u TUs\n",
9076                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9077                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9078     }
9079
9080   return dwp_file;
9081 }
9082
9083 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9084    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9085    or in the DWP file for the objfile, referenced by THIS_UNIT.
9086    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9087    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9088
9089    This is called, for example, when wanting to read a variable with a
9090    complex location.  Therefore we don't want to do file i/o for every call.
9091    Therefore we don't want to look for a DWO file on every call.
9092    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9093    then we check if we've already seen DWO_NAME, and only THEN do we check
9094    for a DWO file.
9095
9096    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9097    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9098
9099 static struct dwo_unit *
9100 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9101                  const char *dwo_name, const char *comp_dir,
9102                  ULONGEST signature, int is_debug_types)
9103 {
9104   struct objfile *objfile = dwarf2_per_objfile->objfile;
9105   const char *kind = is_debug_types ? "TU" : "CU";
9106   void **dwo_file_slot;
9107   struct dwo_file *dwo_file;
9108   struct dwp_file *dwp_file;
9109
9110   /* Have we already read SIGNATURE from a DWP file?  */
9111
9112   if (! dwarf2_per_objfile->dwp_checked)
9113     {
9114       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file (comp_dir);
9115       dwarf2_per_objfile->dwp_checked = 1;
9116     }
9117   dwp_file = dwarf2_per_objfile->dwp_file;
9118
9119   if (dwp_file != NULL)
9120     {
9121       const struct dwp_hash_table *dwp_htab =
9122         is_debug_types ? dwp_file->tus : dwp_file->cus;
9123
9124       if (dwp_htab != NULL)
9125         {
9126           struct dwo_unit *dwo_cutu =
9127             lookup_dwo_in_dwp (dwp_file, dwp_htab, signature, is_debug_types);
9128
9129           if (dwo_cutu != NULL)
9130             {
9131               if (dwarf2_read_debug)
9132                 {
9133                   fprintf_unfiltered (gdb_stdlog,
9134                                       "Virtual DWO %s %s found: @%s\n",
9135                                       kind, hex_string (signature),
9136                                       host_address_to_string (dwo_cutu));
9137                 }
9138               return dwo_cutu;
9139             }
9140         }
9141     }
9142
9143   /* Have we already seen DWO_NAME?  */
9144
9145   dwo_file_slot = lookup_dwo_file_slot (dwo_name);
9146   if (*dwo_file_slot == NULL)
9147     {
9148       /* Read in the file and build a table of the DWOs it contains.  */
9149       *dwo_file_slot = open_and_init_dwo_file (dwo_name, comp_dir);
9150     }
9151   /* NOTE: This will be NULL if unable to open the file.  */
9152   dwo_file = *dwo_file_slot;
9153
9154   if (dwo_file != NULL)
9155     {
9156       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9157
9158       if (htab != NULL)
9159         {
9160           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9161
9162           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9163           find_dwo_cutu.signature = signature;
9164           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9165
9166           if (dwo_cutu != NULL)
9167             {
9168               if (dwarf2_read_debug)
9169                 {
9170                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9171                                       kind, dwo_name, hex_string (signature),
9172                                       host_address_to_string (dwo_cutu));
9173                 }
9174               return dwo_cutu;
9175             }
9176         }
9177     }
9178
9179   /* We didn't find it.  This could mean a dwo_id mismatch, or
9180      someone deleted the DWO/DWP file, or the search path isn't set up
9181      correctly to find the file.  */
9182
9183   if (dwarf2_read_debug)
9184     {
9185       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9186                           kind, dwo_name, hex_string (signature));
9187     }
9188
9189   complaint (&symfile_complaints,
9190              _("Could not find DWO CU referenced by CU at offset 0x%x"
9191                " [in module %s]"),
9192              this_unit->offset.sect_off, objfile->name);
9193   return NULL;
9194 }
9195
9196 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9197    See lookup_dwo_cutu_unit for details.  */
9198
9199 static struct dwo_unit *
9200 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9201                       const char *dwo_name, const char *comp_dir,
9202                       ULONGEST signature)
9203 {
9204   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9205 }
9206
9207 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9208    See lookup_dwo_cutu_unit for details.  */
9209
9210 static struct dwo_unit *
9211 lookup_dwo_type_unit (struct signatured_type *this_tu,
9212                       const char *dwo_name, const char *comp_dir)
9213 {
9214   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9215 }
9216
9217 /* Free all resources associated with DWO_FILE.
9218    Close the DWO file and munmap the sections.
9219    All memory should be on the objfile obstack.  */
9220
9221 static void
9222 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9223 {
9224   int ix;
9225   struct dwarf2_section_info *section;
9226
9227   gdb_bfd_unref (dwo_file->dbfd);
9228
9229   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9230 }
9231
9232 /* Wrapper for free_dwo_file for use in cleanups.  */
9233
9234 static void
9235 free_dwo_file_cleanup (void *arg)
9236 {
9237   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9238   struct objfile *objfile = dwarf2_per_objfile->objfile;
9239
9240   free_dwo_file (dwo_file, objfile);
9241 }
9242
9243 /* Traversal function for free_dwo_files.  */
9244
9245 static int
9246 free_dwo_file_from_slot (void **slot, void *info)
9247 {
9248   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9249   struct objfile *objfile = (struct objfile *) info;
9250
9251   free_dwo_file (dwo_file, objfile);
9252
9253   return 1;
9254 }
9255
9256 /* Free all resources associated with DWO_FILES.  */
9257
9258 static void
9259 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9260 {
9261   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9262 }
9263 \f
9264 /* Read in various DIEs.  */
9265
9266 /* qsort helper for inherit_abstract_dies.  */
9267
9268 static int
9269 unsigned_int_compar (const void *ap, const void *bp)
9270 {
9271   unsigned int a = *(unsigned int *) ap;
9272   unsigned int b = *(unsigned int *) bp;
9273
9274   return (a > b) - (b > a);
9275 }
9276
9277 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9278    Inherit only the children of the DW_AT_abstract_origin DIE not being
9279    already referenced by DW_AT_abstract_origin from the children of the
9280    current DIE.  */
9281
9282 static void
9283 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9284 {
9285   struct die_info *child_die;
9286   unsigned die_children_count;
9287   /* CU offsets which were referenced by children of the current DIE.  */
9288   sect_offset *offsets;
9289   sect_offset *offsets_end, *offsetp;
9290   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9291   struct die_info *origin_die;
9292   /* Iterator of the ORIGIN_DIE children.  */
9293   struct die_info *origin_child_die;
9294   struct cleanup *cleanups;
9295   struct attribute *attr;
9296   struct dwarf2_cu *origin_cu;
9297   struct pending **origin_previous_list_in_scope;
9298
9299   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9300   if (!attr)
9301     return;
9302
9303   /* Note that following die references may follow to a die in a
9304      different cu.  */
9305
9306   origin_cu = cu;
9307   origin_die = follow_die_ref (die, attr, &origin_cu);
9308
9309   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9310      symbols in.  */
9311   origin_previous_list_in_scope = origin_cu->list_in_scope;
9312   origin_cu->list_in_scope = cu->list_in_scope;
9313
9314   if (die->tag != origin_die->tag
9315       && !(die->tag == DW_TAG_inlined_subroutine
9316            && origin_die->tag == DW_TAG_subprogram))
9317     complaint (&symfile_complaints,
9318                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9319                die->offset.sect_off, origin_die->offset.sect_off);
9320
9321   child_die = die->child;
9322   die_children_count = 0;
9323   while (child_die && child_die->tag)
9324     {
9325       child_die = sibling_die (child_die);
9326       die_children_count++;
9327     }
9328   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9329   cleanups = make_cleanup (xfree, offsets);
9330
9331   offsets_end = offsets;
9332   child_die = die->child;
9333   while (child_die && child_die->tag)
9334     {
9335       /* For each CHILD_DIE, find the corresponding child of
9336          ORIGIN_DIE.  If there is more than one layer of
9337          DW_AT_abstract_origin, follow them all; there shouldn't be,
9338          but GCC versions at least through 4.4 generate this (GCC PR
9339          40573).  */
9340       struct die_info *child_origin_die = child_die;
9341       struct dwarf2_cu *child_origin_cu = cu;
9342
9343       while (1)
9344         {
9345           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9346                               child_origin_cu);
9347           if (attr == NULL)
9348             break;
9349           child_origin_die = follow_die_ref (child_origin_die, attr,
9350                                              &child_origin_cu);
9351         }
9352
9353       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9354          counterpart may exist.  */
9355       if (child_origin_die != child_die)
9356         {
9357           if (child_die->tag != child_origin_die->tag
9358               && !(child_die->tag == DW_TAG_inlined_subroutine
9359                    && child_origin_die->tag == DW_TAG_subprogram))
9360             complaint (&symfile_complaints,
9361                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9362                          "different tags"), child_die->offset.sect_off,
9363                        child_origin_die->offset.sect_off);
9364           if (child_origin_die->parent != origin_die)
9365             complaint (&symfile_complaints,
9366                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9367                          "different parents"), child_die->offset.sect_off,
9368                        child_origin_die->offset.sect_off);
9369           else
9370             *offsets_end++ = child_origin_die->offset;
9371         }
9372       child_die = sibling_die (child_die);
9373     }
9374   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9375          unsigned_int_compar);
9376   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9377     if (offsetp[-1].sect_off == offsetp->sect_off)
9378       complaint (&symfile_complaints,
9379                  _("Multiple children of DIE 0x%x refer "
9380                    "to DIE 0x%x as their abstract origin"),
9381                  die->offset.sect_off, offsetp->sect_off);
9382
9383   offsetp = offsets;
9384   origin_child_die = origin_die->child;
9385   while (origin_child_die && origin_child_die->tag)
9386     {
9387       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9388       while (offsetp < offsets_end
9389              && offsetp->sect_off < origin_child_die->offset.sect_off)
9390         offsetp++;
9391       if (offsetp >= offsets_end
9392           || offsetp->sect_off > origin_child_die->offset.sect_off)
9393         {
9394           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9395           process_die (origin_child_die, origin_cu);
9396         }
9397       origin_child_die = sibling_die (origin_child_die);
9398     }
9399   origin_cu->list_in_scope = origin_previous_list_in_scope;
9400
9401   do_cleanups (cleanups);
9402 }
9403
9404 static void
9405 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9406 {
9407   struct objfile *objfile = cu->objfile;
9408   struct context_stack *new;
9409   CORE_ADDR lowpc;
9410   CORE_ADDR highpc;
9411   struct die_info *child_die;
9412   struct attribute *attr, *call_line, *call_file;
9413   const char *name;
9414   CORE_ADDR baseaddr;
9415   struct block *block;
9416   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9417   VEC (symbolp) *template_args = NULL;
9418   struct template_symbol *templ_func = NULL;
9419
9420   if (inlined_func)
9421     {
9422       /* If we do not have call site information, we can't show the
9423          caller of this inlined function.  That's too confusing, so
9424          only use the scope for local variables.  */
9425       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9426       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9427       if (call_line == NULL || call_file == NULL)
9428         {
9429           read_lexical_block_scope (die, cu);
9430           return;
9431         }
9432     }
9433
9434   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9435
9436   name = dwarf2_name (die, cu);
9437
9438   /* Ignore functions with missing or empty names.  These are actually
9439      illegal according to the DWARF standard.  */
9440   if (name == NULL)
9441     {
9442       complaint (&symfile_complaints,
9443                  _("missing name for subprogram DIE at %d"),
9444                  die->offset.sect_off);
9445       return;
9446     }
9447
9448   /* Ignore functions with missing or invalid low and high pc attributes.  */
9449   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9450     {
9451       attr = dwarf2_attr (die, DW_AT_external, cu);
9452       if (!attr || !DW_UNSND (attr))
9453         complaint (&symfile_complaints,
9454                    _("cannot get low and high bounds "
9455                      "for subprogram DIE at %d"),
9456                    die->offset.sect_off);
9457       return;
9458     }
9459
9460   lowpc += baseaddr;
9461   highpc += baseaddr;
9462
9463   /* If we have any template arguments, then we must allocate a
9464      different sort of symbol.  */
9465   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9466     {
9467       if (child_die->tag == DW_TAG_template_type_param
9468           || child_die->tag == DW_TAG_template_value_param)
9469         {
9470           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9471                                        struct template_symbol);
9472           templ_func->base.is_cplus_template_function = 1;
9473           break;
9474         }
9475     }
9476
9477   new = push_context (0, lowpc);
9478   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9479                                (struct symbol *) templ_func);
9480
9481   /* If there is a location expression for DW_AT_frame_base, record
9482      it.  */
9483   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9484   if (attr)
9485     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
9486        expression is being recorded directly in the function's symbol
9487        and not in a separate frame-base object.  I guess this hack is
9488        to avoid adding some sort of frame-base adjunct/annex to the
9489        function's symbol :-(.  The problem with doing this is that it
9490        results in a function symbol with a location expression that
9491        has nothing to do with the location of the function, ouch!  The
9492        relationship should be: a function's symbol has-a frame base; a
9493        frame-base has-a location expression.  */
9494     dwarf2_symbol_mark_computed (attr, new->name, cu);
9495
9496   cu->list_in_scope = &local_symbols;
9497
9498   if (die->child != NULL)
9499     {
9500       child_die = die->child;
9501       while (child_die && child_die->tag)
9502         {
9503           if (child_die->tag == DW_TAG_template_type_param
9504               || child_die->tag == DW_TAG_template_value_param)
9505             {
9506               struct symbol *arg = new_symbol (child_die, NULL, cu);
9507
9508               if (arg != NULL)
9509                 VEC_safe_push (symbolp, template_args, arg);
9510             }
9511           else
9512             process_die (child_die, cu);
9513           child_die = sibling_die (child_die);
9514         }
9515     }
9516
9517   inherit_abstract_dies (die, cu);
9518
9519   /* If we have a DW_AT_specification, we might need to import using
9520      directives from the context of the specification DIE.  See the
9521      comment in determine_prefix.  */
9522   if (cu->language == language_cplus
9523       && dwarf2_attr (die, DW_AT_specification, cu))
9524     {
9525       struct dwarf2_cu *spec_cu = cu;
9526       struct die_info *spec_die = die_specification (die, &spec_cu);
9527
9528       while (spec_die)
9529         {
9530           child_die = spec_die->child;
9531           while (child_die && child_die->tag)
9532             {
9533               if (child_die->tag == DW_TAG_imported_module)
9534                 process_die (child_die, spec_cu);
9535               child_die = sibling_die (child_die);
9536             }
9537
9538           /* In some cases, GCC generates specification DIEs that
9539              themselves contain DW_AT_specification attributes.  */
9540           spec_die = die_specification (spec_die, &spec_cu);
9541         }
9542     }
9543
9544   new = pop_context ();
9545   /* Make a block for the local symbols within.  */
9546   block = finish_block (new->name, &local_symbols, new->old_blocks,
9547                         lowpc, highpc, objfile);
9548
9549   /* For C++, set the block's scope.  */
9550   if ((cu->language == language_cplus || cu->language == language_fortran)
9551       && cu->processing_has_namespace_info)
9552     block_set_scope (block, determine_prefix (die, cu),
9553                      &objfile->objfile_obstack);
9554
9555   /* If we have address ranges, record them.  */
9556   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9557
9558   /* Attach template arguments to function.  */
9559   if (! VEC_empty (symbolp, template_args))
9560     {
9561       gdb_assert (templ_func != NULL);
9562
9563       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9564       templ_func->template_arguments
9565         = obstack_alloc (&objfile->objfile_obstack,
9566                          (templ_func->n_template_arguments
9567                           * sizeof (struct symbol *)));
9568       memcpy (templ_func->template_arguments,
9569               VEC_address (symbolp, template_args),
9570               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9571       VEC_free (symbolp, template_args);
9572     }
9573
9574   /* In C++, we can have functions nested inside functions (e.g., when
9575      a function declares a class that has methods).  This means that
9576      when we finish processing a function scope, we may need to go
9577      back to building a containing block's symbol lists.  */
9578   local_symbols = new->locals;
9579   using_directives = new->using_directives;
9580
9581   /* If we've finished processing a top-level function, subsequent
9582      symbols go in the file symbol list.  */
9583   if (outermost_context_p ())
9584     cu->list_in_scope = &file_symbols;
9585 }
9586
9587 /* Process all the DIES contained within a lexical block scope.  Start
9588    a new scope, process the dies, and then close the scope.  */
9589
9590 static void
9591 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9592 {
9593   struct objfile *objfile = cu->objfile;
9594   struct context_stack *new;
9595   CORE_ADDR lowpc, highpc;
9596   struct die_info *child_die;
9597   CORE_ADDR baseaddr;
9598
9599   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9600
9601   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9602   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9603      as multiple lexical blocks?  Handling children in a sane way would
9604      be nasty.  Might be easier to properly extend generic blocks to
9605      describe ranges.  */
9606   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9607     return;
9608   lowpc += baseaddr;
9609   highpc += baseaddr;
9610
9611   push_context (0, lowpc);
9612   if (die->child != NULL)
9613     {
9614       child_die = die->child;
9615       while (child_die && child_die->tag)
9616         {
9617           process_die (child_die, cu);
9618           child_die = sibling_die (child_die);
9619         }
9620     }
9621   new = pop_context ();
9622
9623   if (local_symbols != NULL || using_directives != NULL)
9624     {
9625       struct block *block
9626         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9627                         highpc, objfile);
9628
9629       /* Note that recording ranges after traversing children, as we
9630          do here, means that recording a parent's ranges entails
9631          walking across all its children's ranges as they appear in
9632          the address map, which is quadratic behavior.
9633
9634          It would be nicer to record the parent's ranges before
9635          traversing its children, simply overriding whatever you find
9636          there.  But since we don't even decide whether to create a
9637          block until after we've traversed its children, that's hard
9638          to do.  */
9639       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9640     }
9641   local_symbols = new->locals;
9642   using_directives = new->using_directives;
9643 }
9644
9645 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9646
9647 static void
9648 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9649 {
9650   struct objfile *objfile = cu->objfile;
9651   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9652   CORE_ADDR pc, baseaddr;
9653   struct attribute *attr;
9654   struct call_site *call_site, call_site_local;
9655   void **slot;
9656   int nparams;
9657   struct die_info *child_die;
9658
9659   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9660
9661   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9662   if (!attr)
9663     {
9664       complaint (&symfile_complaints,
9665                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9666                    "DIE 0x%x [in module %s]"),
9667                  die->offset.sect_off, objfile->name);
9668       return;
9669     }
9670   pc = DW_ADDR (attr) + baseaddr;
9671
9672   if (cu->call_site_htab == NULL)
9673     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9674                                                NULL, &objfile->objfile_obstack,
9675                                                hashtab_obstack_allocate, NULL);
9676   call_site_local.pc = pc;
9677   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9678   if (*slot != NULL)
9679     {
9680       complaint (&symfile_complaints,
9681                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9682                    "DIE 0x%x [in module %s]"),
9683                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9684       return;
9685     }
9686
9687   /* Count parameters at the caller.  */
9688
9689   nparams = 0;
9690   for (child_die = die->child; child_die && child_die->tag;
9691        child_die = sibling_die (child_die))
9692     {
9693       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9694         {
9695           complaint (&symfile_complaints,
9696                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9697                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9698                      child_die->tag, child_die->offset.sect_off, objfile->name);
9699           continue;
9700         }
9701
9702       nparams++;
9703     }
9704
9705   call_site = obstack_alloc (&objfile->objfile_obstack,
9706                              (sizeof (*call_site)
9707                               + (sizeof (*call_site->parameter)
9708                                  * (nparams - 1))));
9709   *slot = call_site;
9710   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9711   call_site->pc = pc;
9712
9713   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9714     {
9715       struct die_info *func_die;
9716
9717       /* Skip also over DW_TAG_inlined_subroutine.  */
9718       for (func_die = die->parent;
9719            func_die && func_die->tag != DW_TAG_subprogram
9720            && func_die->tag != DW_TAG_subroutine_type;
9721            func_die = func_die->parent);
9722
9723       /* DW_AT_GNU_all_call_sites is a superset
9724          of DW_AT_GNU_all_tail_call_sites.  */
9725       if (func_die
9726           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9727           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9728         {
9729           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9730              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9731              both the initial caller containing the real return address PC and
9732              the final callee containing the current PC of a chain of tail
9733              calls do not need to have the tail call list complete.  But any
9734              function candidate for a virtual tail call frame searched via
9735              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9736              determined unambiguously.  */
9737         }
9738       else
9739         {
9740           struct type *func_type = NULL;
9741
9742           if (func_die)
9743             func_type = get_die_type (func_die, cu);
9744           if (func_type != NULL)
9745             {
9746               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9747
9748               /* Enlist this call site to the function.  */
9749               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9750               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9751             }
9752           else
9753             complaint (&symfile_complaints,
9754                        _("Cannot find function owning DW_TAG_GNU_call_site "
9755                          "DIE 0x%x [in module %s]"),
9756                        die->offset.sect_off, objfile->name);
9757         }
9758     }
9759
9760   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9761   if (attr == NULL)
9762     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9763   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9764   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9765     /* Keep NULL DWARF_BLOCK.  */;
9766   else if (attr_form_is_block (attr))
9767     {
9768       struct dwarf2_locexpr_baton *dlbaton;
9769
9770       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9771       dlbaton->data = DW_BLOCK (attr)->data;
9772       dlbaton->size = DW_BLOCK (attr)->size;
9773       dlbaton->per_cu = cu->per_cu;
9774
9775       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9776     }
9777   else if (is_ref_attr (attr))
9778     {
9779       struct dwarf2_cu *target_cu = cu;
9780       struct die_info *target_die;
9781
9782       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9783       gdb_assert (target_cu->objfile == objfile);
9784       if (die_is_declaration (target_die, target_cu))
9785         {
9786           const char *target_physname;
9787
9788           target_physname = dwarf2_physname (NULL, target_die, target_cu);
9789           if (target_physname == NULL)
9790             complaint (&symfile_complaints,
9791                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9792                          "physname, for referencing DIE 0x%x [in module %s]"),
9793                        die->offset.sect_off, objfile->name);
9794           else
9795             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9796         }
9797       else
9798         {
9799           CORE_ADDR lowpc;
9800
9801           /* DW_AT_entry_pc should be preferred.  */
9802           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9803             complaint (&symfile_complaints,
9804                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9805                          "low pc, for referencing DIE 0x%x [in module %s]"),
9806                        die->offset.sect_off, objfile->name);
9807           else
9808             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9809         }
9810     }
9811   else
9812     complaint (&symfile_complaints,
9813                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9814                  "block nor reference, for DIE 0x%x [in module %s]"),
9815                die->offset.sect_off, objfile->name);
9816
9817   call_site->per_cu = cu->per_cu;
9818
9819   for (child_die = die->child;
9820        child_die && child_die->tag;
9821        child_die = sibling_die (child_die))
9822     {
9823       struct call_site_parameter *parameter;
9824       struct attribute *loc, *origin;
9825
9826       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9827         {
9828           /* Already printed the complaint above.  */
9829           continue;
9830         }
9831
9832       gdb_assert (call_site->parameter_count < nparams);
9833       parameter = &call_site->parameter[call_site->parameter_count];
9834
9835       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
9836          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
9837          register is contained in DW_AT_GNU_call_site_value.  */
9838
9839       loc = dwarf2_attr (child_die, DW_AT_location, cu);
9840       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
9841       if (loc == NULL && origin != NULL && is_ref_attr (origin))
9842         {
9843           sect_offset offset;
9844
9845           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
9846           offset = dwarf2_get_ref_die_offset (origin);
9847           if (!offset_in_cu_p (&cu->header, offset))
9848             {
9849               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
9850                  binding can be done only inside one CU.  Such referenced DIE
9851                  therefore cannot be even moved to DW_TAG_partial_unit.  */
9852               complaint (&symfile_complaints,
9853                          _("DW_AT_abstract_origin offset is not in CU for "
9854                            "DW_TAG_GNU_call_site child DIE 0x%x "
9855                            "[in module %s]"),
9856                          child_die->offset.sect_off, objfile->name);
9857               continue;
9858             }
9859           parameter->u.param_offset.cu_off = (offset.sect_off
9860                                               - cu->header.offset.sect_off);
9861         }
9862       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
9863         {
9864           complaint (&symfile_complaints,
9865                      _("No DW_FORM_block* DW_AT_location for "
9866                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9867                      child_die->offset.sect_off, objfile->name);
9868           continue;
9869         }
9870       else
9871         {
9872           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
9873             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
9874           if (parameter->u.dwarf_reg != -1)
9875             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
9876           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
9877                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
9878                                              &parameter->u.fb_offset))
9879             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
9880           else
9881             {
9882               complaint (&symfile_complaints,
9883                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
9884                            "for DW_FORM_block* DW_AT_location is supported for "
9885                            "DW_TAG_GNU_call_site child DIE 0x%x "
9886                            "[in module %s]"),
9887                          child_die->offset.sect_off, objfile->name);
9888               continue;
9889             }
9890         }
9891
9892       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
9893       if (!attr_form_is_block (attr))
9894         {
9895           complaint (&symfile_complaints,
9896                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
9897                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9898                      child_die->offset.sect_off, objfile->name);
9899           continue;
9900         }
9901       parameter->value = DW_BLOCK (attr)->data;
9902       parameter->value_size = DW_BLOCK (attr)->size;
9903
9904       /* Parameters are not pre-cleared by memset above.  */
9905       parameter->data_value = NULL;
9906       parameter->data_value_size = 0;
9907       call_site->parameter_count++;
9908
9909       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
9910       if (attr)
9911         {
9912           if (!attr_form_is_block (attr))
9913             complaint (&symfile_complaints,
9914                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
9915                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9916                        child_die->offset.sect_off, objfile->name);
9917           else
9918             {
9919               parameter->data_value = DW_BLOCK (attr)->data;
9920               parameter->data_value_size = DW_BLOCK (attr)->size;
9921             }
9922         }
9923     }
9924 }
9925
9926 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
9927    Return 1 if the attributes are present and valid, otherwise, return 0.
9928    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
9929
9930 static int
9931 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
9932                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
9933                     struct partial_symtab *ranges_pst)
9934 {
9935   struct objfile *objfile = cu->objfile;
9936   struct comp_unit_head *cu_header = &cu->header;
9937   bfd *obfd = objfile->obfd;
9938   unsigned int addr_size = cu_header->addr_size;
9939   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9940   /* Base address selection entry.  */
9941   CORE_ADDR base;
9942   int found_base;
9943   unsigned int dummy;
9944   gdb_byte *buffer;
9945   CORE_ADDR marker;
9946   int low_set;
9947   CORE_ADDR low = 0;
9948   CORE_ADDR high = 0;
9949   CORE_ADDR baseaddr;
9950
9951   found_base = cu->base_known;
9952   base = cu->base_address;
9953
9954   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
9955   if (offset >= dwarf2_per_objfile->ranges.size)
9956     {
9957       complaint (&symfile_complaints,
9958                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
9959                  offset);
9960       return 0;
9961     }
9962   buffer = dwarf2_per_objfile->ranges.buffer + offset;
9963
9964   /* Read in the largest possible address.  */
9965   marker = read_address (obfd, buffer, cu, &dummy);
9966   if ((marker & mask) == mask)
9967     {
9968       /* If we found the largest possible address, then
9969          read the base address.  */
9970       base = read_address (obfd, buffer + addr_size, cu, &dummy);
9971       buffer += 2 * addr_size;
9972       offset += 2 * addr_size;
9973       found_base = 1;
9974     }
9975
9976   low_set = 0;
9977
9978   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9979
9980   while (1)
9981     {
9982       CORE_ADDR range_beginning, range_end;
9983
9984       range_beginning = read_address (obfd, buffer, cu, &dummy);
9985       buffer += addr_size;
9986       range_end = read_address (obfd, buffer, cu, &dummy);
9987       buffer += addr_size;
9988       offset += 2 * addr_size;
9989
9990       /* An end of list marker is a pair of zero addresses.  */
9991       if (range_beginning == 0 && range_end == 0)
9992         /* Found the end of list entry.  */
9993         break;
9994
9995       /* Each base address selection entry is a pair of 2 values.
9996          The first is the largest possible address, the second is
9997          the base address.  Check for a base address here.  */
9998       if ((range_beginning & mask) == mask)
9999         {
10000           /* If we found the largest possible address, then
10001              read the base address.  */
10002           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10003           found_base = 1;
10004           continue;
10005         }
10006
10007       if (!found_base)
10008         {
10009           /* We have no valid base address for the ranges
10010              data.  */
10011           complaint (&symfile_complaints,
10012                      _("Invalid .debug_ranges data (no base address)"));
10013           return 0;
10014         }
10015
10016       if (range_beginning > range_end)
10017         {
10018           /* Inverted range entries are invalid.  */
10019           complaint (&symfile_complaints,
10020                      _("Invalid .debug_ranges data (inverted range)"));
10021           return 0;
10022         }
10023
10024       /* Empty range entries have no effect.  */
10025       if (range_beginning == range_end)
10026         continue;
10027
10028       range_beginning += base;
10029       range_end += base;
10030
10031       /* A not-uncommon case of bad debug info.
10032          Don't pollute the addrmap with bad data.  */
10033       if (range_beginning + baseaddr == 0
10034           && !dwarf2_per_objfile->has_section_at_zero)
10035         {
10036           complaint (&symfile_complaints,
10037                      _(".debug_ranges entry has start address of zero"
10038                        " [in module %s]"), objfile->name);
10039           continue;
10040         }
10041
10042       if (ranges_pst != NULL)
10043         addrmap_set_empty (objfile->psymtabs_addrmap,
10044                            range_beginning + baseaddr,
10045                            range_end - 1 + baseaddr,
10046                            ranges_pst);
10047
10048       /* FIXME: This is recording everything as a low-high
10049          segment of consecutive addresses.  We should have a
10050          data structure for discontiguous block ranges
10051          instead.  */
10052       if (! low_set)
10053         {
10054           low = range_beginning;
10055           high = range_end;
10056           low_set = 1;
10057         }
10058       else
10059         {
10060           if (range_beginning < low)
10061             low = range_beginning;
10062           if (range_end > high)
10063             high = range_end;
10064         }
10065     }
10066
10067   if (! low_set)
10068     /* If the first entry is an end-of-list marker, the range
10069        describes an empty scope, i.e. no instructions.  */
10070     return 0;
10071
10072   if (low_return)
10073     *low_return = low;
10074   if (high_return)
10075     *high_return = high;
10076   return 1;
10077 }
10078
10079 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10080    are present and valid, otherwise, return 0.  Return -1 if the range is
10081    discontinuous, i.e. derived from DW_AT_ranges information.  */
10082
10083 static int
10084 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10085                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10086                       struct partial_symtab *pst)
10087 {
10088   struct attribute *attr;
10089   struct attribute *attr_high;
10090   CORE_ADDR low = 0;
10091   CORE_ADDR high = 0;
10092   int ret = 0;
10093
10094   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10095   if (attr_high)
10096     {
10097       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10098       if (attr)
10099         {
10100           low = DW_ADDR (attr);
10101           if (attr_high->form == DW_FORM_addr
10102               || attr_high->form == DW_FORM_GNU_addr_index)
10103             high = DW_ADDR (attr_high);
10104           else
10105             high = low + DW_UNSND (attr_high);
10106         }
10107       else
10108         /* Found high w/o low attribute.  */
10109         return 0;
10110
10111       /* Found consecutive range of addresses.  */
10112       ret = 1;
10113     }
10114   else
10115     {
10116       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10117       if (attr != NULL)
10118         {
10119           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10120              We take advantage of the fact that DW_AT_ranges does not appear
10121              in DW_TAG_compile_unit of DWO files.  */
10122           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10123           unsigned int ranges_offset = (DW_UNSND (attr)
10124                                         + (need_ranges_base
10125                                            ? cu->ranges_base
10126                                            : 0));
10127
10128           /* Value of the DW_AT_ranges attribute is the offset in the
10129              .debug_ranges section.  */
10130           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10131             return 0;
10132           /* Found discontinuous range of addresses.  */
10133           ret = -1;
10134         }
10135     }
10136
10137   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10138   if (high <= low)
10139     return 0;
10140
10141   /* When using the GNU linker, .gnu.linkonce. sections are used to
10142      eliminate duplicate copies of functions and vtables and such.
10143      The linker will arbitrarily choose one and discard the others.
10144      The AT_*_pc values for such functions refer to local labels in
10145      these sections.  If the section from that file was discarded, the
10146      labels are not in the output, so the relocs get a value of 0.
10147      If this is a discarded function, mark the pc bounds as invalid,
10148      so that GDB will ignore it.  */
10149   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10150     return 0;
10151
10152   *lowpc = low;
10153   if (highpc)
10154     *highpc = high;
10155   return ret;
10156 }
10157
10158 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10159    its low and high PC addresses.  Do nothing if these addresses could not
10160    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10161    and HIGHPC to the high address if greater than HIGHPC.  */
10162
10163 static void
10164 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10165                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10166                                  struct dwarf2_cu *cu)
10167 {
10168   CORE_ADDR low, high;
10169   struct die_info *child = die->child;
10170
10171   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10172     {
10173       *lowpc = min (*lowpc, low);
10174       *highpc = max (*highpc, high);
10175     }
10176
10177   /* If the language does not allow nested subprograms (either inside
10178      subprograms or lexical blocks), we're done.  */
10179   if (cu->language != language_ada)
10180     return;
10181
10182   /* Check all the children of the given DIE.  If it contains nested
10183      subprograms, then check their pc bounds.  Likewise, we need to
10184      check lexical blocks as well, as they may also contain subprogram
10185      definitions.  */
10186   while (child && child->tag)
10187     {
10188       if (child->tag == DW_TAG_subprogram
10189           || child->tag == DW_TAG_lexical_block)
10190         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10191       child = sibling_die (child);
10192     }
10193 }
10194
10195 /* Get the low and high pc's represented by the scope DIE, and store
10196    them in *LOWPC and *HIGHPC.  If the correct values can't be
10197    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10198
10199 static void
10200 get_scope_pc_bounds (struct die_info *die,
10201                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10202                      struct dwarf2_cu *cu)
10203 {
10204   CORE_ADDR best_low = (CORE_ADDR) -1;
10205   CORE_ADDR best_high = (CORE_ADDR) 0;
10206   CORE_ADDR current_low, current_high;
10207
10208   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10209     {
10210       best_low = current_low;
10211       best_high = current_high;
10212     }
10213   else
10214     {
10215       struct die_info *child = die->child;
10216
10217       while (child && child->tag)
10218         {
10219           switch (child->tag) {
10220           case DW_TAG_subprogram:
10221             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10222             break;
10223           case DW_TAG_namespace:
10224           case DW_TAG_module:
10225             /* FIXME: carlton/2004-01-16: Should we do this for
10226                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10227                that current GCC's always emit the DIEs corresponding
10228                to definitions of methods of classes as children of a
10229                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10230                the DIEs giving the declarations, which could be
10231                anywhere).  But I don't see any reason why the
10232                standards says that they have to be there.  */
10233             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10234
10235             if (current_low != ((CORE_ADDR) -1))
10236               {
10237                 best_low = min (best_low, current_low);
10238                 best_high = max (best_high, current_high);
10239               }
10240             break;
10241           default:
10242             /* Ignore.  */
10243             break;
10244           }
10245
10246           child = sibling_die (child);
10247         }
10248     }
10249
10250   *lowpc = best_low;
10251   *highpc = best_high;
10252 }
10253
10254 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10255    in DIE.  */
10256
10257 static void
10258 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10259                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10260 {
10261   struct objfile *objfile = cu->objfile;
10262   struct attribute *attr;
10263   struct attribute *attr_high;
10264
10265   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10266   if (attr_high)
10267     {
10268       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10269       if (attr)
10270         {
10271           CORE_ADDR low = DW_ADDR (attr);
10272           CORE_ADDR high;
10273           if (attr_high->form == DW_FORM_addr
10274               || attr_high->form == DW_FORM_GNU_addr_index)
10275             high = DW_ADDR (attr_high);
10276           else
10277             high = low + DW_UNSND (attr_high);
10278
10279           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10280         }
10281     }
10282
10283   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10284   if (attr)
10285     {
10286       bfd *obfd = objfile->obfd;
10287       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10288          We take advantage of the fact that DW_AT_ranges does not appear
10289          in DW_TAG_compile_unit of DWO files.  */
10290       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10291
10292       /* The value of the DW_AT_ranges attribute is the offset of the
10293          address range list in the .debug_ranges section.  */
10294       unsigned long offset = (DW_UNSND (attr)
10295                               + (need_ranges_base ? cu->ranges_base : 0));
10296       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10297
10298       /* For some target architectures, but not others, the
10299          read_address function sign-extends the addresses it returns.
10300          To recognize base address selection entries, we need a
10301          mask.  */
10302       unsigned int addr_size = cu->header.addr_size;
10303       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10304
10305       /* The base address, to which the next pair is relative.  Note
10306          that this 'base' is a DWARF concept: most entries in a range
10307          list are relative, to reduce the number of relocs against the
10308          debugging information.  This is separate from this function's
10309          'baseaddr' argument, which GDB uses to relocate debugging
10310          information from a shared library based on the address at
10311          which the library was loaded.  */
10312       CORE_ADDR base = cu->base_address;
10313       int base_known = cu->base_known;
10314
10315       gdb_assert (dwarf2_per_objfile->ranges.readin);
10316       if (offset >= dwarf2_per_objfile->ranges.size)
10317         {
10318           complaint (&symfile_complaints,
10319                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10320                      offset);
10321           return;
10322         }
10323
10324       for (;;)
10325         {
10326           unsigned int bytes_read;
10327           CORE_ADDR start, end;
10328
10329           start = read_address (obfd, buffer, cu, &bytes_read);
10330           buffer += bytes_read;
10331           end = read_address (obfd, buffer, cu, &bytes_read);
10332           buffer += bytes_read;
10333
10334           /* Did we find the end of the range list?  */
10335           if (start == 0 && end == 0)
10336             break;
10337
10338           /* Did we find a base address selection entry?  */
10339           else if ((start & base_select_mask) == base_select_mask)
10340             {
10341               base = end;
10342               base_known = 1;
10343             }
10344
10345           /* We found an ordinary address range.  */
10346           else
10347             {
10348               if (!base_known)
10349                 {
10350                   complaint (&symfile_complaints,
10351                              _("Invalid .debug_ranges data "
10352                                "(no base address)"));
10353                   return;
10354                 }
10355
10356               if (start > end)
10357                 {
10358                   /* Inverted range entries are invalid.  */
10359                   complaint (&symfile_complaints,
10360                              _("Invalid .debug_ranges data "
10361                                "(inverted range)"));
10362                   return;
10363                 }
10364
10365               /* Empty range entries have no effect.  */
10366               if (start == end)
10367                 continue;
10368
10369               start += base + baseaddr;
10370               end += base + baseaddr;
10371
10372               /* A not-uncommon case of bad debug info.
10373                  Don't pollute the addrmap with bad data.  */
10374               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10375                 {
10376                   complaint (&symfile_complaints,
10377                              _(".debug_ranges entry has start address of zero"
10378                                " [in module %s]"), objfile->name);
10379                   continue;
10380                 }
10381
10382               record_block_range (block, start, end - 1);
10383             }
10384         }
10385     }
10386 }
10387
10388 /* Check whether the producer field indicates either of GCC < 4.6, or the
10389    Intel C/C++ compiler, and cache the result in CU.  */
10390
10391 static void
10392 check_producer (struct dwarf2_cu *cu)
10393 {
10394   const char *cs;
10395   int major, minor, release;
10396
10397   if (cu->producer == NULL)
10398     {
10399       /* For unknown compilers expect their behavior is DWARF version
10400          compliant.
10401
10402          GCC started to support .debug_types sections by -gdwarf-4 since
10403          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10404          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10405          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10406          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10407     }
10408   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10409     {
10410       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10411
10412       cs = &cu->producer[strlen ("GNU ")];
10413       while (*cs && !isdigit (*cs))
10414         cs++;
10415       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10416         {
10417           /* Not recognized as GCC.  */
10418         }
10419       else
10420         {
10421           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10422           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10423         }
10424     }
10425   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10426     cu->producer_is_icc = 1;
10427   else
10428     {
10429       /* For other non-GCC compilers, expect their behavior is DWARF version
10430          compliant.  */
10431     }
10432
10433   cu->checked_producer = 1;
10434 }
10435
10436 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10437    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10438    during 4.6.0 experimental.  */
10439
10440 static int
10441 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10442 {
10443   if (!cu->checked_producer)
10444     check_producer (cu);
10445
10446   return cu->producer_is_gxx_lt_4_6;
10447 }
10448
10449 /* Return the default accessibility type if it is not overriden by
10450    DW_AT_accessibility.  */
10451
10452 static enum dwarf_access_attribute
10453 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10454 {
10455   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10456     {
10457       /* The default DWARF 2 accessibility for members is public, the default
10458          accessibility for inheritance is private.  */
10459
10460       if (die->tag != DW_TAG_inheritance)
10461         return DW_ACCESS_public;
10462       else
10463         return DW_ACCESS_private;
10464     }
10465   else
10466     {
10467       /* DWARF 3+ defines the default accessibility a different way.  The same
10468          rules apply now for DW_TAG_inheritance as for the members and it only
10469          depends on the container kind.  */
10470
10471       if (die->parent->tag == DW_TAG_class_type)
10472         return DW_ACCESS_private;
10473       else
10474         return DW_ACCESS_public;
10475     }
10476 }
10477
10478 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10479    offset.  If the attribute was not found return 0, otherwise return
10480    1.  If it was found but could not properly be handled, set *OFFSET
10481    to 0.  */
10482
10483 static int
10484 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10485                              LONGEST *offset)
10486 {
10487   struct attribute *attr;
10488
10489   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10490   if (attr != NULL)
10491     {
10492       *offset = 0;
10493
10494       /* Note that we do not check for a section offset first here.
10495          This is because DW_AT_data_member_location is new in DWARF 4,
10496          so if we see it, we can assume that a constant form is really
10497          a constant and not a section offset.  */
10498       if (attr_form_is_constant (attr))
10499         *offset = dwarf2_get_attr_constant_value (attr, 0);
10500       else if (attr_form_is_section_offset (attr))
10501         dwarf2_complex_location_expr_complaint ();
10502       else if (attr_form_is_block (attr))
10503         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10504       else
10505         dwarf2_complex_location_expr_complaint ();
10506
10507       return 1;
10508     }
10509
10510   return 0;
10511 }
10512
10513 /* Add an aggregate field to the field list.  */
10514
10515 static void
10516 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10517                   struct dwarf2_cu *cu)
10518 {
10519   struct objfile *objfile = cu->objfile;
10520   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10521   struct nextfield *new_field;
10522   struct attribute *attr;
10523   struct field *fp;
10524   const char *fieldname = "";
10525
10526   /* Allocate a new field list entry and link it in.  */
10527   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10528   make_cleanup (xfree, new_field);
10529   memset (new_field, 0, sizeof (struct nextfield));
10530
10531   if (die->tag == DW_TAG_inheritance)
10532     {
10533       new_field->next = fip->baseclasses;
10534       fip->baseclasses = new_field;
10535     }
10536   else
10537     {
10538       new_field->next = fip->fields;
10539       fip->fields = new_field;
10540     }
10541   fip->nfields++;
10542
10543   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10544   if (attr)
10545     new_field->accessibility = DW_UNSND (attr);
10546   else
10547     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10548   if (new_field->accessibility != DW_ACCESS_public)
10549     fip->non_public_fields = 1;
10550
10551   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10552   if (attr)
10553     new_field->virtuality = DW_UNSND (attr);
10554   else
10555     new_field->virtuality = DW_VIRTUALITY_none;
10556
10557   fp = &new_field->field;
10558
10559   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10560     {
10561       LONGEST offset;
10562
10563       /* Data member other than a C++ static data member.  */
10564
10565       /* Get type of field.  */
10566       fp->type = die_type (die, cu);
10567
10568       SET_FIELD_BITPOS (*fp, 0);
10569
10570       /* Get bit size of field (zero if none).  */
10571       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10572       if (attr)
10573         {
10574           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10575         }
10576       else
10577         {
10578           FIELD_BITSIZE (*fp) = 0;
10579         }
10580
10581       /* Get bit offset of field.  */
10582       if (handle_data_member_location (die, cu, &offset))
10583         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10584       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10585       if (attr)
10586         {
10587           if (gdbarch_bits_big_endian (gdbarch))
10588             {
10589               /* For big endian bits, the DW_AT_bit_offset gives the
10590                  additional bit offset from the MSB of the containing
10591                  anonymous object to the MSB of the field.  We don't
10592                  have to do anything special since we don't need to
10593                  know the size of the anonymous object.  */
10594               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10595             }
10596           else
10597             {
10598               /* For little endian bits, compute the bit offset to the
10599                  MSB of the anonymous object, subtract off the number of
10600                  bits from the MSB of the field to the MSB of the
10601                  object, and then subtract off the number of bits of
10602                  the field itself.  The result is the bit offset of
10603                  the LSB of the field.  */
10604               int anonymous_size;
10605               int bit_offset = DW_UNSND (attr);
10606
10607               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10608               if (attr)
10609                 {
10610                   /* The size of the anonymous object containing
10611                      the bit field is explicit, so use the
10612                      indicated size (in bytes).  */
10613                   anonymous_size = DW_UNSND (attr);
10614                 }
10615               else
10616                 {
10617                   /* The size of the anonymous object containing
10618                      the bit field must be inferred from the type
10619                      attribute of the data member containing the
10620                      bit field.  */
10621                   anonymous_size = TYPE_LENGTH (fp->type);
10622                 }
10623               SET_FIELD_BITPOS (*fp,
10624                                 (FIELD_BITPOS (*fp)
10625                                  + anonymous_size * bits_per_byte
10626                                  - bit_offset - FIELD_BITSIZE (*fp)));
10627             }
10628         }
10629
10630       /* Get name of field.  */
10631       fieldname = dwarf2_name (die, cu);
10632       if (fieldname == NULL)
10633         fieldname = "";
10634
10635       /* The name is already allocated along with this objfile, so we don't
10636          need to duplicate it for the type.  */
10637       fp->name = fieldname;
10638
10639       /* Change accessibility for artificial fields (e.g. virtual table
10640          pointer or virtual base class pointer) to private.  */
10641       if (dwarf2_attr (die, DW_AT_artificial, cu))
10642         {
10643           FIELD_ARTIFICIAL (*fp) = 1;
10644           new_field->accessibility = DW_ACCESS_private;
10645           fip->non_public_fields = 1;
10646         }
10647     }
10648   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10649     {
10650       /* C++ static member.  */
10651
10652       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10653          is a declaration, but all versions of G++ as of this writing
10654          (so through at least 3.2.1) incorrectly generate
10655          DW_TAG_variable tags.  */
10656
10657       const char *physname;
10658
10659       /* Get name of field.  */
10660       fieldname = dwarf2_name (die, cu);
10661       if (fieldname == NULL)
10662         return;
10663
10664       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10665       if (attr
10666           /* Only create a symbol if this is an external value.
10667              new_symbol checks this and puts the value in the global symbol
10668              table, which we want.  If it is not external, new_symbol
10669              will try to put the value in cu->list_in_scope which is wrong.  */
10670           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10671         {
10672           /* A static const member, not much different than an enum as far as
10673              we're concerned, except that we can support more types.  */
10674           new_symbol (die, NULL, cu);
10675         }
10676
10677       /* Get physical name.  */
10678       physname = dwarf2_physname (fieldname, die, cu);
10679
10680       /* The name is already allocated along with this objfile, so we don't
10681          need to duplicate it for the type.  */
10682       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10683       FIELD_TYPE (*fp) = die_type (die, cu);
10684       FIELD_NAME (*fp) = fieldname;
10685     }
10686   else if (die->tag == DW_TAG_inheritance)
10687     {
10688       LONGEST offset;
10689
10690       /* C++ base class field.  */
10691       if (handle_data_member_location (die, cu, &offset))
10692         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10693       FIELD_BITSIZE (*fp) = 0;
10694       FIELD_TYPE (*fp) = die_type (die, cu);
10695       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10696       fip->nbaseclasses++;
10697     }
10698 }
10699
10700 /* Add a typedef defined in the scope of the FIP's class.  */
10701
10702 static void
10703 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10704                     struct dwarf2_cu *cu)
10705 {
10706   struct objfile *objfile = cu->objfile;
10707   struct typedef_field_list *new_field;
10708   struct attribute *attr;
10709   struct typedef_field *fp;
10710   char *fieldname = "";
10711
10712   /* Allocate a new field list entry and link it in.  */
10713   new_field = xzalloc (sizeof (*new_field));
10714   make_cleanup (xfree, new_field);
10715
10716   gdb_assert (die->tag == DW_TAG_typedef);
10717
10718   fp = &new_field->field;
10719
10720   /* Get name of field.  */
10721   fp->name = dwarf2_name (die, cu);
10722   if (fp->name == NULL)
10723     return;
10724
10725   fp->type = read_type_die (die, cu);
10726
10727   new_field->next = fip->typedef_field_list;
10728   fip->typedef_field_list = new_field;
10729   fip->typedef_field_list_count++;
10730 }
10731
10732 /* Create the vector of fields, and attach it to the type.  */
10733
10734 static void
10735 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10736                               struct dwarf2_cu *cu)
10737 {
10738   int nfields = fip->nfields;
10739
10740   /* Record the field count, allocate space for the array of fields,
10741      and create blank accessibility bitfields if necessary.  */
10742   TYPE_NFIELDS (type) = nfields;
10743   TYPE_FIELDS (type) = (struct field *)
10744     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10745   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10746
10747   if (fip->non_public_fields && cu->language != language_ada)
10748     {
10749       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10750
10751       TYPE_FIELD_PRIVATE_BITS (type) =
10752         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10753       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10754
10755       TYPE_FIELD_PROTECTED_BITS (type) =
10756         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10757       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10758
10759       TYPE_FIELD_IGNORE_BITS (type) =
10760         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10761       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10762     }
10763
10764   /* If the type has baseclasses, allocate and clear a bit vector for
10765      TYPE_FIELD_VIRTUAL_BITS.  */
10766   if (fip->nbaseclasses && cu->language != language_ada)
10767     {
10768       int num_bytes = B_BYTES (fip->nbaseclasses);
10769       unsigned char *pointer;
10770
10771       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10772       pointer = TYPE_ALLOC (type, num_bytes);
10773       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10774       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10775       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10776     }
10777
10778   /* Copy the saved-up fields into the field vector.  Start from the head of
10779      the list, adding to the tail of the field array, so that they end up in
10780      the same order in the array in which they were added to the list.  */
10781   while (nfields-- > 0)
10782     {
10783       struct nextfield *fieldp;
10784
10785       if (fip->fields)
10786         {
10787           fieldp = fip->fields;
10788           fip->fields = fieldp->next;
10789         }
10790       else
10791         {
10792           fieldp = fip->baseclasses;
10793           fip->baseclasses = fieldp->next;
10794         }
10795
10796       TYPE_FIELD (type, nfields) = fieldp->field;
10797       switch (fieldp->accessibility)
10798         {
10799         case DW_ACCESS_private:
10800           if (cu->language != language_ada)
10801             SET_TYPE_FIELD_PRIVATE (type, nfields);
10802           break;
10803
10804         case DW_ACCESS_protected:
10805           if (cu->language != language_ada)
10806             SET_TYPE_FIELD_PROTECTED (type, nfields);
10807           break;
10808
10809         case DW_ACCESS_public:
10810           break;
10811
10812         default:
10813           /* Unknown accessibility.  Complain and treat it as public.  */
10814           {
10815             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10816                        fieldp->accessibility);
10817           }
10818           break;
10819         }
10820       if (nfields < fip->nbaseclasses)
10821         {
10822           switch (fieldp->virtuality)
10823             {
10824             case DW_VIRTUALITY_virtual:
10825             case DW_VIRTUALITY_pure_virtual:
10826               if (cu->language == language_ada)
10827                 error (_("unexpected virtuality in component of Ada type"));
10828               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10829               break;
10830             }
10831         }
10832     }
10833 }
10834
10835 /* Return true if this member function is a constructor, false
10836    otherwise.  */
10837
10838 static int
10839 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
10840 {
10841   const char *fieldname;
10842   const char *typename;
10843   int len;
10844
10845   if (die->parent == NULL)
10846     return 0;
10847
10848   if (die->parent->tag != DW_TAG_structure_type
10849       && die->parent->tag != DW_TAG_union_type
10850       && die->parent->tag != DW_TAG_class_type)
10851     return 0;
10852
10853   fieldname = dwarf2_name (die, cu);
10854   typename = dwarf2_name (die->parent, cu);
10855   if (fieldname == NULL || typename == NULL)
10856     return 0;
10857
10858   len = strlen (fieldname);
10859   return (strncmp (fieldname, typename, len) == 0
10860           && (typename[len] == '\0' || typename[len] == '<'));
10861 }
10862
10863 /* Add a member function to the proper fieldlist.  */
10864
10865 static void
10866 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
10867                       struct type *type, struct dwarf2_cu *cu)
10868 {
10869   struct objfile *objfile = cu->objfile;
10870   struct attribute *attr;
10871   struct fnfieldlist *flp;
10872   int i;
10873   struct fn_field *fnp;
10874   const char *fieldname;
10875   struct nextfnfield *new_fnfield;
10876   struct type *this_type;
10877   enum dwarf_access_attribute accessibility;
10878
10879   if (cu->language == language_ada)
10880     error (_("unexpected member function in Ada type"));
10881
10882   /* Get name of member function.  */
10883   fieldname = dwarf2_name (die, cu);
10884   if (fieldname == NULL)
10885     return;
10886
10887   /* Look up member function name in fieldlist.  */
10888   for (i = 0; i < fip->nfnfields; i++)
10889     {
10890       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
10891         break;
10892     }
10893
10894   /* Create new list element if necessary.  */
10895   if (i < fip->nfnfields)
10896     flp = &fip->fnfieldlists[i];
10897   else
10898     {
10899       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
10900         {
10901           fip->fnfieldlists = (struct fnfieldlist *)
10902             xrealloc (fip->fnfieldlists,
10903                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
10904                       * sizeof (struct fnfieldlist));
10905           if (fip->nfnfields == 0)
10906             make_cleanup (free_current_contents, &fip->fnfieldlists);
10907         }
10908       flp = &fip->fnfieldlists[fip->nfnfields];
10909       flp->name = fieldname;
10910       flp->length = 0;
10911       flp->head = NULL;
10912       i = fip->nfnfields++;
10913     }
10914
10915   /* Create a new member function field and chain it to the field list
10916      entry.  */
10917   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
10918   make_cleanup (xfree, new_fnfield);
10919   memset (new_fnfield, 0, sizeof (struct nextfnfield));
10920   new_fnfield->next = flp->head;
10921   flp->head = new_fnfield;
10922   flp->length++;
10923
10924   /* Fill in the member function field info.  */
10925   fnp = &new_fnfield->fnfield;
10926
10927   /* Delay processing of the physname until later.  */
10928   if (cu->language == language_cplus || cu->language == language_java)
10929     {
10930       add_to_method_list (type, i, flp->length - 1, fieldname,
10931                           die, cu);
10932     }
10933   else
10934     {
10935       const char *physname = dwarf2_physname (fieldname, die, cu);
10936       fnp->physname = physname ? physname : "";
10937     }
10938
10939   fnp->type = alloc_type (objfile);
10940   this_type = read_type_die (die, cu);
10941   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
10942     {
10943       int nparams = TYPE_NFIELDS (this_type);
10944
10945       /* TYPE is the domain of this method, and THIS_TYPE is the type
10946            of the method itself (TYPE_CODE_METHOD).  */
10947       smash_to_method_type (fnp->type, type,
10948                             TYPE_TARGET_TYPE (this_type),
10949                             TYPE_FIELDS (this_type),
10950                             TYPE_NFIELDS (this_type),
10951                             TYPE_VARARGS (this_type));
10952
10953       /* Handle static member functions.
10954          Dwarf2 has no clean way to discern C++ static and non-static
10955          member functions.  G++ helps GDB by marking the first
10956          parameter for non-static member functions (which is the this
10957          pointer) as artificial.  We obtain this information from
10958          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
10959       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
10960         fnp->voffset = VOFFSET_STATIC;
10961     }
10962   else
10963     complaint (&symfile_complaints, _("member function type missing for '%s'"),
10964                dwarf2_full_name (fieldname, die, cu));
10965
10966   /* Get fcontext from DW_AT_containing_type if present.  */
10967   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10968     fnp->fcontext = die_containing_type (die, cu);
10969
10970   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
10971      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
10972
10973   /* Get accessibility.  */
10974   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10975   if (attr)
10976     accessibility = DW_UNSND (attr);
10977   else
10978     accessibility = dwarf2_default_access_attribute (die, cu);
10979   switch (accessibility)
10980     {
10981     case DW_ACCESS_private:
10982       fnp->is_private = 1;
10983       break;
10984     case DW_ACCESS_protected:
10985       fnp->is_protected = 1;
10986       break;
10987     }
10988
10989   /* Check for artificial methods.  */
10990   attr = dwarf2_attr (die, DW_AT_artificial, cu);
10991   if (attr && DW_UNSND (attr) != 0)
10992     fnp->is_artificial = 1;
10993
10994   fnp->is_constructor = dwarf2_is_constructor (die, cu);
10995
10996   /* Get index in virtual function table if it is a virtual member
10997      function.  For older versions of GCC, this is an offset in the
10998      appropriate virtual table, as specified by DW_AT_containing_type.
10999      For everyone else, it is an expression to be evaluated relative
11000      to the object address.  */
11001
11002   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11003   if (attr)
11004     {
11005       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11006         {
11007           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11008             {
11009               /* Old-style GCC.  */
11010               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11011             }
11012           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11013                    || (DW_BLOCK (attr)->size > 1
11014                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11015                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11016             {
11017               struct dwarf_block blk;
11018               int offset;
11019
11020               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11021                         ? 1 : 2);
11022               blk.size = DW_BLOCK (attr)->size - offset;
11023               blk.data = DW_BLOCK (attr)->data + offset;
11024               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11025               if ((fnp->voffset % cu->header.addr_size) != 0)
11026                 dwarf2_complex_location_expr_complaint ();
11027               else
11028                 fnp->voffset /= cu->header.addr_size;
11029               fnp->voffset += 2;
11030             }
11031           else
11032             dwarf2_complex_location_expr_complaint ();
11033
11034           if (!fnp->fcontext)
11035             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11036         }
11037       else if (attr_form_is_section_offset (attr))
11038         {
11039           dwarf2_complex_location_expr_complaint ();
11040         }
11041       else
11042         {
11043           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11044                                                  fieldname);
11045         }
11046     }
11047   else
11048     {
11049       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11050       if (attr && DW_UNSND (attr))
11051         {
11052           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11053           complaint (&symfile_complaints,
11054                      _("Member function \"%s\" (offset %d) is virtual "
11055                        "but the vtable offset is not specified"),
11056                      fieldname, die->offset.sect_off);
11057           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11058           TYPE_CPLUS_DYNAMIC (type) = 1;
11059         }
11060     }
11061 }
11062
11063 /* Create the vector of member function fields, and attach it to the type.  */
11064
11065 static void
11066 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11067                                  struct dwarf2_cu *cu)
11068 {
11069   struct fnfieldlist *flp;
11070   int i;
11071
11072   if (cu->language == language_ada)
11073     error (_("unexpected member functions in Ada type"));
11074
11075   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11076   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11077     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11078
11079   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11080     {
11081       struct nextfnfield *nfp = flp->head;
11082       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11083       int k;
11084
11085       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11086       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11087       fn_flp->fn_fields = (struct fn_field *)
11088         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11089       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11090         fn_flp->fn_fields[k] = nfp->fnfield;
11091     }
11092
11093   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11094 }
11095
11096 /* Returns non-zero if NAME is the name of a vtable member in CU's
11097    language, zero otherwise.  */
11098 static int
11099 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11100 {
11101   static const char vptr[] = "_vptr";
11102   static const char vtable[] = "vtable";
11103
11104   /* Look for the C++ and Java forms of the vtable.  */
11105   if ((cu->language == language_java
11106        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11107        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11108        && is_cplus_marker (name[sizeof (vptr) - 1])))
11109     return 1;
11110
11111   return 0;
11112 }
11113
11114 /* GCC outputs unnamed structures that are really pointers to member
11115    functions, with the ABI-specified layout.  If TYPE describes
11116    such a structure, smash it into a member function type.
11117
11118    GCC shouldn't do this; it should just output pointer to member DIEs.
11119    This is GCC PR debug/28767.  */
11120
11121 static void
11122 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11123 {
11124   struct type *pfn_type, *domain_type, *new_type;
11125
11126   /* Check for a structure with no name and two children.  */
11127   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11128     return;
11129
11130   /* Check for __pfn and __delta members.  */
11131   if (TYPE_FIELD_NAME (type, 0) == NULL
11132       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11133       || TYPE_FIELD_NAME (type, 1) == NULL
11134       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11135     return;
11136
11137   /* Find the type of the method.  */
11138   pfn_type = TYPE_FIELD_TYPE (type, 0);
11139   if (pfn_type == NULL
11140       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11141       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11142     return;
11143
11144   /* Look for the "this" argument.  */
11145   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11146   if (TYPE_NFIELDS (pfn_type) == 0
11147       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11148       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11149     return;
11150
11151   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11152   new_type = alloc_type (objfile);
11153   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11154                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11155                         TYPE_VARARGS (pfn_type));
11156   smash_to_methodptr_type (type, new_type);
11157 }
11158
11159 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11160    (icc).  */
11161
11162 static int
11163 producer_is_icc (struct dwarf2_cu *cu)
11164 {
11165   if (!cu->checked_producer)
11166     check_producer (cu);
11167
11168   return cu->producer_is_icc;
11169 }
11170
11171 /* Called when we find the DIE that starts a structure or union scope
11172    (definition) to create a type for the structure or union.  Fill in
11173    the type's name and general properties; the members will not be
11174    processed until process_structure_type.
11175
11176    NOTE: we need to call these functions regardless of whether or not the
11177    DIE has a DW_AT_name attribute, since it might be an anonymous
11178    structure or union.  This gets the type entered into our set of
11179    user defined types.
11180
11181    However, if the structure is incomplete (an opaque struct/union)
11182    then suppress creating a symbol table entry for it since gdb only
11183    wants to find the one with the complete definition.  Note that if
11184    it is complete, we just call new_symbol, which does it's own
11185    checking about whether the struct/union is anonymous or not (and
11186    suppresses creating a symbol table entry itself).  */
11187
11188 static struct type *
11189 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11190 {
11191   struct objfile *objfile = cu->objfile;
11192   struct type *type;
11193   struct attribute *attr;
11194   const char *name;
11195
11196   /* If the definition of this type lives in .debug_types, read that type.
11197      Don't follow DW_AT_specification though, that will take us back up
11198      the chain and we want to go down.  */
11199   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11200   if (attr)
11201     {
11202       struct dwarf2_cu *type_cu = cu;
11203       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11204
11205       /* We could just recurse on read_structure_type, but we need to call
11206          get_die_type to ensure only one type for this DIE is created.
11207          This is important, for example, because for c++ classes we need
11208          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11209       type = read_type_die (type_die, type_cu);
11210
11211       /* TYPE_CU may not be the same as CU.
11212          Ensure TYPE is recorded in CU's type_hash table.  */
11213       return set_die_type (die, type, cu);
11214     }
11215
11216   type = alloc_type (objfile);
11217   INIT_CPLUS_SPECIFIC (type);
11218
11219   name = dwarf2_name (die, cu);
11220   if (name != NULL)
11221     {
11222       if (cu->language == language_cplus
11223           || cu->language == language_java)
11224         {
11225           const char *full_name = dwarf2_full_name (name, die, cu);
11226
11227           /* dwarf2_full_name might have already finished building the DIE's
11228              type.  If so, there is no need to continue.  */
11229           if (get_die_type (die, cu) != NULL)
11230             return get_die_type (die, cu);
11231
11232           TYPE_TAG_NAME (type) = full_name;
11233           if (die->tag == DW_TAG_structure_type
11234               || die->tag == DW_TAG_class_type)
11235             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11236         }
11237       else
11238         {
11239           /* The name is already allocated along with this objfile, so
11240              we don't need to duplicate it for the type.  */
11241           TYPE_TAG_NAME (type) = name;
11242           if (die->tag == DW_TAG_class_type)
11243             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11244         }
11245     }
11246
11247   if (die->tag == DW_TAG_structure_type)
11248     {
11249       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11250     }
11251   else if (die->tag == DW_TAG_union_type)
11252     {
11253       TYPE_CODE (type) = TYPE_CODE_UNION;
11254     }
11255   else
11256     {
11257       TYPE_CODE (type) = TYPE_CODE_CLASS;
11258     }
11259
11260   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11261     TYPE_DECLARED_CLASS (type) = 1;
11262
11263   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11264   if (attr)
11265     {
11266       TYPE_LENGTH (type) = DW_UNSND (attr);
11267     }
11268   else
11269     {
11270       TYPE_LENGTH (type) = 0;
11271     }
11272
11273   if (producer_is_icc (cu))
11274     {
11275       /* ICC does not output the required DW_AT_declaration
11276          on incomplete types, but gives them a size of zero.  */
11277     }
11278   else
11279     TYPE_STUB_SUPPORTED (type) = 1;
11280
11281   if (die_is_declaration (die, cu))
11282     TYPE_STUB (type) = 1;
11283   else if (attr == NULL && die->child == NULL
11284            && producer_is_realview (cu->producer))
11285     /* RealView does not output the required DW_AT_declaration
11286        on incomplete types.  */
11287     TYPE_STUB (type) = 1;
11288
11289   /* We need to add the type field to the die immediately so we don't
11290      infinitely recurse when dealing with pointers to the structure
11291      type within the structure itself.  */
11292   set_die_type (die, type, cu);
11293
11294   /* set_die_type should be already done.  */
11295   set_descriptive_type (type, die, cu);
11296
11297   return type;
11298 }
11299
11300 /* Finish creating a structure or union type, including filling in
11301    its members and creating a symbol for it.  */
11302
11303 static void
11304 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11305 {
11306   struct objfile *objfile = cu->objfile;
11307   struct die_info *child_die = die->child;
11308   struct type *type;
11309
11310   type = get_die_type (die, cu);
11311   if (type == NULL)
11312     type = read_structure_type (die, cu);
11313
11314   if (die->child != NULL && ! die_is_declaration (die, cu))
11315     {
11316       struct field_info fi;
11317       struct die_info *child_die;
11318       VEC (symbolp) *template_args = NULL;
11319       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11320
11321       memset (&fi, 0, sizeof (struct field_info));
11322
11323       child_die = die->child;
11324
11325       while (child_die && child_die->tag)
11326         {
11327           if (child_die->tag == DW_TAG_member
11328               || child_die->tag == DW_TAG_variable)
11329             {
11330               /* NOTE: carlton/2002-11-05: A C++ static data member
11331                  should be a DW_TAG_member that is a declaration, but
11332                  all versions of G++ as of this writing (so through at
11333                  least 3.2.1) incorrectly generate DW_TAG_variable
11334                  tags for them instead.  */
11335               dwarf2_add_field (&fi, child_die, cu);
11336             }
11337           else if (child_die->tag == DW_TAG_subprogram)
11338             {
11339               /* C++ member function.  */
11340               dwarf2_add_member_fn (&fi, child_die, type, cu);
11341             }
11342           else if (child_die->tag == DW_TAG_inheritance)
11343             {
11344               /* C++ base class field.  */
11345               dwarf2_add_field (&fi, child_die, cu);
11346             }
11347           else if (child_die->tag == DW_TAG_typedef)
11348             dwarf2_add_typedef (&fi, child_die, cu);
11349           else if (child_die->tag == DW_TAG_template_type_param
11350                    || child_die->tag == DW_TAG_template_value_param)
11351             {
11352               struct symbol *arg = new_symbol (child_die, NULL, cu);
11353
11354               if (arg != NULL)
11355                 VEC_safe_push (symbolp, template_args, arg);
11356             }
11357
11358           child_die = sibling_die (child_die);
11359         }
11360
11361       /* Attach template arguments to type.  */
11362       if (! VEC_empty (symbolp, template_args))
11363         {
11364           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11365           TYPE_N_TEMPLATE_ARGUMENTS (type)
11366             = VEC_length (symbolp, template_args);
11367           TYPE_TEMPLATE_ARGUMENTS (type)
11368             = obstack_alloc (&objfile->objfile_obstack,
11369                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11370                               * sizeof (struct symbol *)));
11371           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11372                   VEC_address (symbolp, template_args),
11373                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11374                    * sizeof (struct symbol *)));
11375           VEC_free (symbolp, template_args);
11376         }
11377
11378       /* Attach fields and member functions to the type.  */
11379       if (fi.nfields)
11380         dwarf2_attach_fields_to_type (&fi, type, cu);
11381       if (fi.nfnfields)
11382         {
11383           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11384
11385           /* Get the type which refers to the base class (possibly this
11386              class itself) which contains the vtable pointer for the current
11387              class from the DW_AT_containing_type attribute.  This use of
11388              DW_AT_containing_type is a GNU extension.  */
11389
11390           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11391             {
11392               struct type *t = die_containing_type (die, cu);
11393
11394               TYPE_VPTR_BASETYPE (type) = t;
11395               if (type == t)
11396                 {
11397                   int i;
11398
11399                   /* Our own class provides vtbl ptr.  */
11400                   for (i = TYPE_NFIELDS (t) - 1;
11401                        i >= TYPE_N_BASECLASSES (t);
11402                        --i)
11403                     {
11404                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11405
11406                       if (is_vtable_name (fieldname, cu))
11407                         {
11408                           TYPE_VPTR_FIELDNO (type) = i;
11409                           break;
11410                         }
11411                     }
11412
11413                   /* Complain if virtual function table field not found.  */
11414                   if (i < TYPE_N_BASECLASSES (t))
11415                     complaint (&symfile_complaints,
11416                                _("virtual function table pointer "
11417                                  "not found when defining class '%s'"),
11418                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11419                                "");
11420                 }
11421               else
11422                 {
11423                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11424                 }
11425             }
11426           else if (cu->producer
11427                    && strncmp (cu->producer,
11428                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11429             {
11430               /* The IBM XLC compiler does not provide direct indication
11431                  of the containing type, but the vtable pointer is
11432                  always named __vfp.  */
11433
11434               int i;
11435
11436               for (i = TYPE_NFIELDS (type) - 1;
11437                    i >= TYPE_N_BASECLASSES (type);
11438                    --i)
11439                 {
11440                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11441                     {
11442                       TYPE_VPTR_FIELDNO (type) = i;
11443                       TYPE_VPTR_BASETYPE (type) = type;
11444                       break;
11445                     }
11446                 }
11447             }
11448         }
11449
11450       /* Copy fi.typedef_field_list linked list elements content into the
11451          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11452       if (fi.typedef_field_list)
11453         {
11454           int i = fi.typedef_field_list_count;
11455
11456           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11457           TYPE_TYPEDEF_FIELD_ARRAY (type)
11458             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11459           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11460
11461           /* Reverse the list order to keep the debug info elements order.  */
11462           while (--i >= 0)
11463             {
11464               struct typedef_field *dest, *src;
11465
11466               dest = &TYPE_TYPEDEF_FIELD (type, i);
11467               src = &fi.typedef_field_list->field;
11468               fi.typedef_field_list = fi.typedef_field_list->next;
11469               *dest = *src;
11470             }
11471         }
11472
11473       do_cleanups (back_to);
11474
11475       if (HAVE_CPLUS_STRUCT (type))
11476         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11477     }
11478
11479   quirk_gcc_member_function_pointer (type, objfile);
11480
11481   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11482      snapshots) has been known to create a die giving a declaration
11483      for a class that has, as a child, a die giving a definition for a
11484      nested class.  So we have to process our children even if the
11485      current die is a declaration.  Normally, of course, a declaration
11486      won't have any children at all.  */
11487
11488   while (child_die != NULL && child_die->tag)
11489     {
11490       if (child_die->tag == DW_TAG_member
11491           || child_die->tag == DW_TAG_variable
11492           || child_die->tag == DW_TAG_inheritance
11493           || child_die->tag == DW_TAG_template_value_param
11494           || child_die->tag == DW_TAG_template_type_param)
11495         {
11496           /* Do nothing.  */
11497         }
11498       else
11499         process_die (child_die, cu);
11500
11501       child_die = sibling_die (child_die);
11502     }
11503
11504   /* Do not consider external references.  According to the DWARF standard,
11505      these DIEs are identified by the fact that they have no byte_size
11506      attribute, and a declaration attribute.  */
11507   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11508       || !die_is_declaration (die, cu))
11509     new_symbol (die, type, cu);
11510 }
11511
11512 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11513    complete the type's fields yet, or create any symbols.  */
11514
11515 static struct type *
11516 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11517 {
11518   struct objfile *objfile = cu->objfile;
11519   struct type *type;
11520   struct attribute *attr;
11521   const char *name;
11522
11523   /* If the definition of this type lives in .debug_types, read that type.
11524      Don't follow DW_AT_specification though, that will take us back up
11525      the chain and we want to go down.  */
11526   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11527   if (attr)
11528     {
11529       struct dwarf2_cu *type_cu = cu;
11530       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11531
11532       type = read_type_die (type_die, type_cu);
11533
11534       /* TYPE_CU may not be the same as CU.
11535          Ensure TYPE is recorded in CU's type_hash table.  */
11536       return set_die_type (die, type, cu);
11537     }
11538
11539   type = alloc_type (objfile);
11540
11541   TYPE_CODE (type) = TYPE_CODE_ENUM;
11542   name = dwarf2_full_name (NULL, die, cu);
11543   if (name != NULL)
11544     TYPE_TAG_NAME (type) = name;
11545
11546   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11547   if (attr)
11548     {
11549       TYPE_LENGTH (type) = DW_UNSND (attr);
11550     }
11551   else
11552     {
11553       TYPE_LENGTH (type) = 0;
11554     }
11555
11556   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11557      declared as private in the package spec, and then defined only
11558      inside the package body.  Such types are known as Taft Amendment
11559      Types.  When another package uses such a type, an incomplete DIE
11560      may be generated by the compiler.  */
11561   if (die_is_declaration (die, cu))
11562     TYPE_STUB (type) = 1;
11563
11564   return set_die_type (die, type, cu);
11565 }
11566
11567 /* Given a pointer to a die which begins an enumeration, process all
11568    the dies that define the members of the enumeration, and create the
11569    symbol for the enumeration type.
11570
11571    NOTE: We reverse the order of the element list.  */
11572
11573 static void
11574 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11575 {
11576   struct type *this_type;
11577
11578   this_type = get_die_type (die, cu);
11579   if (this_type == NULL)
11580     this_type = read_enumeration_type (die, cu);
11581
11582   if (die->child != NULL)
11583     {
11584       struct die_info *child_die;
11585       struct symbol *sym;
11586       struct field *fields = NULL;
11587       int num_fields = 0;
11588       int unsigned_enum = 1;
11589       const char *name;
11590       int flag_enum = 1;
11591       ULONGEST mask = 0;
11592
11593       child_die = die->child;
11594       while (child_die && child_die->tag)
11595         {
11596           if (child_die->tag != DW_TAG_enumerator)
11597             {
11598               process_die (child_die, cu);
11599             }
11600           else
11601             {
11602               name = dwarf2_name (child_die, cu);
11603               if (name)
11604                 {
11605                   sym = new_symbol (child_die, this_type, cu);
11606                   if (SYMBOL_VALUE (sym) < 0)
11607                     {
11608                       unsigned_enum = 0;
11609                       flag_enum = 0;
11610                     }
11611                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11612                     flag_enum = 0;
11613                   else
11614                     mask |= SYMBOL_VALUE (sym);
11615
11616                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11617                     {
11618                       fields = (struct field *)
11619                         xrealloc (fields,
11620                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11621                                   * sizeof (struct field));
11622                     }
11623
11624                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11625                   FIELD_TYPE (fields[num_fields]) = NULL;
11626                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11627                   FIELD_BITSIZE (fields[num_fields]) = 0;
11628
11629                   num_fields++;
11630                 }
11631             }
11632
11633           child_die = sibling_die (child_die);
11634         }
11635
11636       if (num_fields)
11637         {
11638           TYPE_NFIELDS (this_type) = num_fields;
11639           TYPE_FIELDS (this_type) = (struct field *)
11640             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11641           memcpy (TYPE_FIELDS (this_type), fields,
11642                   sizeof (struct field) * num_fields);
11643           xfree (fields);
11644         }
11645       if (unsigned_enum)
11646         TYPE_UNSIGNED (this_type) = 1;
11647       if (flag_enum)
11648         TYPE_FLAG_ENUM (this_type) = 1;
11649     }
11650
11651   /* If we are reading an enum from a .debug_types unit, and the enum
11652      is a declaration, and the enum is not the signatured type in the
11653      unit, then we do not want to add a symbol for it.  Adding a
11654      symbol would in some cases obscure the true definition of the
11655      enum, giving users an incomplete type when the definition is
11656      actually available.  Note that we do not want to do this for all
11657      enums which are just declarations, because C++0x allows forward
11658      enum declarations.  */
11659   if (cu->per_cu->is_debug_types
11660       && die_is_declaration (die, cu))
11661     {
11662       struct signatured_type *sig_type;
11663
11664       sig_type
11665         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
11666                                             cu->per_cu->info_or_types_section,
11667                                             cu->per_cu->offset);
11668       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11669       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11670         return;
11671     }
11672
11673   new_symbol (die, this_type, cu);
11674 }
11675
11676 /* Extract all information from a DW_TAG_array_type DIE and put it in
11677    the DIE's type field.  For now, this only handles one dimensional
11678    arrays.  */
11679
11680 static struct type *
11681 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11682 {
11683   struct objfile *objfile = cu->objfile;
11684   struct die_info *child_die;
11685   struct type *type;
11686   struct type *element_type, *range_type, *index_type;
11687   struct type **range_types = NULL;
11688   struct attribute *attr;
11689   int ndim = 0;
11690   struct cleanup *back_to;
11691   const char *name;
11692
11693   element_type = die_type (die, cu);
11694
11695   /* The die_type call above may have already set the type for this DIE.  */
11696   type = get_die_type (die, cu);
11697   if (type)
11698     return type;
11699
11700   /* Irix 6.2 native cc creates array types without children for
11701      arrays with unspecified length.  */
11702   if (die->child == NULL)
11703     {
11704       index_type = objfile_type (objfile)->builtin_int;
11705       range_type = create_range_type (NULL, index_type, 0, -1);
11706       type = create_array_type (NULL, element_type, range_type);
11707       return set_die_type (die, type, cu);
11708     }
11709
11710   back_to = make_cleanup (null_cleanup, NULL);
11711   child_die = die->child;
11712   while (child_die && child_die->tag)
11713     {
11714       if (child_die->tag == DW_TAG_subrange_type)
11715         {
11716           struct type *child_type = read_type_die (child_die, cu);
11717
11718           if (child_type != NULL)
11719             {
11720               /* The range type was succesfully read.  Save it for the
11721                  array type creation.  */
11722               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11723                 {
11724                   range_types = (struct type **)
11725                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11726                               * sizeof (struct type *));
11727                   if (ndim == 0)
11728                     make_cleanup (free_current_contents, &range_types);
11729                 }
11730               range_types[ndim++] = child_type;
11731             }
11732         }
11733       child_die = sibling_die (child_die);
11734     }
11735
11736   /* Dwarf2 dimensions are output from left to right, create the
11737      necessary array types in backwards order.  */
11738
11739   type = element_type;
11740
11741   if (read_array_order (die, cu) == DW_ORD_col_major)
11742     {
11743       int i = 0;
11744
11745       while (i < ndim)
11746         type = create_array_type (NULL, type, range_types[i++]);
11747     }
11748   else
11749     {
11750       while (ndim-- > 0)
11751         type = create_array_type (NULL, type, range_types[ndim]);
11752     }
11753
11754   /* Understand Dwarf2 support for vector types (like they occur on
11755      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11756      array type.  This is not part of the Dwarf2/3 standard yet, but a
11757      custom vendor extension.  The main difference between a regular
11758      array and the vector variant is that vectors are passed by value
11759      to functions.  */
11760   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11761   if (attr)
11762     make_vector_type (type);
11763
11764   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11765      implementation may choose to implement triple vectors using this
11766      attribute.  */
11767   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11768   if (attr)
11769     {
11770       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11771         TYPE_LENGTH (type) = DW_UNSND (attr);
11772       else
11773         complaint (&symfile_complaints,
11774                    _("DW_AT_byte_size for array type smaller "
11775                      "than the total size of elements"));
11776     }
11777
11778   name = dwarf2_name (die, cu);
11779   if (name)
11780     TYPE_NAME (type) = name;
11781
11782   /* Install the type in the die.  */
11783   set_die_type (die, type, cu);
11784
11785   /* set_die_type should be already done.  */
11786   set_descriptive_type (type, die, cu);
11787
11788   do_cleanups (back_to);
11789
11790   return type;
11791 }
11792
11793 static enum dwarf_array_dim_ordering
11794 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11795 {
11796   struct attribute *attr;
11797
11798   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11799
11800   if (attr) return DW_SND (attr);
11801
11802   /* GNU F77 is a special case, as at 08/2004 array type info is the
11803      opposite order to the dwarf2 specification, but data is still
11804      laid out as per normal fortran.
11805
11806      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11807      version checking.  */
11808
11809   if (cu->language == language_fortran
11810       && cu->producer && strstr (cu->producer, "GNU F77"))
11811     {
11812       return DW_ORD_row_major;
11813     }
11814
11815   switch (cu->language_defn->la_array_ordering)
11816     {
11817     case array_column_major:
11818       return DW_ORD_col_major;
11819     case array_row_major:
11820     default:
11821       return DW_ORD_row_major;
11822     };
11823 }
11824
11825 /* Extract all information from a DW_TAG_set_type DIE and put it in
11826    the DIE's type field.  */
11827
11828 static struct type *
11829 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11830 {
11831   struct type *domain_type, *set_type;
11832   struct attribute *attr;
11833
11834   domain_type = die_type (die, cu);
11835
11836   /* The die_type call above may have already set the type for this DIE.  */
11837   set_type = get_die_type (die, cu);
11838   if (set_type)
11839     return set_type;
11840
11841   set_type = create_set_type (NULL, domain_type);
11842
11843   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11844   if (attr)
11845     TYPE_LENGTH (set_type) = DW_UNSND (attr);
11846
11847   return set_die_type (die, set_type, cu);
11848 }
11849
11850 /* A helper for read_common_block that creates a locexpr baton.
11851    SYM is the symbol which we are marking as computed.
11852    COMMON_DIE is the DIE for the common block.
11853    COMMON_LOC is the location expression attribute for the common
11854    block itself.
11855    MEMBER_LOC is the location expression attribute for the particular
11856    member of the common block that we are processing.
11857    CU is the CU from which the above come.  */
11858
11859 static void
11860 mark_common_block_symbol_computed (struct symbol *sym,
11861                                    struct die_info *common_die,
11862                                    struct attribute *common_loc,
11863                                    struct attribute *member_loc,
11864                                    struct dwarf2_cu *cu)
11865 {
11866   struct objfile *objfile = dwarf2_per_objfile->objfile;
11867   struct dwarf2_locexpr_baton *baton;
11868   gdb_byte *ptr;
11869   unsigned int cu_off;
11870   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
11871   LONGEST offset = 0;
11872
11873   gdb_assert (common_loc && member_loc);
11874   gdb_assert (attr_form_is_block (common_loc));
11875   gdb_assert (attr_form_is_block (member_loc)
11876               || attr_form_is_constant (member_loc));
11877
11878   baton = obstack_alloc (&objfile->objfile_obstack,
11879                          sizeof (struct dwarf2_locexpr_baton));
11880   baton->per_cu = cu->per_cu;
11881   gdb_assert (baton->per_cu);
11882
11883   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
11884
11885   if (attr_form_is_constant (member_loc))
11886     {
11887       offset = dwarf2_get_attr_constant_value (member_loc, 0);
11888       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
11889     }
11890   else
11891     baton->size += DW_BLOCK (member_loc)->size;
11892
11893   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
11894   baton->data = ptr;
11895
11896   *ptr++ = DW_OP_call4;
11897   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
11898   store_unsigned_integer (ptr, 4, byte_order, cu_off);
11899   ptr += 4;
11900
11901   if (attr_form_is_constant (member_loc))
11902     {
11903       *ptr++ = DW_OP_addr;
11904       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
11905       ptr += cu->header.addr_size;
11906     }
11907   else
11908     {
11909       /* We have to copy the data here, because DW_OP_call4 will only
11910          use a DW_AT_location attribute.  */
11911       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
11912       ptr += DW_BLOCK (member_loc)->size;
11913     }
11914
11915   *ptr++ = DW_OP_plus;
11916   gdb_assert (ptr - baton->data == baton->size);
11917
11918   SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
11919   SYMBOL_LOCATION_BATON (sym) = baton;
11920   SYMBOL_CLASS (sym) = LOC_COMPUTED;
11921 }
11922
11923 /* Create appropriate locally-scoped variables for all the
11924    DW_TAG_common_block entries.  Also create a struct common_block
11925    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
11926    is used to sepate the common blocks name namespace from regular
11927    variable names.  */
11928
11929 static void
11930 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
11931 {
11932   struct attribute *attr;
11933
11934   attr = dwarf2_attr (die, DW_AT_location, cu);
11935   if (attr)
11936     {
11937       /* Support the .debug_loc offsets.  */
11938       if (attr_form_is_block (attr))
11939         {
11940           /* Ok.  */
11941         }
11942       else if (attr_form_is_section_offset (attr))
11943         {
11944           dwarf2_complex_location_expr_complaint ();
11945           attr = NULL;
11946         }
11947       else
11948         {
11949           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11950                                                  "common block member");
11951           attr = NULL;
11952         }
11953     }
11954
11955   if (die->child != NULL)
11956     {
11957       struct objfile *objfile = cu->objfile;
11958       struct die_info *child_die;
11959       size_t n_entries = 0, size;
11960       struct common_block *common_block;
11961       struct symbol *sym;
11962
11963       for (child_die = die->child;
11964            child_die && child_die->tag;
11965            child_die = sibling_die (child_die))
11966         ++n_entries;
11967
11968       size = (sizeof (struct common_block)
11969               + (n_entries - 1) * sizeof (struct symbol *));
11970       common_block = obstack_alloc (&objfile->objfile_obstack, size);
11971       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
11972       common_block->n_entries = 0;
11973
11974       for (child_die = die->child;
11975            child_die && child_die->tag;
11976            child_die = sibling_die (child_die))
11977         {
11978           /* Create the symbol in the DW_TAG_common_block block in the current
11979              symbol scope.  */
11980           sym = new_symbol (child_die, NULL, cu);
11981           if (sym != NULL)
11982             {
11983               struct attribute *member_loc;
11984
11985               common_block->contents[common_block->n_entries++] = sym;
11986
11987               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
11988                                         cu);
11989               if (member_loc)
11990                 {
11991                   /* GDB has handled this for a long time, but it is
11992                      not specified by DWARF.  It seems to have been
11993                      emitted by gfortran at least as recently as:
11994                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
11995                   complaint (&symfile_complaints,
11996                              _("Variable in common block has "
11997                                "DW_AT_data_member_location "
11998                                "- DIE at 0x%x [in module %s]"),
11999                              child_die->offset.sect_off, cu->objfile->name);
12000
12001                   if (attr_form_is_section_offset (member_loc))
12002                     dwarf2_complex_location_expr_complaint ();
12003                   else if (attr_form_is_constant (member_loc)
12004                            || attr_form_is_block (member_loc))
12005                     {
12006                       if (attr)
12007                         mark_common_block_symbol_computed (sym, die, attr,
12008                                                            member_loc, cu);
12009                     }
12010                   else
12011                     dwarf2_complex_location_expr_complaint ();
12012                 }
12013             }
12014         }
12015
12016       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12017       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12018     }
12019 }
12020
12021 /* Create a type for a C++ namespace.  */
12022
12023 static struct type *
12024 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12025 {
12026   struct objfile *objfile = cu->objfile;
12027   const char *previous_prefix, *name;
12028   int is_anonymous;
12029   struct type *type;
12030
12031   /* For extensions, reuse the type of the original namespace.  */
12032   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12033     {
12034       struct die_info *ext_die;
12035       struct dwarf2_cu *ext_cu = cu;
12036
12037       ext_die = dwarf2_extension (die, &ext_cu);
12038       type = read_type_die (ext_die, ext_cu);
12039
12040       /* EXT_CU may not be the same as CU.
12041          Ensure TYPE is recorded in CU's type_hash table.  */
12042       return set_die_type (die, type, cu);
12043     }
12044
12045   name = namespace_name (die, &is_anonymous, cu);
12046
12047   /* Now build the name of the current namespace.  */
12048
12049   previous_prefix = determine_prefix (die, cu);
12050   if (previous_prefix[0] != '\0')
12051     name = typename_concat (&objfile->objfile_obstack,
12052                             previous_prefix, name, 0, cu);
12053
12054   /* Create the type.  */
12055   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12056                     objfile);
12057   TYPE_NAME (type) = name;
12058   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12059
12060   return set_die_type (die, type, cu);
12061 }
12062
12063 /* Read a C++ namespace.  */
12064
12065 static void
12066 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12067 {
12068   struct objfile *objfile = cu->objfile;
12069   int is_anonymous;
12070
12071   /* Add a symbol associated to this if we haven't seen the namespace
12072      before.  Also, add a using directive if it's an anonymous
12073      namespace.  */
12074
12075   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12076     {
12077       struct type *type;
12078
12079       type = read_type_die (die, cu);
12080       new_symbol (die, type, cu);
12081
12082       namespace_name (die, &is_anonymous, cu);
12083       if (is_anonymous)
12084         {
12085           const char *previous_prefix = determine_prefix (die, cu);
12086
12087           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12088                                   NULL, NULL, 0, &objfile->objfile_obstack);
12089         }
12090     }
12091
12092   if (die->child != NULL)
12093     {
12094       struct die_info *child_die = die->child;
12095
12096       while (child_die && child_die->tag)
12097         {
12098           process_die (child_die, cu);
12099           child_die = sibling_die (child_die);
12100         }
12101     }
12102 }
12103
12104 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12105    imported module.  Still we need that type as local Fortran "use ... only"
12106    declaration imports depend on the created type in determine_prefix.  */
12107
12108 static struct type *
12109 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12110 {
12111   struct objfile *objfile = cu->objfile;
12112   const char *module_name;
12113   struct type *type;
12114
12115   module_name = dwarf2_name (die, cu);
12116   if (!module_name)
12117     complaint (&symfile_complaints,
12118                _("DW_TAG_module has no name, offset 0x%x"),
12119                die->offset.sect_off);
12120   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12121
12122   /* determine_prefix uses TYPE_TAG_NAME.  */
12123   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12124
12125   return set_die_type (die, type, cu);
12126 }
12127
12128 /* Read a Fortran module.  */
12129
12130 static void
12131 read_module (struct die_info *die, struct dwarf2_cu *cu)
12132 {
12133   struct die_info *child_die = die->child;
12134
12135   while (child_die && child_die->tag)
12136     {
12137       process_die (child_die, cu);
12138       child_die = sibling_die (child_die);
12139     }
12140 }
12141
12142 /* Return the name of the namespace represented by DIE.  Set
12143    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12144    namespace.  */
12145
12146 static const char *
12147 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12148 {
12149   struct die_info *current_die;
12150   const char *name = NULL;
12151
12152   /* Loop through the extensions until we find a name.  */
12153
12154   for (current_die = die;
12155        current_die != NULL;
12156        current_die = dwarf2_extension (die, &cu))
12157     {
12158       name = dwarf2_name (current_die, cu);
12159       if (name != NULL)
12160         break;
12161     }
12162
12163   /* Is it an anonymous namespace?  */
12164
12165   *is_anonymous = (name == NULL);
12166   if (*is_anonymous)
12167     name = CP_ANONYMOUS_NAMESPACE_STR;
12168
12169   return name;
12170 }
12171
12172 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12173    the user defined type vector.  */
12174
12175 static struct type *
12176 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12177 {
12178   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12179   struct comp_unit_head *cu_header = &cu->header;
12180   struct type *type;
12181   struct attribute *attr_byte_size;
12182   struct attribute *attr_address_class;
12183   int byte_size, addr_class;
12184   struct type *target_type;
12185
12186   target_type = die_type (die, cu);
12187
12188   /* The die_type call above may have already set the type for this DIE.  */
12189   type = get_die_type (die, cu);
12190   if (type)
12191     return type;
12192
12193   type = lookup_pointer_type (target_type);
12194
12195   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12196   if (attr_byte_size)
12197     byte_size = DW_UNSND (attr_byte_size);
12198   else
12199     byte_size = cu_header->addr_size;
12200
12201   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12202   if (attr_address_class)
12203     addr_class = DW_UNSND (attr_address_class);
12204   else
12205     addr_class = DW_ADDR_none;
12206
12207   /* If the pointer size or address class is different than the
12208      default, create a type variant marked as such and set the
12209      length accordingly.  */
12210   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12211     {
12212       if (gdbarch_address_class_type_flags_p (gdbarch))
12213         {
12214           int type_flags;
12215
12216           type_flags = gdbarch_address_class_type_flags
12217                          (gdbarch, byte_size, addr_class);
12218           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12219                       == 0);
12220           type = make_type_with_address_space (type, type_flags);
12221         }
12222       else if (TYPE_LENGTH (type) != byte_size)
12223         {
12224           complaint (&symfile_complaints,
12225                      _("invalid pointer size %d"), byte_size);
12226         }
12227       else
12228         {
12229           /* Should we also complain about unhandled address classes?  */
12230         }
12231     }
12232
12233   TYPE_LENGTH (type) = byte_size;
12234   return set_die_type (die, type, cu);
12235 }
12236
12237 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12238    the user defined type vector.  */
12239
12240 static struct type *
12241 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12242 {
12243   struct type *type;
12244   struct type *to_type;
12245   struct type *domain;
12246
12247   to_type = die_type (die, cu);
12248   domain = die_containing_type (die, cu);
12249
12250   /* The calls above may have already set the type for this DIE.  */
12251   type = get_die_type (die, cu);
12252   if (type)
12253     return type;
12254
12255   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12256     type = lookup_methodptr_type (to_type);
12257   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12258     {
12259       struct type *new_type = alloc_type (cu->objfile);
12260
12261       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12262                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12263                             TYPE_VARARGS (to_type));
12264       type = lookup_methodptr_type (new_type);
12265     }
12266   else
12267     type = lookup_memberptr_type (to_type, domain);
12268
12269   return set_die_type (die, type, cu);
12270 }
12271
12272 /* Extract all information from a DW_TAG_reference_type DIE and add to
12273    the user defined type vector.  */
12274
12275 static struct type *
12276 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12277 {
12278   struct comp_unit_head *cu_header = &cu->header;
12279   struct type *type, *target_type;
12280   struct attribute *attr;
12281
12282   target_type = die_type (die, cu);
12283
12284   /* The die_type call above may have already set the type for this DIE.  */
12285   type = get_die_type (die, cu);
12286   if (type)
12287     return type;
12288
12289   type = lookup_reference_type (target_type);
12290   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12291   if (attr)
12292     {
12293       TYPE_LENGTH (type) = DW_UNSND (attr);
12294     }
12295   else
12296     {
12297       TYPE_LENGTH (type) = cu_header->addr_size;
12298     }
12299   return set_die_type (die, type, cu);
12300 }
12301
12302 static struct type *
12303 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12304 {
12305   struct type *base_type, *cv_type;
12306
12307   base_type = die_type (die, cu);
12308
12309   /* The die_type call above may have already set the type for this DIE.  */
12310   cv_type = get_die_type (die, cu);
12311   if (cv_type)
12312     return cv_type;
12313
12314   /* In case the const qualifier is applied to an array type, the element type
12315      is so qualified, not the array type (section 6.7.3 of C99).  */
12316   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12317     {
12318       struct type *el_type, *inner_array;
12319
12320       base_type = copy_type (base_type);
12321       inner_array = base_type;
12322
12323       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12324         {
12325           TYPE_TARGET_TYPE (inner_array) =
12326             copy_type (TYPE_TARGET_TYPE (inner_array));
12327           inner_array = TYPE_TARGET_TYPE (inner_array);
12328         }
12329
12330       el_type = TYPE_TARGET_TYPE (inner_array);
12331       TYPE_TARGET_TYPE (inner_array) =
12332         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12333
12334       return set_die_type (die, base_type, cu);
12335     }
12336
12337   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12338   return set_die_type (die, cv_type, cu);
12339 }
12340
12341 static struct type *
12342 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12343 {
12344   struct type *base_type, *cv_type;
12345
12346   base_type = die_type (die, cu);
12347
12348   /* The die_type call above may have already set the type for this DIE.  */
12349   cv_type = get_die_type (die, cu);
12350   if (cv_type)
12351     return cv_type;
12352
12353   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12354   return set_die_type (die, cv_type, cu);
12355 }
12356
12357 /* Handle DW_TAG_restrict_type.  */
12358
12359 static struct type *
12360 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12361 {
12362   struct type *base_type, *cv_type;
12363
12364   base_type = die_type (die, cu);
12365
12366   /* The die_type call above may have already set the type for this DIE.  */
12367   cv_type = get_die_type (die, cu);
12368   if (cv_type)
12369     return cv_type;
12370
12371   cv_type = make_restrict_type (base_type);
12372   return set_die_type (die, cv_type, cu);
12373 }
12374
12375 /* Extract all information from a DW_TAG_string_type DIE and add to
12376    the user defined type vector.  It isn't really a user defined type,
12377    but it behaves like one, with other DIE's using an AT_user_def_type
12378    attribute to reference it.  */
12379
12380 static struct type *
12381 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12382 {
12383   struct objfile *objfile = cu->objfile;
12384   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12385   struct type *type, *range_type, *index_type, *char_type;
12386   struct attribute *attr;
12387   unsigned int length;
12388
12389   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12390   if (attr)
12391     {
12392       length = DW_UNSND (attr);
12393     }
12394   else
12395     {
12396       /* Check for the DW_AT_byte_size attribute.  */
12397       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12398       if (attr)
12399         {
12400           length = DW_UNSND (attr);
12401         }
12402       else
12403         {
12404           length = 1;
12405         }
12406     }
12407
12408   index_type = objfile_type (objfile)->builtin_int;
12409   range_type = create_range_type (NULL, index_type, 1, length);
12410   char_type = language_string_char_type (cu->language_defn, gdbarch);
12411   type = create_string_type (NULL, char_type, range_type);
12412
12413   return set_die_type (die, type, cu);
12414 }
12415
12416 /* Handle DIES due to C code like:
12417
12418    struct foo
12419    {
12420    int (*funcp)(int a, long l);
12421    int b;
12422    };
12423
12424    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12425
12426 static struct type *
12427 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12428 {
12429   struct objfile *objfile = cu->objfile;
12430   struct type *type;            /* Type that this function returns.  */
12431   struct type *ftype;           /* Function that returns above type.  */
12432   struct attribute *attr;
12433
12434   type = die_type (die, cu);
12435
12436   /* The die_type call above may have already set the type for this DIE.  */
12437   ftype = get_die_type (die, cu);
12438   if (ftype)
12439     return ftype;
12440
12441   ftype = lookup_function_type (type);
12442
12443   /* All functions in C++, Pascal and Java have prototypes.  */
12444   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12445   if ((attr && (DW_UNSND (attr) != 0))
12446       || cu->language == language_cplus
12447       || cu->language == language_java
12448       || cu->language == language_pascal)
12449     TYPE_PROTOTYPED (ftype) = 1;
12450   else if (producer_is_realview (cu->producer))
12451     /* RealView does not emit DW_AT_prototyped.  We can not
12452        distinguish prototyped and unprototyped functions; default to
12453        prototyped, since that is more common in modern code (and
12454        RealView warns about unprototyped functions).  */
12455     TYPE_PROTOTYPED (ftype) = 1;
12456
12457   /* Store the calling convention in the type if it's available in
12458      the subroutine die.  Otherwise set the calling convention to
12459      the default value DW_CC_normal.  */
12460   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12461   if (attr)
12462     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12463   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12464     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12465   else
12466     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12467
12468   /* We need to add the subroutine type to the die immediately so
12469      we don't infinitely recurse when dealing with parameters
12470      declared as the same subroutine type.  */
12471   set_die_type (die, ftype, cu);
12472
12473   if (die->child != NULL)
12474     {
12475       struct type *void_type = objfile_type (objfile)->builtin_void;
12476       struct die_info *child_die;
12477       int nparams, iparams;
12478
12479       /* Count the number of parameters.
12480          FIXME: GDB currently ignores vararg functions, but knows about
12481          vararg member functions.  */
12482       nparams = 0;
12483       child_die = die->child;
12484       while (child_die && child_die->tag)
12485         {
12486           if (child_die->tag == DW_TAG_formal_parameter)
12487             nparams++;
12488           else if (child_die->tag == DW_TAG_unspecified_parameters)
12489             TYPE_VARARGS (ftype) = 1;
12490           child_die = sibling_die (child_die);
12491         }
12492
12493       /* Allocate storage for parameters and fill them in.  */
12494       TYPE_NFIELDS (ftype) = nparams;
12495       TYPE_FIELDS (ftype) = (struct field *)
12496         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12497
12498       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12499          even if we error out during the parameters reading below.  */
12500       for (iparams = 0; iparams < nparams; iparams++)
12501         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12502
12503       iparams = 0;
12504       child_die = die->child;
12505       while (child_die && child_die->tag)
12506         {
12507           if (child_die->tag == DW_TAG_formal_parameter)
12508             {
12509               struct type *arg_type;
12510
12511               /* DWARF version 2 has no clean way to discern C++
12512                  static and non-static member functions.  G++ helps
12513                  GDB by marking the first parameter for non-static
12514                  member functions (which is the this pointer) as
12515                  artificial.  We pass this information to
12516                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12517
12518                  DWARF version 3 added DW_AT_object_pointer, which GCC
12519                  4.5 does not yet generate.  */
12520               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12521               if (attr)
12522                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12523               else
12524                 {
12525                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12526
12527                   /* GCC/43521: In java, the formal parameter
12528                      "this" is sometimes not marked with DW_AT_artificial.  */
12529                   if (cu->language == language_java)
12530                     {
12531                       const char *name = dwarf2_name (child_die, cu);
12532
12533                       if (name && !strcmp (name, "this"))
12534                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12535                     }
12536                 }
12537               arg_type = die_type (child_die, cu);
12538
12539               /* RealView does not mark THIS as const, which the testsuite
12540                  expects.  GCC marks THIS as const in method definitions,
12541                  but not in the class specifications (GCC PR 43053).  */
12542               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12543                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12544                 {
12545                   int is_this = 0;
12546                   struct dwarf2_cu *arg_cu = cu;
12547                   const char *name = dwarf2_name (child_die, cu);
12548
12549                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12550                   if (attr)
12551                     {
12552                       /* If the compiler emits this, use it.  */
12553                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12554                         is_this = 1;
12555                     }
12556                   else if (name && strcmp (name, "this") == 0)
12557                     /* Function definitions will have the argument names.  */
12558                     is_this = 1;
12559                   else if (name == NULL && iparams == 0)
12560                     /* Declarations may not have the names, so like
12561                        elsewhere in GDB, assume an artificial first
12562                        argument is "this".  */
12563                     is_this = 1;
12564
12565                   if (is_this)
12566                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12567                                              arg_type, 0);
12568                 }
12569
12570               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12571               iparams++;
12572             }
12573           child_die = sibling_die (child_die);
12574         }
12575     }
12576
12577   return ftype;
12578 }
12579
12580 static struct type *
12581 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12582 {
12583   struct objfile *objfile = cu->objfile;
12584   const char *name = NULL;
12585   struct type *this_type, *target_type;
12586
12587   name = dwarf2_full_name (NULL, die, cu);
12588   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12589                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12590   TYPE_NAME (this_type) = name;
12591   set_die_type (die, this_type, cu);
12592   target_type = die_type (die, cu);
12593   if (target_type != this_type)
12594     TYPE_TARGET_TYPE (this_type) = target_type;
12595   else
12596     {
12597       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12598          spec and cause infinite loops in GDB.  */
12599       complaint (&symfile_complaints,
12600                  _("Self-referential DW_TAG_typedef "
12601                    "- DIE at 0x%x [in module %s]"),
12602                  die->offset.sect_off, objfile->name);
12603       TYPE_TARGET_TYPE (this_type) = NULL;
12604     }
12605   return this_type;
12606 }
12607
12608 /* Find a representation of a given base type and install
12609    it in the TYPE field of the die.  */
12610
12611 static struct type *
12612 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12613 {
12614   struct objfile *objfile = cu->objfile;
12615   struct type *type;
12616   struct attribute *attr;
12617   int encoding = 0, size = 0;
12618   const char *name;
12619   enum type_code code = TYPE_CODE_INT;
12620   int type_flags = 0;
12621   struct type *target_type = NULL;
12622
12623   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12624   if (attr)
12625     {
12626       encoding = DW_UNSND (attr);
12627     }
12628   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12629   if (attr)
12630     {
12631       size = DW_UNSND (attr);
12632     }
12633   name = dwarf2_name (die, cu);
12634   if (!name)
12635     {
12636       complaint (&symfile_complaints,
12637                  _("DW_AT_name missing from DW_TAG_base_type"));
12638     }
12639
12640   switch (encoding)
12641     {
12642       case DW_ATE_address:
12643         /* Turn DW_ATE_address into a void * pointer.  */
12644         code = TYPE_CODE_PTR;
12645         type_flags |= TYPE_FLAG_UNSIGNED;
12646         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12647         break;
12648       case DW_ATE_boolean:
12649         code = TYPE_CODE_BOOL;
12650         type_flags |= TYPE_FLAG_UNSIGNED;
12651         break;
12652       case DW_ATE_complex_float:
12653         code = TYPE_CODE_COMPLEX;
12654         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12655         break;
12656       case DW_ATE_decimal_float:
12657         code = TYPE_CODE_DECFLOAT;
12658         break;
12659       case DW_ATE_float:
12660         code = TYPE_CODE_FLT;
12661         break;
12662       case DW_ATE_signed:
12663         break;
12664       case DW_ATE_unsigned:
12665         type_flags |= TYPE_FLAG_UNSIGNED;
12666         if (cu->language == language_fortran
12667             && name
12668             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12669           code = TYPE_CODE_CHAR;
12670         break;
12671       case DW_ATE_signed_char:
12672         if (cu->language == language_ada || cu->language == language_m2
12673             || cu->language == language_pascal
12674             || cu->language == language_fortran)
12675           code = TYPE_CODE_CHAR;
12676         break;
12677       case DW_ATE_unsigned_char:
12678         if (cu->language == language_ada || cu->language == language_m2
12679             || cu->language == language_pascal
12680             || cu->language == language_fortran)
12681           code = TYPE_CODE_CHAR;
12682         type_flags |= TYPE_FLAG_UNSIGNED;
12683         break;
12684       case DW_ATE_UTF:
12685         /* We just treat this as an integer and then recognize the
12686            type by name elsewhere.  */
12687         break;
12688
12689       default:
12690         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12691                    dwarf_type_encoding_name (encoding));
12692         break;
12693     }
12694
12695   type = init_type (code, size, type_flags, NULL, objfile);
12696   TYPE_NAME (type) = name;
12697   TYPE_TARGET_TYPE (type) = target_type;
12698
12699   if (name && strcmp (name, "char") == 0)
12700     TYPE_NOSIGN (type) = 1;
12701
12702   return set_die_type (die, type, cu);
12703 }
12704
12705 /* Read the given DW_AT_subrange DIE.  */
12706
12707 static struct type *
12708 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12709 {
12710   struct type *base_type;
12711   struct type *range_type;
12712   struct attribute *attr;
12713   LONGEST low, high;
12714   int low_default_is_valid;
12715   const char *name;
12716   LONGEST negative_mask;
12717
12718   base_type = die_type (die, cu);
12719   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
12720   check_typedef (base_type);
12721
12722   /* The die_type call above may have already set the type for this DIE.  */
12723   range_type = get_die_type (die, cu);
12724   if (range_type)
12725     return range_type;
12726
12727   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12728      omitting DW_AT_lower_bound.  */
12729   switch (cu->language)
12730     {
12731     case language_c:
12732     case language_cplus:
12733       low = 0;
12734       low_default_is_valid = 1;
12735       break;
12736     case language_fortran:
12737       low = 1;
12738       low_default_is_valid = 1;
12739       break;
12740     case language_d:
12741     case language_java:
12742     case language_objc:
12743       low = 0;
12744       low_default_is_valid = (cu->header.version >= 4);
12745       break;
12746     case language_ada:
12747     case language_m2:
12748     case language_pascal:
12749       low = 1;
12750       low_default_is_valid = (cu->header.version >= 4);
12751       break;
12752     default:
12753       low = 0;
12754       low_default_is_valid = 0;
12755       break;
12756     }
12757
12758   /* FIXME: For variable sized arrays either of these could be
12759      a variable rather than a constant value.  We'll allow it,
12760      but we don't know how to handle it.  */
12761   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12762   if (attr)
12763     low = dwarf2_get_attr_constant_value (attr, low);
12764   else if (!low_default_is_valid)
12765     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12766                                       "- DIE at 0x%x [in module %s]"),
12767                die->offset.sect_off, cu->objfile->name);
12768
12769   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12770   if (attr)
12771     {
12772       if (attr_form_is_block (attr) || is_ref_attr (attr))
12773         {
12774           /* GCC encodes arrays with unspecified or dynamic length
12775              with a DW_FORM_block1 attribute or a reference attribute.
12776              FIXME: GDB does not yet know how to handle dynamic
12777              arrays properly, treat them as arrays with unspecified
12778              length for now.
12779
12780              FIXME: jimb/2003-09-22: GDB does not really know
12781              how to handle arrays of unspecified length
12782              either; we just represent them as zero-length
12783              arrays.  Choose an appropriate upper bound given
12784              the lower bound we've computed above.  */
12785           high = low - 1;
12786         }
12787       else
12788         high = dwarf2_get_attr_constant_value (attr, 1);
12789     }
12790   else
12791     {
12792       attr = dwarf2_attr (die, DW_AT_count, cu);
12793       if (attr)
12794         {
12795           int count = dwarf2_get_attr_constant_value (attr, 1);
12796           high = low + count - 1;
12797         }
12798       else
12799         {
12800           /* Unspecified array length.  */
12801           high = low - 1;
12802         }
12803     }
12804
12805   /* Dwarf-2 specifications explicitly allows to create subrange types
12806      without specifying a base type.
12807      In that case, the base type must be set to the type of
12808      the lower bound, upper bound or count, in that order, if any of these
12809      three attributes references an object that has a type.
12810      If no base type is found, the Dwarf-2 specifications say that
12811      a signed integer type of size equal to the size of an address should
12812      be used.
12813      For the following C code: `extern char gdb_int [];'
12814      GCC produces an empty range DIE.
12815      FIXME: muller/2010-05-28: Possible references to object for low bound,
12816      high bound or count are not yet handled by this code.  */
12817   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12818     {
12819       struct objfile *objfile = cu->objfile;
12820       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12821       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12822       struct type *int_type = objfile_type (objfile)->builtin_int;
12823
12824       /* Test "int", "long int", and "long long int" objfile types,
12825          and select the first one having a size above or equal to the
12826          architecture address size.  */
12827       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12828         base_type = int_type;
12829       else
12830         {
12831           int_type = objfile_type (objfile)->builtin_long;
12832           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12833             base_type = int_type;
12834           else
12835             {
12836               int_type = objfile_type (objfile)->builtin_long_long;
12837               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12838                 base_type = int_type;
12839             }
12840         }
12841     }
12842
12843   negative_mask =
12844     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
12845   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
12846     low |= negative_mask;
12847   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
12848     high |= negative_mask;
12849
12850   range_type = create_range_type (NULL, base_type, low, high);
12851
12852   /* Mark arrays with dynamic length at least as an array of unspecified
12853      length.  GDB could check the boundary but before it gets implemented at
12854      least allow accessing the array elements.  */
12855   if (attr && attr_form_is_block (attr))
12856     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12857
12858   /* Ada expects an empty array on no boundary attributes.  */
12859   if (attr == NULL && cu->language != language_ada)
12860     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12861
12862   name = dwarf2_name (die, cu);
12863   if (name)
12864     TYPE_NAME (range_type) = name;
12865
12866   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12867   if (attr)
12868     TYPE_LENGTH (range_type) = DW_UNSND (attr);
12869
12870   set_die_type (die, range_type, cu);
12871
12872   /* set_die_type should be already done.  */
12873   set_descriptive_type (range_type, die, cu);
12874
12875   return range_type;
12876 }
12877
12878 static struct type *
12879 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
12880 {
12881   struct type *type;
12882
12883   /* For now, we only support the C meaning of an unspecified type: void.  */
12884
12885   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
12886   TYPE_NAME (type) = dwarf2_name (die, cu);
12887
12888   return set_die_type (die, type, cu);
12889 }
12890
12891 /* Read a single die and all its descendents.  Set the die's sibling
12892    field to NULL; set other fields in the die correctly, and set all
12893    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
12894    location of the info_ptr after reading all of those dies.  PARENT
12895    is the parent of the die in question.  */
12896
12897 static struct die_info *
12898 read_die_and_children (const struct die_reader_specs *reader,
12899                        gdb_byte *info_ptr,
12900                        gdb_byte **new_info_ptr,
12901                        struct die_info *parent)
12902 {
12903   struct die_info *die;
12904   gdb_byte *cur_ptr;
12905   int has_children;
12906
12907   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
12908   if (die == NULL)
12909     {
12910       *new_info_ptr = cur_ptr;
12911       return NULL;
12912     }
12913   store_in_ref_table (die, reader->cu);
12914
12915   if (has_children)
12916     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
12917   else
12918     {
12919       die->child = NULL;
12920       *new_info_ptr = cur_ptr;
12921     }
12922
12923   die->sibling = NULL;
12924   die->parent = parent;
12925   return die;
12926 }
12927
12928 /* Read a die, all of its descendents, and all of its siblings; set
12929    all of the fields of all of the dies correctly.  Arguments are as
12930    in read_die_and_children.  */
12931
12932 static struct die_info *
12933 read_die_and_siblings (const struct die_reader_specs *reader,
12934                        gdb_byte *info_ptr,
12935                        gdb_byte **new_info_ptr,
12936                        struct die_info *parent)
12937 {
12938   struct die_info *first_die, *last_sibling;
12939   gdb_byte *cur_ptr;
12940
12941   cur_ptr = info_ptr;
12942   first_die = last_sibling = NULL;
12943
12944   while (1)
12945     {
12946       struct die_info *die
12947         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
12948
12949       if (die == NULL)
12950         {
12951           *new_info_ptr = cur_ptr;
12952           return first_die;
12953         }
12954
12955       if (!first_die)
12956         first_die = die;
12957       else
12958         last_sibling->sibling = die;
12959
12960       last_sibling = die;
12961     }
12962 }
12963
12964 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
12965    attributes.
12966    The caller is responsible for filling in the extra attributes
12967    and updating (*DIEP)->num_attrs.
12968    Set DIEP to point to a newly allocated die with its information,
12969    except for its child, sibling, and parent fields.
12970    Set HAS_CHILDREN to tell whether the die has children or not.  */
12971
12972 static gdb_byte *
12973 read_full_die_1 (const struct die_reader_specs *reader,
12974                  struct die_info **diep, gdb_byte *info_ptr,
12975                  int *has_children, int num_extra_attrs)
12976 {
12977   unsigned int abbrev_number, bytes_read, i;
12978   sect_offset offset;
12979   struct abbrev_info *abbrev;
12980   struct die_info *die;
12981   struct dwarf2_cu *cu = reader->cu;
12982   bfd *abfd = reader->abfd;
12983
12984   offset.sect_off = info_ptr - reader->buffer;
12985   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12986   info_ptr += bytes_read;
12987   if (!abbrev_number)
12988     {
12989       *diep = NULL;
12990       *has_children = 0;
12991       return info_ptr;
12992     }
12993
12994   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
12995   if (!abbrev)
12996     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
12997            abbrev_number,
12998            bfd_get_filename (abfd));
12999
13000   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13001   die->offset = offset;
13002   die->tag = abbrev->tag;
13003   die->abbrev = abbrev_number;
13004
13005   /* Make the result usable.
13006      The caller needs to update num_attrs after adding the extra
13007      attributes.  */
13008   die->num_attrs = abbrev->num_attrs;
13009
13010   for (i = 0; i < abbrev->num_attrs; ++i)
13011     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13012                                info_ptr);
13013
13014   *diep = die;
13015   *has_children = abbrev->has_children;
13016   return info_ptr;
13017 }
13018
13019 /* Read a die and all its attributes.
13020    Set DIEP to point to a newly allocated die with its information,
13021    except for its child, sibling, and parent fields.
13022    Set HAS_CHILDREN to tell whether the die has children or not.  */
13023
13024 static gdb_byte *
13025 read_full_die (const struct die_reader_specs *reader,
13026                struct die_info **diep, gdb_byte *info_ptr,
13027                int *has_children)
13028 {
13029   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13030 }
13031 \f
13032 /* Abbreviation tables.
13033
13034    In DWARF version 2, the description of the debugging information is
13035    stored in a separate .debug_abbrev section.  Before we read any
13036    dies from a section we read in all abbreviations and install them
13037    in a hash table.  */
13038
13039 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13040
13041 static struct abbrev_info *
13042 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13043 {
13044   struct abbrev_info *abbrev;
13045
13046   abbrev = (struct abbrev_info *)
13047     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13048   memset (abbrev, 0, sizeof (struct abbrev_info));
13049   return abbrev;
13050 }
13051
13052 /* Add an abbreviation to the table.  */
13053
13054 static void
13055 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13056                          unsigned int abbrev_number,
13057                          struct abbrev_info *abbrev)
13058 {
13059   unsigned int hash_number;
13060
13061   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13062   abbrev->next = abbrev_table->abbrevs[hash_number];
13063   abbrev_table->abbrevs[hash_number] = abbrev;
13064 }
13065
13066 /* Look up an abbrev in the table.
13067    Returns NULL if the abbrev is not found.  */
13068
13069 static struct abbrev_info *
13070 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13071                             unsigned int abbrev_number)
13072 {
13073   unsigned int hash_number;
13074   struct abbrev_info *abbrev;
13075
13076   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13077   abbrev = abbrev_table->abbrevs[hash_number];
13078
13079   while (abbrev)
13080     {
13081       if (abbrev->number == abbrev_number)
13082         return abbrev;
13083       abbrev = abbrev->next;
13084     }
13085   return NULL;
13086 }
13087
13088 /* Read in an abbrev table.  */
13089
13090 static struct abbrev_table *
13091 abbrev_table_read_table (struct dwarf2_section_info *section,
13092                          sect_offset offset)
13093 {
13094   struct objfile *objfile = dwarf2_per_objfile->objfile;
13095   bfd *abfd = section->asection->owner;
13096   struct abbrev_table *abbrev_table;
13097   gdb_byte *abbrev_ptr;
13098   struct abbrev_info *cur_abbrev;
13099   unsigned int abbrev_number, bytes_read, abbrev_name;
13100   unsigned int abbrev_form;
13101   struct attr_abbrev *cur_attrs;
13102   unsigned int allocated_attrs;
13103
13104   abbrev_table = XMALLOC (struct abbrev_table);
13105   abbrev_table->offset = offset;
13106   obstack_init (&abbrev_table->abbrev_obstack);
13107   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13108                                          (ABBREV_HASH_SIZE
13109                                           * sizeof (struct abbrev_info *)));
13110   memset (abbrev_table->abbrevs, 0,
13111           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13112
13113   dwarf2_read_section (objfile, section);
13114   abbrev_ptr = section->buffer + offset.sect_off;
13115   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13116   abbrev_ptr += bytes_read;
13117
13118   allocated_attrs = ATTR_ALLOC_CHUNK;
13119   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13120
13121   /* Loop until we reach an abbrev number of 0.  */
13122   while (abbrev_number)
13123     {
13124       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13125
13126       /* read in abbrev header */
13127       cur_abbrev->number = abbrev_number;
13128       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13129       abbrev_ptr += bytes_read;
13130       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13131       abbrev_ptr += 1;
13132
13133       /* now read in declarations */
13134       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13135       abbrev_ptr += bytes_read;
13136       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13137       abbrev_ptr += bytes_read;
13138       while (abbrev_name)
13139         {
13140           if (cur_abbrev->num_attrs == allocated_attrs)
13141             {
13142               allocated_attrs += ATTR_ALLOC_CHUNK;
13143               cur_attrs
13144                 = xrealloc (cur_attrs, (allocated_attrs
13145                                         * sizeof (struct attr_abbrev)));
13146             }
13147
13148           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13149           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13150           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13151           abbrev_ptr += bytes_read;
13152           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13153           abbrev_ptr += bytes_read;
13154         }
13155
13156       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13157                                          (cur_abbrev->num_attrs
13158                                           * sizeof (struct attr_abbrev)));
13159       memcpy (cur_abbrev->attrs, cur_attrs,
13160               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13161
13162       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13163
13164       /* Get next abbreviation.
13165          Under Irix6 the abbreviations for a compilation unit are not
13166          always properly terminated with an abbrev number of 0.
13167          Exit loop if we encounter an abbreviation which we have
13168          already read (which means we are about to read the abbreviations
13169          for the next compile unit) or if the end of the abbreviation
13170          table is reached.  */
13171       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13172         break;
13173       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13174       abbrev_ptr += bytes_read;
13175       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13176         break;
13177     }
13178
13179   xfree (cur_attrs);
13180   return abbrev_table;
13181 }
13182
13183 /* Free the resources held by ABBREV_TABLE.  */
13184
13185 static void
13186 abbrev_table_free (struct abbrev_table *abbrev_table)
13187 {
13188   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13189   xfree (abbrev_table);
13190 }
13191
13192 /* Same as abbrev_table_free but as a cleanup.
13193    We pass in a pointer to the pointer to the table so that we can
13194    set the pointer to NULL when we're done.  It also simplifies
13195    build_type_unit_groups.  */
13196
13197 static void
13198 abbrev_table_free_cleanup (void *table_ptr)
13199 {
13200   struct abbrev_table **abbrev_table_ptr = table_ptr;
13201
13202   if (*abbrev_table_ptr != NULL)
13203     abbrev_table_free (*abbrev_table_ptr);
13204   *abbrev_table_ptr = NULL;
13205 }
13206
13207 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13208
13209 static void
13210 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13211                      struct dwarf2_section_info *abbrev_section)
13212 {
13213   cu->abbrev_table =
13214     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13215 }
13216
13217 /* Release the memory used by the abbrev table for a compilation unit.  */
13218
13219 static void
13220 dwarf2_free_abbrev_table (void *ptr_to_cu)
13221 {
13222   struct dwarf2_cu *cu = ptr_to_cu;
13223
13224   abbrev_table_free (cu->abbrev_table);
13225   /* Set this to NULL so that we SEGV if we try to read it later,
13226      and also because free_comp_unit verifies this is NULL.  */
13227   cu->abbrev_table = NULL;
13228 }
13229 \f
13230 /* Returns nonzero if TAG represents a type that we might generate a partial
13231    symbol for.  */
13232
13233 static int
13234 is_type_tag_for_partial (int tag)
13235 {
13236   switch (tag)
13237     {
13238 #if 0
13239     /* Some types that would be reasonable to generate partial symbols for,
13240        that we don't at present.  */
13241     case DW_TAG_array_type:
13242     case DW_TAG_file_type:
13243     case DW_TAG_ptr_to_member_type:
13244     case DW_TAG_set_type:
13245     case DW_TAG_string_type:
13246     case DW_TAG_subroutine_type:
13247 #endif
13248     case DW_TAG_base_type:
13249     case DW_TAG_class_type:
13250     case DW_TAG_interface_type:
13251     case DW_TAG_enumeration_type:
13252     case DW_TAG_structure_type:
13253     case DW_TAG_subrange_type:
13254     case DW_TAG_typedef:
13255     case DW_TAG_union_type:
13256       return 1;
13257     default:
13258       return 0;
13259     }
13260 }
13261
13262 /* Load all DIEs that are interesting for partial symbols into memory.  */
13263
13264 static struct partial_die_info *
13265 load_partial_dies (const struct die_reader_specs *reader,
13266                    gdb_byte *info_ptr, int building_psymtab)
13267 {
13268   struct dwarf2_cu *cu = reader->cu;
13269   struct objfile *objfile = cu->objfile;
13270   struct partial_die_info *part_die;
13271   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13272   struct abbrev_info *abbrev;
13273   unsigned int bytes_read;
13274   unsigned int load_all = 0;
13275   int nesting_level = 1;
13276
13277   parent_die = NULL;
13278   last_die = NULL;
13279
13280   gdb_assert (cu->per_cu != NULL);
13281   if (cu->per_cu->load_all_dies)
13282     load_all = 1;
13283
13284   cu->partial_dies
13285     = htab_create_alloc_ex (cu->header.length / 12,
13286                             partial_die_hash,
13287                             partial_die_eq,
13288                             NULL,
13289                             &cu->comp_unit_obstack,
13290                             hashtab_obstack_allocate,
13291                             dummy_obstack_deallocate);
13292
13293   part_die = obstack_alloc (&cu->comp_unit_obstack,
13294                             sizeof (struct partial_die_info));
13295
13296   while (1)
13297     {
13298       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13299
13300       /* A NULL abbrev means the end of a series of children.  */
13301       if (abbrev == NULL)
13302         {
13303           if (--nesting_level == 0)
13304             {
13305               /* PART_DIE was probably the last thing allocated on the
13306                  comp_unit_obstack, so we could call obstack_free
13307                  here.  We don't do that because the waste is small,
13308                  and will be cleaned up when we're done with this
13309                  compilation unit.  This way, we're also more robust
13310                  against other users of the comp_unit_obstack.  */
13311               return first_die;
13312             }
13313           info_ptr += bytes_read;
13314           last_die = parent_die;
13315           parent_die = parent_die->die_parent;
13316           continue;
13317         }
13318
13319       /* Check for template arguments.  We never save these; if
13320          they're seen, we just mark the parent, and go on our way.  */
13321       if (parent_die != NULL
13322           && cu->language == language_cplus
13323           && (abbrev->tag == DW_TAG_template_type_param
13324               || abbrev->tag == DW_TAG_template_value_param))
13325         {
13326           parent_die->has_template_arguments = 1;
13327
13328           if (!load_all)
13329             {
13330               /* We don't need a partial DIE for the template argument.  */
13331               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13332               continue;
13333             }
13334         }
13335
13336       /* We only recurse into c++ subprograms looking for template arguments.
13337          Skip their other children.  */
13338       if (!load_all
13339           && cu->language == language_cplus
13340           && parent_die != NULL
13341           && parent_die->tag == DW_TAG_subprogram)
13342         {
13343           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13344           continue;
13345         }
13346
13347       /* Check whether this DIE is interesting enough to save.  Normally
13348          we would not be interested in members here, but there may be
13349          later variables referencing them via DW_AT_specification (for
13350          static members).  */
13351       if (!load_all
13352           && !is_type_tag_for_partial (abbrev->tag)
13353           && abbrev->tag != DW_TAG_constant
13354           && abbrev->tag != DW_TAG_enumerator
13355           && abbrev->tag != DW_TAG_subprogram
13356           && abbrev->tag != DW_TAG_lexical_block
13357           && abbrev->tag != DW_TAG_variable
13358           && abbrev->tag != DW_TAG_namespace
13359           && abbrev->tag != DW_TAG_module
13360           && abbrev->tag != DW_TAG_member
13361           && abbrev->tag != DW_TAG_imported_unit)
13362         {
13363           /* Otherwise we skip to the next sibling, if any.  */
13364           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13365           continue;
13366         }
13367
13368       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13369                                    info_ptr);
13370
13371       /* This two-pass algorithm for processing partial symbols has a
13372          high cost in cache pressure.  Thus, handle some simple cases
13373          here which cover the majority of C partial symbols.  DIEs
13374          which neither have specification tags in them, nor could have
13375          specification tags elsewhere pointing at them, can simply be
13376          processed and discarded.
13377
13378          This segment is also optional; scan_partial_symbols and
13379          add_partial_symbol will handle these DIEs if we chain
13380          them in normally.  When compilers which do not emit large
13381          quantities of duplicate debug information are more common,
13382          this code can probably be removed.  */
13383
13384       /* Any complete simple types at the top level (pretty much all
13385          of them, for a language without namespaces), can be processed
13386          directly.  */
13387       if (parent_die == NULL
13388           && part_die->has_specification == 0
13389           && part_die->is_declaration == 0
13390           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13391               || part_die->tag == DW_TAG_base_type
13392               || part_die->tag == DW_TAG_subrange_type))
13393         {
13394           if (building_psymtab && part_die->name != NULL)
13395             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13396                                  VAR_DOMAIN, LOC_TYPEDEF,
13397                                  &objfile->static_psymbols,
13398                                  0, (CORE_ADDR) 0, cu->language, objfile);
13399           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13400           continue;
13401         }
13402
13403       /* The exception for DW_TAG_typedef with has_children above is
13404          a workaround of GCC PR debug/47510.  In the case of this complaint
13405          type_name_no_tag_or_error will error on such types later.
13406
13407          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13408          it could not find the child DIEs referenced later, this is checked
13409          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13410
13411       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13412         complaint (&symfile_complaints,
13413                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13414                      "- DIE at 0x%x [in module %s]"),
13415                    part_die->offset.sect_off, objfile->name);
13416
13417       /* If we're at the second level, and we're an enumerator, and
13418          our parent has no specification (meaning possibly lives in a
13419          namespace elsewhere), then we can add the partial symbol now
13420          instead of queueing it.  */
13421       if (part_die->tag == DW_TAG_enumerator
13422           && parent_die != NULL
13423           && parent_die->die_parent == NULL
13424           && parent_die->tag == DW_TAG_enumeration_type
13425           && parent_die->has_specification == 0)
13426         {
13427           if (part_die->name == NULL)
13428             complaint (&symfile_complaints,
13429                        _("malformed enumerator DIE ignored"));
13430           else if (building_psymtab)
13431             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13432                                  VAR_DOMAIN, LOC_CONST,
13433                                  (cu->language == language_cplus
13434                                   || cu->language == language_java)
13435                                  ? &objfile->global_psymbols
13436                                  : &objfile->static_psymbols,
13437                                  0, (CORE_ADDR) 0, cu->language, objfile);
13438
13439           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13440           continue;
13441         }
13442
13443       /* We'll save this DIE so link it in.  */
13444       part_die->die_parent = parent_die;
13445       part_die->die_sibling = NULL;
13446       part_die->die_child = NULL;
13447
13448       if (last_die && last_die == parent_die)
13449         last_die->die_child = part_die;
13450       else if (last_die)
13451         last_die->die_sibling = part_die;
13452
13453       last_die = part_die;
13454
13455       if (first_die == NULL)
13456         first_die = part_die;
13457
13458       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13459          find interesting need to be in the hash table, because we
13460          also have the parent/sibling/child chains; only those that we
13461          might refer to by offset later during partial symbol reading.
13462
13463          For now this means things that might have be the target of a
13464          DW_AT_specification, DW_AT_abstract_origin, or
13465          DW_AT_extension.  DW_AT_extension will refer only to
13466          namespaces; DW_AT_abstract_origin refers to functions (and
13467          many things under the function DIE, but we do not recurse
13468          into function DIEs during partial symbol reading) and
13469          possibly variables as well; DW_AT_specification refers to
13470          declarations.  Declarations ought to have the DW_AT_declaration
13471          flag.  It happens that GCC forgets to put it in sometimes, but
13472          only for functions, not for types.
13473
13474          Adding more things than necessary to the hash table is harmless
13475          except for the performance cost.  Adding too few will result in
13476          wasted time in find_partial_die, when we reread the compilation
13477          unit with load_all_dies set.  */
13478
13479       if (load_all
13480           || abbrev->tag == DW_TAG_constant
13481           || abbrev->tag == DW_TAG_subprogram
13482           || abbrev->tag == DW_TAG_variable
13483           || abbrev->tag == DW_TAG_namespace
13484           || part_die->is_declaration)
13485         {
13486           void **slot;
13487
13488           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13489                                            part_die->offset.sect_off, INSERT);
13490           *slot = part_die;
13491         }
13492
13493       part_die = obstack_alloc (&cu->comp_unit_obstack,
13494                                 sizeof (struct partial_die_info));
13495
13496       /* For some DIEs we want to follow their children (if any).  For C
13497          we have no reason to follow the children of structures; for other
13498          languages we have to, so that we can get at method physnames
13499          to infer fully qualified class names, for DW_AT_specification,
13500          and for C++ template arguments.  For C++, we also look one level
13501          inside functions to find template arguments (if the name of the
13502          function does not already contain the template arguments).
13503
13504          For Ada, we need to scan the children of subprograms and lexical
13505          blocks as well because Ada allows the definition of nested
13506          entities that could be interesting for the debugger, such as
13507          nested subprograms for instance.  */
13508       if (last_die->has_children
13509           && (load_all
13510               || last_die->tag == DW_TAG_namespace
13511               || last_die->tag == DW_TAG_module
13512               || last_die->tag == DW_TAG_enumeration_type
13513               || (cu->language == language_cplus
13514                   && last_die->tag == DW_TAG_subprogram
13515                   && (last_die->name == NULL
13516                       || strchr (last_die->name, '<') == NULL))
13517               || (cu->language != language_c
13518                   && (last_die->tag == DW_TAG_class_type
13519                       || last_die->tag == DW_TAG_interface_type
13520                       || last_die->tag == DW_TAG_structure_type
13521                       || last_die->tag == DW_TAG_union_type))
13522               || (cu->language == language_ada
13523                   && (last_die->tag == DW_TAG_subprogram
13524                       || last_die->tag == DW_TAG_lexical_block))))
13525         {
13526           nesting_level++;
13527           parent_die = last_die;
13528           continue;
13529         }
13530
13531       /* Otherwise we skip to the next sibling, if any.  */
13532       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13533
13534       /* Back to the top, do it again.  */
13535     }
13536 }
13537
13538 /* Read a minimal amount of information into the minimal die structure.  */
13539
13540 static gdb_byte *
13541 read_partial_die (const struct die_reader_specs *reader,
13542                   struct partial_die_info *part_die,
13543                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13544                   gdb_byte *info_ptr)
13545 {
13546   struct dwarf2_cu *cu = reader->cu;
13547   struct objfile *objfile = cu->objfile;
13548   gdb_byte *buffer = reader->buffer;
13549   unsigned int i;
13550   struct attribute attr;
13551   int has_low_pc_attr = 0;
13552   int has_high_pc_attr = 0;
13553   int high_pc_relative = 0;
13554
13555   memset (part_die, 0, sizeof (struct partial_die_info));
13556
13557   part_die->offset.sect_off = info_ptr - buffer;
13558
13559   info_ptr += abbrev_len;
13560
13561   if (abbrev == NULL)
13562     return info_ptr;
13563
13564   part_die->tag = abbrev->tag;
13565   part_die->has_children = abbrev->has_children;
13566
13567   for (i = 0; i < abbrev->num_attrs; ++i)
13568     {
13569       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13570
13571       /* Store the data if it is of an attribute we want to keep in a
13572          partial symbol table.  */
13573       switch (attr.name)
13574         {
13575         case DW_AT_name:
13576           switch (part_die->tag)
13577             {
13578             case DW_TAG_compile_unit:
13579             case DW_TAG_partial_unit:
13580             case DW_TAG_type_unit:
13581               /* Compilation units have a DW_AT_name that is a filename, not
13582                  a source language identifier.  */
13583             case DW_TAG_enumeration_type:
13584             case DW_TAG_enumerator:
13585               /* These tags always have simple identifiers already; no need
13586                  to canonicalize them.  */
13587               part_die->name = DW_STRING (&attr);
13588               break;
13589             default:
13590               part_die->name
13591                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13592                                             &objfile->objfile_obstack);
13593               break;
13594             }
13595           break;
13596         case DW_AT_linkage_name:
13597         case DW_AT_MIPS_linkage_name:
13598           /* Note that both forms of linkage name might appear.  We
13599              assume they will be the same, and we only store the last
13600              one we see.  */
13601           if (cu->language == language_ada)
13602             part_die->name = DW_STRING (&attr);
13603           part_die->linkage_name = DW_STRING (&attr);
13604           break;
13605         case DW_AT_low_pc:
13606           has_low_pc_attr = 1;
13607           part_die->lowpc = DW_ADDR (&attr);
13608           break;
13609         case DW_AT_high_pc:
13610           has_high_pc_attr = 1;
13611           if (attr.form == DW_FORM_addr
13612               || attr.form == DW_FORM_GNU_addr_index)
13613             part_die->highpc = DW_ADDR (&attr);
13614           else
13615             {
13616               high_pc_relative = 1;
13617               part_die->highpc = DW_UNSND (&attr);
13618             }
13619           break;
13620         case DW_AT_location:
13621           /* Support the .debug_loc offsets.  */
13622           if (attr_form_is_block (&attr))
13623             {
13624                part_die->d.locdesc = DW_BLOCK (&attr);
13625             }
13626           else if (attr_form_is_section_offset (&attr))
13627             {
13628               dwarf2_complex_location_expr_complaint ();
13629             }
13630           else
13631             {
13632               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13633                                                      "partial symbol information");
13634             }
13635           break;
13636         case DW_AT_external:
13637           part_die->is_external = DW_UNSND (&attr);
13638           break;
13639         case DW_AT_declaration:
13640           part_die->is_declaration = DW_UNSND (&attr);
13641           break;
13642         case DW_AT_type:
13643           part_die->has_type = 1;
13644           break;
13645         case DW_AT_abstract_origin:
13646         case DW_AT_specification:
13647         case DW_AT_extension:
13648           part_die->has_specification = 1;
13649           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13650           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13651                                    || cu->per_cu->is_dwz);
13652           break;
13653         case DW_AT_sibling:
13654           /* Ignore absolute siblings, they might point outside of
13655              the current compile unit.  */
13656           if (attr.form == DW_FORM_ref_addr)
13657             complaint (&symfile_complaints,
13658                        _("ignoring absolute DW_AT_sibling"));
13659           else
13660             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13661           break;
13662         case DW_AT_byte_size:
13663           part_die->has_byte_size = 1;
13664           break;
13665         case DW_AT_calling_convention:
13666           /* DWARF doesn't provide a way to identify a program's source-level
13667              entry point.  DW_AT_calling_convention attributes are only meant
13668              to describe functions' calling conventions.
13669
13670              However, because it's a necessary piece of information in
13671              Fortran, and because DW_CC_program is the only piece of debugging
13672              information whose definition refers to a 'main program' at all,
13673              several compilers have begun marking Fortran main programs with
13674              DW_CC_program --- even when those functions use the standard
13675              calling conventions.
13676
13677              So until DWARF specifies a way to provide this information and
13678              compilers pick up the new representation, we'll support this
13679              practice.  */
13680           if (DW_UNSND (&attr) == DW_CC_program
13681               && cu->language == language_fortran)
13682             {
13683               set_main_name (part_die->name);
13684
13685               /* As this DIE has a static linkage the name would be difficult
13686                  to look up later.  */
13687               language_of_main = language_fortran;
13688             }
13689           break;
13690         case DW_AT_inline:
13691           if (DW_UNSND (&attr) == DW_INL_inlined
13692               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13693             part_die->may_be_inlined = 1;
13694           break;
13695
13696         case DW_AT_import:
13697           if (part_die->tag == DW_TAG_imported_unit)
13698             {
13699               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13700               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13701                                   || cu->per_cu->is_dwz);
13702             }
13703           break;
13704
13705         default:
13706           break;
13707         }
13708     }
13709
13710   if (high_pc_relative)
13711     part_die->highpc += part_die->lowpc;
13712
13713   if (has_low_pc_attr && has_high_pc_attr)
13714     {
13715       /* When using the GNU linker, .gnu.linkonce. sections are used to
13716          eliminate duplicate copies of functions and vtables and such.
13717          The linker will arbitrarily choose one and discard the others.
13718          The AT_*_pc values for such functions refer to local labels in
13719          these sections.  If the section from that file was discarded, the
13720          labels are not in the output, so the relocs get a value of 0.
13721          If this is a discarded function, mark the pc bounds as invalid,
13722          so that GDB will ignore it.  */
13723       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13724         {
13725           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13726
13727           complaint (&symfile_complaints,
13728                      _("DW_AT_low_pc %s is zero "
13729                        "for DIE at 0x%x [in module %s]"),
13730                      paddress (gdbarch, part_die->lowpc),
13731                      part_die->offset.sect_off, objfile->name);
13732         }
13733       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13734       else if (part_die->lowpc >= part_die->highpc)
13735         {
13736           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13737
13738           complaint (&symfile_complaints,
13739                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13740                        "for DIE at 0x%x [in module %s]"),
13741                      paddress (gdbarch, part_die->lowpc),
13742                      paddress (gdbarch, part_die->highpc),
13743                      part_die->offset.sect_off, objfile->name);
13744         }
13745       else
13746         part_die->has_pc_info = 1;
13747     }
13748
13749   return info_ptr;
13750 }
13751
13752 /* Find a cached partial DIE at OFFSET in CU.  */
13753
13754 static struct partial_die_info *
13755 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13756 {
13757   struct partial_die_info *lookup_die = NULL;
13758   struct partial_die_info part_die;
13759
13760   part_die.offset = offset;
13761   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13762                                     offset.sect_off);
13763
13764   return lookup_die;
13765 }
13766
13767 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13768    except in the case of .debug_types DIEs which do not reference
13769    outside their CU (they do however referencing other types via
13770    DW_FORM_ref_sig8).  */
13771
13772 static struct partial_die_info *
13773 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13774 {
13775   struct objfile *objfile = cu->objfile;
13776   struct dwarf2_per_cu_data *per_cu = NULL;
13777   struct partial_die_info *pd = NULL;
13778
13779   if (offset_in_dwz == cu->per_cu->is_dwz
13780       && offset_in_cu_p (&cu->header, offset))
13781     {
13782       pd = find_partial_die_in_comp_unit (offset, cu);
13783       if (pd != NULL)
13784         return pd;
13785       /* We missed recording what we needed.
13786          Load all dies and try again.  */
13787       per_cu = cu->per_cu;
13788     }
13789   else
13790     {
13791       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13792       if (cu->per_cu->is_debug_types)
13793         {
13794           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13795                    " external reference to offset 0x%lx [in module %s].\n"),
13796                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
13797                  bfd_get_filename (objfile->obfd));
13798         }
13799       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
13800                                                  objfile);
13801
13802       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
13803         load_partial_comp_unit (per_cu);
13804
13805       per_cu->cu->last_used = 0;
13806       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13807     }
13808
13809   /* If we didn't find it, and not all dies have been loaded,
13810      load them all and try again.  */
13811
13812   if (pd == NULL && per_cu->load_all_dies == 0)
13813     {
13814       per_cu->load_all_dies = 1;
13815
13816       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
13817          THIS_CU->cu may already be in use.  So we can't just free it and
13818          replace its DIEs with the ones we read in.  Instead, we leave those
13819          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
13820          and clobber THIS_CU->cu->partial_dies with the hash table for the new
13821          set.  */
13822       load_partial_comp_unit (per_cu);
13823
13824       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13825     }
13826
13827   if (pd == NULL)
13828     internal_error (__FILE__, __LINE__,
13829                     _("could not find partial DIE 0x%x "
13830                       "in cache [from module %s]\n"),
13831                     offset.sect_off, bfd_get_filename (objfile->obfd));
13832   return pd;
13833 }
13834
13835 /* See if we can figure out if the class lives in a namespace.  We do
13836    this by looking for a member function; its demangled name will
13837    contain namespace info, if there is any.  */
13838
13839 static void
13840 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
13841                                   struct dwarf2_cu *cu)
13842 {
13843   /* NOTE: carlton/2003-10-07: Getting the info this way changes
13844      what template types look like, because the demangler
13845      frequently doesn't give the same name as the debug info.  We
13846      could fix this by only using the demangled name to get the
13847      prefix (but see comment in read_structure_type).  */
13848
13849   struct partial_die_info *real_pdi;
13850   struct partial_die_info *child_pdi;
13851
13852   /* If this DIE (this DIE's specification, if any) has a parent, then
13853      we should not do this.  We'll prepend the parent's fully qualified
13854      name when we create the partial symbol.  */
13855
13856   real_pdi = struct_pdi;
13857   while (real_pdi->has_specification)
13858     real_pdi = find_partial_die (real_pdi->spec_offset,
13859                                  real_pdi->spec_is_dwz, cu);
13860
13861   if (real_pdi->die_parent != NULL)
13862     return;
13863
13864   for (child_pdi = struct_pdi->die_child;
13865        child_pdi != NULL;
13866        child_pdi = child_pdi->die_sibling)
13867     {
13868       if (child_pdi->tag == DW_TAG_subprogram
13869           && child_pdi->linkage_name != NULL)
13870         {
13871           char *actual_class_name
13872             = language_class_name_from_physname (cu->language_defn,
13873                                                  child_pdi->linkage_name);
13874           if (actual_class_name != NULL)
13875             {
13876               struct_pdi->name
13877                 = obstack_copy0 (&cu->objfile->objfile_obstack,
13878                                  actual_class_name,
13879                                  strlen (actual_class_name));
13880               xfree (actual_class_name);
13881             }
13882           break;
13883         }
13884     }
13885 }
13886
13887 /* Adjust PART_DIE before generating a symbol for it.  This function
13888    may set the is_external flag or change the DIE's name.  */
13889
13890 static void
13891 fixup_partial_die (struct partial_die_info *part_die,
13892                    struct dwarf2_cu *cu)
13893 {
13894   /* Once we've fixed up a die, there's no point in doing so again.
13895      This also avoids a memory leak if we were to call
13896      guess_partial_die_structure_name multiple times.  */
13897   if (part_die->fixup_called)
13898     return;
13899
13900   /* If we found a reference attribute and the DIE has no name, try
13901      to find a name in the referred to DIE.  */
13902
13903   if (part_die->name == NULL && part_die->has_specification)
13904     {
13905       struct partial_die_info *spec_die;
13906
13907       spec_die = find_partial_die (part_die->spec_offset,
13908                                    part_die->spec_is_dwz, cu);
13909
13910       fixup_partial_die (spec_die, cu);
13911
13912       if (spec_die->name)
13913         {
13914           part_die->name = spec_die->name;
13915
13916           /* Copy DW_AT_external attribute if it is set.  */
13917           if (spec_die->is_external)
13918             part_die->is_external = spec_die->is_external;
13919         }
13920     }
13921
13922   /* Set default names for some unnamed DIEs.  */
13923
13924   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
13925     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
13926
13927   /* If there is no parent die to provide a namespace, and there are
13928      children, see if we can determine the namespace from their linkage
13929      name.  */
13930   if (cu->language == language_cplus
13931       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
13932       && part_die->die_parent == NULL
13933       && part_die->has_children
13934       && (part_die->tag == DW_TAG_class_type
13935           || part_die->tag == DW_TAG_structure_type
13936           || part_die->tag == DW_TAG_union_type))
13937     guess_partial_die_structure_name (part_die, cu);
13938
13939   /* GCC might emit a nameless struct or union that has a linkage
13940      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
13941   if (part_die->name == NULL
13942       && (part_die->tag == DW_TAG_class_type
13943           || part_die->tag == DW_TAG_interface_type
13944           || part_die->tag == DW_TAG_structure_type
13945           || part_die->tag == DW_TAG_union_type)
13946       && part_die->linkage_name != NULL)
13947     {
13948       char *demangled;
13949
13950       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
13951       if (demangled)
13952         {
13953           const char *base;
13954
13955           /* Strip any leading namespaces/classes, keep only the base name.
13956              DW_AT_name for named DIEs does not contain the prefixes.  */
13957           base = strrchr (demangled, ':');
13958           if (base && base > demangled && base[-1] == ':')
13959             base++;
13960           else
13961             base = demangled;
13962
13963           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
13964                                           base, strlen (base));
13965           xfree (demangled);
13966         }
13967     }
13968
13969   part_die->fixup_called = 1;
13970 }
13971
13972 /* Read an attribute value described by an attribute form.  */
13973
13974 static gdb_byte *
13975 read_attribute_value (const struct die_reader_specs *reader,
13976                       struct attribute *attr, unsigned form,
13977                       gdb_byte *info_ptr)
13978 {
13979   struct dwarf2_cu *cu = reader->cu;
13980   bfd *abfd = reader->abfd;
13981   struct comp_unit_head *cu_header = &cu->header;
13982   unsigned int bytes_read;
13983   struct dwarf_block *blk;
13984
13985   attr->form = form;
13986   switch (form)
13987     {
13988     case DW_FORM_ref_addr:
13989       if (cu->header.version == 2)
13990         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
13991       else
13992         DW_UNSND (attr) = read_offset (abfd, info_ptr,
13993                                        &cu->header, &bytes_read);
13994       info_ptr += bytes_read;
13995       break;
13996     case DW_FORM_GNU_ref_alt:
13997       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
13998       info_ptr += bytes_read;
13999       break;
14000     case DW_FORM_addr:
14001       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14002       info_ptr += bytes_read;
14003       break;
14004     case DW_FORM_block2:
14005       blk = dwarf_alloc_block (cu);
14006       blk->size = read_2_bytes (abfd, info_ptr);
14007       info_ptr += 2;
14008       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14009       info_ptr += blk->size;
14010       DW_BLOCK (attr) = blk;
14011       break;
14012     case DW_FORM_block4:
14013       blk = dwarf_alloc_block (cu);
14014       blk->size = read_4_bytes (abfd, info_ptr);
14015       info_ptr += 4;
14016       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14017       info_ptr += blk->size;
14018       DW_BLOCK (attr) = blk;
14019       break;
14020     case DW_FORM_data2:
14021       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14022       info_ptr += 2;
14023       break;
14024     case DW_FORM_data4:
14025       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14026       info_ptr += 4;
14027       break;
14028     case DW_FORM_data8:
14029       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14030       info_ptr += 8;
14031       break;
14032     case DW_FORM_sec_offset:
14033       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14034       info_ptr += bytes_read;
14035       break;
14036     case DW_FORM_string:
14037       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14038       DW_STRING_IS_CANONICAL (attr) = 0;
14039       info_ptr += bytes_read;
14040       break;
14041     case DW_FORM_strp:
14042       if (!cu->per_cu->is_dwz)
14043         {
14044           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14045                                                    &bytes_read);
14046           DW_STRING_IS_CANONICAL (attr) = 0;
14047           info_ptr += bytes_read;
14048           break;
14049         }
14050       /* FALLTHROUGH */
14051     case DW_FORM_GNU_strp_alt:
14052       {
14053         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14054         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14055                                           &bytes_read);
14056
14057         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14058         DW_STRING_IS_CANONICAL (attr) = 0;
14059         info_ptr += bytes_read;
14060       }
14061       break;
14062     case DW_FORM_exprloc:
14063     case DW_FORM_block:
14064       blk = dwarf_alloc_block (cu);
14065       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14066       info_ptr += bytes_read;
14067       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14068       info_ptr += blk->size;
14069       DW_BLOCK (attr) = blk;
14070       break;
14071     case DW_FORM_block1:
14072       blk = dwarf_alloc_block (cu);
14073       blk->size = read_1_byte (abfd, info_ptr);
14074       info_ptr += 1;
14075       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14076       info_ptr += blk->size;
14077       DW_BLOCK (attr) = blk;
14078       break;
14079     case DW_FORM_data1:
14080       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14081       info_ptr += 1;
14082       break;
14083     case DW_FORM_flag:
14084       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14085       info_ptr += 1;
14086       break;
14087     case DW_FORM_flag_present:
14088       DW_UNSND (attr) = 1;
14089       break;
14090     case DW_FORM_sdata:
14091       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14092       info_ptr += bytes_read;
14093       break;
14094     case DW_FORM_udata:
14095       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14096       info_ptr += bytes_read;
14097       break;
14098     case DW_FORM_ref1:
14099       DW_UNSND (attr) = (cu->header.offset.sect_off
14100                          + read_1_byte (abfd, info_ptr));
14101       info_ptr += 1;
14102       break;
14103     case DW_FORM_ref2:
14104       DW_UNSND (attr) = (cu->header.offset.sect_off
14105                          + read_2_bytes (abfd, info_ptr));
14106       info_ptr += 2;
14107       break;
14108     case DW_FORM_ref4:
14109       DW_UNSND (attr) = (cu->header.offset.sect_off
14110                          + read_4_bytes (abfd, info_ptr));
14111       info_ptr += 4;
14112       break;
14113     case DW_FORM_ref8:
14114       DW_UNSND (attr) = (cu->header.offset.sect_off
14115                          + read_8_bytes (abfd, info_ptr));
14116       info_ptr += 8;
14117       break;
14118     case DW_FORM_ref_sig8:
14119       /* Convert the signature to something we can record in DW_UNSND
14120          for later lookup.
14121          NOTE: This is NULL if the type wasn't found.  */
14122       DW_SIGNATURED_TYPE (attr) =
14123         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14124       info_ptr += 8;
14125       break;
14126     case DW_FORM_ref_udata:
14127       DW_UNSND (attr) = (cu->header.offset.sect_off
14128                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14129       info_ptr += bytes_read;
14130       break;
14131     case DW_FORM_indirect:
14132       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14133       info_ptr += bytes_read;
14134       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14135       break;
14136     case DW_FORM_GNU_addr_index:
14137       if (reader->dwo_file == NULL)
14138         {
14139           /* For now flag a hard error.
14140              Later we can turn this into a complaint.  */
14141           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14142                  dwarf_form_name (form),
14143                  bfd_get_filename (abfd));
14144         }
14145       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14146       info_ptr += bytes_read;
14147       break;
14148     case DW_FORM_GNU_str_index:
14149       if (reader->dwo_file == NULL)
14150         {
14151           /* For now flag a hard error.
14152              Later we can turn this into a complaint if warranted.  */
14153           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14154                  dwarf_form_name (form),
14155                  bfd_get_filename (abfd));
14156         }
14157       {
14158         ULONGEST str_index =
14159           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14160
14161         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14162         DW_STRING_IS_CANONICAL (attr) = 0;
14163         info_ptr += bytes_read;
14164       }
14165       break;
14166     default:
14167       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14168              dwarf_form_name (form),
14169              bfd_get_filename (abfd));
14170     }
14171
14172   /* Super hack.  */
14173   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14174     attr->form = DW_FORM_GNU_ref_alt;
14175
14176   /* We have seen instances where the compiler tried to emit a byte
14177      size attribute of -1 which ended up being encoded as an unsigned
14178      0xffffffff.  Although 0xffffffff is technically a valid size value,
14179      an object of this size seems pretty unlikely so we can relatively
14180      safely treat these cases as if the size attribute was invalid and
14181      treat them as zero by default.  */
14182   if (attr->name == DW_AT_byte_size
14183       && form == DW_FORM_data4
14184       && DW_UNSND (attr) >= 0xffffffff)
14185     {
14186       complaint
14187         (&symfile_complaints,
14188          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14189          hex_string (DW_UNSND (attr)));
14190       DW_UNSND (attr) = 0;
14191     }
14192
14193   return info_ptr;
14194 }
14195
14196 /* Read an attribute described by an abbreviated attribute.  */
14197
14198 static gdb_byte *
14199 read_attribute (const struct die_reader_specs *reader,
14200                 struct attribute *attr, struct attr_abbrev *abbrev,
14201                 gdb_byte *info_ptr)
14202 {
14203   attr->name = abbrev->name;
14204   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14205 }
14206
14207 /* Read dwarf information from a buffer.  */
14208
14209 static unsigned int
14210 read_1_byte (bfd *abfd, const gdb_byte *buf)
14211 {
14212   return bfd_get_8 (abfd, buf);
14213 }
14214
14215 static int
14216 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14217 {
14218   return bfd_get_signed_8 (abfd, buf);
14219 }
14220
14221 static unsigned int
14222 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14223 {
14224   return bfd_get_16 (abfd, buf);
14225 }
14226
14227 static int
14228 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14229 {
14230   return bfd_get_signed_16 (abfd, buf);
14231 }
14232
14233 static unsigned int
14234 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14235 {
14236   return bfd_get_32 (abfd, buf);
14237 }
14238
14239 static int
14240 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14241 {
14242   return bfd_get_signed_32 (abfd, buf);
14243 }
14244
14245 static ULONGEST
14246 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14247 {
14248   return bfd_get_64 (abfd, buf);
14249 }
14250
14251 static CORE_ADDR
14252 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
14253               unsigned int *bytes_read)
14254 {
14255   struct comp_unit_head *cu_header = &cu->header;
14256   CORE_ADDR retval = 0;
14257
14258   if (cu_header->signed_addr_p)
14259     {
14260       switch (cu_header->addr_size)
14261         {
14262         case 2:
14263           retval = bfd_get_signed_16 (abfd, buf);
14264           break;
14265         case 4:
14266           retval = bfd_get_signed_32 (abfd, buf);
14267           break;
14268         case 8:
14269           retval = bfd_get_signed_64 (abfd, buf);
14270           break;
14271         default:
14272           internal_error (__FILE__, __LINE__,
14273                           _("read_address: bad switch, signed [in module %s]"),
14274                           bfd_get_filename (abfd));
14275         }
14276     }
14277   else
14278     {
14279       switch (cu_header->addr_size)
14280         {
14281         case 2:
14282           retval = bfd_get_16 (abfd, buf);
14283           break;
14284         case 4:
14285           retval = bfd_get_32 (abfd, buf);
14286           break;
14287         case 8:
14288           retval = bfd_get_64 (abfd, buf);
14289           break;
14290         default:
14291           internal_error (__FILE__, __LINE__,
14292                           _("read_address: bad switch, "
14293                             "unsigned [in module %s]"),
14294                           bfd_get_filename (abfd));
14295         }
14296     }
14297
14298   *bytes_read = cu_header->addr_size;
14299   return retval;
14300 }
14301
14302 /* Read the initial length from a section.  The (draft) DWARF 3
14303    specification allows the initial length to take up either 4 bytes
14304    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14305    bytes describe the length and all offsets will be 8 bytes in length
14306    instead of 4.
14307
14308    An older, non-standard 64-bit format is also handled by this
14309    function.  The older format in question stores the initial length
14310    as an 8-byte quantity without an escape value.  Lengths greater
14311    than 2^32 aren't very common which means that the initial 4 bytes
14312    is almost always zero.  Since a length value of zero doesn't make
14313    sense for the 32-bit format, this initial zero can be considered to
14314    be an escape value which indicates the presence of the older 64-bit
14315    format.  As written, the code can't detect (old format) lengths
14316    greater than 4GB.  If it becomes necessary to handle lengths
14317    somewhat larger than 4GB, we could allow other small values (such
14318    as the non-sensical values of 1, 2, and 3) to also be used as
14319    escape values indicating the presence of the old format.
14320
14321    The value returned via bytes_read should be used to increment the
14322    relevant pointer after calling read_initial_length().
14323
14324    [ Note:  read_initial_length() and read_offset() are based on the
14325      document entitled "DWARF Debugging Information Format", revision
14326      3, draft 8, dated November 19, 2001.  This document was obtained
14327      from:
14328
14329         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14330
14331      This document is only a draft and is subject to change.  (So beware.)
14332
14333      Details regarding the older, non-standard 64-bit format were
14334      determined empirically by examining 64-bit ELF files produced by
14335      the SGI toolchain on an IRIX 6.5 machine.
14336
14337      - Kevin, July 16, 2002
14338    ] */
14339
14340 static LONGEST
14341 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
14342 {
14343   LONGEST length = bfd_get_32 (abfd, buf);
14344
14345   if (length == 0xffffffff)
14346     {
14347       length = bfd_get_64 (abfd, buf + 4);
14348       *bytes_read = 12;
14349     }
14350   else if (length == 0)
14351     {
14352       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14353       length = bfd_get_64 (abfd, buf);
14354       *bytes_read = 8;
14355     }
14356   else
14357     {
14358       *bytes_read = 4;
14359     }
14360
14361   return length;
14362 }
14363
14364 /* Cover function for read_initial_length.
14365    Returns the length of the object at BUF, and stores the size of the
14366    initial length in *BYTES_READ and stores the size that offsets will be in
14367    *OFFSET_SIZE.
14368    If the initial length size is not equivalent to that specified in
14369    CU_HEADER then issue a complaint.
14370    This is useful when reading non-comp-unit headers.  */
14371
14372 static LONGEST
14373 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
14374                                         const struct comp_unit_head *cu_header,
14375                                         unsigned int *bytes_read,
14376                                         unsigned int *offset_size)
14377 {
14378   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14379
14380   gdb_assert (cu_header->initial_length_size == 4
14381               || cu_header->initial_length_size == 8
14382               || cu_header->initial_length_size == 12);
14383
14384   if (cu_header->initial_length_size != *bytes_read)
14385     complaint (&symfile_complaints,
14386                _("intermixed 32-bit and 64-bit DWARF sections"));
14387
14388   *offset_size = (*bytes_read == 4) ? 4 : 8;
14389   return length;
14390 }
14391
14392 /* Read an offset from the data stream.  The size of the offset is
14393    given by cu_header->offset_size.  */
14394
14395 static LONGEST
14396 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
14397              unsigned int *bytes_read)
14398 {
14399   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14400
14401   *bytes_read = cu_header->offset_size;
14402   return offset;
14403 }
14404
14405 /* Read an offset from the data stream.  */
14406
14407 static LONGEST
14408 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
14409 {
14410   LONGEST retval = 0;
14411
14412   switch (offset_size)
14413     {
14414     case 4:
14415       retval = bfd_get_32 (abfd, buf);
14416       break;
14417     case 8:
14418       retval = bfd_get_64 (abfd, buf);
14419       break;
14420     default:
14421       internal_error (__FILE__, __LINE__,
14422                       _("read_offset_1: bad switch [in module %s]"),
14423                       bfd_get_filename (abfd));
14424     }
14425
14426   return retval;
14427 }
14428
14429 static gdb_byte *
14430 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
14431 {
14432   /* If the size of a host char is 8 bits, we can return a pointer
14433      to the buffer, otherwise we have to copy the data to a buffer
14434      allocated on the temporary obstack.  */
14435   gdb_assert (HOST_CHAR_BIT == 8);
14436   return buf;
14437 }
14438
14439 static char *
14440 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14441 {
14442   /* If the size of a host char is 8 bits, we can return a pointer
14443      to the string, otherwise we have to copy the string to a buffer
14444      allocated on the temporary obstack.  */
14445   gdb_assert (HOST_CHAR_BIT == 8);
14446   if (*buf == '\0')
14447     {
14448       *bytes_read_ptr = 1;
14449       return NULL;
14450     }
14451   *bytes_read_ptr = strlen ((char *) buf) + 1;
14452   return (char *) buf;
14453 }
14454
14455 static char *
14456 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14457 {
14458   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14459   if (dwarf2_per_objfile->str.buffer == NULL)
14460     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14461            bfd_get_filename (abfd));
14462   if (str_offset >= dwarf2_per_objfile->str.size)
14463     error (_("DW_FORM_strp pointing outside of "
14464              ".debug_str section [in module %s]"),
14465            bfd_get_filename (abfd));
14466   gdb_assert (HOST_CHAR_BIT == 8);
14467   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14468     return NULL;
14469   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
14470 }
14471
14472 /* Read a string at offset STR_OFFSET in the .debug_str section from
14473    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14474    the string consists of a single NUL byte, return NULL; otherwise
14475    return a pointer to the string.  */
14476
14477 static char *
14478 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14479 {
14480   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14481
14482   if (dwz->str.buffer == NULL)
14483     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14484              "section [in module %s]"),
14485            bfd_get_filename (dwz->dwz_bfd));
14486   if (str_offset >= dwz->str.size)
14487     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14488              ".debug_str section [in module %s]"),
14489            bfd_get_filename (dwz->dwz_bfd));
14490   gdb_assert (HOST_CHAR_BIT == 8);
14491   if (dwz->str.buffer[str_offset] == '\0')
14492     return NULL;
14493   return (char *) (dwz->str.buffer + str_offset);
14494 }
14495
14496 static char *
14497 read_indirect_string (bfd *abfd, gdb_byte *buf,
14498                       const struct comp_unit_head *cu_header,
14499                       unsigned int *bytes_read_ptr)
14500 {
14501   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14502
14503   return read_indirect_string_at_offset (abfd, str_offset);
14504 }
14505
14506 static ULONGEST
14507 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14508 {
14509   ULONGEST result;
14510   unsigned int num_read;
14511   int i, shift;
14512   unsigned char byte;
14513
14514   result = 0;
14515   shift = 0;
14516   num_read = 0;
14517   i = 0;
14518   while (1)
14519     {
14520       byte = bfd_get_8 (abfd, buf);
14521       buf++;
14522       num_read++;
14523       result |= ((ULONGEST) (byte & 127) << shift);
14524       if ((byte & 128) == 0)
14525         {
14526           break;
14527         }
14528       shift += 7;
14529     }
14530   *bytes_read_ptr = num_read;
14531   return result;
14532 }
14533
14534 static LONGEST
14535 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14536 {
14537   LONGEST result;
14538   int i, shift, num_read;
14539   unsigned char byte;
14540
14541   result = 0;
14542   shift = 0;
14543   num_read = 0;
14544   i = 0;
14545   while (1)
14546     {
14547       byte = bfd_get_8 (abfd, buf);
14548       buf++;
14549       num_read++;
14550       result |= ((LONGEST) (byte & 127) << shift);
14551       shift += 7;
14552       if ((byte & 128) == 0)
14553         {
14554           break;
14555         }
14556     }
14557   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14558     result |= -(((LONGEST) 1) << shift);
14559   *bytes_read_ptr = num_read;
14560   return result;
14561 }
14562
14563 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14564    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14565    ADDR_SIZE is the size of addresses from the CU header.  */
14566
14567 static CORE_ADDR
14568 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14569 {
14570   struct objfile *objfile = dwarf2_per_objfile->objfile;
14571   bfd *abfd = objfile->obfd;
14572   const gdb_byte *info_ptr;
14573
14574   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14575   if (dwarf2_per_objfile->addr.buffer == NULL)
14576     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14577            objfile->name);
14578   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14579     error (_("DW_FORM_addr_index pointing outside of "
14580              ".debug_addr section [in module %s]"),
14581            objfile->name);
14582   info_ptr = (dwarf2_per_objfile->addr.buffer
14583               + addr_base + addr_index * addr_size);
14584   if (addr_size == 4)
14585     return bfd_get_32 (abfd, info_ptr);
14586   else
14587     return bfd_get_64 (abfd, info_ptr);
14588 }
14589
14590 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14591
14592 static CORE_ADDR
14593 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14594 {
14595   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14596 }
14597
14598 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14599
14600 static CORE_ADDR
14601 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
14602                              unsigned int *bytes_read)
14603 {
14604   bfd *abfd = cu->objfile->obfd;
14605   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14606
14607   return read_addr_index (cu, addr_index);
14608 }
14609
14610 /* Data structure to pass results from dwarf2_read_addr_index_reader
14611    back to dwarf2_read_addr_index.  */
14612
14613 struct dwarf2_read_addr_index_data
14614 {
14615   ULONGEST addr_base;
14616   int addr_size;
14617 };
14618
14619 /* die_reader_func for dwarf2_read_addr_index.  */
14620
14621 static void
14622 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14623                                gdb_byte *info_ptr,
14624                                struct die_info *comp_unit_die,
14625                                int has_children,
14626                                void *data)
14627 {
14628   struct dwarf2_cu *cu = reader->cu;
14629   struct dwarf2_read_addr_index_data *aidata =
14630     (struct dwarf2_read_addr_index_data *) data;
14631
14632   aidata->addr_base = cu->addr_base;
14633   aidata->addr_size = cu->header.addr_size;
14634 }
14635
14636 /* Given an index in .debug_addr, fetch the value.
14637    NOTE: This can be called during dwarf expression evaluation,
14638    long after the debug information has been read, and thus per_cu->cu
14639    may no longer exist.  */
14640
14641 CORE_ADDR
14642 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14643                         unsigned int addr_index)
14644 {
14645   struct objfile *objfile = per_cu->objfile;
14646   struct dwarf2_cu *cu = per_cu->cu;
14647   ULONGEST addr_base;
14648   int addr_size;
14649
14650   /* This is intended to be called from outside this file.  */
14651   dw2_setup (objfile);
14652
14653   /* We need addr_base and addr_size.
14654      If we don't have PER_CU->cu, we have to get it.
14655      Nasty, but the alternative is storing the needed info in PER_CU,
14656      which at this point doesn't seem justified: it's not clear how frequently
14657      it would get used and it would increase the size of every PER_CU.
14658      Entry points like dwarf2_per_cu_addr_size do a similar thing
14659      so we're not in uncharted territory here.
14660      Alas we need to be a bit more complicated as addr_base is contained
14661      in the DIE.
14662
14663      We don't need to read the entire CU(/TU).
14664      We just need the header and top level die.
14665
14666      IWBN to use the aging mechanism to let us lazily later discard the CU.
14667      For now we skip this optimization.  */
14668
14669   if (cu != NULL)
14670     {
14671       addr_base = cu->addr_base;
14672       addr_size = cu->header.addr_size;
14673     }
14674   else
14675     {
14676       struct dwarf2_read_addr_index_data aidata;
14677
14678       /* Note: We can't use init_cutu_and_read_dies_simple here,
14679          we need addr_base.  */
14680       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14681                                dwarf2_read_addr_index_reader, &aidata);
14682       addr_base = aidata.addr_base;
14683       addr_size = aidata.addr_size;
14684     }
14685
14686   return read_addr_index_1 (addr_index, addr_base, addr_size);
14687 }
14688
14689 /* Given a DW_AT_str_index, fetch the string.  */
14690
14691 static char *
14692 read_str_index (const struct die_reader_specs *reader,
14693                 struct dwarf2_cu *cu, ULONGEST str_index)
14694 {
14695   struct objfile *objfile = dwarf2_per_objfile->objfile;
14696   const char *dwo_name = objfile->name;
14697   bfd *abfd = objfile->obfd;
14698   struct dwo_sections *sections = &reader->dwo_file->sections;
14699   gdb_byte *info_ptr;
14700   ULONGEST str_offset;
14701
14702   dwarf2_read_section (objfile, &sections->str);
14703   dwarf2_read_section (objfile, &sections->str_offsets);
14704   if (sections->str.buffer == NULL)
14705     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14706              " in CU at offset 0x%lx [in module %s]"),
14707            (long) cu->header.offset.sect_off, dwo_name);
14708   if (sections->str_offsets.buffer == NULL)
14709     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14710              " in CU at offset 0x%lx [in module %s]"),
14711            (long) cu->header.offset.sect_off, dwo_name);
14712   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14713     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14714              " section in CU at offset 0x%lx [in module %s]"),
14715            (long) cu->header.offset.sect_off, dwo_name);
14716   info_ptr = (sections->str_offsets.buffer
14717               + str_index * cu->header.offset_size);
14718   if (cu->header.offset_size == 4)
14719     str_offset = bfd_get_32 (abfd, info_ptr);
14720   else
14721     str_offset = bfd_get_64 (abfd, info_ptr);
14722   if (str_offset >= sections->str.size)
14723     error (_("Offset from DW_FORM_str_index pointing outside of"
14724              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14725            (long) cu->header.offset.sect_off, dwo_name);
14726   return (char *) (sections->str.buffer + str_offset);
14727 }
14728
14729 /* Return the length of an LEB128 number in BUF.  */
14730
14731 static int
14732 leb128_size (const gdb_byte *buf)
14733 {
14734   const gdb_byte *begin = buf;
14735   gdb_byte byte;
14736
14737   while (1)
14738     {
14739       byte = *buf++;
14740       if ((byte & 128) == 0)
14741         return buf - begin;
14742     }
14743 }
14744
14745 static void
14746 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14747 {
14748   switch (lang)
14749     {
14750     case DW_LANG_C89:
14751     case DW_LANG_C99:
14752     case DW_LANG_C:
14753       cu->language = language_c;
14754       break;
14755     case DW_LANG_C_plus_plus:
14756       cu->language = language_cplus;
14757       break;
14758     case DW_LANG_D:
14759       cu->language = language_d;
14760       break;
14761     case DW_LANG_Fortran77:
14762     case DW_LANG_Fortran90:
14763     case DW_LANG_Fortran95:
14764       cu->language = language_fortran;
14765       break;
14766     case DW_LANG_Go:
14767       cu->language = language_go;
14768       break;
14769     case DW_LANG_Mips_Assembler:
14770       cu->language = language_asm;
14771       break;
14772     case DW_LANG_Java:
14773       cu->language = language_java;
14774       break;
14775     case DW_LANG_Ada83:
14776     case DW_LANG_Ada95:
14777       cu->language = language_ada;
14778       break;
14779     case DW_LANG_Modula2:
14780       cu->language = language_m2;
14781       break;
14782     case DW_LANG_Pascal83:
14783       cu->language = language_pascal;
14784       break;
14785     case DW_LANG_ObjC:
14786       cu->language = language_objc;
14787       break;
14788     case DW_LANG_Cobol74:
14789     case DW_LANG_Cobol85:
14790     default:
14791       cu->language = language_minimal;
14792       break;
14793     }
14794   cu->language_defn = language_def (cu->language);
14795 }
14796
14797 /* Return the named attribute or NULL if not there.  */
14798
14799 static struct attribute *
14800 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
14801 {
14802   for (;;)
14803     {
14804       unsigned int i;
14805       struct attribute *spec = NULL;
14806
14807       for (i = 0; i < die->num_attrs; ++i)
14808         {
14809           if (die->attrs[i].name == name)
14810             return &die->attrs[i];
14811           if (die->attrs[i].name == DW_AT_specification
14812               || die->attrs[i].name == DW_AT_abstract_origin)
14813             spec = &die->attrs[i];
14814         }
14815
14816       if (!spec)
14817         break;
14818
14819       die = follow_die_ref (die, spec, &cu);
14820     }
14821
14822   return NULL;
14823 }
14824
14825 /* Return the named attribute or NULL if not there,
14826    but do not follow DW_AT_specification, etc.
14827    This is for use in contexts where we're reading .debug_types dies.
14828    Following DW_AT_specification, DW_AT_abstract_origin will take us
14829    back up the chain, and we want to go down.  */
14830
14831 static struct attribute *
14832 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
14833 {
14834   unsigned int i;
14835
14836   for (i = 0; i < die->num_attrs; ++i)
14837     if (die->attrs[i].name == name)
14838       return &die->attrs[i];
14839
14840   return NULL;
14841 }
14842
14843 /* Return non-zero iff the attribute NAME is defined for the given DIE,
14844    and holds a non-zero value.  This function should only be used for
14845    DW_FORM_flag or DW_FORM_flag_present attributes.  */
14846
14847 static int
14848 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
14849 {
14850   struct attribute *attr = dwarf2_attr (die, name, cu);
14851
14852   return (attr && DW_UNSND (attr));
14853 }
14854
14855 static int
14856 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
14857 {
14858   /* A DIE is a declaration if it has a DW_AT_declaration attribute
14859      which value is non-zero.  However, we have to be careful with
14860      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
14861      (via dwarf2_flag_true_p) follows this attribute.  So we may
14862      end up accidently finding a declaration attribute that belongs
14863      to a different DIE referenced by the specification attribute,
14864      even though the given DIE does not have a declaration attribute.  */
14865   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
14866           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
14867 }
14868
14869 /* Return the die giving the specification for DIE, if there is
14870    one.  *SPEC_CU is the CU containing DIE on input, and the CU
14871    containing the return value on output.  If there is no
14872    specification, but there is an abstract origin, that is
14873    returned.  */
14874
14875 static struct die_info *
14876 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
14877 {
14878   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
14879                                              *spec_cu);
14880
14881   if (spec_attr == NULL)
14882     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
14883
14884   if (spec_attr == NULL)
14885     return NULL;
14886   else
14887     return follow_die_ref (die, spec_attr, spec_cu);
14888 }
14889
14890 /* Free the line_header structure *LH, and any arrays and strings it
14891    refers to.
14892    NOTE: This is also used as a "cleanup" function.  */
14893
14894 static void
14895 free_line_header (struct line_header *lh)
14896 {
14897   if (lh->standard_opcode_lengths)
14898     xfree (lh->standard_opcode_lengths);
14899
14900   /* Remember that all the lh->file_names[i].name pointers are
14901      pointers into debug_line_buffer, and don't need to be freed.  */
14902   if (lh->file_names)
14903     xfree (lh->file_names);
14904
14905   /* Similarly for the include directory names.  */
14906   if (lh->include_dirs)
14907     xfree (lh->include_dirs);
14908
14909   xfree (lh);
14910 }
14911
14912 /* Add an entry to LH's include directory table.  */
14913
14914 static void
14915 add_include_dir (struct line_header *lh, char *include_dir)
14916 {
14917   /* Grow the array if necessary.  */
14918   if (lh->include_dirs_size == 0)
14919     {
14920       lh->include_dirs_size = 1; /* for testing */
14921       lh->include_dirs = xmalloc (lh->include_dirs_size
14922                                   * sizeof (*lh->include_dirs));
14923     }
14924   else if (lh->num_include_dirs >= lh->include_dirs_size)
14925     {
14926       lh->include_dirs_size *= 2;
14927       lh->include_dirs = xrealloc (lh->include_dirs,
14928                                    (lh->include_dirs_size
14929                                     * sizeof (*lh->include_dirs)));
14930     }
14931
14932   lh->include_dirs[lh->num_include_dirs++] = include_dir;
14933 }
14934
14935 /* Add an entry to LH's file name table.  */
14936
14937 static void
14938 add_file_name (struct line_header *lh,
14939                char *name,
14940                unsigned int dir_index,
14941                unsigned int mod_time,
14942                unsigned int length)
14943 {
14944   struct file_entry *fe;
14945
14946   /* Grow the array if necessary.  */
14947   if (lh->file_names_size == 0)
14948     {
14949       lh->file_names_size = 1; /* for testing */
14950       lh->file_names = xmalloc (lh->file_names_size
14951                                 * sizeof (*lh->file_names));
14952     }
14953   else if (lh->num_file_names >= lh->file_names_size)
14954     {
14955       lh->file_names_size *= 2;
14956       lh->file_names = xrealloc (lh->file_names,
14957                                  (lh->file_names_size
14958                                   * sizeof (*lh->file_names)));
14959     }
14960
14961   fe = &lh->file_names[lh->num_file_names++];
14962   fe->name = name;
14963   fe->dir_index = dir_index;
14964   fe->mod_time = mod_time;
14965   fe->length = length;
14966   fe->included_p = 0;
14967   fe->symtab = NULL;
14968 }
14969
14970 /* A convenience function to find the proper .debug_line section for a
14971    CU.  */
14972
14973 static struct dwarf2_section_info *
14974 get_debug_line_section (struct dwarf2_cu *cu)
14975 {
14976   struct dwarf2_section_info *section;
14977
14978   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
14979      DWO file.  */
14980   if (cu->dwo_unit && cu->per_cu->is_debug_types)
14981     section = &cu->dwo_unit->dwo_file->sections.line;
14982   else if (cu->per_cu->is_dwz)
14983     {
14984       struct dwz_file *dwz = dwarf2_get_dwz_file ();
14985
14986       section = &dwz->line;
14987     }
14988   else
14989     section = &dwarf2_per_objfile->line;
14990
14991   return section;
14992 }
14993
14994 /* Read the statement program header starting at OFFSET in
14995    .debug_line, or .debug_line.dwo.  Return a pointer
14996    to a struct line_header, allocated using xmalloc.
14997
14998    NOTE: the strings in the include directory and file name tables of
14999    the returned object point into the dwarf line section buffer,
15000    and must not be freed.  */
15001
15002 static struct line_header *
15003 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15004 {
15005   struct cleanup *back_to;
15006   struct line_header *lh;
15007   gdb_byte *line_ptr;
15008   unsigned int bytes_read, offset_size;
15009   int i;
15010   char *cur_dir, *cur_file;
15011   struct dwarf2_section_info *section;
15012   bfd *abfd;
15013
15014   section = get_debug_line_section (cu);
15015   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15016   if (section->buffer == NULL)
15017     {
15018       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15019         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15020       else
15021         complaint (&symfile_complaints, _("missing .debug_line section"));
15022       return 0;
15023     }
15024
15025   /* We can't do this until we know the section is non-empty.
15026      Only then do we know we have such a section.  */
15027   abfd = section->asection->owner;
15028
15029   /* Make sure that at least there's room for the total_length field.
15030      That could be 12 bytes long, but we're just going to fudge that.  */
15031   if (offset + 4 >= section->size)
15032     {
15033       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15034       return 0;
15035     }
15036
15037   lh = xmalloc (sizeof (*lh));
15038   memset (lh, 0, sizeof (*lh));
15039   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15040                           (void *) lh);
15041
15042   line_ptr = section->buffer + offset;
15043
15044   /* Read in the header.  */
15045   lh->total_length =
15046     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15047                                             &bytes_read, &offset_size);
15048   line_ptr += bytes_read;
15049   if (line_ptr + lh->total_length > (section->buffer + section->size))
15050     {
15051       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15052       return 0;
15053     }
15054   lh->statement_program_end = line_ptr + lh->total_length;
15055   lh->version = read_2_bytes (abfd, line_ptr);
15056   line_ptr += 2;
15057   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15058   line_ptr += offset_size;
15059   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15060   line_ptr += 1;
15061   if (lh->version >= 4)
15062     {
15063       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15064       line_ptr += 1;
15065     }
15066   else
15067     lh->maximum_ops_per_instruction = 1;
15068
15069   if (lh->maximum_ops_per_instruction == 0)
15070     {
15071       lh->maximum_ops_per_instruction = 1;
15072       complaint (&symfile_complaints,
15073                  _("invalid maximum_ops_per_instruction "
15074                    "in `.debug_line' section"));
15075     }
15076
15077   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15078   line_ptr += 1;
15079   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15080   line_ptr += 1;
15081   lh->line_range = read_1_byte (abfd, line_ptr);
15082   line_ptr += 1;
15083   lh->opcode_base = read_1_byte (abfd, line_ptr);
15084   line_ptr += 1;
15085   lh->standard_opcode_lengths
15086     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15087
15088   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15089   for (i = 1; i < lh->opcode_base; ++i)
15090     {
15091       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15092       line_ptr += 1;
15093     }
15094
15095   /* Read directory table.  */
15096   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15097     {
15098       line_ptr += bytes_read;
15099       add_include_dir (lh, cur_dir);
15100     }
15101   line_ptr += bytes_read;
15102
15103   /* Read file name table.  */
15104   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15105     {
15106       unsigned int dir_index, mod_time, length;
15107
15108       line_ptr += bytes_read;
15109       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15110       line_ptr += bytes_read;
15111       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15112       line_ptr += bytes_read;
15113       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15114       line_ptr += bytes_read;
15115
15116       add_file_name (lh, cur_file, dir_index, mod_time, length);
15117     }
15118   line_ptr += bytes_read;
15119   lh->statement_program_start = line_ptr;
15120
15121   if (line_ptr > (section->buffer + section->size))
15122     complaint (&symfile_complaints,
15123                _("line number info header doesn't "
15124                  "fit in `.debug_line' section"));
15125
15126   discard_cleanups (back_to);
15127   return lh;
15128 }
15129
15130 /* Subroutine of dwarf_decode_lines to simplify it.
15131    Return the file name of the psymtab for included file FILE_INDEX
15132    in line header LH of PST.
15133    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15134    If space for the result is malloc'd, it will be freed by a cleanup.
15135    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15136
15137    The function creates dangling cleanup registration.  */
15138
15139 static char *
15140 psymtab_include_file_name (const struct line_header *lh, int file_index,
15141                            const struct partial_symtab *pst,
15142                            const char *comp_dir)
15143 {
15144   const struct file_entry fe = lh->file_names [file_index];
15145   char *include_name = fe.name;
15146   char *include_name_to_compare = include_name;
15147   char *dir_name = NULL;
15148   const char *pst_filename;
15149   char *copied_name = NULL;
15150   int file_is_pst;
15151
15152   if (fe.dir_index)
15153     dir_name = lh->include_dirs[fe.dir_index - 1];
15154
15155   if (!IS_ABSOLUTE_PATH (include_name)
15156       && (dir_name != NULL || comp_dir != NULL))
15157     {
15158       /* Avoid creating a duplicate psymtab for PST.
15159          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15160          Before we do the comparison, however, we need to account
15161          for DIR_NAME and COMP_DIR.
15162          First prepend dir_name (if non-NULL).  If we still don't
15163          have an absolute path prepend comp_dir (if non-NULL).
15164          However, the directory we record in the include-file's
15165          psymtab does not contain COMP_DIR (to match the
15166          corresponding symtab(s)).
15167
15168          Example:
15169
15170          bash$ cd /tmp
15171          bash$ gcc -g ./hello.c
15172          include_name = "hello.c"
15173          dir_name = "."
15174          DW_AT_comp_dir = comp_dir = "/tmp"
15175          DW_AT_name = "./hello.c"  */
15176
15177       if (dir_name != NULL)
15178         {
15179           include_name = concat (dir_name, SLASH_STRING,
15180                                  include_name, (char *)NULL);
15181           include_name_to_compare = include_name;
15182           make_cleanup (xfree, include_name);
15183         }
15184       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15185         {
15186           include_name_to_compare = concat (comp_dir, SLASH_STRING,
15187                                             include_name, (char *)NULL);
15188         }
15189     }
15190
15191   pst_filename = pst->filename;
15192   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15193     {
15194       copied_name = concat (pst->dirname, SLASH_STRING,
15195                             pst_filename, (char *)NULL);
15196       pst_filename = copied_name;
15197     }
15198
15199   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15200
15201   if (include_name_to_compare != include_name)
15202     xfree (include_name_to_compare);
15203   if (copied_name != NULL)
15204     xfree (copied_name);
15205
15206   if (file_is_pst)
15207     return NULL;
15208   return include_name;
15209 }
15210
15211 /* Ignore this record_line request.  */
15212
15213 static void
15214 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15215 {
15216   return;
15217 }
15218
15219 /* Subroutine of dwarf_decode_lines to simplify it.
15220    Process the line number information in LH.  */
15221
15222 static void
15223 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15224                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15225 {
15226   gdb_byte *line_ptr, *extended_end;
15227   gdb_byte *line_end;
15228   unsigned int bytes_read, extended_len;
15229   unsigned char op_code, extended_op, adj_opcode;
15230   CORE_ADDR baseaddr;
15231   struct objfile *objfile = cu->objfile;
15232   bfd *abfd = objfile->obfd;
15233   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15234   const int decode_for_pst_p = (pst != NULL);
15235   struct subfile *last_subfile = NULL;
15236   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15237     = record_line;
15238
15239   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15240
15241   line_ptr = lh->statement_program_start;
15242   line_end = lh->statement_program_end;
15243
15244   /* Read the statement sequences until there's nothing left.  */
15245   while (line_ptr < line_end)
15246     {
15247       /* state machine registers  */
15248       CORE_ADDR address = 0;
15249       unsigned int file = 1;
15250       unsigned int line = 1;
15251       unsigned int column = 0;
15252       int is_stmt = lh->default_is_stmt;
15253       int basic_block = 0;
15254       int end_sequence = 0;
15255       CORE_ADDR addr;
15256       unsigned char op_index = 0;
15257
15258       if (!decode_for_pst_p && lh->num_file_names >= file)
15259         {
15260           /* Start a subfile for the current file of the state machine.  */
15261           /* lh->include_dirs and lh->file_names are 0-based, but the
15262              directory and file name numbers in the statement program
15263              are 1-based.  */
15264           struct file_entry *fe = &lh->file_names[file - 1];
15265           char *dir = NULL;
15266
15267           if (fe->dir_index)
15268             dir = lh->include_dirs[fe->dir_index - 1];
15269
15270           dwarf2_start_subfile (fe->name, dir, comp_dir);
15271         }
15272
15273       /* Decode the table.  */
15274       while (!end_sequence)
15275         {
15276           op_code = read_1_byte (abfd, line_ptr);
15277           line_ptr += 1;
15278           if (line_ptr > line_end)
15279             {
15280               dwarf2_debug_line_missing_end_sequence_complaint ();
15281               break;
15282             }
15283
15284           if (op_code >= lh->opcode_base)
15285             {
15286               /* Special operand.  */
15287               adj_opcode = op_code - lh->opcode_base;
15288               address += (((op_index + (adj_opcode / lh->line_range))
15289                            / lh->maximum_ops_per_instruction)
15290                           * lh->minimum_instruction_length);
15291               op_index = ((op_index + (adj_opcode / lh->line_range))
15292                           % lh->maximum_ops_per_instruction);
15293               line += lh->line_base + (adj_opcode % lh->line_range);
15294               if (lh->num_file_names < file || file == 0)
15295                 dwarf2_debug_line_missing_file_complaint ();
15296               /* For now we ignore lines not starting on an
15297                  instruction boundary.  */
15298               else if (op_index == 0)
15299                 {
15300                   lh->file_names[file - 1].included_p = 1;
15301                   if (!decode_for_pst_p && is_stmt)
15302                     {
15303                       if (last_subfile != current_subfile)
15304                         {
15305                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15306                           if (last_subfile)
15307                             (*p_record_line) (last_subfile, 0, addr);
15308                           last_subfile = current_subfile;
15309                         }
15310                       /* Append row to matrix using current values.  */
15311                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15312                       (*p_record_line) (current_subfile, line, addr);
15313                     }
15314                 }
15315               basic_block = 0;
15316             }
15317           else switch (op_code)
15318             {
15319             case DW_LNS_extended_op:
15320               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15321                                                    &bytes_read);
15322               line_ptr += bytes_read;
15323               extended_end = line_ptr + extended_len;
15324               extended_op = read_1_byte (abfd, line_ptr);
15325               line_ptr += 1;
15326               switch (extended_op)
15327                 {
15328                 case DW_LNE_end_sequence:
15329                   p_record_line = record_line;
15330                   end_sequence = 1;
15331                   break;
15332                 case DW_LNE_set_address:
15333                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15334
15335                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15336                     {
15337                       /* This line table is for a function which has been
15338                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15339
15340                       long line_offset
15341                         = line_ptr - get_debug_line_section (cu)->buffer;
15342
15343                       complaint (&symfile_complaints,
15344                                  _(".debug_line address at offset 0x%lx is 0 "
15345                                    "[in module %s]"),
15346                                  line_offset, objfile->name);
15347                       p_record_line = noop_record_line;
15348                     }
15349
15350                   op_index = 0;
15351                   line_ptr += bytes_read;
15352                   address += baseaddr;
15353                   break;
15354                 case DW_LNE_define_file:
15355                   {
15356                     char *cur_file;
15357                     unsigned int dir_index, mod_time, length;
15358
15359                     cur_file = read_direct_string (abfd, line_ptr,
15360                                                    &bytes_read);
15361                     line_ptr += bytes_read;
15362                     dir_index =
15363                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15364                     line_ptr += bytes_read;
15365                     mod_time =
15366                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15367                     line_ptr += bytes_read;
15368                     length =
15369                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15370                     line_ptr += bytes_read;
15371                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15372                   }
15373                   break;
15374                 case DW_LNE_set_discriminator:
15375                   /* The discriminator is not interesting to the debugger;
15376                      just ignore it.  */
15377                   line_ptr = extended_end;
15378                   break;
15379                 default:
15380                   complaint (&symfile_complaints,
15381                              _("mangled .debug_line section"));
15382                   return;
15383                 }
15384               /* Make sure that we parsed the extended op correctly.  If e.g.
15385                  we expected a different address size than the producer used,
15386                  we may have read the wrong number of bytes.  */
15387               if (line_ptr != extended_end)
15388                 {
15389                   complaint (&symfile_complaints,
15390                              _("mangled .debug_line section"));
15391                   return;
15392                 }
15393               break;
15394             case DW_LNS_copy:
15395               if (lh->num_file_names < file || file == 0)
15396                 dwarf2_debug_line_missing_file_complaint ();
15397               else
15398                 {
15399                   lh->file_names[file - 1].included_p = 1;
15400                   if (!decode_for_pst_p && is_stmt)
15401                     {
15402                       if (last_subfile != current_subfile)
15403                         {
15404                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15405                           if (last_subfile)
15406                             (*p_record_line) (last_subfile, 0, addr);
15407                           last_subfile = current_subfile;
15408                         }
15409                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15410                       (*p_record_line) (current_subfile, line, addr);
15411                     }
15412                 }
15413               basic_block = 0;
15414               break;
15415             case DW_LNS_advance_pc:
15416               {
15417                 CORE_ADDR adjust
15418                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15419
15420                 address += (((op_index + adjust)
15421                              / lh->maximum_ops_per_instruction)
15422                             * lh->minimum_instruction_length);
15423                 op_index = ((op_index + adjust)
15424                             % lh->maximum_ops_per_instruction);
15425                 line_ptr += bytes_read;
15426               }
15427               break;
15428             case DW_LNS_advance_line:
15429               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15430               line_ptr += bytes_read;
15431               break;
15432             case DW_LNS_set_file:
15433               {
15434                 /* The arrays lh->include_dirs and lh->file_names are
15435                    0-based, but the directory and file name numbers in
15436                    the statement program are 1-based.  */
15437                 struct file_entry *fe;
15438                 char *dir = NULL;
15439
15440                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15441                 line_ptr += bytes_read;
15442                 if (lh->num_file_names < file || file == 0)
15443                   dwarf2_debug_line_missing_file_complaint ();
15444                 else
15445                   {
15446                     fe = &lh->file_names[file - 1];
15447                     if (fe->dir_index)
15448                       dir = lh->include_dirs[fe->dir_index - 1];
15449                     if (!decode_for_pst_p)
15450                       {
15451                         last_subfile = current_subfile;
15452                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15453                       }
15454                   }
15455               }
15456               break;
15457             case DW_LNS_set_column:
15458               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15459               line_ptr += bytes_read;
15460               break;
15461             case DW_LNS_negate_stmt:
15462               is_stmt = (!is_stmt);
15463               break;
15464             case DW_LNS_set_basic_block:
15465               basic_block = 1;
15466               break;
15467             /* Add to the address register of the state machine the
15468                address increment value corresponding to special opcode
15469                255.  I.e., this value is scaled by the minimum
15470                instruction length since special opcode 255 would have
15471                scaled the increment.  */
15472             case DW_LNS_const_add_pc:
15473               {
15474                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15475
15476                 address += (((op_index + adjust)
15477                              / lh->maximum_ops_per_instruction)
15478                             * lh->minimum_instruction_length);
15479                 op_index = ((op_index + adjust)
15480                             % lh->maximum_ops_per_instruction);
15481               }
15482               break;
15483             case DW_LNS_fixed_advance_pc:
15484               address += read_2_bytes (abfd, line_ptr);
15485               op_index = 0;
15486               line_ptr += 2;
15487               break;
15488             default:
15489               {
15490                 /* Unknown standard opcode, ignore it.  */
15491                 int i;
15492
15493                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15494                   {
15495                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15496                     line_ptr += bytes_read;
15497                   }
15498               }
15499             }
15500         }
15501       if (lh->num_file_names < file || file == 0)
15502         dwarf2_debug_line_missing_file_complaint ();
15503       else
15504         {
15505           lh->file_names[file - 1].included_p = 1;
15506           if (!decode_for_pst_p)
15507             {
15508               addr = gdbarch_addr_bits_remove (gdbarch, address);
15509               (*p_record_line) (current_subfile, 0, addr);
15510             }
15511         }
15512     }
15513 }
15514
15515 /* Decode the Line Number Program (LNP) for the given line_header
15516    structure and CU.  The actual information extracted and the type
15517    of structures created from the LNP depends on the value of PST.
15518
15519    1. If PST is NULL, then this procedure uses the data from the program
15520       to create all necessary symbol tables, and their linetables.
15521
15522    2. If PST is not NULL, this procedure reads the program to determine
15523       the list of files included by the unit represented by PST, and
15524       builds all the associated partial symbol tables.
15525
15526    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15527    It is used for relative paths in the line table.
15528    NOTE: When processing partial symtabs (pst != NULL),
15529    comp_dir == pst->dirname.
15530
15531    NOTE: It is important that psymtabs have the same file name (via strcmp)
15532    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15533    symtab we don't use it in the name of the psymtabs we create.
15534    E.g. expand_line_sal requires this when finding psymtabs to expand.
15535    A good testcase for this is mb-inline.exp.  */
15536
15537 static void
15538 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15539                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15540                     int want_line_info)
15541 {
15542   struct objfile *objfile = cu->objfile;
15543   const int decode_for_pst_p = (pst != NULL);
15544   struct subfile *first_subfile = current_subfile;
15545
15546   if (want_line_info)
15547     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15548
15549   if (decode_for_pst_p)
15550     {
15551       int file_index;
15552
15553       /* Now that we're done scanning the Line Header Program, we can
15554          create the psymtab of each included file.  */
15555       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15556         if (lh->file_names[file_index].included_p == 1)
15557           {
15558             char *include_name =
15559               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15560             if (include_name != NULL)
15561               dwarf2_create_include_psymtab (include_name, pst, objfile);
15562           }
15563     }
15564   else
15565     {
15566       /* Make sure a symtab is created for every file, even files
15567          which contain only variables (i.e. no code with associated
15568          line numbers).  */
15569       int i;
15570
15571       for (i = 0; i < lh->num_file_names; i++)
15572         {
15573           char *dir = NULL;
15574           struct file_entry *fe;
15575
15576           fe = &lh->file_names[i];
15577           if (fe->dir_index)
15578             dir = lh->include_dirs[fe->dir_index - 1];
15579           dwarf2_start_subfile (fe->name, dir, comp_dir);
15580
15581           /* Skip the main file; we don't need it, and it must be
15582              allocated last, so that it will show up before the
15583              non-primary symtabs in the objfile's symtab list.  */
15584           if (current_subfile == first_subfile)
15585             continue;
15586
15587           if (current_subfile->symtab == NULL)
15588             current_subfile->symtab = allocate_symtab (current_subfile->name,
15589                                                        objfile);
15590           fe->symtab = current_subfile->symtab;
15591         }
15592     }
15593 }
15594
15595 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15596    DIRNAME the name of the source directory which contains FILENAME
15597    or NULL if not known.  COMP_DIR is the compilation directory for the
15598    linetable's compilation unit or NULL if not known.
15599    This routine tries to keep line numbers from identical absolute and
15600    relative file names in a common subfile.
15601
15602    Using the `list' example from the GDB testsuite, which resides in
15603    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15604    of /srcdir/list0.c yields the following debugging information for list0.c:
15605
15606    DW_AT_name:          /srcdir/list0.c
15607    DW_AT_comp_dir:              /compdir
15608    files.files[0].name: list0.h
15609    files.files[0].dir:  /srcdir
15610    files.files[1].name: list0.c
15611    files.files[1].dir:  /srcdir
15612
15613    The line number information for list0.c has to end up in a single
15614    subfile, so that `break /srcdir/list0.c:1' works as expected.
15615    start_subfile will ensure that this happens provided that we pass the
15616    concatenation of files.files[1].dir and files.files[1].name as the
15617    subfile's name.  */
15618
15619 static void
15620 dwarf2_start_subfile (char *filename, const char *dirname,
15621                       const char *comp_dir)
15622 {
15623   char *fullname;
15624
15625   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15626      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15627      second argument to start_subfile.  To be consistent, we do the
15628      same here.  In order not to lose the line information directory,
15629      we concatenate it to the filename when it makes sense.
15630      Note that the Dwarf3 standard says (speaking of filenames in line
15631      information): ``The directory index is ignored for file names
15632      that represent full path names''.  Thus ignoring dirname in the
15633      `else' branch below isn't an issue.  */
15634
15635   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15636     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15637   else
15638     fullname = filename;
15639
15640   start_subfile (fullname, comp_dir);
15641
15642   if (fullname != filename)
15643     xfree (fullname);
15644 }
15645
15646 /* Start a symtab for DWARF.
15647    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15648
15649 static void
15650 dwarf2_start_symtab (struct dwarf2_cu *cu,
15651                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15652 {
15653   start_symtab (name, comp_dir, low_pc);
15654   record_debugformat ("DWARF 2");
15655   record_producer (cu->producer);
15656
15657   /* We assume that we're processing GCC output.  */
15658   processing_gcc_compilation = 2;
15659
15660   cu->processing_has_namespace_info = 0;
15661 }
15662
15663 static void
15664 var_decode_location (struct attribute *attr, struct symbol *sym,
15665                      struct dwarf2_cu *cu)
15666 {
15667   struct objfile *objfile = cu->objfile;
15668   struct comp_unit_head *cu_header = &cu->header;
15669
15670   /* NOTE drow/2003-01-30: There used to be a comment and some special
15671      code here to turn a symbol with DW_AT_external and a
15672      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15673      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15674      with some versions of binutils) where shared libraries could have
15675      relocations against symbols in their debug information - the
15676      minimal symbol would have the right address, but the debug info
15677      would not.  It's no longer necessary, because we will explicitly
15678      apply relocations when we read in the debug information now.  */
15679
15680   /* A DW_AT_location attribute with no contents indicates that a
15681      variable has been optimized away.  */
15682   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15683     {
15684       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15685       return;
15686     }
15687
15688   /* Handle one degenerate form of location expression specially, to
15689      preserve GDB's previous behavior when section offsets are
15690      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15691      then mark this symbol as LOC_STATIC.  */
15692
15693   if (attr_form_is_block (attr)
15694       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15695            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15696           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15697               && (DW_BLOCK (attr)->size
15698                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15699     {
15700       unsigned int dummy;
15701
15702       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15703         SYMBOL_VALUE_ADDRESS (sym) =
15704           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15705       else
15706         SYMBOL_VALUE_ADDRESS (sym) =
15707           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15708       SYMBOL_CLASS (sym) = LOC_STATIC;
15709       fixup_symbol_section (sym, objfile);
15710       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15711                                               SYMBOL_SECTION (sym));
15712       return;
15713     }
15714
15715   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15716      expression evaluator, and use LOC_COMPUTED only when necessary
15717      (i.e. when the value of a register or memory location is
15718      referenced, or a thread-local block, etc.).  Then again, it might
15719      not be worthwhile.  I'm assuming that it isn't unless performance
15720      or memory numbers show me otherwise.  */
15721
15722   dwarf2_symbol_mark_computed (attr, sym, cu);
15723   SYMBOL_CLASS (sym) = LOC_COMPUTED;
15724
15725   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
15726     cu->has_loclist = 1;
15727 }
15728
15729 /* Given a pointer to a DWARF information entry, figure out if we need
15730    to make a symbol table entry for it, and if so, create a new entry
15731    and return a pointer to it.
15732    If TYPE is NULL, determine symbol type from the die, otherwise
15733    used the passed type.
15734    If SPACE is not NULL, use it to hold the new symbol.  If it is
15735    NULL, allocate a new symbol on the objfile's obstack.  */
15736
15737 static struct symbol *
15738 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15739                  struct symbol *space)
15740 {
15741   struct objfile *objfile = cu->objfile;
15742   struct symbol *sym = NULL;
15743   const char *name;
15744   struct attribute *attr = NULL;
15745   struct attribute *attr2 = NULL;
15746   CORE_ADDR baseaddr;
15747   struct pending **list_to_add = NULL;
15748
15749   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15750
15751   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15752
15753   name = dwarf2_name (die, cu);
15754   if (name)
15755     {
15756       const char *linkagename;
15757       int suppress_add = 0;
15758
15759       if (space)
15760         sym = space;
15761       else
15762         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
15763       OBJSTAT (objfile, n_syms++);
15764
15765       /* Cache this symbol's name and the name's demangled form (if any).  */
15766       SYMBOL_SET_LANGUAGE (sym, cu->language);
15767       linkagename = dwarf2_physname (name, die, cu);
15768       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15769
15770       /* Fortran does not have mangling standard and the mangling does differ
15771          between gfortran, iFort etc.  */
15772       if (cu->language == language_fortran
15773           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15774         symbol_set_demangled_name (&(sym->ginfo),
15775                                    dwarf2_full_name (name, die, cu),
15776                                    NULL);
15777
15778       /* Default assumptions.
15779          Use the passed type or decode it from the die.  */
15780       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15781       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15782       if (type != NULL)
15783         SYMBOL_TYPE (sym) = type;
15784       else
15785         SYMBOL_TYPE (sym) = die_type (die, cu);
15786       attr = dwarf2_attr (die,
15787                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15788                           cu);
15789       if (attr)
15790         {
15791           SYMBOL_LINE (sym) = DW_UNSND (attr);
15792         }
15793
15794       attr = dwarf2_attr (die,
15795                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
15796                           cu);
15797       if (attr)
15798         {
15799           int file_index = DW_UNSND (attr);
15800
15801           if (cu->line_header == NULL
15802               || file_index > cu->line_header->num_file_names)
15803             complaint (&symfile_complaints,
15804                        _("file index out of range"));
15805           else if (file_index > 0)
15806             {
15807               struct file_entry *fe;
15808
15809               fe = &cu->line_header->file_names[file_index - 1];
15810               SYMBOL_SYMTAB (sym) = fe->symtab;
15811             }
15812         }
15813
15814       switch (die->tag)
15815         {
15816         case DW_TAG_label:
15817           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15818           if (attr)
15819             {
15820               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
15821             }
15822           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
15823           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
15824           SYMBOL_CLASS (sym) = LOC_LABEL;
15825           add_symbol_to_list (sym, cu->list_in_scope);
15826           break;
15827         case DW_TAG_subprogram:
15828           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15829              finish_block.  */
15830           SYMBOL_CLASS (sym) = LOC_BLOCK;
15831           attr2 = dwarf2_attr (die, DW_AT_external, cu);
15832           if ((attr2 && (DW_UNSND (attr2) != 0))
15833               || cu->language == language_ada)
15834             {
15835               /* Subprograms marked external are stored as a global symbol.
15836                  Ada subprograms, whether marked external or not, are always
15837                  stored as a global symbol, because we want to be able to
15838                  access them globally.  For instance, we want to be able
15839                  to break on a nested subprogram without having to
15840                  specify the context.  */
15841               list_to_add = &global_symbols;
15842             }
15843           else
15844             {
15845               list_to_add = cu->list_in_scope;
15846             }
15847           break;
15848         case DW_TAG_inlined_subroutine:
15849           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15850              finish_block.  */
15851           SYMBOL_CLASS (sym) = LOC_BLOCK;
15852           SYMBOL_INLINED (sym) = 1;
15853           list_to_add = cu->list_in_scope;
15854           break;
15855         case DW_TAG_template_value_param:
15856           suppress_add = 1;
15857           /* Fall through.  */
15858         case DW_TAG_constant:
15859         case DW_TAG_variable:
15860         case DW_TAG_member:
15861           /* Compilation with minimal debug info may result in
15862              variables with missing type entries.  Change the
15863              misleading `void' type to something sensible.  */
15864           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
15865             SYMBOL_TYPE (sym)
15866               = objfile_type (objfile)->nodebug_data_symbol;
15867
15868           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15869           /* In the case of DW_TAG_member, we should only be called for
15870              static const members.  */
15871           if (die->tag == DW_TAG_member)
15872             {
15873               /* dwarf2_add_field uses die_is_declaration,
15874                  so we do the same.  */
15875               gdb_assert (die_is_declaration (die, cu));
15876               gdb_assert (attr);
15877             }
15878           if (attr)
15879             {
15880               dwarf2_const_value (attr, sym, cu);
15881               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15882               if (!suppress_add)
15883                 {
15884                   if (attr2 && (DW_UNSND (attr2) != 0))
15885                     list_to_add = &global_symbols;
15886                   else
15887                     list_to_add = cu->list_in_scope;
15888                 }
15889               break;
15890             }
15891           attr = dwarf2_attr (die, DW_AT_location, cu);
15892           if (attr)
15893             {
15894               var_decode_location (attr, sym, cu);
15895               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15896
15897               /* Fortran explicitly imports any global symbols to the local
15898                  scope by DW_TAG_common_block.  */
15899               if (cu->language == language_fortran && die->parent
15900                   && die->parent->tag == DW_TAG_common_block)
15901                 attr2 = NULL;
15902
15903               if (SYMBOL_CLASS (sym) == LOC_STATIC
15904                   && SYMBOL_VALUE_ADDRESS (sym) == 0
15905                   && !dwarf2_per_objfile->has_section_at_zero)
15906                 {
15907                   /* When a static variable is eliminated by the linker,
15908                      the corresponding debug information is not stripped
15909                      out, but the variable address is set to null;
15910                      do not add such variables into symbol table.  */
15911                 }
15912               else if (attr2 && (DW_UNSND (attr2) != 0))
15913                 {
15914                   /* Workaround gfortran PR debug/40040 - it uses
15915                      DW_AT_location for variables in -fPIC libraries which may
15916                      get overriden by other libraries/executable and get
15917                      a different address.  Resolve it by the minimal symbol
15918                      which may come from inferior's executable using copy
15919                      relocation.  Make this workaround only for gfortran as for
15920                      other compilers GDB cannot guess the minimal symbol
15921                      Fortran mangling kind.  */
15922                   if (cu->language == language_fortran && die->parent
15923                       && die->parent->tag == DW_TAG_module
15924                       && cu->producer
15925                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
15926                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15927
15928                   /* A variable with DW_AT_external is never static,
15929                      but it may be block-scoped.  */
15930                   list_to_add = (cu->list_in_scope == &file_symbols
15931                                  ? &global_symbols : cu->list_in_scope);
15932                 }
15933               else
15934                 list_to_add = cu->list_in_scope;
15935             }
15936           else
15937             {
15938               /* We do not know the address of this symbol.
15939                  If it is an external symbol and we have type information
15940                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
15941                  The address of the variable will then be determined from
15942                  the minimal symbol table whenever the variable is
15943                  referenced.  */
15944               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15945
15946               /* Fortran explicitly imports any global symbols to the local
15947                  scope by DW_TAG_common_block.  */
15948               if (cu->language == language_fortran && die->parent
15949                   && die->parent->tag == DW_TAG_common_block)
15950                 {
15951                   /* SYMBOL_CLASS doesn't matter here because
15952                      read_common_block is going to reset it.  */
15953                   if (!suppress_add)
15954                     list_to_add = cu->list_in_scope;
15955                 }
15956               else if (attr2 && (DW_UNSND (attr2) != 0)
15957                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
15958                 {
15959                   /* A variable with DW_AT_external is never static, but it
15960                      may be block-scoped.  */
15961                   list_to_add = (cu->list_in_scope == &file_symbols
15962                                  ? &global_symbols : cu->list_in_scope);
15963
15964                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15965                 }
15966               else if (!die_is_declaration (die, cu))
15967                 {
15968                   /* Use the default LOC_OPTIMIZED_OUT class.  */
15969                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
15970                   if (!suppress_add)
15971                     list_to_add = cu->list_in_scope;
15972                 }
15973             }
15974           break;
15975         case DW_TAG_formal_parameter:
15976           /* If we are inside a function, mark this as an argument.  If
15977              not, we might be looking at an argument to an inlined function
15978              when we do not have enough information to show inlined frames;
15979              pretend it's a local variable in that case so that the user can
15980              still see it.  */
15981           if (context_stack_depth > 0
15982               && context_stack[context_stack_depth - 1].name != NULL)
15983             SYMBOL_IS_ARGUMENT (sym) = 1;
15984           attr = dwarf2_attr (die, DW_AT_location, cu);
15985           if (attr)
15986             {
15987               var_decode_location (attr, sym, cu);
15988             }
15989           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15990           if (attr)
15991             {
15992               dwarf2_const_value (attr, sym, cu);
15993             }
15994
15995           list_to_add = cu->list_in_scope;
15996           break;
15997         case DW_TAG_unspecified_parameters:
15998           /* From varargs functions; gdb doesn't seem to have any
15999              interest in this information, so just ignore it for now.
16000              (FIXME?) */
16001           break;
16002         case DW_TAG_template_type_param:
16003           suppress_add = 1;
16004           /* Fall through.  */
16005         case DW_TAG_class_type:
16006         case DW_TAG_interface_type:
16007         case DW_TAG_structure_type:
16008         case DW_TAG_union_type:
16009         case DW_TAG_set_type:
16010         case DW_TAG_enumeration_type:
16011           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16012           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16013
16014           {
16015             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16016                really ever be static objects: otherwise, if you try
16017                to, say, break of a class's method and you're in a file
16018                which doesn't mention that class, it won't work unless
16019                the check for all static symbols in lookup_symbol_aux
16020                saves you.  See the OtherFileClass tests in
16021                gdb.c++/namespace.exp.  */
16022
16023             if (!suppress_add)
16024               {
16025                 list_to_add = (cu->list_in_scope == &file_symbols
16026                                && (cu->language == language_cplus
16027                                    || cu->language == language_java)
16028                                ? &global_symbols : cu->list_in_scope);
16029
16030                 /* The semantics of C++ state that "struct foo {
16031                    ... }" also defines a typedef for "foo".  A Java
16032                    class declaration also defines a typedef for the
16033                    class.  */
16034                 if (cu->language == language_cplus
16035                     || cu->language == language_java
16036                     || cu->language == language_ada)
16037                   {
16038                     /* The symbol's name is already allocated along
16039                        with this objfile, so we don't need to
16040                        duplicate it for the type.  */
16041                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16042                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16043                   }
16044               }
16045           }
16046           break;
16047         case DW_TAG_typedef:
16048           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16049           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16050           list_to_add = cu->list_in_scope;
16051           break;
16052         case DW_TAG_base_type:
16053         case DW_TAG_subrange_type:
16054           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16055           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16056           list_to_add = cu->list_in_scope;
16057           break;
16058         case DW_TAG_enumerator:
16059           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16060           if (attr)
16061             {
16062               dwarf2_const_value (attr, sym, cu);
16063             }
16064           {
16065             /* NOTE: carlton/2003-11-10: See comment above in the
16066                DW_TAG_class_type, etc. block.  */
16067
16068             list_to_add = (cu->list_in_scope == &file_symbols
16069                            && (cu->language == language_cplus
16070                                || cu->language == language_java)
16071                            ? &global_symbols : cu->list_in_scope);
16072           }
16073           break;
16074         case DW_TAG_namespace:
16075           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16076           list_to_add = &global_symbols;
16077           break;
16078         case DW_TAG_common_block:
16079           SYMBOL_CLASS (sym) = LOC_COMMON_BLOCK;
16080           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16081           add_symbol_to_list (sym, cu->list_in_scope);
16082           break;
16083         default:
16084           /* Not a tag we recognize.  Hopefully we aren't processing
16085              trash data, but since we must specifically ignore things
16086              we don't recognize, there is nothing else we should do at
16087              this point.  */
16088           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16089                      dwarf_tag_name (die->tag));
16090           break;
16091         }
16092
16093       if (suppress_add)
16094         {
16095           sym->hash_next = objfile->template_symbols;
16096           objfile->template_symbols = sym;
16097           list_to_add = NULL;
16098         }
16099
16100       if (list_to_add != NULL)
16101         add_symbol_to_list (sym, list_to_add);
16102
16103       /* For the benefit of old versions of GCC, check for anonymous
16104          namespaces based on the demangled name.  */
16105       if (!cu->processing_has_namespace_info
16106           && cu->language == language_cplus)
16107         cp_scan_for_anonymous_namespaces (sym, objfile);
16108     }
16109   return (sym);
16110 }
16111
16112 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16113
16114 static struct symbol *
16115 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16116 {
16117   return new_symbol_full (die, type, cu, NULL);
16118 }
16119
16120 /* Given an attr with a DW_FORM_dataN value in host byte order,
16121    zero-extend it as appropriate for the symbol's type.  The DWARF
16122    standard (v4) is not entirely clear about the meaning of using
16123    DW_FORM_dataN for a constant with a signed type, where the type is
16124    wider than the data.  The conclusion of a discussion on the DWARF
16125    list was that this is unspecified.  We choose to always zero-extend
16126    because that is the interpretation long in use by GCC.  */
16127
16128 static gdb_byte *
16129 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16130                          const char *name, struct obstack *obstack,
16131                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16132 {
16133   struct objfile *objfile = cu->objfile;
16134   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16135                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16136   LONGEST l = DW_UNSND (attr);
16137
16138   if (bits < sizeof (*value) * 8)
16139     {
16140       l &= ((LONGEST) 1 << bits) - 1;
16141       *value = l;
16142     }
16143   else if (bits == sizeof (*value) * 8)
16144     *value = l;
16145   else
16146     {
16147       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16148       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16149       return bytes;
16150     }
16151
16152   return NULL;
16153 }
16154
16155 /* Read a constant value from an attribute.  Either set *VALUE, or if
16156    the value does not fit in *VALUE, set *BYTES - either already
16157    allocated on the objfile obstack, or newly allocated on OBSTACK,
16158    or, set *BATON, if we translated the constant to a location
16159    expression.  */
16160
16161 static void
16162 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16163                          const char *name, struct obstack *obstack,
16164                          struct dwarf2_cu *cu,
16165                          LONGEST *value, gdb_byte **bytes,
16166                          struct dwarf2_locexpr_baton **baton)
16167 {
16168   struct objfile *objfile = cu->objfile;
16169   struct comp_unit_head *cu_header = &cu->header;
16170   struct dwarf_block *blk;
16171   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16172                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16173
16174   *value = 0;
16175   *bytes = NULL;
16176   *baton = NULL;
16177
16178   switch (attr->form)
16179     {
16180     case DW_FORM_addr:
16181     case DW_FORM_GNU_addr_index:
16182       {
16183         gdb_byte *data;
16184
16185         if (TYPE_LENGTH (type) != cu_header->addr_size)
16186           dwarf2_const_value_length_mismatch_complaint (name,
16187                                                         cu_header->addr_size,
16188                                                         TYPE_LENGTH (type));
16189         /* Symbols of this form are reasonably rare, so we just
16190            piggyback on the existing location code rather than writing
16191            a new implementation of symbol_computed_ops.  */
16192         *baton = obstack_alloc (&objfile->objfile_obstack,
16193                                 sizeof (struct dwarf2_locexpr_baton));
16194         (*baton)->per_cu = cu->per_cu;
16195         gdb_assert ((*baton)->per_cu);
16196
16197         (*baton)->size = 2 + cu_header->addr_size;
16198         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16199         (*baton)->data = data;
16200
16201         data[0] = DW_OP_addr;
16202         store_unsigned_integer (&data[1], cu_header->addr_size,
16203                                 byte_order, DW_ADDR (attr));
16204         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16205       }
16206       break;
16207     case DW_FORM_string:
16208     case DW_FORM_strp:
16209     case DW_FORM_GNU_str_index:
16210     case DW_FORM_GNU_strp_alt:
16211       /* DW_STRING is already allocated on the objfile obstack, point
16212          directly to it.  */
16213       *bytes = (gdb_byte *) DW_STRING (attr);
16214       break;
16215     case DW_FORM_block1:
16216     case DW_FORM_block2:
16217     case DW_FORM_block4:
16218     case DW_FORM_block:
16219     case DW_FORM_exprloc:
16220       blk = DW_BLOCK (attr);
16221       if (TYPE_LENGTH (type) != blk->size)
16222         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16223                                                       TYPE_LENGTH (type));
16224       *bytes = blk->data;
16225       break;
16226
16227       /* The DW_AT_const_value attributes are supposed to carry the
16228          symbol's value "represented as it would be on the target
16229          architecture."  By the time we get here, it's already been
16230          converted to host endianness, so we just need to sign- or
16231          zero-extend it as appropriate.  */
16232     case DW_FORM_data1:
16233       *bytes = dwarf2_const_value_data (attr, type, name,
16234                                         obstack, cu, value, 8);
16235       break;
16236     case DW_FORM_data2:
16237       *bytes = dwarf2_const_value_data (attr, type, name,
16238                                         obstack, cu, value, 16);
16239       break;
16240     case DW_FORM_data4:
16241       *bytes = dwarf2_const_value_data (attr, type, name,
16242                                         obstack, cu, value, 32);
16243       break;
16244     case DW_FORM_data8:
16245       *bytes = dwarf2_const_value_data (attr, type, name,
16246                                         obstack, cu, value, 64);
16247       break;
16248
16249     case DW_FORM_sdata:
16250       *value = DW_SND (attr);
16251       break;
16252
16253     case DW_FORM_udata:
16254       *value = DW_UNSND (attr);
16255       break;
16256
16257     default:
16258       complaint (&symfile_complaints,
16259                  _("unsupported const value attribute form: '%s'"),
16260                  dwarf_form_name (attr->form));
16261       *value = 0;
16262       break;
16263     }
16264 }
16265
16266
16267 /* Copy constant value from an attribute to a symbol.  */
16268
16269 static void
16270 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16271                     struct dwarf2_cu *cu)
16272 {
16273   struct objfile *objfile = cu->objfile;
16274   struct comp_unit_head *cu_header = &cu->header;
16275   LONGEST value;
16276   gdb_byte *bytes;
16277   struct dwarf2_locexpr_baton *baton;
16278
16279   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16280                            SYMBOL_PRINT_NAME (sym),
16281                            &objfile->objfile_obstack, cu,
16282                            &value, &bytes, &baton);
16283
16284   if (baton != NULL)
16285     {
16286       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
16287       SYMBOL_LOCATION_BATON (sym) = baton;
16288       SYMBOL_CLASS (sym) = LOC_COMPUTED;
16289     }
16290   else if (bytes != NULL)
16291      {
16292       SYMBOL_VALUE_BYTES (sym) = bytes;
16293       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
16294     }
16295   else
16296     {
16297       SYMBOL_VALUE (sym) = value;
16298       SYMBOL_CLASS (sym) = LOC_CONST;
16299     }
16300 }
16301
16302 /* Return the type of the die in question using its DW_AT_type attribute.  */
16303
16304 static struct type *
16305 die_type (struct die_info *die, struct dwarf2_cu *cu)
16306 {
16307   struct attribute *type_attr;
16308
16309   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16310   if (!type_attr)
16311     {
16312       /* A missing DW_AT_type represents a void type.  */
16313       return objfile_type (cu->objfile)->builtin_void;
16314     }
16315
16316   return lookup_die_type (die, type_attr, cu);
16317 }
16318
16319 /* True iff CU's producer generates GNAT Ada auxiliary information
16320    that allows to find parallel types through that information instead
16321    of having to do expensive parallel lookups by type name.  */
16322
16323 static int
16324 need_gnat_info (struct dwarf2_cu *cu)
16325 {
16326   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16327      of GNAT produces this auxiliary information, without any indication
16328      that it is produced.  Part of enhancing the FSF version of GNAT
16329      to produce that information will be to put in place an indicator
16330      that we can use in order to determine whether the descriptive type
16331      info is available or not.  One suggestion that has been made is
16332      to use a new attribute, attached to the CU die.  For now, assume
16333      that the descriptive type info is not available.  */
16334   return 0;
16335 }
16336
16337 /* Return the auxiliary type of the die in question using its
16338    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16339    attribute is not present.  */
16340
16341 static struct type *
16342 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16343 {
16344   struct attribute *type_attr;
16345
16346   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16347   if (!type_attr)
16348     return NULL;
16349
16350   return lookup_die_type (die, type_attr, cu);
16351 }
16352
16353 /* If DIE has a descriptive_type attribute, then set the TYPE's
16354    descriptive type accordingly.  */
16355
16356 static void
16357 set_descriptive_type (struct type *type, struct die_info *die,
16358                       struct dwarf2_cu *cu)
16359 {
16360   struct type *descriptive_type = die_descriptive_type (die, cu);
16361
16362   if (descriptive_type)
16363     {
16364       ALLOCATE_GNAT_AUX_TYPE (type);
16365       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16366     }
16367 }
16368
16369 /* Return the containing type of the die in question using its
16370    DW_AT_containing_type attribute.  */
16371
16372 static struct type *
16373 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16374 {
16375   struct attribute *type_attr;
16376
16377   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16378   if (!type_attr)
16379     error (_("Dwarf Error: Problem turning containing type into gdb type "
16380              "[in module %s]"), cu->objfile->name);
16381
16382   return lookup_die_type (die, type_attr, cu);
16383 }
16384
16385 /* Look up the type of DIE in CU using its type attribute ATTR.
16386    If there is no type substitute an error marker.  */
16387
16388 static struct type *
16389 lookup_die_type (struct die_info *die, struct attribute *attr,
16390                  struct dwarf2_cu *cu)
16391 {
16392   struct objfile *objfile = cu->objfile;
16393   struct type *this_type;
16394
16395   /* First see if we have it cached.  */
16396
16397   if (attr->form == DW_FORM_GNU_ref_alt)
16398     {
16399       struct dwarf2_per_cu_data *per_cu;
16400       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16401
16402       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16403       this_type = get_die_type_at_offset (offset, per_cu);
16404     }
16405   else if (is_ref_attr (attr))
16406     {
16407       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16408
16409       this_type = get_die_type_at_offset (offset, cu->per_cu);
16410     }
16411   else if (attr->form == DW_FORM_ref_sig8)
16412     {
16413       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16414
16415       /* sig_type will be NULL if the signatured type is missing from
16416          the debug info.  */
16417       if (sig_type == NULL)
16418         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16419                  "at 0x%x [in module %s]"),
16420                die->offset.sect_off, objfile->name);
16421
16422       gdb_assert (sig_type->per_cu.is_debug_types);
16423       /* If we haven't filled in type_offset_in_section yet, then we
16424          haven't read the type in yet.  */
16425       this_type = NULL;
16426       if (sig_type->type_offset_in_section.sect_off != 0)
16427         {
16428           this_type =
16429             get_die_type_at_offset (sig_type->type_offset_in_section,
16430                                     &sig_type->per_cu);
16431         }
16432     }
16433   else
16434     {
16435       dump_die_for_error (die);
16436       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16437              dwarf_attr_name (attr->name), objfile->name);
16438     }
16439
16440   /* If not cached we need to read it in.  */
16441
16442   if (this_type == NULL)
16443     {
16444       struct die_info *type_die;
16445       struct dwarf2_cu *type_cu = cu;
16446
16447       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16448       /* If we found the type now, it's probably because the type came
16449          from an inter-CU reference and the type's CU got expanded before
16450          ours.  */
16451       this_type = get_die_type (type_die, type_cu);
16452       if (this_type == NULL)
16453         this_type = read_type_die_1 (type_die, type_cu);
16454     }
16455
16456   /* If we still don't have a type use an error marker.  */
16457
16458   if (this_type == NULL)
16459     {
16460       char *message, *saved;
16461
16462       /* read_type_die already issued a complaint.  */
16463       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16464                             objfile->name,
16465                             cu->header.offset.sect_off,
16466                             die->offset.sect_off);
16467       saved = obstack_copy0 (&objfile->objfile_obstack,
16468                              message, strlen (message));
16469       xfree (message);
16470
16471       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16472     }
16473
16474   return this_type;
16475 }
16476
16477 /* Return the type in DIE, CU.
16478    Returns NULL for invalid types.
16479
16480    This first does a lookup in the appropriate type_hash table,
16481    and only reads the die in if necessary.
16482
16483    NOTE: This can be called when reading in partial or full symbols.  */
16484
16485 static struct type *
16486 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16487 {
16488   struct type *this_type;
16489
16490   this_type = get_die_type (die, cu);
16491   if (this_type)
16492     return this_type;
16493
16494   return read_type_die_1 (die, cu);
16495 }
16496
16497 /* Read the type in DIE, CU.
16498    Returns NULL for invalid types.  */
16499
16500 static struct type *
16501 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16502 {
16503   struct type *this_type = NULL;
16504
16505   switch (die->tag)
16506     {
16507     case DW_TAG_class_type:
16508     case DW_TAG_interface_type:
16509     case DW_TAG_structure_type:
16510     case DW_TAG_union_type:
16511       this_type = read_structure_type (die, cu);
16512       break;
16513     case DW_TAG_enumeration_type:
16514       this_type = read_enumeration_type (die, cu);
16515       break;
16516     case DW_TAG_subprogram:
16517     case DW_TAG_subroutine_type:
16518     case DW_TAG_inlined_subroutine:
16519       this_type = read_subroutine_type (die, cu);
16520       break;
16521     case DW_TAG_array_type:
16522       this_type = read_array_type (die, cu);
16523       break;
16524     case DW_TAG_set_type:
16525       this_type = read_set_type (die, cu);
16526       break;
16527     case DW_TAG_pointer_type:
16528       this_type = read_tag_pointer_type (die, cu);
16529       break;
16530     case DW_TAG_ptr_to_member_type:
16531       this_type = read_tag_ptr_to_member_type (die, cu);
16532       break;
16533     case DW_TAG_reference_type:
16534       this_type = read_tag_reference_type (die, cu);
16535       break;
16536     case DW_TAG_const_type:
16537       this_type = read_tag_const_type (die, cu);
16538       break;
16539     case DW_TAG_volatile_type:
16540       this_type = read_tag_volatile_type (die, cu);
16541       break;
16542     case DW_TAG_restrict_type:
16543       this_type = read_tag_restrict_type (die, cu);
16544       break;
16545     case DW_TAG_string_type:
16546       this_type = read_tag_string_type (die, cu);
16547       break;
16548     case DW_TAG_typedef:
16549       this_type = read_typedef (die, cu);
16550       break;
16551     case DW_TAG_subrange_type:
16552       this_type = read_subrange_type (die, cu);
16553       break;
16554     case DW_TAG_base_type:
16555       this_type = read_base_type (die, cu);
16556       break;
16557     case DW_TAG_unspecified_type:
16558       this_type = read_unspecified_type (die, cu);
16559       break;
16560     case DW_TAG_namespace:
16561       this_type = read_namespace_type (die, cu);
16562       break;
16563     case DW_TAG_module:
16564       this_type = read_module_type (die, cu);
16565       break;
16566     default:
16567       complaint (&symfile_complaints,
16568                  _("unexpected tag in read_type_die: '%s'"),
16569                  dwarf_tag_name (die->tag));
16570       break;
16571     }
16572
16573   return this_type;
16574 }
16575
16576 /* See if we can figure out if the class lives in a namespace.  We do
16577    this by looking for a member function; its demangled name will
16578    contain namespace info, if there is any.
16579    Return the computed name or NULL.
16580    Space for the result is allocated on the objfile's obstack.
16581    This is the full-die version of guess_partial_die_structure_name.
16582    In this case we know DIE has no useful parent.  */
16583
16584 static char *
16585 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16586 {
16587   struct die_info *spec_die;
16588   struct dwarf2_cu *spec_cu;
16589   struct die_info *child;
16590
16591   spec_cu = cu;
16592   spec_die = die_specification (die, &spec_cu);
16593   if (spec_die != NULL)
16594     {
16595       die = spec_die;
16596       cu = spec_cu;
16597     }
16598
16599   for (child = die->child;
16600        child != NULL;
16601        child = child->sibling)
16602     {
16603       if (child->tag == DW_TAG_subprogram)
16604         {
16605           struct attribute *attr;
16606
16607           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16608           if (attr == NULL)
16609             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16610           if (attr != NULL)
16611             {
16612               char *actual_name
16613                 = language_class_name_from_physname (cu->language_defn,
16614                                                      DW_STRING (attr));
16615               char *name = NULL;
16616
16617               if (actual_name != NULL)
16618                 {
16619                   const char *die_name = dwarf2_name (die, cu);
16620
16621                   if (die_name != NULL
16622                       && strcmp (die_name, actual_name) != 0)
16623                     {
16624                       /* Strip off the class name from the full name.
16625                          We want the prefix.  */
16626                       int die_name_len = strlen (die_name);
16627                       int actual_name_len = strlen (actual_name);
16628
16629                       /* Test for '::' as a sanity check.  */
16630                       if (actual_name_len > die_name_len + 2
16631                           && actual_name[actual_name_len
16632                                          - die_name_len - 1] == ':')
16633                         name =
16634                           obstack_copy0 (&cu->objfile->objfile_obstack,
16635                                          actual_name,
16636                                          actual_name_len - die_name_len - 2);
16637                     }
16638                 }
16639               xfree (actual_name);
16640               return name;
16641             }
16642         }
16643     }
16644
16645   return NULL;
16646 }
16647
16648 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16649    prefix part in such case.  See
16650    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16651
16652 static char *
16653 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16654 {
16655   struct attribute *attr;
16656   char *base;
16657
16658   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16659       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16660     return NULL;
16661
16662   attr = dwarf2_attr (die, DW_AT_name, cu);
16663   if (attr != NULL && DW_STRING (attr) != NULL)
16664     return NULL;
16665
16666   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16667   if (attr == NULL)
16668     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16669   if (attr == NULL || DW_STRING (attr) == NULL)
16670     return NULL;
16671
16672   /* dwarf2_name had to be already called.  */
16673   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16674
16675   /* Strip the base name, keep any leading namespaces/classes.  */
16676   base = strrchr (DW_STRING (attr), ':');
16677   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16678     return "";
16679
16680   return obstack_copy0 (&cu->objfile->objfile_obstack,
16681                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16682 }
16683
16684 /* Return the name of the namespace/class that DIE is defined within,
16685    or "" if we can't tell.  The caller should not xfree the result.
16686
16687    For example, if we're within the method foo() in the following
16688    code:
16689
16690    namespace N {
16691      class C {
16692        void foo () {
16693        }
16694      };
16695    }
16696
16697    then determine_prefix on foo's die will return "N::C".  */
16698
16699 static const char *
16700 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16701 {
16702   struct die_info *parent, *spec_die;
16703   struct dwarf2_cu *spec_cu;
16704   struct type *parent_type;
16705   char *retval;
16706
16707   if (cu->language != language_cplus && cu->language != language_java
16708       && cu->language != language_fortran)
16709     return "";
16710
16711   retval = anonymous_struct_prefix (die, cu);
16712   if (retval)
16713     return retval;
16714
16715   /* We have to be careful in the presence of DW_AT_specification.
16716      For example, with GCC 3.4, given the code
16717
16718      namespace N {
16719        void foo() {
16720          // Definition of N::foo.
16721        }
16722      }
16723
16724      then we'll have a tree of DIEs like this:
16725
16726      1: DW_TAG_compile_unit
16727        2: DW_TAG_namespace        // N
16728          3: DW_TAG_subprogram     // declaration of N::foo
16729        4: DW_TAG_subprogram       // definition of N::foo
16730             DW_AT_specification   // refers to die #3
16731
16732      Thus, when processing die #4, we have to pretend that we're in
16733      the context of its DW_AT_specification, namely the contex of die
16734      #3.  */
16735   spec_cu = cu;
16736   spec_die = die_specification (die, &spec_cu);
16737   if (spec_die == NULL)
16738     parent = die->parent;
16739   else
16740     {
16741       parent = spec_die->parent;
16742       cu = spec_cu;
16743     }
16744
16745   if (parent == NULL)
16746     return "";
16747   else if (parent->building_fullname)
16748     {
16749       const char *name;
16750       const char *parent_name;
16751
16752       /* It has been seen on RealView 2.2 built binaries,
16753          DW_TAG_template_type_param types actually _defined_ as
16754          children of the parent class:
16755
16756          enum E {};
16757          template class <class Enum> Class{};
16758          Class<enum E> class_e;
16759
16760          1: DW_TAG_class_type (Class)
16761            2: DW_TAG_enumeration_type (E)
16762              3: DW_TAG_enumerator (enum1:0)
16763              3: DW_TAG_enumerator (enum2:1)
16764              ...
16765            2: DW_TAG_template_type_param
16766               DW_AT_type  DW_FORM_ref_udata (E)
16767
16768          Besides being broken debug info, it can put GDB into an
16769          infinite loop.  Consider:
16770
16771          When we're building the full name for Class<E>, we'll start
16772          at Class, and go look over its template type parameters,
16773          finding E.  We'll then try to build the full name of E, and
16774          reach here.  We're now trying to build the full name of E,
16775          and look over the parent DIE for containing scope.  In the
16776          broken case, if we followed the parent DIE of E, we'd again
16777          find Class, and once again go look at its template type
16778          arguments, etc., etc.  Simply don't consider such parent die
16779          as source-level parent of this die (it can't be, the language
16780          doesn't allow it), and break the loop here.  */
16781       name = dwarf2_name (die, cu);
16782       parent_name = dwarf2_name (parent, cu);
16783       complaint (&symfile_complaints,
16784                  _("template param type '%s' defined within parent '%s'"),
16785                  name ? name : "<unknown>",
16786                  parent_name ? parent_name : "<unknown>");
16787       return "";
16788     }
16789   else
16790     switch (parent->tag)
16791       {
16792       case DW_TAG_namespace:
16793         parent_type = read_type_die (parent, cu);
16794         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
16795            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
16796            Work around this problem here.  */
16797         if (cu->language == language_cplus
16798             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
16799           return "";
16800         /* We give a name to even anonymous namespaces.  */
16801         return TYPE_TAG_NAME (parent_type);
16802       case DW_TAG_class_type:
16803       case DW_TAG_interface_type:
16804       case DW_TAG_structure_type:
16805       case DW_TAG_union_type:
16806       case DW_TAG_module:
16807         parent_type = read_type_die (parent, cu);
16808         if (TYPE_TAG_NAME (parent_type) != NULL)
16809           return TYPE_TAG_NAME (parent_type);
16810         else
16811           /* An anonymous structure is only allowed non-static data
16812              members; no typedefs, no member functions, et cetera.
16813              So it does not need a prefix.  */
16814           return "";
16815       case DW_TAG_compile_unit:
16816       case DW_TAG_partial_unit:
16817         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
16818         if (cu->language == language_cplus
16819             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16820             && die->child != NULL
16821             && (die->tag == DW_TAG_class_type
16822                 || die->tag == DW_TAG_structure_type
16823                 || die->tag == DW_TAG_union_type))
16824           {
16825             char *name = guess_full_die_structure_name (die, cu);
16826             if (name != NULL)
16827               return name;
16828           }
16829         return "";
16830       default:
16831         return determine_prefix (parent, cu);
16832       }
16833 }
16834
16835 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
16836    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
16837    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
16838    an obconcat, otherwise allocate storage for the result.  The CU argument is
16839    used to determine the language and hence, the appropriate separator.  */
16840
16841 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
16842
16843 static char *
16844 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
16845                  int physname, struct dwarf2_cu *cu)
16846 {
16847   const char *lead = "";
16848   const char *sep;
16849
16850   if (suffix == NULL || suffix[0] == '\0'
16851       || prefix == NULL || prefix[0] == '\0')
16852     sep = "";
16853   else if (cu->language == language_java)
16854     sep = ".";
16855   else if (cu->language == language_fortran && physname)
16856     {
16857       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
16858          DW_AT_MIPS_linkage_name is preferred and used instead.  */
16859
16860       lead = "__";
16861       sep = "_MOD_";
16862     }
16863   else
16864     sep = "::";
16865
16866   if (prefix == NULL)
16867     prefix = "";
16868   if (suffix == NULL)
16869     suffix = "";
16870
16871   if (obs == NULL)
16872     {
16873       char *retval
16874         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
16875
16876       strcpy (retval, lead);
16877       strcat (retval, prefix);
16878       strcat (retval, sep);
16879       strcat (retval, suffix);
16880       return retval;
16881     }
16882   else
16883     {
16884       /* We have an obstack.  */
16885       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
16886     }
16887 }
16888
16889 /* Return sibling of die, NULL if no sibling.  */
16890
16891 static struct die_info *
16892 sibling_die (struct die_info *die)
16893 {
16894   return die->sibling;
16895 }
16896
16897 /* Get name of a die, return NULL if not found.  */
16898
16899 static const char *
16900 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
16901                           struct obstack *obstack)
16902 {
16903   if (name && cu->language == language_cplus)
16904     {
16905       char *canon_name = cp_canonicalize_string (name);
16906
16907       if (canon_name != NULL)
16908         {
16909           if (strcmp (canon_name, name) != 0)
16910             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
16911           xfree (canon_name);
16912         }
16913     }
16914
16915   return name;
16916 }
16917
16918 /* Get name of a die, return NULL if not found.  */
16919
16920 static const char *
16921 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
16922 {
16923   struct attribute *attr;
16924
16925   attr = dwarf2_attr (die, DW_AT_name, cu);
16926   if ((!attr || !DW_STRING (attr))
16927       && die->tag != DW_TAG_class_type
16928       && die->tag != DW_TAG_interface_type
16929       && die->tag != DW_TAG_structure_type
16930       && die->tag != DW_TAG_union_type)
16931     return NULL;
16932
16933   switch (die->tag)
16934     {
16935     case DW_TAG_compile_unit:
16936     case DW_TAG_partial_unit:
16937       /* Compilation units have a DW_AT_name that is a filename, not
16938          a source language identifier.  */
16939     case DW_TAG_enumeration_type:
16940     case DW_TAG_enumerator:
16941       /* These tags always have simple identifiers already; no need
16942          to canonicalize them.  */
16943       return DW_STRING (attr);
16944
16945     case DW_TAG_subprogram:
16946       /* Java constructors will all be named "<init>", so return
16947          the class name when we see this special case.  */
16948       if (cu->language == language_java
16949           && DW_STRING (attr) != NULL
16950           && strcmp (DW_STRING (attr), "<init>") == 0)
16951         {
16952           struct dwarf2_cu *spec_cu = cu;
16953           struct die_info *spec_die;
16954
16955           /* GCJ will output '<init>' for Java constructor names.
16956              For this special case, return the name of the parent class.  */
16957
16958           /* GCJ may output suprogram DIEs with AT_specification set.
16959              If so, use the name of the specified DIE.  */
16960           spec_die = die_specification (die, &spec_cu);
16961           if (spec_die != NULL)
16962             return dwarf2_name (spec_die, spec_cu);
16963
16964           do
16965             {
16966               die = die->parent;
16967               if (die->tag == DW_TAG_class_type)
16968                 return dwarf2_name (die, cu);
16969             }
16970           while (die->tag != DW_TAG_compile_unit
16971                  && die->tag != DW_TAG_partial_unit);
16972         }
16973       break;
16974
16975     case DW_TAG_class_type:
16976     case DW_TAG_interface_type:
16977     case DW_TAG_structure_type:
16978     case DW_TAG_union_type:
16979       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
16980          structures or unions.  These were of the form "._%d" in GCC 4.1,
16981          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
16982          and GCC 4.4.  We work around this problem by ignoring these.  */
16983       if (attr && DW_STRING (attr)
16984           && (strncmp (DW_STRING (attr), "._", 2) == 0
16985               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
16986         return NULL;
16987
16988       /* GCC might emit a nameless typedef that has a linkage name.  See
16989          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16990       if (!attr || DW_STRING (attr) == NULL)
16991         {
16992           char *demangled = NULL;
16993
16994           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16995           if (attr == NULL)
16996             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16997
16998           if (attr == NULL || DW_STRING (attr) == NULL)
16999             return NULL;
17000
17001           /* Avoid demangling DW_STRING (attr) the second time on a second
17002              call for the same DIE.  */
17003           if (!DW_STRING_IS_CANONICAL (attr))
17004             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
17005
17006           if (demangled)
17007             {
17008               char *base;
17009
17010               /* FIXME: we already did this for the partial symbol... */
17011               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17012                                                 demangled, strlen (demangled));
17013               DW_STRING_IS_CANONICAL (attr) = 1;
17014               xfree (demangled);
17015
17016               /* Strip any leading namespaces/classes, keep only the base name.
17017                  DW_AT_name for named DIEs does not contain the prefixes.  */
17018               base = strrchr (DW_STRING (attr), ':');
17019               if (base && base > DW_STRING (attr) && base[-1] == ':')
17020                 return &base[1];
17021               else
17022                 return DW_STRING (attr);
17023             }
17024         }
17025       break;
17026
17027     default:
17028       break;
17029     }
17030
17031   if (!DW_STRING_IS_CANONICAL (attr))
17032     {
17033       DW_STRING (attr)
17034         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17035                                     &cu->objfile->objfile_obstack);
17036       DW_STRING_IS_CANONICAL (attr) = 1;
17037     }
17038   return DW_STRING (attr);
17039 }
17040
17041 /* Return the die that this die in an extension of, or NULL if there
17042    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17043    containing the return value on output.  */
17044
17045 static struct die_info *
17046 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17047 {
17048   struct attribute *attr;
17049
17050   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17051   if (attr == NULL)
17052     return NULL;
17053
17054   return follow_die_ref (die, attr, ext_cu);
17055 }
17056
17057 /* Convert a DIE tag into its string name.  */
17058
17059 static const char *
17060 dwarf_tag_name (unsigned tag)
17061 {
17062   const char *name = get_DW_TAG_name (tag);
17063
17064   if (name == NULL)
17065     return "DW_TAG_<unknown>";
17066
17067   return name;
17068 }
17069
17070 /* Convert a DWARF attribute code into its string name.  */
17071
17072 static const char *
17073 dwarf_attr_name (unsigned attr)
17074 {
17075   const char *name;
17076
17077 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17078   if (attr == DW_AT_MIPS_fde)
17079     return "DW_AT_MIPS_fde";
17080 #else
17081   if (attr == DW_AT_HP_block_index)
17082     return "DW_AT_HP_block_index";
17083 #endif
17084
17085   name = get_DW_AT_name (attr);
17086
17087   if (name == NULL)
17088     return "DW_AT_<unknown>";
17089
17090   return name;
17091 }
17092
17093 /* Convert a DWARF value form code into its string name.  */
17094
17095 static const char *
17096 dwarf_form_name (unsigned form)
17097 {
17098   const char *name = get_DW_FORM_name (form);
17099
17100   if (name == NULL)
17101     return "DW_FORM_<unknown>";
17102
17103   return name;
17104 }
17105
17106 static char *
17107 dwarf_bool_name (unsigned mybool)
17108 {
17109   if (mybool)
17110     return "TRUE";
17111   else
17112     return "FALSE";
17113 }
17114
17115 /* Convert a DWARF type code into its string name.  */
17116
17117 static const char *
17118 dwarf_type_encoding_name (unsigned enc)
17119 {
17120   const char *name = get_DW_ATE_name (enc);
17121
17122   if (name == NULL)
17123     return "DW_ATE_<unknown>";
17124
17125   return name;
17126 }
17127
17128 static void
17129 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17130 {
17131   unsigned int i;
17132
17133   print_spaces (indent, f);
17134   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17135            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17136
17137   if (die->parent != NULL)
17138     {
17139       print_spaces (indent, f);
17140       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17141                           die->parent->offset.sect_off);
17142     }
17143
17144   print_spaces (indent, f);
17145   fprintf_unfiltered (f, "  has children: %s\n",
17146            dwarf_bool_name (die->child != NULL));
17147
17148   print_spaces (indent, f);
17149   fprintf_unfiltered (f, "  attributes:\n");
17150
17151   for (i = 0; i < die->num_attrs; ++i)
17152     {
17153       print_spaces (indent, f);
17154       fprintf_unfiltered (f, "    %s (%s) ",
17155                dwarf_attr_name (die->attrs[i].name),
17156                dwarf_form_name (die->attrs[i].form));
17157
17158       switch (die->attrs[i].form)
17159         {
17160         case DW_FORM_addr:
17161         case DW_FORM_GNU_addr_index:
17162           fprintf_unfiltered (f, "address: ");
17163           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17164           break;
17165         case DW_FORM_block2:
17166         case DW_FORM_block4:
17167         case DW_FORM_block:
17168         case DW_FORM_block1:
17169           fprintf_unfiltered (f, "block: size %s",
17170                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17171           break;
17172         case DW_FORM_exprloc:
17173           fprintf_unfiltered (f, "expression: size %s",
17174                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17175           break;
17176         case DW_FORM_ref_addr:
17177           fprintf_unfiltered (f, "ref address: ");
17178           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17179           break;
17180         case DW_FORM_GNU_ref_alt:
17181           fprintf_unfiltered (f, "alt ref address: ");
17182           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17183           break;
17184         case DW_FORM_ref1:
17185         case DW_FORM_ref2:
17186         case DW_FORM_ref4:
17187         case DW_FORM_ref8:
17188         case DW_FORM_ref_udata:
17189           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17190                               (long) (DW_UNSND (&die->attrs[i])));
17191           break;
17192         case DW_FORM_data1:
17193         case DW_FORM_data2:
17194         case DW_FORM_data4:
17195         case DW_FORM_data8:
17196         case DW_FORM_udata:
17197         case DW_FORM_sdata:
17198           fprintf_unfiltered (f, "constant: %s",
17199                               pulongest (DW_UNSND (&die->attrs[i])));
17200           break;
17201         case DW_FORM_sec_offset:
17202           fprintf_unfiltered (f, "section offset: %s",
17203                               pulongest (DW_UNSND (&die->attrs[i])));
17204           break;
17205         case DW_FORM_ref_sig8:
17206           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17207             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
17208                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
17209           else
17210             fprintf_unfiltered (f, "signatured type, offset: unknown");
17211           break;
17212         case DW_FORM_string:
17213         case DW_FORM_strp:
17214         case DW_FORM_GNU_str_index:
17215         case DW_FORM_GNU_strp_alt:
17216           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17217                    DW_STRING (&die->attrs[i])
17218                    ? DW_STRING (&die->attrs[i]) : "",
17219                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17220           break;
17221         case DW_FORM_flag:
17222           if (DW_UNSND (&die->attrs[i]))
17223             fprintf_unfiltered (f, "flag: TRUE");
17224           else
17225             fprintf_unfiltered (f, "flag: FALSE");
17226           break;
17227         case DW_FORM_flag_present:
17228           fprintf_unfiltered (f, "flag: TRUE");
17229           break;
17230         case DW_FORM_indirect:
17231           /* The reader will have reduced the indirect form to
17232              the "base form" so this form should not occur.  */
17233           fprintf_unfiltered (f, 
17234                               "unexpected attribute form: DW_FORM_indirect");
17235           break;
17236         default:
17237           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17238                    die->attrs[i].form);
17239           break;
17240         }
17241       fprintf_unfiltered (f, "\n");
17242     }
17243 }
17244
17245 static void
17246 dump_die_for_error (struct die_info *die)
17247 {
17248   dump_die_shallow (gdb_stderr, 0, die);
17249 }
17250
17251 static void
17252 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17253 {
17254   int indent = level * 4;
17255
17256   gdb_assert (die != NULL);
17257
17258   if (level >= max_level)
17259     return;
17260
17261   dump_die_shallow (f, indent, die);
17262
17263   if (die->child != NULL)
17264     {
17265       print_spaces (indent, f);
17266       fprintf_unfiltered (f, "  Children:");
17267       if (level + 1 < max_level)
17268         {
17269           fprintf_unfiltered (f, "\n");
17270           dump_die_1 (f, level + 1, max_level, die->child);
17271         }
17272       else
17273         {
17274           fprintf_unfiltered (f,
17275                               " [not printed, max nesting level reached]\n");
17276         }
17277     }
17278
17279   if (die->sibling != NULL && level > 0)
17280     {
17281       dump_die_1 (f, level, max_level, die->sibling);
17282     }
17283 }
17284
17285 /* This is called from the pdie macro in gdbinit.in.
17286    It's not static so gcc will keep a copy callable from gdb.  */
17287
17288 void
17289 dump_die (struct die_info *die, int max_level)
17290 {
17291   dump_die_1 (gdb_stdlog, 0, max_level, die);
17292 }
17293
17294 static void
17295 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17296 {
17297   void **slot;
17298
17299   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17300                                    INSERT);
17301
17302   *slot = die;
17303 }
17304
17305 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17306    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17307
17308 static int
17309 is_ref_attr (struct attribute *attr)
17310 {
17311   switch (attr->form)
17312     {
17313     case DW_FORM_ref_addr:
17314     case DW_FORM_ref1:
17315     case DW_FORM_ref2:
17316     case DW_FORM_ref4:
17317     case DW_FORM_ref8:
17318     case DW_FORM_ref_udata:
17319     case DW_FORM_GNU_ref_alt:
17320       return 1;
17321     default:
17322       return 0;
17323     }
17324 }
17325
17326 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17327    required kind.  */
17328
17329 static sect_offset
17330 dwarf2_get_ref_die_offset (struct attribute *attr)
17331 {
17332   sect_offset retval = { DW_UNSND (attr) };
17333
17334   if (is_ref_attr (attr))
17335     return retval;
17336
17337   retval.sect_off = 0;
17338   complaint (&symfile_complaints,
17339              _("unsupported die ref attribute form: '%s'"),
17340              dwarf_form_name (attr->form));
17341   return retval;
17342 }
17343
17344 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17345  * the value held by the attribute is not constant.  */
17346
17347 static LONGEST
17348 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17349 {
17350   if (attr->form == DW_FORM_sdata)
17351     return DW_SND (attr);
17352   else if (attr->form == DW_FORM_udata
17353            || attr->form == DW_FORM_data1
17354            || attr->form == DW_FORM_data2
17355            || attr->form == DW_FORM_data4
17356            || attr->form == DW_FORM_data8)
17357     return DW_UNSND (attr);
17358   else
17359     {
17360       complaint (&symfile_complaints,
17361                  _("Attribute value is not a constant (%s)"),
17362                  dwarf_form_name (attr->form));
17363       return default_value;
17364     }
17365 }
17366
17367 /* Follow reference or signature attribute ATTR of SRC_DIE.
17368    On entry *REF_CU is the CU of SRC_DIE.
17369    On exit *REF_CU is the CU of the result.  */
17370
17371 static struct die_info *
17372 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17373                        struct dwarf2_cu **ref_cu)
17374 {
17375   struct die_info *die;
17376
17377   if (is_ref_attr (attr))
17378     die = follow_die_ref (src_die, attr, ref_cu);
17379   else if (attr->form == DW_FORM_ref_sig8)
17380     die = follow_die_sig (src_die, attr, ref_cu);
17381   else
17382     {
17383       dump_die_for_error (src_die);
17384       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17385              (*ref_cu)->objfile->name);
17386     }
17387
17388   return die;
17389 }
17390
17391 /* Follow reference OFFSET.
17392    On entry *REF_CU is the CU of the source die referencing OFFSET.
17393    On exit *REF_CU is the CU of the result.
17394    Returns NULL if OFFSET is invalid.  */
17395
17396 static struct die_info *
17397 follow_die_offset (sect_offset offset, int offset_in_dwz,
17398                    struct dwarf2_cu **ref_cu)
17399 {
17400   struct die_info temp_die;
17401   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17402
17403   gdb_assert (cu->per_cu != NULL);
17404
17405   target_cu = cu;
17406
17407   if (cu->per_cu->is_debug_types)
17408     {
17409       /* .debug_types CUs cannot reference anything outside their CU.
17410          If they need to, they have to reference a signatured type via
17411          DW_FORM_ref_sig8.  */
17412       if (! offset_in_cu_p (&cu->header, offset))
17413         return NULL;
17414     }
17415   else if (offset_in_dwz != cu->per_cu->is_dwz
17416            || ! offset_in_cu_p (&cu->header, offset))
17417     {
17418       struct dwarf2_per_cu_data *per_cu;
17419
17420       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17421                                                  cu->objfile);
17422
17423       /* If necessary, add it to the queue and load its DIEs.  */
17424       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17425         load_full_comp_unit (per_cu, cu->language);
17426
17427       target_cu = per_cu->cu;
17428     }
17429   else if (cu->dies == NULL)
17430     {
17431       /* We're loading full DIEs during partial symbol reading.  */
17432       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17433       load_full_comp_unit (cu->per_cu, language_minimal);
17434     }
17435
17436   *ref_cu = target_cu;
17437   temp_die.offset = offset;
17438   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17439 }
17440
17441 /* Follow reference attribute ATTR of SRC_DIE.
17442    On entry *REF_CU is the CU of SRC_DIE.
17443    On exit *REF_CU is the CU of the result.  */
17444
17445 static struct die_info *
17446 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17447                 struct dwarf2_cu **ref_cu)
17448 {
17449   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17450   struct dwarf2_cu *cu = *ref_cu;
17451   struct die_info *die;
17452
17453   die = follow_die_offset (offset,
17454                            (attr->form == DW_FORM_GNU_ref_alt
17455                             || cu->per_cu->is_dwz),
17456                            ref_cu);
17457   if (!die)
17458     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17459            "at 0x%x [in module %s]"),
17460            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17461
17462   return die;
17463 }
17464
17465 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17466    Returned value is intended for DW_OP_call*.  Returned
17467    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17468
17469 struct dwarf2_locexpr_baton
17470 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17471                                struct dwarf2_per_cu_data *per_cu,
17472                                CORE_ADDR (*get_frame_pc) (void *baton),
17473                                void *baton)
17474 {
17475   struct dwarf2_cu *cu;
17476   struct die_info *die;
17477   struct attribute *attr;
17478   struct dwarf2_locexpr_baton retval;
17479
17480   dw2_setup (per_cu->objfile);
17481
17482   if (per_cu->cu == NULL)
17483     load_cu (per_cu);
17484   cu = per_cu->cu;
17485
17486   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17487   if (!die)
17488     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17489            offset.sect_off, per_cu->objfile->name);
17490
17491   attr = dwarf2_attr (die, DW_AT_location, cu);
17492   if (!attr)
17493     {
17494       /* DWARF: "If there is no such attribute, then there is no effect.".
17495          DATA is ignored if SIZE is 0.  */
17496
17497       retval.data = NULL;
17498       retval.size = 0;
17499     }
17500   else if (attr_form_is_section_offset (attr))
17501     {
17502       struct dwarf2_loclist_baton loclist_baton;
17503       CORE_ADDR pc = (*get_frame_pc) (baton);
17504       size_t size;
17505
17506       fill_in_loclist_baton (cu, &loclist_baton, attr);
17507
17508       retval.data = dwarf2_find_location_expression (&loclist_baton,
17509                                                      &size, pc);
17510       retval.size = size;
17511     }
17512   else
17513     {
17514       if (!attr_form_is_block (attr))
17515         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17516                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17517                offset.sect_off, per_cu->objfile->name);
17518
17519       retval.data = DW_BLOCK (attr)->data;
17520       retval.size = DW_BLOCK (attr)->size;
17521     }
17522   retval.per_cu = cu->per_cu;
17523
17524   age_cached_comp_units ();
17525
17526   return retval;
17527 }
17528
17529 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17530    offset.  */
17531
17532 struct dwarf2_locexpr_baton
17533 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17534                              struct dwarf2_per_cu_data *per_cu,
17535                              CORE_ADDR (*get_frame_pc) (void *baton),
17536                              void *baton)
17537 {
17538   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17539
17540   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17541 }
17542
17543 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17544    PER_CU.  */
17545
17546 struct type *
17547 dwarf2_get_die_type (cu_offset die_offset,
17548                      struct dwarf2_per_cu_data *per_cu)
17549 {
17550   sect_offset die_offset_sect;
17551
17552   dw2_setup (per_cu->objfile);
17553
17554   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17555   return get_die_type_at_offset (die_offset_sect, per_cu);
17556 }
17557
17558 /* Follow the signature attribute ATTR in SRC_DIE.
17559    On entry *REF_CU is the CU of SRC_DIE.
17560    On exit *REF_CU is the CU of the result.  */
17561
17562 static struct die_info *
17563 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17564                 struct dwarf2_cu **ref_cu)
17565 {
17566   struct objfile *objfile = (*ref_cu)->objfile;
17567   struct die_info temp_die;
17568   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17569   struct dwarf2_cu *sig_cu;
17570   struct die_info *die;
17571
17572   /* sig_type will be NULL if the signatured type is missing from
17573      the debug info.  */
17574   if (sig_type == NULL)
17575     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17576              "at 0x%x [in module %s]"),
17577            src_die->offset.sect_off, objfile->name);
17578
17579   /* If necessary, add it to the queue and load its DIEs.  */
17580
17581   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17582     read_signatured_type (sig_type);
17583
17584   gdb_assert (sig_type->per_cu.cu != NULL);
17585
17586   sig_cu = sig_type->per_cu.cu;
17587   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17588   temp_die.offset = sig_type->type_offset_in_section;
17589   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17590                              temp_die.offset.sect_off);
17591   if (die)
17592     {
17593       /* For .gdb_index version 7 keep track of included TUs.
17594          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17595       if (dwarf2_per_objfile->index_table != NULL
17596           && dwarf2_per_objfile->index_table->version <= 7)
17597         {
17598           VEC_safe_push (dwarf2_per_cu_ptr,
17599                          (*ref_cu)->per_cu->imported_symtabs,
17600                          sig_cu->per_cu);
17601         }
17602
17603       *ref_cu = sig_cu;
17604       return die;
17605     }
17606
17607   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17608          "from DIE at 0x%x [in module %s]"),
17609          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17610 }
17611
17612 /* Given an offset of a signatured type, return its signatured_type.  */
17613
17614 static struct signatured_type *
17615 lookup_signatured_type_at_offset (struct objfile *objfile,
17616                                   struct dwarf2_section_info *section,
17617                                   sect_offset offset)
17618 {
17619   gdb_byte *info_ptr = section->buffer + offset.sect_off;
17620   unsigned int length, initial_length_size;
17621   unsigned int sig_offset;
17622   struct signatured_type find_entry, *sig_type;
17623
17624   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
17625   sig_offset = (initial_length_size
17626                 + 2 /*version*/
17627                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
17628                 + 1 /*address_size*/);
17629   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
17630   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
17631
17632   /* This is only used to lookup previously recorded types.
17633      If we didn't find it, it's our bug.  */
17634   gdb_assert (sig_type != NULL);
17635   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
17636
17637   return sig_type;
17638 }
17639
17640 /* Load the DIEs associated with type unit PER_CU into memory.  */
17641
17642 static void
17643 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17644 {
17645   struct signatured_type *sig_type;
17646
17647   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17648   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17649
17650   /* We have the per_cu, but we need the signatured_type.
17651      Fortunately this is an easy translation.  */
17652   gdb_assert (per_cu->is_debug_types);
17653   sig_type = (struct signatured_type *) per_cu;
17654
17655   gdb_assert (per_cu->cu == NULL);
17656
17657   read_signatured_type (sig_type);
17658
17659   gdb_assert (per_cu->cu != NULL);
17660 }
17661
17662 /* die_reader_func for read_signatured_type.
17663    This is identical to load_full_comp_unit_reader,
17664    but is kept separate for now.  */
17665
17666 static void
17667 read_signatured_type_reader (const struct die_reader_specs *reader,
17668                              gdb_byte *info_ptr,
17669                              struct die_info *comp_unit_die,
17670                              int has_children,
17671                              void *data)
17672 {
17673   struct dwarf2_cu *cu = reader->cu;
17674
17675   gdb_assert (cu->die_hash == NULL);
17676   cu->die_hash =
17677     htab_create_alloc_ex (cu->header.length / 12,
17678                           die_hash,
17679                           die_eq,
17680                           NULL,
17681                           &cu->comp_unit_obstack,
17682                           hashtab_obstack_allocate,
17683                           dummy_obstack_deallocate);
17684
17685   if (has_children)
17686     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17687                                                   &info_ptr, comp_unit_die);
17688   cu->dies = comp_unit_die;
17689   /* comp_unit_die is not stored in die_hash, no need.  */
17690
17691   /* We try not to read any attributes in this function, because not
17692      all CUs needed for references have been loaded yet, and symbol
17693      table processing isn't initialized.  But we have to set the CU language,
17694      or we won't be able to build types correctly.
17695      Similarly, if we do not read the producer, we can not apply
17696      producer-specific interpretation.  */
17697   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17698 }
17699
17700 /* Read in a signatured type and build its CU and DIEs.
17701    If the type is a stub for the real type in a DWO file,
17702    read in the real type from the DWO file as well.  */
17703
17704 static void
17705 read_signatured_type (struct signatured_type *sig_type)
17706 {
17707   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17708
17709   gdb_assert (per_cu->is_debug_types);
17710   gdb_assert (per_cu->cu == NULL);
17711
17712   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17713                            read_signatured_type_reader, NULL);
17714 }
17715
17716 /* Decode simple location descriptions.
17717    Given a pointer to a dwarf block that defines a location, compute
17718    the location and return the value.
17719
17720    NOTE drow/2003-11-18: This function is called in two situations
17721    now: for the address of static or global variables (partial symbols
17722    only) and for offsets into structures which are expected to be
17723    (more or less) constant.  The partial symbol case should go away,
17724    and only the constant case should remain.  That will let this
17725    function complain more accurately.  A few special modes are allowed
17726    without complaint for global variables (for instance, global
17727    register values and thread-local values).
17728
17729    A location description containing no operations indicates that the
17730    object is optimized out.  The return value is 0 for that case.
17731    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17732    callers will only want a very basic result and this can become a
17733    complaint.
17734
17735    Note that stack[0] is unused except as a default error return.  */
17736
17737 static CORE_ADDR
17738 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17739 {
17740   struct objfile *objfile = cu->objfile;
17741   size_t i;
17742   size_t size = blk->size;
17743   gdb_byte *data = blk->data;
17744   CORE_ADDR stack[64];
17745   int stacki;
17746   unsigned int bytes_read, unsnd;
17747   gdb_byte op;
17748
17749   i = 0;
17750   stacki = 0;
17751   stack[stacki] = 0;
17752   stack[++stacki] = 0;
17753
17754   while (i < size)
17755     {
17756       op = data[i++];
17757       switch (op)
17758         {
17759         case DW_OP_lit0:
17760         case DW_OP_lit1:
17761         case DW_OP_lit2:
17762         case DW_OP_lit3:
17763         case DW_OP_lit4:
17764         case DW_OP_lit5:
17765         case DW_OP_lit6:
17766         case DW_OP_lit7:
17767         case DW_OP_lit8:
17768         case DW_OP_lit9:
17769         case DW_OP_lit10:
17770         case DW_OP_lit11:
17771         case DW_OP_lit12:
17772         case DW_OP_lit13:
17773         case DW_OP_lit14:
17774         case DW_OP_lit15:
17775         case DW_OP_lit16:
17776         case DW_OP_lit17:
17777         case DW_OP_lit18:
17778         case DW_OP_lit19:
17779         case DW_OP_lit20:
17780         case DW_OP_lit21:
17781         case DW_OP_lit22:
17782         case DW_OP_lit23:
17783         case DW_OP_lit24:
17784         case DW_OP_lit25:
17785         case DW_OP_lit26:
17786         case DW_OP_lit27:
17787         case DW_OP_lit28:
17788         case DW_OP_lit29:
17789         case DW_OP_lit30:
17790         case DW_OP_lit31:
17791           stack[++stacki] = op - DW_OP_lit0;
17792           break;
17793
17794         case DW_OP_reg0:
17795         case DW_OP_reg1:
17796         case DW_OP_reg2:
17797         case DW_OP_reg3:
17798         case DW_OP_reg4:
17799         case DW_OP_reg5:
17800         case DW_OP_reg6:
17801         case DW_OP_reg7:
17802         case DW_OP_reg8:
17803         case DW_OP_reg9:
17804         case DW_OP_reg10:
17805         case DW_OP_reg11:
17806         case DW_OP_reg12:
17807         case DW_OP_reg13:
17808         case DW_OP_reg14:
17809         case DW_OP_reg15:
17810         case DW_OP_reg16:
17811         case DW_OP_reg17:
17812         case DW_OP_reg18:
17813         case DW_OP_reg19:
17814         case DW_OP_reg20:
17815         case DW_OP_reg21:
17816         case DW_OP_reg22:
17817         case DW_OP_reg23:
17818         case DW_OP_reg24:
17819         case DW_OP_reg25:
17820         case DW_OP_reg26:
17821         case DW_OP_reg27:
17822         case DW_OP_reg28:
17823         case DW_OP_reg29:
17824         case DW_OP_reg30:
17825         case DW_OP_reg31:
17826           stack[++stacki] = op - DW_OP_reg0;
17827           if (i < size)
17828             dwarf2_complex_location_expr_complaint ();
17829           break;
17830
17831         case DW_OP_regx:
17832           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
17833           i += bytes_read;
17834           stack[++stacki] = unsnd;
17835           if (i < size)
17836             dwarf2_complex_location_expr_complaint ();
17837           break;
17838
17839         case DW_OP_addr:
17840           stack[++stacki] = read_address (objfile->obfd, &data[i],
17841                                           cu, &bytes_read);
17842           i += bytes_read;
17843           break;
17844
17845         case DW_OP_const1u:
17846           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
17847           i += 1;
17848           break;
17849
17850         case DW_OP_const1s:
17851           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
17852           i += 1;
17853           break;
17854
17855         case DW_OP_const2u:
17856           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
17857           i += 2;
17858           break;
17859
17860         case DW_OP_const2s:
17861           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
17862           i += 2;
17863           break;
17864
17865         case DW_OP_const4u:
17866           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
17867           i += 4;
17868           break;
17869
17870         case DW_OP_const4s:
17871           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
17872           i += 4;
17873           break;
17874
17875         case DW_OP_const8u:
17876           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
17877           i += 8;
17878           break;
17879
17880         case DW_OP_constu:
17881           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
17882                                                   &bytes_read);
17883           i += bytes_read;
17884           break;
17885
17886         case DW_OP_consts:
17887           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
17888           i += bytes_read;
17889           break;
17890
17891         case DW_OP_dup:
17892           stack[stacki + 1] = stack[stacki];
17893           stacki++;
17894           break;
17895
17896         case DW_OP_plus:
17897           stack[stacki - 1] += stack[stacki];
17898           stacki--;
17899           break;
17900
17901         case DW_OP_plus_uconst:
17902           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
17903                                                  &bytes_read);
17904           i += bytes_read;
17905           break;
17906
17907         case DW_OP_minus:
17908           stack[stacki - 1] -= stack[stacki];
17909           stacki--;
17910           break;
17911
17912         case DW_OP_deref:
17913           /* If we're not the last op, then we definitely can't encode
17914              this using GDB's address_class enum.  This is valid for partial
17915              global symbols, although the variable's address will be bogus
17916              in the psymtab.  */
17917           if (i < size)
17918             dwarf2_complex_location_expr_complaint ();
17919           break;
17920
17921         case DW_OP_GNU_push_tls_address:
17922           /* The top of the stack has the offset from the beginning
17923              of the thread control block at which the variable is located.  */
17924           /* Nothing should follow this operator, so the top of stack would
17925              be returned.  */
17926           /* This is valid for partial global symbols, but the variable's
17927              address will be bogus in the psymtab.  Make it always at least
17928              non-zero to not look as a variable garbage collected by linker
17929              which have DW_OP_addr 0.  */
17930           if (i < size)
17931             dwarf2_complex_location_expr_complaint ();
17932           stack[stacki]++;
17933           break;
17934
17935         case DW_OP_GNU_uninit:
17936           break;
17937
17938         case DW_OP_GNU_addr_index:
17939         case DW_OP_GNU_const_index:
17940           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
17941                                                          &bytes_read);
17942           i += bytes_read;
17943           break;
17944
17945         default:
17946           {
17947             const char *name = get_DW_OP_name (op);
17948
17949             if (name)
17950               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
17951                          name);
17952             else
17953               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
17954                          op);
17955           }
17956
17957           return (stack[stacki]);
17958         }
17959
17960       /* Enforce maximum stack depth of SIZE-1 to avoid writing
17961          outside of the allocated space.  Also enforce minimum>0.  */
17962       if (stacki >= ARRAY_SIZE (stack) - 1)
17963         {
17964           complaint (&symfile_complaints,
17965                      _("location description stack overflow"));
17966           return 0;
17967         }
17968
17969       if (stacki <= 0)
17970         {
17971           complaint (&symfile_complaints,
17972                      _("location description stack underflow"));
17973           return 0;
17974         }
17975     }
17976   return (stack[stacki]);
17977 }
17978
17979 /* memory allocation interface */
17980
17981 static struct dwarf_block *
17982 dwarf_alloc_block (struct dwarf2_cu *cu)
17983 {
17984   struct dwarf_block *blk;
17985
17986   blk = (struct dwarf_block *)
17987     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
17988   return (blk);
17989 }
17990
17991 static struct die_info *
17992 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
17993 {
17994   struct die_info *die;
17995   size_t size = sizeof (struct die_info);
17996
17997   if (num_attrs > 1)
17998     size += (num_attrs - 1) * sizeof (struct attribute);
17999
18000   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18001   memset (die, 0, sizeof (struct die_info));
18002   return (die);
18003 }
18004
18005 \f
18006 /* Macro support.  */
18007
18008 /* Return the full name of file number I in *LH's file name table.
18009    Use COMP_DIR as the name of the current directory of the
18010    compilation.  The result is allocated using xmalloc; the caller is
18011    responsible for freeing it.  */
18012 static char *
18013 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18014 {
18015   /* Is the file number a valid index into the line header's file name
18016      table?  Remember that file numbers start with one, not zero.  */
18017   if (1 <= file && file <= lh->num_file_names)
18018     {
18019       struct file_entry *fe = &lh->file_names[file - 1];
18020
18021       if (IS_ABSOLUTE_PATH (fe->name))
18022         return xstrdup (fe->name);
18023       else
18024         {
18025           const char *dir;
18026           int dir_len;
18027           char *full_name;
18028
18029           if (fe->dir_index)
18030             dir = lh->include_dirs[fe->dir_index - 1];
18031           else
18032             dir = comp_dir;
18033
18034           if (dir)
18035             {
18036               dir_len = strlen (dir);
18037               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
18038               strcpy (full_name, dir);
18039               full_name[dir_len] = '/';
18040               strcpy (full_name + dir_len + 1, fe->name);
18041               return full_name;
18042             }
18043           else
18044             return xstrdup (fe->name);
18045         }
18046     }
18047   else
18048     {
18049       /* The compiler produced a bogus file number.  We can at least
18050          record the macro definitions made in the file, even if we
18051          won't be able to find the file by name.  */
18052       char fake_name[80];
18053
18054       xsnprintf (fake_name, sizeof (fake_name),
18055                  "<bad macro file number %d>", file);
18056
18057       complaint (&symfile_complaints,
18058                  _("bad file number in macro information (%d)"),
18059                  file);
18060
18061       return xstrdup (fake_name);
18062     }
18063 }
18064
18065
18066 static struct macro_source_file *
18067 macro_start_file (int file, int line,
18068                   struct macro_source_file *current_file,
18069                   const char *comp_dir,
18070                   struct line_header *lh, struct objfile *objfile)
18071 {
18072   /* The full name of this source file.  */
18073   char *full_name = file_full_name (file, lh, comp_dir);
18074
18075   /* We don't create a macro table for this compilation unit
18076      at all until we actually get a filename.  */
18077   if (! pending_macros)
18078     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18079                                       objfile->per_bfd->macro_cache);
18080
18081   if (! current_file)
18082     {
18083       /* If we have no current file, then this must be the start_file
18084          directive for the compilation unit's main source file.  */
18085       current_file = macro_set_main (pending_macros, full_name);
18086       macro_define_special (pending_macros);
18087     }
18088   else
18089     current_file = macro_include (current_file, line, full_name);
18090
18091   xfree (full_name);
18092
18093   return current_file;
18094 }
18095
18096
18097 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18098    followed by a null byte.  */
18099 static char *
18100 copy_string (const char *buf, int len)
18101 {
18102   char *s = xmalloc (len + 1);
18103
18104   memcpy (s, buf, len);
18105   s[len] = '\0';
18106   return s;
18107 }
18108
18109
18110 static const char *
18111 consume_improper_spaces (const char *p, const char *body)
18112 {
18113   if (*p == ' ')
18114     {
18115       complaint (&symfile_complaints,
18116                  _("macro definition contains spaces "
18117                    "in formal argument list:\n`%s'"),
18118                  body);
18119
18120       while (*p == ' ')
18121         p++;
18122     }
18123
18124   return p;
18125 }
18126
18127
18128 static void
18129 parse_macro_definition (struct macro_source_file *file, int line,
18130                         const char *body)
18131 {
18132   const char *p;
18133
18134   /* The body string takes one of two forms.  For object-like macro
18135      definitions, it should be:
18136
18137         <macro name> " " <definition>
18138
18139      For function-like macro definitions, it should be:
18140
18141         <macro name> "() " <definition>
18142      or
18143         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18144
18145      Spaces may appear only where explicitly indicated, and in the
18146      <definition>.
18147
18148      The Dwarf 2 spec says that an object-like macro's name is always
18149      followed by a space, but versions of GCC around March 2002 omit
18150      the space when the macro's definition is the empty string.
18151
18152      The Dwarf 2 spec says that there should be no spaces between the
18153      formal arguments in a function-like macro's formal argument list,
18154      but versions of GCC around March 2002 include spaces after the
18155      commas.  */
18156
18157
18158   /* Find the extent of the macro name.  The macro name is terminated
18159      by either a space or null character (for an object-like macro) or
18160      an opening paren (for a function-like macro).  */
18161   for (p = body; *p; p++)
18162     if (*p == ' ' || *p == '(')
18163       break;
18164
18165   if (*p == ' ' || *p == '\0')
18166     {
18167       /* It's an object-like macro.  */
18168       int name_len = p - body;
18169       char *name = copy_string (body, name_len);
18170       const char *replacement;
18171
18172       if (*p == ' ')
18173         replacement = body + name_len + 1;
18174       else
18175         {
18176           dwarf2_macro_malformed_definition_complaint (body);
18177           replacement = body + name_len;
18178         }
18179
18180       macro_define_object (file, line, name, replacement);
18181
18182       xfree (name);
18183     }
18184   else if (*p == '(')
18185     {
18186       /* It's a function-like macro.  */
18187       char *name = copy_string (body, p - body);
18188       int argc = 0;
18189       int argv_size = 1;
18190       char **argv = xmalloc (argv_size * sizeof (*argv));
18191
18192       p++;
18193
18194       p = consume_improper_spaces (p, body);
18195
18196       /* Parse the formal argument list.  */
18197       while (*p && *p != ')')
18198         {
18199           /* Find the extent of the current argument name.  */
18200           const char *arg_start = p;
18201
18202           while (*p && *p != ',' && *p != ')' && *p != ' ')
18203             p++;
18204
18205           if (! *p || p == arg_start)
18206             dwarf2_macro_malformed_definition_complaint (body);
18207           else
18208             {
18209               /* Make sure argv has room for the new argument.  */
18210               if (argc >= argv_size)
18211                 {
18212                   argv_size *= 2;
18213                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18214                 }
18215
18216               argv[argc++] = copy_string (arg_start, p - arg_start);
18217             }
18218
18219           p = consume_improper_spaces (p, body);
18220
18221           /* Consume the comma, if present.  */
18222           if (*p == ',')
18223             {
18224               p++;
18225
18226               p = consume_improper_spaces (p, body);
18227             }
18228         }
18229
18230       if (*p == ')')
18231         {
18232           p++;
18233
18234           if (*p == ' ')
18235             /* Perfectly formed definition, no complaints.  */
18236             macro_define_function (file, line, name,
18237                                    argc, (const char **) argv,
18238                                    p + 1);
18239           else if (*p == '\0')
18240             {
18241               /* Complain, but do define it.  */
18242               dwarf2_macro_malformed_definition_complaint (body);
18243               macro_define_function (file, line, name,
18244                                      argc, (const char **) argv,
18245                                      p);
18246             }
18247           else
18248             /* Just complain.  */
18249             dwarf2_macro_malformed_definition_complaint (body);
18250         }
18251       else
18252         /* Just complain.  */
18253         dwarf2_macro_malformed_definition_complaint (body);
18254
18255       xfree (name);
18256       {
18257         int i;
18258
18259         for (i = 0; i < argc; i++)
18260           xfree (argv[i]);
18261       }
18262       xfree (argv);
18263     }
18264   else
18265     dwarf2_macro_malformed_definition_complaint (body);
18266 }
18267
18268 /* Skip some bytes from BYTES according to the form given in FORM.
18269    Returns the new pointer.  */
18270
18271 static gdb_byte *
18272 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
18273                  enum dwarf_form form,
18274                  unsigned int offset_size,
18275                  struct dwarf2_section_info *section)
18276 {
18277   unsigned int bytes_read;
18278
18279   switch (form)
18280     {
18281     case DW_FORM_data1:
18282     case DW_FORM_flag:
18283       ++bytes;
18284       break;
18285
18286     case DW_FORM_data2:
18287       bytes += 2;
18288       break;
18289
18290     case DW_FORM_data4:
18291       bytes += 4;
18292       break;
18293
18294     case DW_FORM_data8:
18295       bytes += 8;
18296       break;
18297
18298     case DW_FORM_string:
18299       read_direct_string (abfd, bytes, &bytes_read);
18300       bytes += bytes_read;
18301       break;
18302
18303     case DW_FORM_sec_offset:
18304     case DW_FORM_strp:
18305     case DW_FORM_GNU_strp_alt:
18306       bytes += offset_size;
18307       break;
18308
18309     case DW_FORM_block:
18310       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18311       bytes += bytes_read;
18312       break;
18313
18314     case DW_FORM_block1:
18315       bytes += 1 + read_1_byte (abfd, bytes);
18316       break;
18317     case DW_FORM_block2:
18318       bytes += 2 + read_2_bytes (abfd, bytes);
18319       break;
18320     case DW_FORM_block4:
18321       bytes += 4 + read_4_bytes (abfd, bytes);
18322       break;
18323
18324     case DW_FORM_sdata:
18325     case DW_FORM_udata:
18326     case DW_FORM_GNU_addr_index:
18327     case DW_FORM_GNU_str_index:
18328       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
18329       if (bytes == NULL)
18330         {
18331           dwarf2_section_buffer_overflow_complaint (section);
18332           return NULL;
18333         }
18334       break;
18335
18336     default:
18337       {
18338       complain:
18339         complaint (&symfile_complaints,
18340                    _("invalid form 0x%x in `%s'"),
18341                    form,
18342                    section->asection->name);
18343         return NULL;
18344       }
18345     }
18346
18347   return bytes;
18348 }
18349
18350 /* A helper for dwarf_decode_macros that handles skipping an unknown
18351    opcode.  Returns an updated pointer to the macro data buffer; or,
18352    on error, issues a complaint and returns NULL.  */
18353
18354 static gdb_byte *
18355 skip_unknown_opcode (unsigned int opcode,
18356                      gdb_byte **opcode_definitions,
18357                      gdb_byte *mac_ptr, gdb_byte *mac_end,
18358                      bfd *abfd,
18359                      unsigned int offset_size,
18360                      struct dwarf2_section_info *section)
18361 {
18362   unsigned int bytes_read, i;
18363   unsigned long arg;
18364   gdb_byte *defn;
18365
18366   if (opcode_definitions[opcode] == NULL)
18367     {
18368       complaint (&symfile_complaints,
18369                  _("unrecognized DW_MACFINO opcode 0x%x"),
18370                  opcode);
18371       return NULL;
18372     }
18373
18374   defn = opcode_definitions[opcode];
18375   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18376   defn += bytes_read;
18377
18378   for (i = 0; i < arg; ++i)
18379     {
18380       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18381                                  section);
18382       if (mac_ptr == NULL)
18383         {
18384           /* skip_form_bytes already issued the complaint.  */
18385           return NULL;
18386         }
18387     }
18388
18389   return mac_ptr;
18390 }
18391
18392 /* A helper function which parses the header of a macro section.
18393    If the macro section is the extended (for now called "GNU") type,
18394    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18395    the header, or issues a complaint and returns NULL on error.  */
18396
18397 static gdb_byte *
18398 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
18399                           bfd *abfd,
18400                           gdb_byte *mac_ptr,
18401                           unsigned int *offset_size,
18402                           int section_is_gnu)
18403 {
18404   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18405
18406   if (section_is_gnu)
18407     {
18408       unsigned int version, flags;
18409
18410       version = read_2_bytes (abfd, mac_ptr);
18411       if (version != 4)
18412         {
18413           complaint (&symfile_complaints,
18414                      _("unrecognized version `%d' in .debug_macro section"),
18415                      version);
18416           return NULL;
18417         }
18418       mac_ptr += 2;
18419
18420       flags = read_1_byte (abfd, mac_ptr);
18421       ++mac_ptr;
18422       *offset_size = (flags & 1) ? 8 : 4;
18423
18424       if ((flags & 2) != 0)
18425         /* We don't need the line table offset.  */
18426         mac_ptr += *offset_size;
18427
18428       /* Vendor opcode descriptions.  */
18429       if ((flags & 4) != 0)
18430         {
18431           unsigned int i, count;
18432
18433           count = read_1_byte (abfd, mac_ptr);
18434           ++mac_ptr;
18435           for (i = 0; i < count; ++i)
18436             {
18437               unsigned int opcode, bytes_read;
18438               unsigned long arg;
18439
18440               opcode = read_1_byte (abfd, mac_ptr);
18441               ++mac_ptr;
18442               opcode_definitions[opcode] = mac_ptr;
18443               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18444               mac_ptr += bytes_read;
18445               mac_ptr += arg;
18446             }
18447         }
18448     }
18449
18450   return mac_ptr;
18451 }
18452
18453 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18454    including DW_MACRO_GNU_transparent_include.  */
18455
18456 static void
18457 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
18458                           struct macro_source_file *current_file,
18459                           struct line_header *lh, const char *comp_dir,
18460                           struct dwarf2_section_info *section,
18461                           int section_is_gnu, int section_is_dwz,
18462                           unsigned int offset_size,
18463                           struct objfile *objfile,
18464                           htab_t include_hash)
18465 {
18466   enum dwarf_macro_record_type macinfo_type;
18467   int at_commandline;
18468   gdb_byte *opcode_definitions[256];
18469
18470   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18471                                       &offset_size, section_is_gnu);
18472   if (mac_ptr == NULL)
18473     {
18474       /* We already issued a complaint.  */
18475       return;
18476     }
18477
18478   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18479      GDB is still reading the definitions from command line.  First
18480      DW_MACINFO_start_file will need to be ignored as it was already executed
18481      to create CURRENT_FILE for the main source holding also the command line
18482      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18483      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18484
18485   at_commandline = 1;
18486
18487   do
18488     {
18489       /* Do we at least have room for a macinfo type byte?  */
18490       if (mac_ptr >= mac_end)
18491         {
18492           dwarf2_section_buffer_overflow_complaint (section);
18493           break;
18494         }
18495
18496       macinfo_type = read_1_byte (abfd, mac_ptr);
18497       mac_ptr++;
18498
18499       /* Note that we rely on the fact that the corresponding GNU and
18500          DWARF constants are the same.  */
18501       switch (macinfo_type)
18502         {
18503           /* A zero macinfo type indicates the end of the macro
18504              information.  */
18505         case 0:
18506           break;
18507
18508         case DW_MACRO_GNU_define:
18509         case DW_MACRO_GNU_undef:
18510         case DW_MACRO_GNU_define_indirect:
18511         case DW_MACRO_GNU_undef_indirect:
18512         case DW_MACRO_GNU_define_indirect_alt:
18513         case DW_MACRO_GNU_undef_indirect_alt:
18514           {
18515             unsigned int bytes_read;
18516             int line;
18517             char *body;
18518             int is_define;
18519
18520             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18521             mac_ptr += bytes_read;
18522
18523             if (macinfo_type == DW_MACRO_GNU_define
18524                 || macinfo_type == DW_MACRO_GNU_undef)
18525               {
18526                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18527                 mac_ptr += bytes_read;
18528               }
18529             else
18530               {
18531                 LONGEST str_offset;
18532
18533                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18534                 mac_ptr += offset_size;
18535
18536                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18537                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18538                     || section_is_dwz)
18539                   {
18540                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18541
18542                     body = read_indirect_string_from_dwz (dwz, str_offset);
18543                   }
18544                 else
18545                   body = read_indirect_string_at_offset (abfd, str_offset);
18546               }
18547
18548             is_define = (macinfo_type == DW_MACRO_GNU_define
18549                          || macinfo_type == DW_MACRO_GNU_define_indirect
18550                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18551             if (! current_file)
18552               {
18553                 /* DWARF violation as no main source is present.  */
18554                 complaint (&symfile_complaints,
18555                            _("debug info with no main source gives macro %s "
18556                              "on line %d: %s"),
18557                            is_define ? _("definition") : _("undefinition"),
18558                            line, body);
18559                 break;
18560               }
18561             if ((line == 0 && !at_commandline)
18562                 || (line != 0 && at_commandline))
18563               complaint (&symfile_complaints,
18564                          _("debug info gives %s macro %s with %s line %d: %s"),
18565                          at_commandline ? _("command-line") : _("in-file"),
18566                          is_define ? _("definition") : _("undefinition"),
18567                          line == 0 ? _("zero") : _("non-zero"), line, body);
18568
18569             if (is_define)
18570               parse_macro_definition (current_file, line, body);
18571             else
18572               {
18573                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18574                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18575                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18576                 macro_undef (current_file, line, body);
18577               }
18578           }
18579           break;
18580
18581         case DW_MACRO_GNU_start_file:
18582           {
18583             unsigned int bytes_read;
18584             int line, file;
18585
18586             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18587             mac_ptr += bytes_read;
18588             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18589             mac_ptr += bytes_read;
18590
18591             if ((line == 0 && !at_commandline)
18592                 || (line != 0 && at_commandline))
18593               complaint (&symfile_complaints,
18594                          _("debug info gives source %d included "
18595                            "from %s at %s line %d"),
18596                          file, at_commandline ? _("command-line") : _("file"),
18597                          line == 0 ? _("zero") : _("non-zero"), line);
18598
18599             if (at_commandline)
18600               {
18601                 /* This DW_MACRO_GNU_start_file was executed in the
18602                    pass one.  */
18603                 at_commandline = 0;
18604               }
18605             else
18606               current_file = macro_start_file (file, line,
18607                                                current_file, comp_dir,
18608                                                lh, objfile);
18609           }
18610           break;
18611
18612         case DW_MACRO_GNU_end_file:
18613           if (! current_file)
18614             complaint (&symfile_complaints,
18615                        _("macro debug info has an unmatched "
18616                          "`close_file' directive"));
18617           else
18618             {
18619               current_file = current_file->included_by;
18620               if (! current_file)
18621                 {
18622                   enum dwarf_macro_record_type next_type;
18623
18624                   /* GCC circa March 2002 doesn't produce the zero
18625                      type byte marking the end of the compilation
18626                      unit.  Complain if it's not there, but exit no
18627                      matter what.  */
18628
18629                   /* Do we at least have room for a macinfo type byte?  */
18630                   if (mac_ptr >= mac_end)
18631                     {
18632                       dwarf2_section_buffer_overflow_complaint (section);
18633                       return;
18634                     }
18635
18636                   /* We don't increment mac_ptr here, so this is just
18637                      a look-ahead.  */
18638                   next_type = read_1_byte (abfd, mac_ptr);
18639                   if (next_type != 0)
18640                     complaint (&symfile_complaints,
18641                                _("no terminating 0-type entry for "
18642                                  "macros in `.debug_macinfo' section"));
18643
18644                   return;
18645                 }
18646             }
18647           break;
18648
18649         case DW_MACRO_GNU_transparent_include:
18650         case DW_MACRO_GNU_transparent_include_alt:
18651           {
18652             LONGEST offset;
18653             void **slot;
18654             bfd *include_bfd = abfd;
18655             struct dwarf2_section_info *include_section = section;
18656             struct dwarf2_section_info alt_section;
18657             gdb_byte *include_mac_end = mac_end;
18658             int is_dwz = section_is_dwz;
18659             gdb_byte *new_mac_ptr;
18660
18661             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18662             mac_ptr += offset_size;
18663
18664             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18665               {
18666                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18667
18668                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18669                                      &dwz->macro);
18670
18671                 include_bfd = dwz->macro.asection->owner;
18672                 include_section = &dwz->macro;
18673                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18674                 is_dwz = 1;
18675               }
18676
18677             new_mac_ptr = include_section->buffer + offset;
18678             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18679
18680             if (*slot != NULL)
18681               {
18682                 /* This has actually happened; see
18683                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18684                 complaint (&symfile_complaints,
18685                            _("recursive DW_MACRO_GNU_transparent_include in "
18686                              ".debug_macro section"));
18687               }
18688             else
18689               {
18690                 *slot = new_mac_ptr;
18691
18692                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18693                                           include_mac_end, current_file,
18694                                           lh, comp_dir,
18695                                           section, section_is_gnu, is_dwz,
18696                                           offset_size, objfile, include_hash);
18697
18698                 htab_remove_elt (include_hash, new_mac_ptr);
18699               }
18700           }
18701           break;
18702
18703         case DW_MACINFO_vendor_ext:
18704           if (!section_is_gnu)
18705             {
18706               unsigned int bytes_read;
18707               int constant;
18708
18709               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18710               mac_ptr += bytes_read;
18711               read_direct_string (abfd, mac_ptr, &bytes_read);
18712               mac_ptr += bytes_read;
18713
18714               /* We don't recognize any vendor extensions.  */
18715               break;
18716             }
18717           /* FALLTHROUGH */
18718
18719         default:
18720           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18721                                          mac_ptr, mac_end, abfd, offset_size,
18722                                          section);
18723           if (mac_ptr == NULL)
18724             return;
18725           break;
18726         }
18727     } while (macinfo_type != 0);
18728 }
18729
18730 static void
18731 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18732                      const char *comp_dir, int section_is_gnu)
18733 {
18734   struct objfile *objfile = dwarf2_per_objfile->objfile;
18735   struct line_header *lh = cu->line_header;
18736   bfd *abfd;
18737   gdb_byte *mac_ptr, *mac_end;
18738   struct macro_source_file *current_file = 0;
18739   enum dwarf_macro_record_type macinfo_type;
18740   unsigned int offset_size = cu->header.offset_size;
18741   gdb_byte *opcode_definitions[256];
18742   struct cleanup *cleanup;
18743   htab_t include_hash;
18744   void **slot;
18745   struct dwarf2_section_info *section;
18746   const char *section_name;
18747
18748   if (cu->dwo_unit != NULL)
18749     {
18750       if (section_is_gnu)
18751         {
18752           section = &cu->dwo_unit->dwo_file->sections.macro;
18753           section_name = ".debug_macro.dwo";
18754         }
18755       else
18756         {
18757           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18758           section_name = ".debug_macinfo.dwo";
18759         }
18760     }
18761   else
18762     {
18763       if (section_is_gnu)
18764         {
18765           section = &dwarf2_per_objfile->macro;
18766           section_name = ".debug_macro";
18767         }
18768       else
18769         {
18770           section = &dwarf2_per_objfile->macinfo;
18771           section_name = ".debug_macinfo";
18772         }
18773     }
18774
18775   dwarf2_read_section (objfile, section);
18776   if (section->buffer == NULL)
18777     {
18778       complaint (&symfile_complaints, _("missing %s section"), section_name);
18779       return;
18780     }
18781   abfd = section->asection->owner;
18782
18783   /* First pass: Find the name of the base filename.
18784      This filename is needed in order to process all macros whose definition
18785      (or undefinition) comes from the command line.  These macros are defined
18786      before the first DW_MACINFO_start_file entry, and yet still need to be
18787      associated to the base file.
18788
18789      To determine the base file name, we scan the macro definitions until we
18790      reach the first DW_MACINFO_start_file entry.  We then initialize
18791      CURRENT_FILE accordingly so that any macro definition found before the
18792      first DW_MACINFO_start_file can still be associated to the base file.  */
18793
18794   mac_ptr = section->buffer + offset;
18795   mac_end = section->buffer + section->size;
18796
18797   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18798                                       &offset_size, section_is_gnu);
18799   if (mac_ptr == NULL)
18800     {
18801       /* We already issued a complaint.  */
18802       return;
18803     }
18804
18805   do
18806     {
18807       /* Do we at least have room for a macinfo type byte?  */
18808       if (mac_ptr >= mac_end)
18809         {
18810           /* Complaint is printed during the second pass as GDB will probably
18811              stop the first pass earlier upon finding
18812              DW_MACINFO_start_file.  */
18813           break;
18814         }
18815
18816       macinfo_type = read_1_byte (abfd, mac_ptr);
18817       mac_ptr++;
18818
18819       /* Note that we rely on the fact that the corresponding GNU and
18820          DWARF constants are the same.  */
18821       switch (macinfo_type)
18822         {
18823           /* A zero macinfo type indicates the end of the macro
18824              information.  */
18825         case 0:
18826           break;
18827
18828         case DW_MACRO_GNU_define:
18829         case DW_MACRO_GNU_undef:
18830           /* Only skip the data by MAC_PTR.  */
18831           {
18832             unsigned int bytes_read;
18833
18834             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18835             mac_ptr += bytes_read;
18836             read_direct_string (abfd, mac_ptr, &bytes_read);
18837             mac_ptr += bytes_read;
18838           }
18839           break;
18840
18841         case DW_MACRO_GNU_start_file:
18842           {
18843             unsigned int bytes_read;
18844             int line, file;
18845
18846             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18847             mac_ptr += bytes_read;
18848             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18849             mac_ptr += bytes_read;
18850
18851             current_file = macro_start_file (file, line, current_file,
18852                                              comp_dir, lh, objfile);
18853           }
18854           break;
18855
18856         case DW_MACRO_GNU_end_file:
18857           /* No data to skip by MAC_PTR.  */
18858           break;
18859
18860         case DW_MACRO_GNU_define_indirect:
18861         case DW_MACRO_GNU_undef_indirect:
18862         case DW_MACRO_GNU_define_indirect_alt:
18863         case DW_MACRO_GNU_undef_indirect_alt:
18864           {
18865             unsigned int bytes_read;
18866
18867             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18868             mac_ptr += bytes_read;
18869             mac_ptr += offset_size;
18870           }
18871           break;
18872
18873         case DW_MACRO_GNU_transparent_include:
18874         case DW_MACRO_GNU_transparent_include_alt:
18875           /* Note that, according to the spec, a transparent include
18876              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
18877              skip this opcode.  */
18878           mac_ptr += offset_size;
18879           break;
18880
18881         case DW_MACINFO_vendor_ext:
18882           /* Only skip the data by MAC_PTR.  */
18883           if (!section_is_gnu)
18884             {
18885               unsigned int bytes_read;
18886
18887               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18888               mac_ptr += bytes_read;
18889               read_direct_string (abfd, mac_ptr, &bytes_read);
18890               mac_ptr += bytes_read;
18891             }
18892           /* FALLTHROUGH */
18893
18894         default:
18895           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18896                                          mac_ptr, mac_end, abfd, offset_size,
18897                                          section);
18898           if (mac_ptr == NULL)
18899             return;
18900           break;
18901         }
18902     } while (macinfo_type != 0 && current_file == NULL);
18903
18904   /* Second pass: Process all entries.
18905
18906      Use the AT_COMMAND_LINE flag to determine whether we are still processing
18907      command-line macro definitions/undefinitions.  This flag is unset when we
18908      reach the first DW_MACINFO_start_file entry.  */
18909
18910   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
18911                                     NULL, xcalloc, xfree);
18912   cleanup = make_cleanup_htab_delete (include_hash);
18913   mac_ptr = section->buffer + offset;
18914   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
18915   *slot = mac_ptr;
18916   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
18917                             current_file, lh, comp_dir, section,
18918                             section_is_gnu, 0,
18919                             offset_size, objfile, include_hash);
18920   do_cleanups (cleanup);
18921 }
18922
18923 /* Check if the attribute's form is a DW_FORM_block*
18924    if so return true else false.  */
18925
18926 static int
18927 attr_form_is_block (struct attribute *attr)
18928 {
18929   return (attr == NULL ? 0 :
18930       attr->form == DW_FORM_block1
18931       || attr->form == DW_FORM_block2
18932       || attr->form == DW_FORM_block4
18933       || attr->form == DW_FORM_block
18934       || attr->form == DW_FORM_exprloc);
18935 }
18936
18937 /* Return non-zero if ATTR's value is a section offset --- classes
18938    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
18939    You may use DW_UNSND (attr) to retrieve such offsets.
18940
18941    Section 7.5.4, "Attribute Encodings", explains that no attribute
18942    may have a value that belongs to more than one of these classes; it
18943    would be ambiguous if we did, because we use the same forms for all
18944    of them.  */
18945
18946 static int
18947 attr_form_is_section_offset (struct attribute *attr)
18948 {
18949   return (attr->form == DW_FORM_data4
18950           || attr->form == DW_FORM_data8
18951           || attr->form == DW_FORM_sec_offset);
18952 }
18953
18954 /* Return non-zero if ATTR's value falls in the 'constant' class, or
18955    zero otherwise.  When this function returns true, you can apply
18956    dwarf2_get_attr_constant_value to it.
18957
18958    However, note that for some attributes you must check
18959    attr_form_is_section_offset before using this test.  DW_FORM_data4
18960    and DW_FORM_data8 are members of both the constant class, and of
18961    the classes that contain offsets into other debug sections
18962    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
18963    that, if an attribute's can be either a constant or one of the
18964    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
18965    taken as section offsets, not constants.  */
18966
18967 static int
18968 attr_form_is_constant (struct attribute *attr)
18969 {
18970   switch (attr->form)
18971     {
18972     case DW_FORM_sdata:
18973     case DW_FORM_udata:
18974     case DW_FORM_data1:
18975     case DW_FORM_data2:
18976     case DW_FORM_data4:
18977     case DW_FORM_data8:
18978       return 1;
18979     default:
18980       return 0;
18981     }
18982 }
18983
18984 /* Return the .debug_loc section to use for CU.
18985    For DWO files use .debug_loc.dwo.  */
18986
18987 static struct dwarf2_section_info *
18988 cu_debug_loc_section (struct dwarf2_cu *cu)
18989 {
18990   if (cu->dwo_unit)
18991     return &cu->dwo_unit->dwo_file->sections.loc;
18992   return &dwarf2_per_objfile->loc;
18993 }
18994
18995 /* A helper function that fills in a dwarf2_loclist_baton.  */
18996
18997 static void
18998 fill_in_loclist_baton (struct dwarf2_cu *cu,
18999                        struct dwarf2_loclist_baton *baton,
19000                        struct attribute *attr)
19001 {
19002   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19003
19004   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19005
19006   baton->per_cu = cu->per_cu;
19007   gdb_assert (baton->per_cu);
19008   /* We don't know how long the location list is, but make sure we
19009      don't run off the edge of the section.  */
19010   baton->size = section->size - DW_UNSND (attr);
19011   baton->data = section->buffer + DW_UNSND (attr);
19012   baton->base_address = cu->base_address;
19013   baton->from_dwo = cu->dwo_unit != NULL;
19014 }
19015
19016 static void
19017 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19018                              struct dwarf2_cu *cu)
19019 {
19020   struct objfile *objfile = dwarf2_per_objfile->objfile;
19021   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19022
19023   if (attr_form_is_section_offset (attr)
19024       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19025          the section.  If so, fall through to the complaint in the
19026          other branch.  */
19027       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19028     {
19029       struct dwarf2_loclist_baton *baton;
19030
19031       baton = obstack_alloc (&objfile->objfile_obstack,
19032                              sizeof (struct dwarf2_loclist_baton));
19033
19034       fill_in_loclist_baton (cu, baton, attr);
19035
19036       if (cu->base_known == 0)
19037         complaint (&symfile_complaints,
19038                    _("Location list used without "
19039                      "specifying the CU base address."));
19040
19041       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
19042       SYMBOL_LOCATION_BATON (sym) = baton;
19043     }
19044   else
19045     {
19046       struct dwarf2_locexpr_baton *baton;
19047
19048       baton = obstack_alloc (&objfile->objfile_obstack,
19049                              sizeof (struct dwarf2_locexpr_baton));
19050       baton->per_cu = cu->per_cu;
19051       gdb_assert (baton->per_cu);
19052
19053       if (attr_form_is_block (attr))
19054         {
19055           /* Note that we're just copying the block's data pointer
19056              here, not the actual data.  We're still pointing into the
19057              info_buffer for SYM's objfile; right now we never release
19058              that buffer, but when we do clean up properly this may
19059              need to change.  */
19060           baton->size = DW_BLOCK (attr)->size;
19061           baton->data = DW_BLOCK (attr)->data;
19062         }
19063       else
19064         {
19065           dwarf2_invalid_attrib_class_complaint ("location description",
19066                                                  SYMBOL_NATURAL_NAME (sym));
19067           baton->size = 0;
19068         }
19069
19070       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
19071       SYMBOL_LOCATION_BATON (sym) = baton;
19072     }
19073 }
19074
19075 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19076    came from a separate debuginfo file, then the master objfile is
19077    returned.  */
19078
19079 struct objfile *
19080 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19081 {
19082   struct objfile *objfile = per_cu->objfile;
19083
19084   /* Return the master objfile, so that we can report and look up the
19085      correct file containing this variable.  */
19086   if (objfile->separate_debug_objfile_backlink)
19087     objfile = objfile->separate_debug_objfile_backlink;
19088
19089   return objfile;
19090 }
19091
19092 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19093    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19094    CU_HEADERP first.  */
19095
19096 static const struct comp_unit_head *
19097 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19098                        struct dwarf2_per_cu_data *per_cu)
19099 {
19100   gdb_byte *info_ptr;
19101
19102   if (per_cu->cu)
19103     return &per_cu->cu->header;
19104
19105   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
19106
19107   memset (cu_headerp, 0, sizeof (*cu_headerp));
19108   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19109
19110   return cu_headerp;
19111 }
19112
19113 /* Return the address size given in the compilation unit header for CU.  */
19114
19115 int
19116 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19117 {
19118   struct comp_unit_head cu_header_local;
19119   const struct comp_unit_head *cu_headerp;
19120
19121   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19122
19123   return cu_headerp->addr_size;
19124 }
19125
19126 /* Return the offset size given in the compilation unit header for CU.  */
19127
19128 int
19129 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19130 {
19131   struct comp_unit_head cu_header_local;
19132   const struct comp_unit_head *cu_headerp;
19133
19134   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19135
19136   return cu_headerp->offset_size;
19137 }
19138
19139 /* See its dwarf2loc.h declaration.  */
19140
19141 int
19142 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19143 {
19144   struct comp_unit_head cu_header_local;
19145   const struct comp_unit_head *cu_headerp;
19146
19147   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19148
19149   if (cu_headerp->version == 2)
19150     return cu_headerp->addr_size;
19151   else
19152     return cu_headerp->offset_size;
19153 }
19154
19155 /* Return the text offset of the CU.  The returned offset comes from
19156    this CU's objfile.  If this objfile came from a separate debuginfo
19157    file, then the offset may be different from the corresponding
19158    offset in the parent objfile.  */
19159
19160 CORE_ADDR
19161 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19162 {
19163   struct objfile *objfile = per_cu->objfile;
19164
19165   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19166 }
19167
19168 /* Locate the .debug_info compilation unit from CU's objfile which contains
19169    the DIE at OFFSET.  Raises an error on failure.  */
19170
19171 static struct dwarf2_per_cu_data *
19172 dwarf2_find_containing_comp_unit (sect_offset offset,
19173                                   unsigned int offset_in_dwz,
19174                                   struct objfile *objfile)
19175 {
19176   struct dwarf2_per_cu_data *this_cu;
19177   int low, high;
19178   const sect_offset *cu_off;
19179
19180   low = 0;
19181   high = dwarf2_per_objfile->n_comp_units - 1;
19182   while (high > low)
19183     {
19184       struct dwarf2_per_cu_data *mid_cu;
19185       int mid = low + (high - low) / 2;
19186
19187       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19188       cu_off = &mid_cu->offset;
19189       if (mid_cu->is_dwz > offset_in_dwz
19190           || (mid_cu->is_dwz == offset_in_dwz
19191               && cu_off->sect_off >= offset.sect_off))
19192         high = mid;
19193       else
19194         low = mid + 1;
19195     }
19196   gdb_assert (low == high);
19197   this_cu = dwarf2_per_objfile->all_comp_units[low];
19198   cu_off = &this_cu->offset;
19199   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19200     {
19201       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19202         error (_("Dwarf Error: could not find partial DIE containing "
19203                "offset 0x%lx [in module %s]"),
19204                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19205
19206       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19207                   <= offset.sect_off);
19208       return dwarf2_per_objfile->all_comp_units[low-1];
19209     }
19210   else
19211     {
19212       this_cu = dwarf2_per_objfile->all_comp_units[low];
19213       if (low == dwarf2_per_objfile->n_comp_units - 1
19214           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19215         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19216       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19217       return this_cu;
19218     }
19219 }
19220
19221 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19222
19223 static void
19224 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19225 {
19226   memset (cu, 0, sizeof (*cu));
19227   per_cu->cu = cu;
19228   cu->per_cu = per_cu;
19229   cu->objfile = per_cu->objfile;
19230   obstack_init (&cu->comp_unit_obstack);
19231 }
19232
19233 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19234
19235 static void
19236 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19237                        enum language pretend_language)
19238 {
19239   struct attribute *attr;
19240
19241   /* Set the language we're debugging.  */
19242   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19243   if (attr)
19244     set_cu_language (DW_UNSND (attr), cu);
19245   else
19246     {
19247       cu->language = pretend_language;
19248       cu->language_defn = language_def (cu->language);
19249     }
19250
19251   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19252   if (attr)
19253     cu->producer = DW_STRING (attr);
19254 }
19255
19256 /* Release one cached compilation unit, CU.  We unlink it from the tree
19257    of compilation units, but we don't remove it from the read_in_chain;
19258    the caller is responsible for that.
19259    NOTE: DATA is a void * because this function is also used as a
19260    cleanup routine.  */
19261
19262 static void
19263 free_heap_comp_unit (void *data)
19264 {
19265   struct dwarf2_cu *cu = data;
19266
19267   gdb_assert (cu->per_cu != NULL);
19268   cu->per_cu->cu = NULL;
19269   cu->per_cu = NULL;
19270
19271   obstack_free (&cu->comp_unit_obstack, NULL);
19272
19273   xfree (cu);
19274 }
19275
19276 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19277    when we're finished with it.  We can't free the pointer itself, but be
19278    sure to unlink it from the cache.  Also release any associated storage.  */
19279
19280 static void
19281 free_stack_comp_unit (void *data)
19282 {
19283   struct dwarf2_cu *cu = data;
19284
19285   gdb_assert (cu->per_cu != NULL);
19286   cu->per_cu->cu = NULL;
19287   cu->per_cu = NULL;
19288
19289   obstack_free (&cu->comp_unit_obstack, NULL);
19290   cu->partial_dies = NULL;
19291 }
19292
19293 /* Free all cached compilation units.  */
19294
19295 static void
19296 free_cached_comp_units (void *data)
19297 {
19298   struct dwarf2_per_cu_data *per_cu, **last_chain;
19299
19300   per_cu = dwarf2_per_objfile->read_in_chain;
19301   last_chain = &dwarf2_per_objfile->read_in_chain;
19302   while (per_cu != NULL)
19303     {
19304       struct dwarf2_per_cu_data *next_cu;
19305
19306       next_cu = per_cu->cu->read_in_chain;
19307
19308       free_heap_comp_unit (per_cu->cu);
19309       *last_chain = next_cu;
19310
19311       per_cu = next_cu;
19312     }
19313 }
19314
19315 /* Increase the age counter on each cached compilation unit, and free
19316    any that are too old.  */
19317
19318 static void
19319 age_cached_comp_units (void)
19320 {
19321   struct dwarf2_per_cu_data *per_cu, **last_chain;
19322
19323   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19324   per_cu = dwarf2_per_objfile->read_in_chain;
19325   while (per_cu != NULL)
19326     {
19327       per_cu->cu->last_used ++;
19328       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19329         dwarf2_mark (per_cu->cu);
19330       per_cu = per_cu->cu->read_in_chain;
19331     }
19332
19333   per_cu = dwarf2_per_objfile->read_in_chain;
19334   last_chain = &dwarf2_per_objfile->read_in_chain;
19335   while (per_cu != NULL)
19336     {
19337       struct dwarf2_per_cu_data *next_cu;
19338
19339       next_cu = per_cu->cu->read_in_chain;
19340
19341       if (!per_cu->cu->mark)
19342         {
19343           free_heap_comp_unit (per_cu->cu);
19344           *last_chain = next_cu;
19345         }
19346       else
19347         last_chain = &per_cu->cu->read_in_chain;
19348
19349       per_cu = next_cu;
19350     }
19351 }
19352
19353 /* Remove a single compilation unit from the cache.  */
19354
19355 static void
19356 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19357 {
19358   struct dwarf2_per_cu_data *per_cu, **last_chain;
19359
19360   per_cu = dwarf2_per_objfile->read_in_chain;
19361   last_chain = &dwarf2_per_objfile->read_in_chain;
19362   while (per_cu != NULL)
19363     {
19364       struct dwarf2_per_cu_data *next_cu;
19365
19366       next_cu = per_cu->cu->read_in_chain;
19367
19368       if (per_cu == target_per_cu)
19369         {
19370           free_heap_comp_unit (per_cu->cu);
19371           per_cu->cu = NULL;
19372           *last_chain = next_cu;
19373           break;
19374         }
19375       else
19376         last_chain = &per_cu->cu->read_in_chain;
19377
19378       per_cu = next_cu;
19379     }
19380 }
19381
19382 /* Release all extra memory associated with OBJFILE.  */
19383
19384 void
19385 dwarf2_free_objfile (struct objfile *objfile)
19386 {
19387   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19388
19389   if (dwarf2_per_objfile == NULL)
19390     return;
19391
19392   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19393   free_cached_comp_units (NULL);
19394
19395   if (dwarf2_per_objfile->quick_file_names_table)
19396     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19397
19398   /* Everything else should be on the objfile obstack.  */
19399 }
19400
19401 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19402    We store these in a hash table separate from the DIEs, and preserve them
19403    when the DIEs are flushed out of cache.
19404
19405    The CU "per_cu" pointer is needed because offset alone is not enough to
19406    uniquely identify the type.  A file may have multiple .debug_types sections,
19407    or the type may come from a DWO file.  We have to use something in
19408    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
19409    routine, get_die_type_at_offset, from outside this file, and thus won't
19410    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
19411    of the objfile.  */
19412
19413 struct dwarf2_per_cu_offset_and_type
19414 {
19415   const struct dwarf2_per_cu_data *per_cu;
19416   sect_offset offset;
19417   struct type *type;
19418 };
19419
19420 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19421
19422 static hashval_t
19423 per_cu_offset_and_type_hash (const void *item)
19424 {
19425   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19426
19427   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19428 }
19429
19430 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19431
19432 static int
19433 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19434 {
19435   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19436   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19437
19438   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19439           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19440 }
19441
19442 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19443    table if necessary.  For convenience, return TYPE.
19444
19445    The DIEs reading must have careful ordering to:
19446     * Not cause infite loops trying to read in DIEs as a prerequisite for
19447       reading current DIE.
19448     * Not trying to dereference contents of still incompletely read in types
19449       while reading in other DIEs.
19450     * Enable referencing still incompletely read in types just by a pointer to
19451       the type without accessing its fields.
19452
19453    Therefore caller should follow these rules:
19454      * Try to fetch any prerequisite types we may need to build this DIE type
19455        before building the type and calling set_die_type.
19456      * After building type call set_die_type for current DIE as soon as
19457        possible before fetching more types to complete the current type.
19458      * Make the type as complete as possible before fetching more types.  */
19459
19460 static struct type *
19461 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19462 {
19463   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19464   struct objfile *objfile = cu->objfile;
19465
19466   /* For Ada types, make sure that the gnat-specific data is always
19467      initialized (if not already set).  There are a few types where
19468      we should not be doing so, because the type-specific area is
19469      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19470      where the type-specific area is used to store the floatformat).
19471      But this is not a problem, because the gnat-specific information
19472      is actually not needed for these types.  */
19473   if (need_gnat_info (cu)
19474       && TYPE_CODE (type) != TYPE_CODE_FUNC
19475       && TYPE_CODE (type) != TYPE_CODE_FLT
19476       && !HAVE_GNAT_AUX_INFO (type))
19477     INIT_GNAT_SPECIFIC (type);
19478
19479   if (dwarf2_per_objfile->die_type_hash == NULL)
19480     {
19481       dwarf2_per_objfile->die_type_hash =
19482         htab_create_alloc_ex (127,
19483                               per_cu_offset_and_type_hash,
19484                               per_cu_offset_and_type_eq,
19485                               NULL,
19486                               &objfile->objfile_obstack,
19487                               hashtab_obstack_allocate,
19488                               dummy_obstack_deallocate);
19489     }
19490
19491   ofs.per_cu = cu->per_cu;
19492   ofs.offset = die->offset;
19493   ofs.type = type;
19494   slot = (struct dwarf2_per_cu_offset_and_type **)
19495     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19496   if (*slot)
19497     complaint (&symfile_complaints,
19498                _("A problem internal to GDB: DIE 0x%x has type already set"),
19499                die->offset.sect_off);
19500   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19501   **slot = ofs;
19502   return type;
19503 }
19504
19505 /* Look up the type for the die at OFFSET in the appropriate type_hash
19506    table, or return NULL if the die does not have a saved type.  */
19507
19508 static struct type *
19509 get_die_type_at_offset (sect_offset offset,
19510                         struct dwarf2_per_cu_data *per_cu)
19511 {
19512   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19513
19514   if (dwarf2_per_objfile->die_type_hash == NULL)
19515     return NULL;
19516
19517   ofs.per_cu = per_cu;
19518   ofs.offset = offset;
19519   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19520   if (slot)
19521     return slot->type;
19522   else
19523     return NULL;
19524 }
19525
19526 /* Look up the type for DIE in the appropriate type_hash table,
19527    or return NULL if DIE does not have a saved type.  */
19528
19529 static struct type *
19530 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19531 {
19532   return get_die_type_at_offset (die->offset, cu->per_cu);
19533 }
19534
19535 /* Add a dependence relationship from CU to REF_PER_CU.  */
19536
19537 static void
19538 dwarf2_add_dependence (struct dwarf2_cu *cu,
19539                        struct dwarf2_per_cu_data *ref_per_cu)
19540 {
19541   void **slot;
19542
19543   if (cu->dependencies == NULL)
19544     cu->dependencies
19545       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19546                               NULL, &cu->comp_unit_obstack,
19547                               hashtab_obstack_allocate,
19548                               dummy_obstack_deallocate);
19549
19550   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19551   if (*slot == NULL)
19552     *slot = ref_per_cu;
19553 }
19554
19555 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19556    Set the mark field in every compilation unit in the
19557    cache that we must keep because we are keeping CU.  */
19558
19559 static int
19560 dwarf2_mark_helper (void **slot, void *data)
19561 {
19562   struct dwarf2_per_cu_data *per_cu;
19563
19564   per_cu = (struct dwarf2_per_cu_data *) *slot;
19565
19566   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19567      reading of the chain.  As such dependencies remain valid it is not much
19568      useful to track and undo them during QUIT cleanups.  */
19569   if (per_cu->cu == NULL)
19570     return 1;
19571
19572   if (per_cu->cu->mark)
19573     return 1;
19574   per_cu->cu->mark = 1;
19575
19576   if (per_cu->cu->dependencies != NULL)
19577     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19578
19579   return 1;
19580 }
19581
19582 /* Set the mark field in CU and in every other compilation unit in the
19583    cache that we must keep because we are keeping CU.  */
19584
19585 static void
19586 dwarf2_mark (struct dwarf2_cu *cu)
19587 {
19588   if (cu->mark)
19589     return;
19590   cu->mark = 1;
19591   if (cu->dependencies != NULL)
19592     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19593 }
19594
19595 static void
19596 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19597 {
19598   while (per_cu)
19599     {
19600       per_cu->cu->mark = 0;
19601       per_cu = per_cu->cu->read_in_chain;
19602     }
19603 }
19604
19605 /* Trivial hash function for partial_die_info: the hash value of a DIE
19606    is its offset in .debug_info for this objfile.  */
19607
19608 static hashval_t
19609 partial_die_hash (const void *item)
19610 {
19611   const struct partial_die_info *part_die = item;
19612
19613   return part_die->offset.sect_off;
19614 }
19615
19616 /* Trivial comparison function for partial_die_info structures: two DIEs
19617    are equal if they have the same offset.  */
19618
19619 static int
19620 partial_die_eq (const void *item_lhs, const void *item_rhs)
19621 {
19622   const struct partial_die_info *part_die_lhs = item_lhs;
19623   const struct partial_die_info *part_die_rhs = item_rhs;
19624
19625   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19626 }
19627
19628 static struct cmd_list_element *set_dwarf2_cmdlist;
19629 static struct cmd_list_element *show_dwarf2_cmdlist;
19630
19631 static void
19632 set_dwarf2_cmd (char *args, int from_tty)
19633 {
19634   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19635 }
19636
19637 static void
19638 show_dwarf2_cmd (char *args, int from_tty)
19639 {
19640   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19641 }
19642
19643 /* Free data associated with OBJFILE, if necessary.  */
19644
19645 static void
19646 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19647 {
19648   struct dwarf2_per_objfile *data = d;
19649   int ix;
19650
19651   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19652     VEC_free (dwarf2_per_cu_ptr,
19653               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19654
19655   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19656     VEC_free (dwarf2_per_cu_ptr,
19657               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19658
19659   VEC_free (dwarf2_section_info_def, data->types);
19660
19661   if (data->dwo_files)
19662     free_dwo_files (data->dwo_files, objfile);
19663
19664   if (data->dwz_file && data->dwz_file->dwz_bfd)
19665     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19666 }
19667
19668 \f
19669 /* The "save gdb-index" command.  */
19670
19671 /* The contents of the hash table we create when building the string
19672    table.  */
19673 struct strtab_entry
19674 {
19675   offset_type offset;
19676   const char *str;
19677 };
19678
19679 /* Hash function for a strtab_entry.
19680
19681    Function is used only during write_hash_table so no index format backward
19682    compatibility is needed.  */
19683
19684 static hashval_t
19685 hash_strtab_entry (const void *e)
19686 {
19687   const struct strtab_entry *entry = e;
19688   return mapped_index_string_hash (INT_MAX, entry->str);
19689 }
19690
19691 /* Equality function for a strtab_entry.  */
19692
19693 static int
19694 eq_strtab_entry (const void *a, const void *b)
19695 {
19696   const struct strtab_entry *ea = a;
19697   const struct strtab_entry *eb = b;
19698   return !strcmp (ea->str, eb->str);
19699 }
19700
19701 /* Create a strtab_entry hash table.  */
19702
19703 static htab_t
19704 create_strtab (void)
19705 {
19706   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19707                             xfree, xcalloc, xfree);
19708 }
19709
19710 /* Add a string to the constant pool.  Return the string's offset in
19711    host order.  */
19712
19713 static offset_type
19714 add_string (htab_t table, struct obstack *cpool, const char *str)
19715 {
19716   void **slot;
19717   struct strtab_entry entry;
19718   struct strtab_entry *result;
19719
19720   entry.str = str;
19721   slot = htab_find_slot (table, &entry, INSERT);
19722   if (*slot)
19723     result = *slot;
19724   else
19725     {
19726       result = XNEW (struct strtab_entry);
19727       result->offset = obstack_object_size (cpool);
19728       result->str = str;
19729       obstack_grow_str0 (cpool, str);
19730       *slot = result;
19731     }
19732   return result->offset;
19733 }
19734
19735 /* An entry in the symbol table.  */
19736 struct symtab_index_entry
19737 {
19738   /* The name of the symbol.  */
19739   const char *name;
19740   /* The offset of the name in the constant pool.  */
19741   offset_type index_offset;
19742   /* A sorted vector of the indices of all the CUs that hold an object
19743      of this name.  */
19744   VEC (offset_type) *cu_indices;
19745 };
19746
19747 /* The symbol table.  This is a power-of-2-sized hash table.  */
19748 struct mapped_symtab
19749 {
19750   offset_type n_elements;
19751   offset_type size;
19752   struct symtab_index_entry **data;
19753 };
19754
19755 /* Hash function for a symtab_index_entry.  */
19756
19757 static hashval_t
19758 hash_symtab_entry (const void *e)
19759 {
19760   const struct symtab_index_entry *entry = e;
19761   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19762                          sizeof (offset_type) * VEC_length (offset_type,
19763                                                             entry->cu_indices),
19764                          0);
19765 }
19766
19767 /* Equality function for a symtab_index_entry.  */
19768
19769 static int
19770 eq_symtab_entry (const void *a, const void *b)
19771 {
19772   const struct symtab_index_entry *ea = a;
19773   const struct symtab_index_entry *eb = b;
19774   int len = VEC_length (offset_type, ea->cu_indices);
19775   if (len != VEC_length (offset_type, eb->cu_indices))
19776     return 0;
19777   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19778                   VEC_address (offset_type, eb->cu_indices),
19779                   sizeof (offset_type) * len);
19780 }
19781
19782 /* Destroy a symtab_index_entry.  */
19783
19784 static void
19785 delete_symtab_entry (void *p)
19786 {
19787   struct symtab_index_entry *entry = p;
19788   VEC_free (offset_type, entry->cu_indices);
19789   xfree (entry);
19790 }
19791
19792 /* Create a hash table holding symtab_index_entry objects.  */
19793
19794 static htab_t
19795 create_symbol_hash_table (void)
19796 {
19797   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19798                             delete_symtab_entry, xcalloc, xfree);
19799 }
19800
19801 /* Create a new mapped symtab object.  */
19802
19803 static struct mapped_symtab *
19804 create_mapped_symtab (void)
19805 {
19806   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
19807   symtab->n_elements = 0;
19808   symtab->size = 1024;
19809   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19810   return symtab;
19811 }
19812
19813 /* Destroy a mapped_symtab.  */
19814
19815 static void
19816 cleanup_mapped_symtab (void *p)
19817 {
19818   struct mapped_symtab *symtab = p;
19819   /* The contents of the array are freed when the other hash table is
19820      destroyed.  */
19821   xfree (symtab->data);
19822   xfree (symtab);
19823 }
19824
19825 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
19826    the slot.
19827    
19828    Function is used only during write_hash_table so no index format backward
19829    compatibility is needed.  */
19830
19831 static struct symtab_index_entry **
19832 find_slot (struct mapped_symtab *symtab, const char *name)
19833 {
19834   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
19835
19836   index = hash & (symtab->size - 1);
19837   step = ((hash * 17) & (symtab->size - 1)) | 1;
19838
19839   for (;;)
19840     {
19841       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
19842         return &symtab->data[index];
19843       index = (index + step) & (symtab->size - 1);
19844     }
19845 }
19846
19847 /* Expand SYMTAB's hash table.  */
19848
19849 static void
19850 hash_expand (struct mapped_symtab *symtab)
19851 {
19852   offset_type old_size = symtab->size;
19853   offset_type i;
19854   struct symtab_index_entry **old_entries = symtab->data;
19855
19856   symtab->size *= 2;
19857   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19858
19859   for (i = 0; i < old_size; ++i)
19860     {
19861       if (old_entries[i])
19862         {
19863           struct symtab_index_entry **slot = find_slot (symtab,
19864                                                         old_entries[i]->name);
19865           *slot = old_entries[i];
19866         }
19867     }
19868
19869   xfree (old_entries);
19870 }
19871
19872 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
19873    CU_INDEX is the index of the CU in which the symbol appears.
19874    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
19875
19876 static void
19877 add_index_entry (struct mapped_symtab *symtab, const char *name,
19878                  int is_static, gdb_index_symbol_kind kind,
19879                  offset_type cu_index)
19880 {
19881   struct symtab_index_entry **slot;
19882   offset_type cu_index_and_attrs;
19883
19884   ++symtab->n_elements;
19885   if (4 * symtab->n_elements / 3 >= symtab->size)
19886     hash_expand (symtab);
19887
19888   slot = find_slot (symtab, name);
19889   if (!*slot)
19890     {
19891       *slot = XNEW (struct symtab_index_entry);
19892       (*slot)->name = name;
19893       /* index_offset is set later.  */
19894       (*slot)->cu_indices = NULL;
19895     }
19896
19897   cu_index_and_attrs = 0;
19898   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
19899   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
19900   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
19901
19902   /* We don't want to record an index value twice as we want to avoid the
19903      duplication.
19904      We process all global symbols and then all static symbols
19905      (which would allow us to avoid the duplication by only having to check
19906      the last entry pushed), but a symbol could have multiple kinds in one CU.
19907      To keep things simple we don't worry about the duplication here and
19908      sort and uniqufy the list after we've processed all symbols.  */
19909   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
19910 }
19911
19912 /* qsort helper routine for uniquify_cu_indices.  */
19913
19914 static int
19915 offset_type_compare (const void *ap, const void *bp)
19916 {
19917   offset_type a = *(offset_type *) ap;
19918   offset_type b = *(offset_type *) bp;
19919
19920   return (a > b) - (b > a);
19921 }
19922
19923 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
19924
19925 static void
19926 uniquify_cu_indices (struct mapped_symtab *symtab)
19927 {
19928   int i;
19929
19930   for (i = 0; i < symtab->size; ++i)
19931     {
19932       struct symtab_index_entry *entry = symtab->data[i];
19933
19934       if (entry
19935           && entry->cu_indices != NULL)
19936         {
19937           unsigned int next_to_insert, next_to_check;
19938           offset_type last_value;
19939
19940           qsort (VEC_address (offset_type, entry->cu_indices),
19941                  VEC_length (offset_type, entry->cu_indices),
19942                  sizeof (offset_type), offset_type_compare);
19943
19944           last_value = VEC_index (offset_type, entry->cu_indices, 0);
19945           next_to_insert = 1;
19946           for (next_to_check = 1;
19947                next_to_check < VEC_length (offset_type, entry->cu_indices);
19948                ++next_to_check)
19949             {
19950               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
19951                   != last_value)
19952                 {
19953                   last_value = VEC_index (offset_type, entry->cu_indices,
19954                                           next_to_check);
19955                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
19956                                last_value);
19957                   ++next_to_insert;
19958                 }
19959             }
19960           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
19961         }
19962     }
19963 }
19964
19965 /* Add a vector of indices to the constant pool.  */
19966
19967 static offset_type
19968 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
19969                       struct symtab_index_entry *entry)
19970 {
19971   void **slot;
19972
19973   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
19974   if (!*slot)
19975     {
19976       offset_type len = VEC_length (offset_type, entry->cu_indices);
19977       offset_type val = MAYBE_SWAP (len);
19978       offset_type iter;
19979       int i;
19980
19981       *slot = entry;
19982       entry->index_offset = obstack_object_size (cpool);
19983
19984       obstack_grow (cpool, &val, sizeof (val));
19985       for (i = 0;
19986            VEC_iterate (offset_type, entry->cu_indices, i, iter);
19987            ++i)
19988         {
19989           val = MAYBE_SWAP (iter);
19990           obstack_grow (cpool, &val, sizeof (val));
19991         }
19992     }
19993   else
19994     {
19995       struct symtab_index_entry *old_entry = *slot;
19996       entry->index_offset = old_entry->index_offset;
19997       entry = old_entry;
19998     }
19999   return entry->index_offset;
20000 }
20001
20002 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20003    constant pool entries going into the obstack CPOOL.  */
20004
20005 static void
20006 write_hash_table (struct mapped_symtab *symtab,
20007                   struct obstack *output, struct obstack *cpool)
20008 {
20009   offset_type i;
20010   htab_t symbol_hash_table;
20011   htab_t str_table;
20012
20013   symbol_hash_table = create_symbol_hash_table ();
20014   str_table = create_strtab ();
20015
20016   /* We add all the index vectors to the constant pool first, to
20017      ensure alignment is ok.  */
20018   for (i = 0; i < symtab->size; ++i)
20019     {
20020       if (symtab->data[i])
20021         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20022     }
20023
20024   /* Now write out the hash table.  */
20025   for (i = 0; i < symtab->size; ++i)
20026     {
20027       offset_type str_off, vec_off;
20028
20029       if (symtab->data[i])
20030         {
20031           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20032           vec_off = symtab->data[i]->index_offset;
20033         }
20034       else
20035         {
20036           /* While 0 is a valid constant pool index, it is not valid
20037              to have 0 for both offsets.  */
20038           str_off = 0;
20039           vec_off = 0;
20040         }
20041
20042       str_off = MAYBE_SWAP (str_off);
20043       vec_off = MAYBE_SWAP (vec_off);
20044
20045       obstack_grow (output, &str_off, sizeof (str_off));
20046       obstack_grow (output, &vec_off, sizeof (vec_off));
20047     }
20048
20049   htab_delete (str_table);
20050   htab_delete (symbol_hash_table);
20051 }
20052
20053 /* Struct to map psymtab to CU index in the index file.  */
20054 struct psymtab_cu_index_map
20055 {
20056   struct partial_symtab *psymtab;
20057   unsigned int cu_index;
20058 };
20059
20060 static hashval_t
20061 hash_psymtab_cu_index (const void *item)
20062 {
20063   const struct psymtab_cu_index_map *map = item;
20064
20065   return htab_hash_pointer (map->psymtab);
20066 }
20067
20068 static int
20069 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20070 {
20071   const struct psymtab_cu_index_map *lhs = item_lhs;
20072   const struct psymtab_cu_index_map *rhs = item_rhs;
20073
20074   return lhs->psymtab == rhs->psymtab;
20075 }
20076
20077 /* Helper struct for building the address table.  */
20078 struct addrmap_index_data
20079 {
20080   struct objfile *objfile;
20081   struct obstack *addr_obstack;
20082   htab_t cu_index_htab;
20083
20084   /* Non-zero if the previous_* fields are valid.
20085      We can't write an entry until we see the next entry (since it is only then
20086      that we know the end of the entry).  */
20087   int previous_valid;
20088   /* Index of the CU in the table of all CUs in the index file.  */
20089   unsigned int previous_cu_index;
20090   /* Start address of the CU.  */
20091   CORE_ADDR previous_cu_start;
20092 };
20093
20094 /* Write an address entry to OBSTACK.  */
20095
20096 static void
20097 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20098                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20099 {
20100   offset_type cu_index_to_write;
20101   char addr[8];
20102   CORE_ADDR baseaddr;
20103
20104   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20105
20106   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20107   obstack_grow (obstack, addr, 8);
20108   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20109   obstack_grow (obstack, addr, 8);
20110   cu_index_to_write = MAYBE_SWAP (cu_index);
20111   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20112 }
20113
20114 /* Worker function for traversing an addrmap to build the address table.  */
20115
20116 static int
20117 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20118 {
20119   struct addrmap_index_data *data = datap;
20120   struct partial_symtab *pst = obj;
20121
20122   if (data->previous_valid)
20123     add_address_entry (data->objfile, data->addr_obstack,
20124                        data->previous_cu_start, start_addr,
20125                        data->previous_cu_index);
20126
20127   data->previous_cu_start = start_addr;
20128   if (pst != NULL)
20129     {
20130       struct psymtab_cu_index_map find_map, *map;
20131       find_map.psymtab = pst;
20132       map = htab_find (data->cu_index_htab, &find_map);
20133       gdb_assert (map != NULL);
20134       data->previous_cu_index = map->cu_index;
20135       data->previous_valid = 1;
20136     }
20137   else
20138       data->previous_valid = 0;
20139
20140   return 0;
20141 }
20142
20143 /* Write OBJFILE's address map to OBSTACK.
20144    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20145    in the index file.  */
20146
20147 static void
20148 write_address_map (struct objfile *objfile, struct obstack *obstack,
20149                    htab_t cu_index_htab)
20150 {
20151   struct addrmap_index_data addrmap_index_data;
20152
20153   /* When writing the address table, we have to cope with the fact that
20154      the addrmap iterator only provides the start of a region; we have to
20155      wait until the next invocation to get the start of the next region.  */
20156
20157   addrmap_index_data.objfile = objfile;
20158   addrmap_index_data.addr_obstack = obstack;
20159   addrmap_index_data.cu_index_htab = cu_index_htab;
20160   addrmap_index_data.previous_valid = 0;
20161
20162   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20163                    &addrmap_index_data);
20164
20165   /* It's highly unlikely the last entry (end address = 0xff...ff)
20166      is valid, but we should still handle it.
20167      The end address is recorded as the start of the next region, but that
20168      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20169      anyway.  */
20170   if (addrmap_index_data.previous_valid)
20171     add_address_entry (objfile, obstack,
20172                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20173                        addrmap_index_data.previous_cu_index);
20174 }
20175
20176 /* Return the symbol kind of PSYM.  */
20177
20178 static gdb_index_symbol_kind
20179 symbol_kind (struct partial_symbol *psym)
20180 {
20181   domain_enum domain = PSYMBOL_DOMAIN (psym);
20182   enum address_class aclass = PSYMBOL_CLASS (psym);
20183
20184   switch (domain)
20185     {
20186     case VAR_DOMAIN:
20187       switch (aclass)
20188         {
20189         case LOC_BLOCK:
20190           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20191         case LOC_TYPEDEF:
20192           return GDB_INDEX_SYMBOL_KIND_TYPE;
20193         case LOC_COMPUTED:
20194         case LOC_CONST_BYTES:
20195         case LOC_OPTIMIZED_OUT:
20196         case LOC_STATIC:
20197           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20198         case LOC_CONST:
20199           /* Note: It's currently impossible to recognize psyms as enum values
20200              short of reading the type info.  For now punt.  */
20201           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20202         default:
20203           /* There are other LOC_FOO values that one might want to classify
20204              as variables, but dwarf2read.c doesn't currently use them.  */
20205           return GDB_INDEX_SYMBOL_KIND_OTHER;
20206         }
20207     case STRUCT_DOMAIN:
20208       return GDB_INDEX_SYMBOL_KIND_TYPE;
20209     default:
20210       return GDB_INDEX_SYMBOL_KIND_OTHER;
20211     }
20212 }
20213
20214 /* Add a list of partial symbols to SYMTAB.  */
20215
20216 static void
20217 write_psymbols (struct mapped_symtab *symtab,
20218                 htab_t psyms_seen,
20219                 struct partial_symbol **psymp,
20220                 int count,
20221                 offset_type cu_index,
20222                 int is_static)
20223 {
20224   for (; count-- > 0; ++psymp)
20225     {
20226       struct partial_symbol *psym = *psymp;
20227       void **slot;
20228
20229       if (SYMBOL_LANGUAGE (psym) == language_ada)
20230         error (_("Ada is not currently supported by the index"));
20231
20232       /* Only add a given psymbol once.  */
20233       slot = htab_find_slot (psyms_seen, psym, INSERT);
20234       if (!*slot)
20235         {
20236           gdb_index_symbol_kind kind = symbol_kind (psym);
20237
20238           *slot = psym;
20239           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20240                            is_static, kind, cu_index);
20241         }
20242     }
20243 }
20244
20245 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20246    exception if there is an error.  */
20247
20248 static void
20249 write_obstack (FILE *file, struct obstack *obstack)
20250 {
20251   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20252               file)
20253       != obstack_object_size (obstack))
20254     error (_("couldn't data write to file"));
20255 }
20256
20257 /* Unlink a file if the argument is not NULL.  */
20258
20259 static void
20260 unlink_if_set (void *p)
20261 {
20262   char **filename = p;
20263   if (*filename)
20264     unlink (*filename);
20265 }
20266
20267 /* A helper struct used when iterating over debug_types.  */
20268 struct signatured_type_index_data
20269 {
20270   struct objfile *objfile;
20271   struct mapped_symtab *symtab;
20272   struct obstack *types_list;
20273   htab_t psyms_seen;
20274   int cu_index;
20275 };
20276
20277 /* A helper function that writes a single signatured_type to an
20278    obstack.  */
20279
20280 static int
20281 write_one_signatured_type (void **slot, void *d)
20282 {
20283   struct signatured_type_index_data *info = d;
20284   struct signatured_type *entry = (struct signatured_type *) *slot;
20285   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
20286   struct partial_symtab *psymtab = per_cu->v.psymtab;
20287   gdb_byte val[8];
20288
20289   write_psymbols (info->symtab,
20290                   info->psyms_seen,
20291                   info->objfile->global_psymbols.list
20292                   + psymtab->globals_offset,
20293                   psymtab->n_global_syms, info->cu_index,
20294                   0);
20295   write_psymbols (info->symtab,
20296                   info->psyms_seen,
20297                   info->objfile->static_psymbols.list
20298                   + psymtab->statics_offset,
20299                   psymtab->n_static_syms, info->cu_index,
20300                   1);
20301
20302   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20303                           entry->per_cu.offset.sect_off);
20304   obstack_grow (info->types_list, val, 8);
20305   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20306                           entry->type_offset_in_tu.cu_off);
20307   obstack_grow (info->types_list, val, 8);
20308   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20309   obstack_grow (info->types_list, val, 8);
20310
20311   ++info->cu_index;
20312
20313   return 1;
20314 }
20315
20316 /* Recurse into all "included" dependencies and write their symbols as
20317    if they appeared in this psymtab.  */
20318
20319 static void
20320 recursively_write_psymbols (struct objfile *objfile,
20321                             struct partial_symtab *psymtab,
20322                             struct mapped_symtab *symtab,
20323                             htab_t psyms_seen,
20324                             offset_type cu_index)
20325 {
20326   int i;
20327
20328   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20329     if (psymtab->dependencies[i]->user != NULL)
20330       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20331                                   symtab, psyms_seen, cu_index);
20332
20333   write_psymbols (symtab,
20334                   psyms_seen,
20335                   objfile->global_psymbols.list + psymtab->globals_offset,
20336                   psymtab->n_global_syms, cu_index,
20337                   0);
20338   write_psymbols (symtab,
20339                   psyms_seen,
20340                   objfile->static_psymbols.list + psymtab->statics_offset,
20341                   psymtab->n_static_syms, cu_index,
20342                   1);
20343 }
20344
20345 /* Create an index file for OBJFILE in the directory DIR.  */
20346
20347 static void
20348 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20349 {
20350   struct cleanup *cleanup;
20351   char *filename, *cleanup_filename;
20352   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20353   struct obstack cu_list, types_cu_list;
20354   int i;
20355   FILE *out_file;
20356   struct mapped_symtab *symtab;
20357   offset_type val, size_of_contents, total_len;
20358   struct stat st;
20359   htab_t psyms_seen;
20360   htab_t cu_index_htab;
20361   struct psymtab_cu_index_map *psymtab_cu_index_map;
20362
20363   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20364     return;
20365
20366   if (dwarf2_per_objfile->using_index)
20367     error (_("Cannot use an index to create the index"));
20368
20369   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20370     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20371
20372   if (stat (objfile->name, &st) < 0)
20373     perror_with_name (objfile->name);
20374
20375   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20376                      INDEX_SUFFIX, (char *) NULL);
20377   cleanup = make_cleanup (xfree, filename);
20378
20379   out_file = fopen (filename, "wb");
20380   if (!out_file)
20381     error (_("Can't open `%s' for writing"), filename);
20382
20383   cleanup_filename = filename;
20384   make_cleanup (unlink_if_set, &cleanup_filename);
20385
20386   symtab = create_mapped_symtab ();
20387   make_cleanup (cleanup_mapped_symtab, symtab);
20388
20389   obstack_init (&addr_obstack);
20390   make_cleanup_obstack_free (&addr_obstack);
20391
20392   obstack_init (&cu_list);
20393   make_cleanup_obstack_free (&cu_list);
20394
20395   obstack_init (&types_cu_list);
20396   make_cleanup_obstack_free (&types_cu_list);
20397
20398   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20399                                   NULL, xcalloc, xfree);
20400   make_cleanup_htab_delete (psyms_seen);
20401
20402   /* While we're scanning CU's create a table that maps a psymtab pointer
20403      (which is what addrmap records) to its index (which is what is recorded
20404      in the index file).  This will later be needed to write the address
20405      table.  */
20406   cu_index_htab = htab_create_alloc (100,
20407                                      hash_psymtab_cu_index,
20408                                      eq_psymtab_cu_index,
20409                                      NULL, xcalloc, xfree);
20410   make_cleanup_htab_delete (cu_index_htab);
20411   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20412     xmalloc (sizeof (struct psymtab_cu_index_map)
20413              * dwarf2_per_objfile->n_comp_units);
20414   make_cleanup (xfree, psymtab_cu_index_map);
20415
20416   /* The CU list is already sorted, so we don't need to do additional
20417      work here.  Also, the debug_types entries do not appear in
20418      all_comp_units, but only in their own hash table.  */
20419   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20420     {
20421       struct dwarf2_per_cu_data *per_cu
20422         = dwarf2_per_objfile->all_comp_units[i];
20423       struct partial_symtab *psymtab = per_cu->v.psymtab;
20424       gdb_byte val[8];
20425       struct psymtab_cu_index_map *map;
20426       void **slot;
20427
20428       if (psymtab->user == NULL)
20429         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20430
20431       map = &psymtab_cu_index_map[i];
20432       map->psymtab = psymtab;
20433       map->cu_index = i;
20434       slot = htab_find_slot (cu_index_htab, map, INSERT);
20435       gdb_assert (slot != NULL);
20436       gdb_assert (*slot == NULL);
20437       *slot = map;
20438
20439       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20440                               per_cu->offset.sect_off);
20441       obstack_grow (&cu_list, val, 8);
20442       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20443       obstack_grow (&cu_list, val, 8);
20444     }
20445
20446   /* Dump the address map.  */
20447   write_address_map (objfile, &addr_obstack, cu_index_htab);
20448
20449   /* Write out the .debug_type entries, if any.  */
20450   if (dwarf2_per_objfile->signatured_types)
20451     {
20452       struct signatured_type_index_data sig_data;
20453
20454       sig_data.objfile = objfile;
20455       sig_data.symtab = symtab;
20456       sig_data.types_list = &types_cu_list;
20457       sig_data.psyms_seen = psyms_seen;
20458       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20459       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20460                               write_one_signatured_type, &sig_data);
20461     }
20462
20463   /* Now that we've processed all symbols we can shrink their cu_indices
20464      lists.  */
20465   uniquify_cu_indices (symtab);
20466
20467   obstack_init (&constant_pool);
20468   make_cleanup_obstack_free (&constant_pool);
20469   obstack_init (&symtab_obstack);
20470   make_cleanup_obstack_free (&symtab_obstack);
20471   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20472
20473   obstack_init (&contents);
20474   make_cleanup_obstack_free (&contents);
20475   size_of_contents = 6 * sizeof (offset_type);
20476   total_len = size_of_contents;
20477
20478   /* The version number.  */
20479   val = MAYBE_SWAP (8);
20480   obstack_grow (&contents, &val, sizeof (val));
20481
20482   /* The offset of the CU list from the start of the file.  */
20483   val = MAYBE_SWAP (total_len);
20484   obstack_grow (&contents, &val, sizeof (val));
20485   total_len += obstack_object_size (&cu_list);
20486
20487   /* The offset of the types CU list from the start of the file.  */
20488   val = MAYBE_SWAP (total_len);
20489   obstack_grow (&contents, &val, sizeof (val));
20490   total_len += obstack_object_size (&types_cu_list);
20491
20492   /* The offset of the address table from the start of the file.  */
20493   val = MAYBE_SWAP (total_len);
20494   obstack_grow (&contents, &val, sizeof (val));
20495   total_len += obstack_object_size (&addr_obstack);
20496
20497   /* The offset of the symbol table from the start of the file.  */
20498   val = MAYBE_SWAP (total_len);
20499   obstack_grow (&contents, &val, sizeof (val));
20500   total_len += obstack_object_size (&symtab_obstack);
20501
20502   /* The offset of the constant pool from the start of the file.  */
20503   val = MAYBE_SWAP (total_len);
20504   obstack_grow (&contents, &val, sizeof (val));
20505   total_len += obstack_object_size (&constant_pool);
20506
20507   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20508
20509   write_obstack (out_file, &contents);
20510   write_obstack (out_file, &cu_list);
20511   write_obstack (out_file, &types_cu_list);
20512   write_obstack (out_file, &addr_obstack);
20513   write_obstack (out_file, &symtab_obstack);
20514   write_obstack (out_file, &constant_pool);
20515
20516   fclose (out_file);
20517
20518   /* We want to keep the file, so we set cleanup_filename to NULL
20519      here.  See unlink_if_set.  */
20520   cleanup_filename = NULL;
20521
20522   do_cleanups (cleanup);
20523 }
20524
20525 /* Implementation of the `save gdb-index' command.
20526    
20527    Note that the file format used by this command is documented in the
20528    GDB manual.  Any changes here must be documented there.  */
20529
20530 static void
20531 save_gdb_index_command (char *arg, int from_tty)
20532 {
20533   struct objfile *objfile;
20534
20535   if (!arg || !*arg)
20536     error (_("usage: save gdb-index DIRECTORY"));
20537
20538   ALL_OBJFILES (objfile)
20539   {
20540     struct stat st;
20541
20542     /* If the objfile does not correspond to an actual file, skip it.  */
20543     if (stat (objfile->name, &st) < 0)
20544       continue;
20545
20546     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20547     if (dwarf2_per_objfile)
20548       {
20549         volatile struct gdb_exception except;
20550
20551         TRY_CATCH (except, RETURN_MASK_ERROR)
20552           {
20553             write_psymtabs_to_index (objfile, arg);
20554           }
20555         if (except.reason < 0)
20556           exception_fprintf (gdb_stderr, except,
20557                              _("Error while writing index for `%s': "),
20558                              objfile->name);
20559       }
20560   }
20561 }
20562
20563 \f
20564
20565 int dwarf2_always_disassemble;
20566
20567 static void
20568 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20569                                 struct cmd_list_element *c, const char *value)
20570 {
20571   fprintf_filtered (file,
20572                     _("Whether to always disassemble "
20573                       "DWARF expressions is %s.\n"),
20574                     value);
20575 }
20576
20577 static void
20578 show_check_physname (struct ui_file *file, int from_tty,
20579                      struct cmd_list_element *c, const char *value)
20580 {
20581   fprintf_filtered (file,
20582                     _("Whether to check \"physname\" is %s.\n"),
20583                     value);
20584 }
20585
20586 void _initialize_dwarf2_read (void);
20587
20588 void
20589 _initialize_dwarf2_read (void)
20590 {
20591   struct cmd_list_element *c;
20592
20593   dwarf2_objfile_data_key
20594     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20595
20596   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20597 Set DWARF 2 specific variables.\n\
20598 Configure DWARF 2 variables such as the cache size"),
20599                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20600                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20601
20602   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20603 Show DWARF 2 specific variables\n\
20604 Show DWARF 2 variables such as the cache size"),
20605                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20606                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20607
20608   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20609                             &dwarf2_max_cache_age, _("\
20610 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20611 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20612 A higher limit means that cached compilation units will be stored\n\
20613 in memory longer, and more total memory will be used.  Zero disables\n\
20614 caching, which can slow down startup."),
20615                             NULL,
20616                             show_dwarf2_max_cache_age,
20617                             &set_dwarf2_cmdlist,
20618                             &show_dwarf2_cmdlist);
20619
20620   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20621                            &dwarf2_always_disassemble, _("\
20622 Set whether `info address' always disassembles DWARF expressions."), _("\
20623 Show whether `info address' always disassembles DWARF expressions."), _("\
20624 When enabled, DWARF expressions are always printed in an assembly-like\n\
20625 syntax.  When disabled, expressions will be printed in a more\n\
20626 conversational style, when possible."),
20627                            NULL,
20628                            show_dwarf2_always_disassemble,
20629                            &set_dwarf2_cmdlist,
20630                            &show_dwarf2_cmdlist);
20631
20632   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20633 Set debugging of the dwarf2 reader."), _("\
20634 Show debugging of the dwarf2 reader."), _("\
20635 When enabled, debugging messages are printed during dwarf2 reading\n\
20636 and symtab expansion."),
20637                             NULL,
20638                             NULL,
20639                             &setdebuglist, &showdebuglist);
20640
20641   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20642 Set debugging of the dwarf2 DIE reader."), _("\
20643 Show debugging of the dwarf2 DIE reader."), _("\
20644 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20645 The value is the maximum depth to print."),
20646                              NULL,
20647                              NULL,
20648                              &setdebuglist, &showdebuglist);
20649
20650   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20651 Set cross-checking of \"physname\" code against demangler."), _("\
20652 Show cross-checking of \"physname\" code against demangler."), _("\
20653 When enabled, GDB's internal \"physname\" code is checked against\n\
20654 the demangler."),
20655                            NULL, show_check_physname,
20656                            &setdebuglist, &showdebuglist);
20657
20658   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20659                            no_class, &use_deprecated_index_sections, _("\
20660 Set whether to use deprecated gdb_index sections."), _("\
20661 Show whether to use deprecated gdb_index sections."), _("\
20662 When enabled, deprecated .gdb_index sections are used anyway.\n\
20663 Normally they are ignored either because of a missing feature or\n\
20664 performance issue.\n\
20665 Warning: This option must be enabled before gdb reads the file."),
20666                            NULL,
20667                            NULL,
20668                            &setlist, &showlist);
20669
20670   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20671                _("\
20672 Save a gdb-index file.\n\
20673 Usage: save gdb-index DIRECTORY"),
20674                &save_cmdlist);
20675   set_cmd_completer (c, filename_completer);
20676 }