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_filename (struct objfile *objfile,
3347                                   const char *filename)
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_name = file_data->file_names[j];
3375           if (FILENAME_CMP (this_name, filename) == 0)
3376             {
3377               dw2_instantiate_symtab (per_cu);
3378               break;
3379             }
3380         }
3381     }
3382 }
3383
3384 /* A helper function for dw2_find_symbol_file that finds the primary
3385    file name for a given CU.  This is a die_reader_func.  */
3386
3387 static void
3388 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3389                                  gdb_byte *info_ptr,
3390                                  struct die_info *comp_unit_die,
3391                                  int has_children,
3392                                  void *data)
3393 {
3394   const char **result_ptr = data;
3395   struct dwarf2_cu *cu = reader->cu;
3396   struct attribute *attr;
3397
3398   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3399   if (attr == NULL)
3400     *result_ptr = NULL;
3401   else
3402     *result_ptr = DW_STRING (attr);
3403 }
3404
3405 static const char *
3406 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3407 {
3408   struct dwarf2_per_cu_data *per_cu;
3409   offset_type *vec;
3410   const char *filename;
3411
3412   dw2_setup (objfile);
3413
3414   /* index_table is NULL if OBJF_READNOW.  */
3415   if (!dwarf2_per_objfile->index_table)
3416     {
3417       struct symtab *s;
3418
3419       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3420         {
3421           struct blockvector *bv = BLOCKVECTOR (s);
3422           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3423           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3424
3425           if (sym)
3426             return SYMBOL_SYMTAB (sym)->filename;
3427         }
3428       return NULL;
3429     }
3430
3431   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3432                                  name, &vec))
3433     return NULL;
3434
3435   /* Note that this just looks at the very first one named NAME -- but
3436      actually we are looking for a function.  find_main_filename
3437      should be rewritten so that it doesn't require a custom hook.  It
3438      could just use the ordinary symbol tables.  */
3439   /* vec[0] is the length, which must always be >0.  */
3440   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3441
3442   if (per_cu->v.quick->symtab != NULL)
3443     return per_cu->v.quick->symtab->filename;
3444
3445   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3446                            dw2_get_primary_filename_reader, &filename);
3447
3448   return filename;
3449 }
3450
3451 static void
3452 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3453                           struct objfile *objfile, int global,
3454                           int (*callback) (struct block *,
3455                                            struct symbol *, void *),
3456                           void *data, symbol_compare_ftype *match,
3457                           symbol_compare_ftype *ordered_compare)
3458 {
3459   /* Currently unimplemented; used for Ada.  The function can be called if the
3460      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3461      does not look for non-Ada symbols this function should just return.  */
3462 }
3463
3464 static void
3465 dw2_expand_symtabs_matching
3466   (struct objfile *objfile,
3467    int (*file_matcher) (const char *, void *),
3468    int (*name_matcher) (const char *, void *),
3469    enum search_domain kind,
3470    void *data)
3471 {
3472   int i;
3473   offset_type iter;
3474   struct mapped_index *index;
3475
3476   dw2_setup (objfile);
3477
3478   /* index_table is NULL if OBJF_READNOW.  */
3479   if (!dwarf2_per_objfile->index_table)
3480     return;
3481   index = dwarf2_per_objfile->index_table;
3482
3483   if (file_matcher != NULL)
3484     {
3485       struct cleanup *cleanup;
3486       htab_t visited_found, visited_not_found;
3487
3488       visited_found = htab_create_alloc (10,
3489                                          htab_hash_pointer, htab_eq_pointer,
3490                                          NULL, xcalloc, xfree);
3491       cleanup = make_cleanup_htab_delete (visited_found);
3492       visited_not_found = htab_create_alloc (10,
3493                                              htab_hash_pointer, htab_eq_pointer,
3494                                              NULL, xcalloc, xfree);
3495       make_cleanup_htab_delete (visited_not_found);
3496
3497       /* The rule is CUs specify all the files, including those used by
3498          any TU, so there's no need to scan TUs here.  */
3499
3500       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3501         {
3502           int j;
3503           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3504           struct quick_file_names *file_data;
3505           void **slot;
3506
3507           per_cu->v.quick->mark = 0;
3508
3509           /* We only need to look at symtabs not already expanded.  */
3510           if (per_cu->v.quick->symtab)
3511             continue;
3512
3513           file_data = dw2_get_file_names (objfile, per_cu);
3514           if (file_data == NULL)
3515             continue;
3516
3517           if (htab_find (visited_not_found, file_data) != NULL)
3518             continue;
3519           else if (htab_find (visited_found, file_data) != NULL)
3520             {
3521               per_cu->v.quick->mark = 1;
3522               continue;
3523             }
3524
3525           for (j = 0; j < file_data->num_file_names; ++j)
3526             {
3527               if (file_matcher (file_data->file_names[j], data))
3528                 {
3529                   per_cu->v.quick->mark = 1;
3530                   break;
3531                 }
3532             }
3533
3534           slot = htab_find_slot (per_cu->v.quick->mark
3535                                  ? visited_found
3536                                  : visited_not_found,
3537                                  file_data, INSERT);
3538           *slot = file_data;
3539         }
3540
3541       do_cleanups (cleanup);
3542     }
3543
3544   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3545     {
3546       offset_type idx = 2 * iter;
3547       const char *name;
3548       offset_type *vec, vec_len, vec_idx;
3549
3550       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3551         continue;
3552
3553       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3554
3555       if (! (*name_matcher) (name, data))
3556         continue;
3557
3558       /* The name was matched, now expand corresponding CUs that were
3559          marked.  */
3560       vec = (offset_type *) (index->constant_pool
3561                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3562       vec_len = MAYBE_SWAP (vec[0]);
3563       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3564         {
3565           struct dwarf2_per_cu_data *per_cu;
3566           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3567           gdb_index_symbol_kind symbol_kind =
3568             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3569           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3570
3571           /* Don't crash on bad data.  */
3572           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3573                            + dwarf2_per_objfile->n_type_units))
3574             continue;
3575
3576           /* Only check the symbol's kind if it has one.
3577              Indices prior to version 7 don't record it.  */
3578           if (index->version >= 7)
3579             {
3580               switch (kind)
3581                 {
3582                 case VARIABLES_DOMAIN:
3583                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3584                     continue;
3585                   break;
3586                 case FUNCTIONS_DOMAIN:
3587                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3588                     continue;
3589                   break;
3590                 case TYPES_DOMAIN:
3591                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3592                     continue;
3593                   break;
3594                 default:
3595                   break;
3596                 }
3597             }
3598
3599           per_cu = dw2_get_cu (cu_index);
3600           if (file_matcher == NULL || per_cu->v.quick->mark)
3601             dw2_instantiate_symtab (per_cu);
3602         }
3603     }
3604 }
3605
3606 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3607    symtab.  */
3608
3609 static struct symtab *
3610 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3611 {
3612   int i;
3613
3614   if (BLOCKVECTOR (symtab) != NULL
3615       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3616     return symtab;
3617
3618   if (symtab->includes == NULL)
3619     return NULL;
3620
3621   for (i = 0; symtab->includes[i]; ++i)
3622     {
3623       struct symtab *s = symtab->includes[i];
3624
3625       s = recursively_find_pc_sect_symtab (s, pc);
3626       if (s != NULL)
3627         return s;
3628     }
3629
3630   return NULL;
3631 }
3632
3633 static struct symtab *
3634 dw2_find_pc_sect_symtab (struct objfile *objfile,
3635                          struct minimal_symbol *msymbol,
3636                          CORE_ADDR pc,
3637                          struct obj_section *section,
3638                          int warn_if_readin)
3639 {
3640   struct dwarf2_per_cu_data *data;
3641   struct symtab *result;
3642
3643   dw2_setup (objfile);
3644
3645   if (!objfile->psymtabs_addrmap)
3646     return NULL;
3647
3648   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3649   if (!data)
3650     return NULL;
3651
3652   if (warn_if_readin && data->v.quick->symtab)
3653     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3654              paddress (get_objfile_arch (objfile), pc));
3655
3656   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3657   gdb_assert (result != NULL);
3658   return result;
3659 }
3660
3661 static void
3662 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3663                           void *data, int need_fullname)
3664 {
3665   int i;
3666   struct cleanup *cleanup;
3667   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3668                                       NULL, xcalloc, xfree);
3669
3670   cleanup = make_cleanup_htab_delete (visited);
3671   dw2_setup (objfile);
3672
3673   /* The rule is CUs specify all the files, including those used by
3674      any TU, so there's no need to scan TUs here.
3675      We can ignore file names coming from already-expanded CUs.  */
3676
3677   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3678     {
3679       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3680
3681       if (per_cu->v.quick->symtab)
3682         {
3683           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3684                                         INSERT);
3685
3686           *slot = per_cu->v.quick->file_names;
3687         }
3688     }
3689
3690   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3691     {
3692       int j;
3693       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3694       struct quick_file_names *file_data;
3695       void **slot;
3696
3697       /* We only need to look at symtabs not already expanded.  */
3698       if (per_cu->v.quick->symtab)
3699         continue;
3700
3701       file_data = dw2_get_file_names (objfile, per_cu);
3702       if (file_data == NULL)
3703         continue;
3704
3705       slot = htab_find_slot (visited, file_data, INSERT);
3706       if (*slot)
3707         {
3708           /* Already visited.  */
3709           continue;
3710         }
3711       *slot = file_data;
3712
3713       for (j = 0; j < file_data->num_file_names; ++j)
3714         {
3715           const char *this_real_name;
3716
3717           if (need_fullname)
3718             this_real_name = dw2_get_real_path (objfile, file_data, j);
3719           else
3720             this_real_name = NULL;
3721           (*fun) (file_data->file_names[j], this_real_name, data);
3722         }
3723     }
3724
3725   do_cleanups (cleanup);
3726 }
3727
3728 static int
3729 dw2_has_symbols (struct objfile *objfile)
3730 {
3731   return 1;
3732 }
3733
3734 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3735 {
3736   dw2_has_symbols,
3737   dw2_find_last_source_symtab,
3738   dw2_forget_cached_source_info,
3739   dw2_map_symtabs_matching_filename,
3740   dw2_lookup_symbol,
3741   dw2_print_stats,
3742   dw2_dump,
3743   dw2_relocate,
3744   dw2_expand_symtabs_for_function,
3745   dw2_expand_all_symtabs,
3746   dw2_expand_symtabs_with_filename,
3747   dw2_find_symbol_file,
3748   dw2_map_matching_symbols,
3749   dw2_expand_symtabs_matching,
3750   dw2_find_pc_sect_symtab,
3751   dw2_map_symbol_filenames
3752 };
3753
3754 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3755    file will use psymtabs, or 1 if using the GNU index.  */
3756
3757 int
3758 dwarf2_initialize_objfile (struct objfile *objfile)
3759 {
3760   /* If we're about to read full symbols, don't bother with the
3761      indices.  In this case we also don't care if some other debug
3762      format is making psymtabs, because they are all about to be
3763      expanded anyway.  */
3764   if ((objfile->flags & OBJF_READNOW))
3765     {
3766       int i;
3767
3768       dwarf2_per_objfile->using_index = 1;
3769       create_all_comp_units (objfile);
3770       create_all_type_units (objfile);
3771       dwarf2_per_objfile->quick_file_names_table =
3772         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3773
3774       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3775                        + dwarf2_per_objfile->n_type_units); ++i)
3776         {
3777           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3778
3779           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3780                                             struct dwarf2_per_cu_quick_data);
3781         }
3782
3783       /* Return 1 so that gdb sees the "quick" functions.  However,
3784          these functions will be no-ops because we will have expanded
3785          all symtabs.  */
3786       return 1;
3787     }
3788
3789   if (dwarf2_read_index (objfile))
3790     return 1;
3791
3792   return 0;
3793 }
3794
3795 \f
3796
3797 /* Build a partial symbol table.  */
3798
3799 void
3800 dwarf2_build_psymtabs (struct objfile *objfile)
3801 {
3802   volatile struct gdb_exception except;
3803
3804   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3805     {
3806       init_psymbol_list (objfile, 1024);
3807     }
3808
3809   TRY_CATCH (except, RETURN_MASK_ERROR)
3810     {
3811       /* This isn't really ideal: all the data we allocate on the
3812          objfile's obstack is still uselessly kept around.  However,
3813          freeing it seems unsafe.  */
3814       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3815
3816       dwarf2_build_psymtabs_hard (objfile);
3817       discard_cleanups (cleanups);
3818     }
3819   if (except.reason < 0)
3820     exception_print (gdb_stderr, except);
3821 }
3822
3823 /* Return the total length of the CU described by HEADER.  */
3824
3825 static unsigned int
3826 get_cu_length (const struct comp_unit_head *header)
3827 {
3828   return header->initial_length_size + header->length;
3829 }
3830
3831 /* Return TRUE if OFFSET is within CU_HEADER.  */
3832
3833 static inline int
3834 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3835 {
3836   sect_offset bottom = { cu_header->offset.sect_off };
3837   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3838
3839   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3840 }
3841
3842 /* Find the base address of the compilation unit for range lists and
3843    location lists.  It will normally be specified by DW_AT_low_pc.
3844    In DWARF-3 draft 4, the base address could be overridden by
3845    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3846    compilation units with discontinuous ranges.  */
3847
3848 static void
3849 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3850 {
3851   struct attribute *attr;
3852
3853   cu->base_known = 0;
3854   cu->base_address = 0;
3855
3856   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3857   if (attr)
3858     {
3859       cu->base_address = DW_ADDR (attr);
3860       cu->base_known = 1;
3861     }
3862   else
3863     {
3864       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3865       if (attr)
3866         {
3867           cu->base_address = DW_ADDR (attr);
3868           cu->base_known = 1;
3869         }
3870     }
3871 }
3872
3873 /* Read in the comp unit header information from the debug_info at info_ptr.
3874    NOTE: This leaves members offset, first_die_offset to be filled in
3875    by the caller.  */
3876
3877 static gdb_byte *
3878 read_comp_unit_head (struct comp_unit_head *cu_header,
3879                      gdb_byte *info_ptr, bfd *abfd)
3880 {
3881   int signed_addr;
3882   unsigned int bytes_read;
3883
3884   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3885   cu_header->initial_length_size = bytes_read;
3886   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3887   info_ptr += bytes_read;
3888   cu_header->version = read_2_bytes (abfd, info_ptr);
3889   info_ptr += 2;
3890   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3891                                              &bytes_read);
3892   info_ptr += bytes_read;
3893   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3894   info_ptr += 1;
3895   signed_addr = bfd_get_sign_extend_vma (abfd);
3896   if (signed_addr < 0)
3897     internal_error (__FILE__, __LINE__,
3898                     _("read_comp_unit_head: dwarf from non elf file"));
3899   cu_header->signed_addr_p = signed_addr;
3900
3901   return info_ptr;
3902 }
3903
3904 /* Helper function that returns the proper abbrev section for
3905    THIS_CU.  */
3906
3907 static struct dwarf2_section_info *
3908 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3909 {
3910   struct dwarf2_section_info *abbrev;
3911
3912   if (this_cu->is_dwz)
3913     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3914   else
3915     abbrev = &dwarf2_per_objfile->abbrev;
3916
3917   return abbrev;
3918 }
3919
3920 /* Subroutine of read_and_check_comp_unit_head and
3921    read_and_check_type_unit_head to simplify them.
3922    Perform various error checking on the header.  */
3923
3924 static void
3925 error_check_comp_unit_head (struct comp_unit_head *header,
3926                             struct dwarf2_section_info *section,
3927                             struct dwarf2_section_info *abbrev_section)
3928 {
3929   bfd *abfd = section->asection->owner;
3930   const char *filename = bfd_get_filename (abfd);
3931
3932   if (header->version != 2 && header->version != 3 && header->version != 4)
3933     error (_("Dwarf Error: wrong version in compilation unit header "
3934            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3935            filename);
3936
3937   if (header->abbrev_offset.sect_off
3938       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3939     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3940            "(offset 0x%lx + 6) [in module %s]"),
3941            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3942            filename);
3943
3944   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3945      avoid potential 32-bit overflow.  */
3946   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3947       > section->size)
3948     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3949            "(offset 0x%lx + 0) [in module %s]"),
3950            (long) header->length, (long) header->offset.sect_off,
3951            filename);
3952 }
3953
3954 /* Read in a CU/TU header and perform some basic error checking.
3955    The contents of the header are stored in HEADER.
3956    The result is a pointer to the start of the first DIE.  */
3957
3958 static gdb_byte *
3959 read_and_check_comp_unit_head (struct comp_unit_head *header,
3960                                struct dwarf2_section_info *section,
3961                                struct dwarf2_section_info *abbrev_section,
3962                                gdb_byte *info_ptr,
3963                                int is_debug_types_section)
3964 {
3965   gdb_byte *beg_of_comp_unit = info_ptr;
3966   bfd *abfd = section->asection->owner;
3967
3968   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3969
3970   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3971
3972   /* If we're reading a type unit, skip over the signature and
3973      type_offset fields.  */
3974   if (is_debug_types_section)
3975     info_ptr += 8 /*signature*/ + header->offset_size;
3976
3977   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
3978
3979   error_check_comp_unit_head (header, section, abbrev_section);
3980
3981   return info_ptr;
3982 }
3983
3984 /* Read in the types comp unit header information from .debug_types entry at
3985    types_ptr.  The result is a pointer to one past the end of the header.  */
3986
3987 static gdb_byte *
3988 read_and_check_type_unit_head (struct comp_unit_head *header,
3989                                struct dwarf2_section_info *section,
3990                                struct dwarf2_section_info *abbrev_section,
3991                                gdb_byte *info_ptr,
3992                                ULONGEST *signature,
3993                                cu_offset *type_offset_in_tu)
3994 {
3995   gdb_byte *beg_of_comp_unit = info_ptr;
3996   bfd *abfd = section->asection->owner;
3997
3998   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3999
4000   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4001
4002   /* If we're reading a type unit, skip over the signature and
4003      type_offset fields.  */
4004   if (signature != NULL)
4005     *signature = read_8_bytes (abfd, info_ptr);
4006   info_ptr += 8;
4007   if (type_offset_in_tu != NULL)
4008     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4009                                                header->offset_size);
4010   info_ptr += header->offset_size;
4011
4012   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4013
4014   error_check_comp_unit_head (header, section, abbrev_section);
4015
4016   return info_ptr;
4017 }
4018
4019 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4020
4021 static sect_offset
4022 read_abbrev_offset (struct dwarf2_section_info *section,
4023                     sect_offset offset)
4024 {
4025   bfd *abfd = section->asection->owner;
4026   gdb_byte *info_ptr;
4027   unsigned int length, initial_length_size, offset_size;
4028   sect_offset abbrev_offset;
4029
4030   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4031   info_ptr = section->buffer + offset.sect_off;
4032   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4033   offset_size = initial_length_size == 4 ? 4 : 8;
4034   info_ptr += initial_length_size + 2 /*version*/;
4035   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4036   return abbrev_offset;
4037 }
4038
4039 /* Allocate a new partial symtab for file named NAME and mark this new
4040    partial symtab as being an include of PST.  */
4041
4042 static void
4043 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
4044                                struct objfile *objfile)
4045 {
4046   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4047
4048   subpst->section_offsets = pst->section_offsets;
4049   subpst->textlow = 0;
4050   subpst->texthigh = 0;
4051
4052   subpst->dependencies = (struct partial_symtab **)
4053     obstack_alloc (&objfile->objfile_obstack,
4054                    sizeof (struct partial_symtab *));
4055   subpst->dependencies[0] = pst;
4056   subpst->number_of_dependencies = 1;
4057
4058   subpst->globals_offset = 0;
4059   subpst->n_global_syms = 0;
4060   subpst->statics_offset = 0;
4061   subpst->n_static_syms = 0;
4062   subpst->symtab = NULL;
4063   subpst->read_symtab = pst->read_symtab;
4064   subpst->readin = 0;
4065
4066   /* No private part is necessary for include psymtabs.  This property
4067      can be used to differentiate between such include psymtabs and
4068      the regular ones.  */
4069   subpst->read_symtab_private = NULL;
4070 }
4071
4072 /* Read the Line Number Program data and extract the list of files
4073    included by the source file represented by PST.  Build an include
4074    partial symtab for each of these included files.  */
4075
4076 static void
4077 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4078                                struct die_info *die,
4079                                struct partial_symtab *pst)
4080 {
4081   struct line_header *lh = NULL;
4082   struct attribute *attr;
4083
4084   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4085   if (attr)
4086     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4087   if (lh == NULL)
4088     return;  /* No linetable, so no includes.  */
4089
4090   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4091   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4092
4093   free_line_header (lh);
4094 }
4095
4096 static hashval_t
4097 hash_signatured_type (const void *item)
4098 {
4099   const struct signatured_type *sig_type = item;
4100
4101   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4102   return sig_type->signature;
4103 }
4104
4105 static int
4106 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4107 {
4108   const struct signatured_type *lhs = item_lhs;
4109   const struct signatured_type *rhs = item_rhs;
4110
4111   return lhs->signature == rhs->signature;
4112 }
4113
4114 /* Allocate a hash table for signatured types.  */
4115
4116 static htab_t
4117 allocate_signatured_type_table (struct objfile *objfile)
4118 {
4119   return htab_create_alloc_ex (41,
4120                                hash_signatured_type,
4121                                eq_signatured_type,
4122                                NULL,
4123                                &objfile->objfile_obstack,
4124                                hashtab_obstack_allocate,
4125                                dummy_obstack_deallocate);
4126 }
4127
4128 /* A helper function to add a signatured type CU to a table.  */
4129
4130 static int
4131 add_signatured_type_cu_to_table (void **slot, void *datum)
4132 {
4133   struct signatured_type *sigt = *slot;
4134   struct signatured_type ***datap = datum;
4135
4136   **datap = sigt;
4137   ++*datap;
4138
4139   return 1;
4140 }
4141
4142 /* Create the hash table of all entries in the .debug_types section.
4143    DWO_FILE is a pointer to the DWO file for .debug_types.dwo,
4144    NULL otherwise.
4145    Note: This function processes DWO files only, not DWP files.
4146    The result is a pointer to the hash table or NULL if there are
4147    no types.  */
4148
4149 static htab_t
4150 create_debug_types_hash_table (struct dwo_file *dwo_file,
4151                                VEC (dwarf2_section_info_def) *types)
4152 {
4153   struct objfile *objfile = dwarf2_per_objfile->objfile;
4154   htab_t types_htab = NULL;
4155   int ix;
4156   struct dwarf2_section_info *section;
4157   struct dwarf2_section_info *abbrev_section;
4158
4159   if (VEC_empty (dwarf2_section_info_def, types))
4160     return NULL;
4161
4162   abbrev_section = (dwo_file != NULL
4163                     ? &dwo_file->sections.abbrev
4164                     : &dwarf2_per_objfile->abbrev);
4165
4166   if (dwarf2_read_debug)
4167     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4168                         dwo_file ? ".dwo" : "",
4169                         bfd_get_filename (abbrev_section->asection->owner));
4170
4171   for (ix = 0;
4172        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4173        ++ix)
4174     {
4175       bfd *abfd;
4176       gdb_byte *info_ptr, *end_ptr;
4177       struct dwarf2_section_info *abbrev_section;
4178
4179       dwarf2_read_section (objfile, section);
4180       info_ptr = section->buffer;
4181
4182       if (info_ptr == NULL)
4183         continue;
4184
4185       /* We can't set abfd until now because the section may be empty or
4186          not present, in which case section->asection will be NULL.  */
4187       abfd = section->asection->owner;
4188
4189       if (dwo_file)
4190         abbrev_section = &dwo_file->sections.abbrev;
4191       else
4192         abbrev_section = &dwarf2_per_objfile->abbrev;
4193
4194       if (types_htab == NULL)
4195         {
4196           if (dwo_file)
4197             types_htab = allocate_dwo_unit_table (objfile);
4198           else
4199             types_htab = allocate_signatured_type_table (objfile);
4200         }
4201
4202       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4203          because we don't need to read any dies: the signature is in the
4204          header.  */
4205
4206       end_ptr = info_ptr + section->size;
4207       while (info_ptr < end_ptr)
4208         {
4209           sect_offset offset;
4210           cu_offset type_offset_in_tu;
4211           ULONGEST signature;
4212           struct signatured_type *sig_type;
4213           struct dwo_unit *dwo_tu;
4214           void **slot;
4215           gdb_byte *ptr = info_ptr;
4216           struct comp_unit_head header;
4217           unsigned int length;
4218
4219           offset.sect_off = ptr - section->buffer;
4220
4221           /* We need to read the type's signature in order to build the hash
4222              table, but we don't need anything else just yet.  */
4223
4224           ptr = read_and_check_type_unit_head (&header, section,
4225                                                abbrev_section, ptr,
4226                                                &signature, &type_offset_in_tu);
4227
4228           length = get_cu_length (&header);
4229
4230           /* Skip dummy type units.  */
4231           if (ptr >= info_ptr + length
4232               || peek_abbrev_code (abfd, ptr) == 0)
4233             {
4234               info_ptr += length;
4235               continue;
4236             }
4237
4238           if (dwo_file)
4239             {
4240               sig_type = NULL;
4241               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4242                                        struct dwo_unit);
4243               dwo_tu->dwo_file = dwo_file;
4244               dwo_tu->signature = signature;
4245               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4246               dwo_tu->info_or_types_section = section;
4247               dwo_tu->offset = offset;
4248               dwo_tu->length = length;
4249             }
4250           else
4251             {
4252               /* N.B.: type_offset is not usable if this type uses a DWO file.
4253                  The real type_offset is in the DWO file.  */
4254               dwo_tu = NULL;
4255               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4256                                          struct signatured_type);
4257               sig_type->signature = signature;
4258               sig_type->type_offset_in_tu = type_offset_in_tu;
4259               sig_type->per_cu.objfile = objfile;
4260               sig_type->per_cu.is_debug_types = 1;
4261               sig_type->per_cu.info_or_types_section = section;
4262               sig_type->per_cu.offset = offset;
4263               sig_type->per_cu.length = length;
4264             }
4265
4266           slot = htab_find_slot (types_htab,
4267                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4268                                  INSERT);
4269           gdb_assert (slot != NULL);
4270           if (*slot != NULL)
4271             {
4272               sect_offset dup_offset;
4273
4274               if (dwo_file)
4275                 {
4276                   const struct dwo_unit *dup_tu = *slot;
4277
4278                   dup_offset = dup_tu->offset;
4279                 }
4280               else
4281                 {
4282                   const struct signatured_type *dup_tu = *slot;
4283
4284                   dup_offset = dup_tu->per_cu.offset;
4285                 }
4286
4287               complaint (&symfile_complaints,
4288                          _("debug type entry at offset 0x%x is duplicate to the "
4289                            "entry at offset 0x%x, signature 0x%s"),
4290                          offset.sect_off, dup_offset.sect_off,
4291                          phex (signature, sizeof (signature)));
4292             }
4293           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4294
4295           if (dwarf2_read_debug)
4296             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4297                                 offset.sect_off,
4298                                 phex (signature, sizeof (signature)));
4299
4300           info_ptr += length;
4301         }
4302     }
4303
4304   return types_htab;
4305 }
4306
4307 /* Create the hash table of all entries in the .debug_types section,
4308    and initialize all_type_units.
4309    The result is zero if there is an error (e.g. missing .debug_types section),
4310    otherwise non-zero.  */
4311
4312 static int
4313 create_all_type_units (struct objfile *objfile)
4314 {
4315   htab_t types_htab;
4316   struct signatured_type **iter;
4317
4318   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4319   if (types_htab == NULL)
4320     {
4321       dwarf2_per_objfile->signatured_types = NULL;
4322       return 0;
4323     }
4324
4325   dwarf2_per_objfile->signatured_types = types_htab;
4326
4327   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4328   dwarf2_per_objfile->all_type_units
4329     = obstack_alloc (&objfile->objfile_obstack,
4330                      dwarf2_per_objfile->n_type_units
4331                      * sizeof (struct signatured_type *));
4332   iter = &dwarf2_per_objfile->all_type_units[0];
4333   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4334   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4335               == dwarf2_per_objfile->n_type_units);
4336
4337   return 1;
4338 }
4339
4340 /* Lookup a signature based type for DW_FORM_ref_sig8.
4341    Returns NULL if signature SIG is not present in the table.  */
4342
4343 static struct signatured_type *
4344 lookup_signatured_type (ULONGEST sig)
4345 {
4346   struct signatured_type find_entry, *entry;
4347
4348   if (dwarf2_per_objfile->signatured_types == NULL)
4349     {
4350       complaint (&symfile_complaints,
4351                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4352       return NULL;
4353     }
4354
4355   find_entry.signature = sig;
4356   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4357   return entry;
4358 }
4359 \f
4360 /* Low level DIE reading support.  */
4361
4362 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4363
4364 static void
4365 init_cu_die_reader (struct die_reader_specs *reader,
4366                     struct dwarf2_cu *cu,
4367                     struct dwarf2_section_info *section,
4368                     struct dwo_file *dwo_file)
4369 {
4370   gdb_assert (section->readin && section->buffer != NULL);
4371   reader->abfd = section->asection->owner;
4372   reader->cu = cu;
4373   reader->dwo_file = dwo_file;
4374   reader->die_section = section;
4375   reader->buffer = section->buffer;
4376   reader->buffer_end = section->buffer + section->size;
4377 }
4378
4379 /* Initialize a CU (or TU) and read its DIEs.
4380    If the CU defers to a DWO file, read the DWO file as well.
4381
4382    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4383    Otherwise the table specified in the comp unit header is read in and used.
4384    This is an optimization for when we already have the abbrev table.
4385
4386    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4387    Otherwise, a new CU is allocated with xmalloc.
4388
4389    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4390    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4391
4392    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4393    linker) then DIE_READER_FUNC will not get called.  */
4394
4395 static void
4396 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4397                          struct abbrev_table *abbrev_table,
4398                          int use_existing_cu, int keep,
4399                          die_reader_func_ftype *die_reader_func,
4400                          void *data)
4401 {
4402   struct objfile *objfile = dwarf2_per_objfile->objfile;
4403   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4404   bfd *abfd = section->asection->owner;
4405   struct dwarf2_cu *cu;
4406   gdb_byte *begin_info_ptr, *info_ptr;
4407   struct die_reader_specs reader;
4408   struct die_info *comp_unit_die;
4409   int has_children;
4410   struct attribute *attr;
4411   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4412   struct signatured_type *sig_type = NULL;
4413   struct dwarf2_section_info *abbrev_section;
4414   /* Non-zero if CU currently points to a DWO file and we need to
4415      reread it.  When this happens we need to reread the skeleton die
4416      before we can reread the DWO file.  */
4417   int rereading_dwo_cu = 0;
4418
4419   if (dwarf2_die_debug)
4420     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4421                         this_cu->is_debug_types ? "type" : "comp",
4422                         this_cu->offset.sect_off);
4423
4424   if (use_existing_cu)
4425     gdb_assert (keep);
4426
4427   cleanups = make_cleanup (null_cleanup, NULL);
4428
4429   /* This is cheap if the section is already read in.  */
4430   dwarf2_read_section (objfile, section);
4431
4432   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4433
4434   abbrev_section = get_abbrev_section_for_cu (this_cu);
4435
4436   if (use_existing_cu && this_cu->cu != NULL)
4437     {
4438       cu = this_cu->cu;
4439
4440       /* If this CU is from a DWO file we need to start over, we need to
4441          refetch the attributes from the skeleton CU.
4442          This could be optimized by retrieving those attributes from when we
4443          were here the first time: the previous comp_unit_die was stored in
4444          comp_unit_obstack.  But there's no data yet that we need this
4445          optimization.  */
4446       if (cu->dwo_unit != NULL)
4447         rereading_dwo_cu = 1;
4448     }
4449   else
4450     {
4451       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4452       gdb_assert (this_cu->cu == NULL);
4453
4454       cu = xmalloc (sizeof (*cu));
4455       init_one_comp_unit (cu, this_cu);
4456
4457       /* If an error occurs while loading, release our storage.  */
4458       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4459     }
4460
4461   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4462     {
4463       /* We already have the header, there's no need to read it in again.  */
4464       info_ptr += cu->header.first_die_offset.cu_off;
4465     }
4466   else
4467     {
4468       if (this_cu->is_debug_types)
4469         {
4470           ULONGEST signature;
4471           cu_offset type_offset_in_tu;
4472
4473           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4474                                                     abbrev_section, info_ptr,
4475                                                     &signature,
4476                                                     &type_offset_in_tu);
4477
4478           /* Since per_cu is the first member of struct signatured_type,
4479              we can go from a pointer to one to a pointer to the other.  */
4480           sig_type = (struct signatured_type *) this_cu;
4481           gdb_assert (sig_type->signature == signature);
4482           gdb_assert (sig_type->type_offset_in_tu.cu_off
4483                       == type_offset_in_tu.cu_off);
4484           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4485
4486           /* LENGTH has not been set yet for type units if we're
4487              using .gdb_index.  */
4488           this_cu->length = get_cu_length (&cu->header);
4489
4490           /* Establish the type offset that can be used to lookup the type.  */
4491           sig_type->type_offset_in_section.sect_off =
4492             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4493         }
4494       else
4495         {
4496           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4497                                                     abbrev_section,
4498                                                     info_ptr, 0);
4499
4500           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4501           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4502         }
4503     }
4504
4505   /* Skip dummy compilation units.  */
4506   if (info_ptr >= begin_info_ptr + this_cu->length
4507       || peek_abbrev_code (abfd, info_ptr) == 0)
4508     {
4509       do_cleanups (cleanups);
4510       return;
4511     }
4512
4513   /* If we don't have them yet, read the abbrevs for this compilation unit.
4514      And if we need to read them now, make sure they're freed when we're
4515      done.  Note that it's important that if the CU had an abbrev table
4516      on entry we don't free it when we're done: Somewhere up the call stack
4517      it may be in use.  */
4518   if (abbrev_table != NULL)
4519     {
4520       gdb_assert (cu->abbrev_table == NULL);
4521       gdb_assert (cu->header.abbrev_offset.sect_off
4522                   == abbrev_table->offset.sect_off);
4523       cu->abbrev_table = abbrev_table;
4524     }
4525   else if (cu->abbrev_table == NULL)
4526     {
4527       dwarf2_read_abbrevs (cu, abbrev_section);
4528       make_cleanup (dwarf2_free_abbrev_table, cu);
4529     }
4530   else if (rereading_dwo_cu)
4531     {
4532       dwarf2_free_abbrev_table (cu);
4533       dwarf2_read_abbrevs (cu, abbrev_section);
4534     }
4535
4536   /* Read the top level CU/TU die.  */
4537   init_cu_die_reader (&reader, cu, section, NULL);
4538   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4539
4540   /* If we have a DWO stub, process it and then read in the DWO file.
4541      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4542      a DWO CU, that this test will fail.  */
4543   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4544   if (attr)
4545     {
4546       const char *dwo_name = DW_STRING (attr);
4547       const char *comp_dir_string;
4548       struct dwo_unit *dwo_unit;
4549       ULONGEST signature; /* Or dwo_id.  */
4550       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4551       int i,num_extra_attrs;
4552       struct dwarf2_section_info *dwo_abbrev_section;
4553
4554       if (has_children)
4555         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4556                  " has children (offset 0x%x) [in module %s]"),
4557                this_cu->offset.sect_off, bfd_get_filename (abfd));
4558
4559       /* These attributes aren't processed until later:
4560          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4561          However, the attribute is found in the stub which we won't have later.
4562          In order to not impose this complication on the rest of the code,
4563          we read them here and copy them to the DWO CU/TU die.  */
4564
4565       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4566          DWO file.  */
4567       stmt_list = NULL;
4568       if (! this_cu->is_debug_types)
4569         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4570       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4571       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4572       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4573       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4574
4575       /* There should be a DW_AT_addr_base attribute here (if needed).
4576          We need the value before we can process DW_FORM_GNU_addr_index.  */
4577       cu->addr_base = 0;
4578       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4579       if (attr)
4580         cu->addr_base = DW_UNSND (attr);
4581
4582       /* There should be a DW_AT_ranges_base attribute here (if needed).
4583          We need the value before we can process DW_AT_ranges.  */
4584       cu->ranges_base = 0;
4585       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4586       if (attr)
4587         cu->ranges_base = DW_UNSND (attr);
4588
4589       if (this_cu->is_debug_types)
4590         {
4591           gdb_assert (sig_type != NULL);
4592           signature = sig_type->signature;
4593         }
4594       else
4595         {
4596           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4597           if (! attr)
4598             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4599                    dwo_name);
4600           signature = DW_UNSND (attr);
4601         }
4602
4603       /* We may need the comp_dir in order to find the DWO file.  */
4604       comp_dir_string = NULL;
4605       if (comp_dir)
4606         comp_dir_string = DW_STRING (comp_dir);
4607
4608       if (this_cu->is_debug_types)
4609         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4610       else
4611         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4612                                          signature);
4613
4614       if (dwo_unit == NULL)
4615         {
4616           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4617                    " with ID %s [in module %s]"),
4618                  this_cu->offset.sect_off,
4619                  phex (signature, sizeof (signature)),
4620                  objfile->name);
4621         }
4622
4623       /* Set up for reading the DWO CU/TU.  */
4624       cu->dwo_unit = dwo_unit;
4625       section = dwo_unit->info_or_types_section;
4626       dwarf2_read_section (objfile, section);
4627       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4628       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4629       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4630
4631       if (this_cu->is_debug_types)
4632         {
4633           ULONGEST signature;
4634           cu_offset type_offset_in_tu;
4635
4636           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4637                                                     dwo_abbrev_section,
4638                                                     info_ptr,
4639                                                     &signature,
4640                                                     &type_offset_in_tu);
4641           gdb_assert (sig_type->signature == signature);
4642           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4643           /* For DWOs coming from DWP files, we don't know the CU length
4644              nor the type's offset in the TU until now.  */
4645           dwo_unit->length = get_cu_length (&cu->header);
4646           dwo_unit->type_offset_in_tu = type_offset_in_tu;
4647
4648           /* Establish the type offset that can be used to lookup the type.
4649              For DWO files, we don't know it until now.  */
4650           sig_type->type_offset_in_section.sect_off =
4651             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4652         }
4653       else
4654         {
4655           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4656                                                     dwo_abbrev_section,
4657                                                     info_ptr, 0);
4658           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4659           /* For DWOs coming from DWP files, we don't know the CU length
4660              until now.  */
4661           dwo_unit->length = get_cu_length (&cu->header);
4662         }
4663
4664       /* Discard the original CU's abbrev table, and read the DWO's.  */
4665       if (abbrev_table == NULL)
4666         {
4667           dwarf2_free_abbrev_table (cu);
4668           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4669         }
4670       else
4671         {
4672           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4673           make_cleanup (dwarf2_free_abbrev_table, cu);
4674         }
4675
4676       /* Read in the die, but leave space to copy over the attributes
4677          from the stub.  This has the benefit of simplifying the rest of
4678          the code - all the real work is done here.  */
4679       num_extra_attrs = ((stmt_list != NULL)
4680                          + (low_pc != NULL)
4681                          + (high_pc != NULL)
4682                          + (ranges != NULL)
4683                          + (comp_dir != NULL));
4684       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4685                                   &has_children, num_extra_attrs);
4686
4687       /* Copy over the attributes from the stub to the DWO die.  */
4688       i = comp_unit_die->num_attrs;
4689       if (stmt_list != NULL)
4690         comp_unit_die->attrs[i++] = *stmt_list;
4691       if (low_pc != NULL)
4692         comp_unit_die->attrs[i++] = *low_pc;
4693       if (high_pc != NULL)
4694         comp_unit_die->attrs[i++] = *high_pc;
4695       if (ranges != NULL)
4696         comp_unit_die->attrs[i++] = *ranges;
4697       if (comp_dir != NULL)
4698         comp_unit_die->attrs[i++] = *comp_dir;
4699       comp_unit_die->num_attrs += num_extra_attrs;
4700
4701       /* Skip dummy compilation units.  */
4702       if (info_ptr >= begin_info_ptr + dwo_unit->length
4703           || peek_abbrev_code (abfd, info_ptr) == 0)
4704         {
4705           do_cleanups (cleanups);
4706           return;
4707         }
4708     }
4709
4710   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4711
4712   if (free_cu_cleanup != NULL)
4713     {
4714       if (keep)
4715         {
4716           /* We've successfully allocated this compilation unit.  Let our
4717              caller clean it up when finished with it.  */
4718           discard_cleanups (free_cu_cleanup);
4719
4720           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4721              So we have to manually free the abbrev table.  */
4722           dwarf2_free_abbrev_table (cu);
4723
4724           /* Link this CU into read_in_chain.  */
4725           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4726           dwarf2_per_objfile->read_in_chain = this_cu;
4727         }
4728       else
4729         do_cleanups (free_cu_cleanup);
4730     }
4731
4732   do_cleanups (cleanups);
4733 }
4734
4735 /* Read CU/TU THIS_CU in section SECTION,
4736    but do not follow DW_AT_GNU_dwo_name if present.
4737    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4738    to have already done the lookup to find the DWO/DWP file).
4739
4740    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4741    THIS_CU->is_debug_types, but nothing else.
4742
4743    We fill in THIS_CU->length.
4744
4745    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4746    linker) then DIE_READER_FUNC will not get called.
4747
4748    THIS_CU->cu is always freed when done.
4749    This is done in order to not leave THIS_CU->cu in a state where we have
4750    to care whether it refers to the "main" CU or the DWO CU.  */
4751
4752 static void
4753 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4754                                    struct dwarf2_section_info *abbrev_section,
4755                                    struct dwo_file *dwo_file,
4756                                    die_reader_func_ftype *die_reader_func,
4757                                    void *data)
4758 {
4759   struct objfile *objfile = dwarf2_per_objfile->objfile;
4760   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4761   bfd *abfd = section->asection->owner;
4762   struct dwarf2_cu cu;
4763   gdb_byte *begin_info_ptr, *info_ptr;
4764   struct die_reader_specs reader;
4765   struct cleanup *cleanups;
4766   struct die_info *comp_unit_die;
4767   int has_children;
4768
4769   if (dwarf2_die_debug)
4770     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4771                         this_cu->is_debug_types ? "type" : "comp",
4772                         this_cu->offset.sect_off);
4773
4774   gdb_assert (this_cu->cu == NULL);
4775
4776   /* This is cheap if the section is already read in.  */
4777   dwarf2_read_section (objfile, section);
4778
4779   init_one_comp_unit (&cu, this_cu);
4780
4781   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4782
4783   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4784   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4785                                             abbrev_section, info_ptr,
4786                                             this_cu->is_debug_types);
4787
4788   this_cu->length = get_cu_length (&cu.header);
4789
4790   /* Skip dummy compilation units.  */
4791   if (info_ptr >= begin_info_ptr + this_cu->length
4792       || peek_abbrev_code (abfd, info_ptr) == 0)
4793     {
4794       do_cleanups (cleanups);
4795       return;
4796     }
4797
4798   dwarf2_read_abbrevs (&cu, abbrev_section);
4799   make_cleanup (dwarf2_free_abbrev_table, &cu);
4800
4801   init_cu_die_reader (&reader, &cu, section, dwo_file);
4802   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4803
4804   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4805
4806   do_cleanups (cleanups);
4807 }
4808
4809 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4810    does not lookup the specified DWO file.
4811    This cannot be used to read DWO files.
4812
4813    THIS_CU->cu is always freed when done.
4814    This is done in order to not leave THIS_CU->cu in a state where we have
4815    to care whether it refers to the "main" CU or the DWO CU.
4816    We can revisit this if the data shows there's a performance issue.  */
4817
4818 static void
4819 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4820                                 die_reader_func_ftype *die_reader_func,
4821                                 void *data)
4822 {
4823   init_cutu_and_read_dies_no_follow (this_cu,
4824                                      get_abbrev_section_for_cu (this_cu),
4825                                      NULL,
4826                                      die_reader_func, data);
4827 }
4828
4829 /* Create a psymtab named NAME and assign it to PER_CU.
4830
4831    The caller must fill in the following details:
4832    dirname, textlow, texthigh.  */
4833
4834 static struct partial_symtab *
4835 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4836 {
4837   struct objfile *objfile = per_cu->objfile;
4838   struct partial_symtab *pst;
4839
4840   pst = start_psymtab_common (objfile, objfile->section_offsets,
4841                               name, 0,
4842                               objfile->global_psymbols.next,
4843                               objfile->static_psymbols.next);
4844
4845   pst->psymtabs_addrmap_supported = 1;
4846
4847   /* This is the glue that links PST into GDB's symbol API.  */
4848   pst->read_symtab_private = per_cu;
4849   pst->read_symtab = dwarf2_read_symtab;
4850   per_cu->v.psymtab = pst;
4851
4852   return pst;
4853 }
4854
4855 /* die_reader_func for process_psymtab_comp_unit.  */
4856
4857 static void
4858 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4859                                   gdb_byte *info_ptr,
4860                                   struct die_info *comp_unit_die,
4861                                   int has_children,
4862                                   void *data)
4863 {
4864   struct dwarf2_cu *cu = reader->cu;
4865   struct objfile *objfile = cu->objfile;
4866   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4867   struct attribute *attr;
4868   CORE_ADDR baseaddr;
4869   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4870   struct partial_symtab *pst;
4871   int has_pc_info;
4872   const char *filename;
4873   int *want_partial_unit_ptr = data;
4874
4875   if (comp_unit_die->tag == DW_TAG_partial_unit
4876       && (want_partial_unit_ptr == NULL
4877           || !*want_partial_unit_ptr))
4878     return;
4879
4880   gdb_assert (! per_cu->is_debug_types);
4881
4882   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4883
4884   cu->list_in_scope = &file_symbols;
4885
4886   /* Allocate a new partial symbol table structure.  */
4887   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4888   if (attr == NULL || !DW_STRING (attr))
4889     filename = "";
4890   else
4891     filename = DW_STRING (attr);
4892
4893   pst = create_partial_symtab (per_cu, filename);
4894
4895   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4896   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4897   if (attr != NULL)
4898     pst->dirname = DW_STRING (attr);
4899
4900   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4901
4902   dwarf2_find_base_address (comp_unit_die, cu);
4903
4904   /* Possibly set the default values of LOWPC and HIGHPC from
4905      `DW_AT_ranges'.  */
4906   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4907                                       &best_highpc, cu, pst);
4908   if (has_pc_info == 1 && best_lowpc < best_highpc)
4909     /* Store the contiguous range if it is not empty; it can be empty for
4910        CUs with no code.  */
4911     addrmap_set_empty (objfile->psymtabs_addrmap,
4912                        best_lowpc + baseaddr,
4913                        best_highpc + baseaddr - 1, pst);
4914
4915   /* Check if comp unit has_children.
4916      If so, read the rest of the partial symbols from this comp unit.
4917      If not, there's no more debug_info for this comp unit.  */
4918   if (has_children)
4919     {
4920       struct partial_die_info *first_die;
4921       CORE_ADDR lowpc, highpc;
4922
4923       lowpc = ((CORE_ADDR) -1);
4924       highpc = ((CORE_ADDR) 0);
4925
4926       first_die = load_partial_dies (reader, info_ptr, 1);
4927
4928       scan_partial_symbols (first_die, &lowpc, &highpc,
4929                             ! has_pc_info, cu);
4930
4931       /* If we didn't find a lowpc, set it to highpc to avoid
4932          complaints from `maint check'.  */
4933       if (lowpc == ((CORE_ADDR) -1))
4934         lowpc = highpc;
4935
4936       /* If the compilation unit didn't have an explicit address range,
4937          then use the information extracted from its child dies.  */
4938       if (! has_pc_info)
4939         {
4940           best_lowpc = lowpc;
4941           best_highpc = highpc;
4942         }
4943     }
4944   pst->textlow = best_lowpc + baseaddr;
4945   pst->texthigh = best_highpc + baseaddr;
4946
4947   pst->n_global_syms = objfile->global_psymbols.next -
4948     (objfile->global_psymbols.list + pst->globals_offset);
4949   pst->n_static_syms = objfile->static_psymbols.next -
4950     (objfile->static_psymbols.list + pst->statics_offset);
4951   sort_pst_symbols (objfile, pst);
4952
4953   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
4954     {
4955       int i;
4956       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4957       struct dwarf2_per_cu_data *iter;
4958
4959       /* Fill in 'dependencies' here; we fill in 'users' in a
4960          post-pass.  */
4961       pst->number_of_dependencies = len;
4962       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
4963                                          len * sizeof (struct symtab *));
4964       for (i = 0;
4965            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
4966                         i, iter);
4967            ++i)
4968         pst->dependencies[i] = iter->v.psymtab;
4969
4970       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
4971     }
4972
4973   /* Get the list of files included in the current compilation unit,
4974      and build a psymtab for each of them.  */
4975   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
4976
4977   if (dwarf2_read_debug)
4978     {
4979       struct gdbarch *gdbarch = get_objfile_arch (objfile);
4980
4981       fprintf_unfiltered (gdb_stdlog,
4982                           "Psymtab for %s unit @0x%x: %s - %s"
4983                           ", %d global, %d static syms\n",
4984                           per_cu->is_debug_types ? "type" : "comp",
4985                           per_cu->offset.sect_off,
4986                           paddress (gdbarch, pst->textlow),
4987                           paddress (gdbarch, pst->texthigh),
4988                           pst->n_global_syms, pst->n_static_syms);
4989     }
4990 }
4991
4992 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
4993    Process compilation unit THIS_CU for a psymtab.  */
4994
4995 static void
4996 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
4997                            int want_partial_unit)
4998 {
4999   /* If this compilation unit was already read in, free the
5000      cached copy in order to read it in again.  This is
5001      necessary because we skipped some symbols when we first
5002      read in the compilation unit (see load_partial_dies).
5003      This problem could be avoided, but the benefit is unclear.  */
5004   if (this_cu->cu != NULL)
5005     free_one_cached_comp_unit (this_cu);
5006
5007   gdb_assert (! this_cu->is_debug_types);
5008   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5009                            process_psymtab_comp_unit_reader,
5010                            &want_partial_unit);
5011
5012   /* Age out any secondary CUs.  */
5013   age_cached_comp_units ();
5014 }
5015
5016 static hashval_t
5017 hash_type_unit_group (const void *item)
5018 {
5019   const struct type_unit_group *tu_group = item;
5020
5021   return hash_stmt_list_entry (&tu_group->hash);
5022 }
5023
5024 static int
5025 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5026 {
5027   const struct type_unit_group *lhs = item_lhs;
5028   const struct type_unit_group *rhs = item_rhs;
5029
5030   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5031 }
5032
5033 /* Allocate a hash table for type unit groups.  */
5034
5035 static htab_t
5036 allocate_type_unit_groups_table (void)
5037 {
5038   return htab_create_alloc_ex (3,
5039                                hash_type_unit_group,
5040                                eq_type_unit_group,
5041                                NULL,
5042                                &dwarf2_per_objfile->objfile->objfile_obstack,
5043                                hashtab_obstack_allocate,
5044                                dummy_obstack_deallocate);
5045 }
5046
5047 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5048    partial symtabs.  We combine several TUs per psymtab to not let the size
5049    of any one psymtab grow too big.  */
5050 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5051 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5052
5053 /* Helper routine for get_type_unit_group.
5054    Create the type_unit_group object used to hold one or more TUs.  */
5055
5056 static struct type_unit_group *
5057 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5058 {
5059   struct objfile *objfile = dwarf2_per_objfile->objfile;
5060   struct dwarf2_per_cu_data *per_cu;
5061   struct type_unit_group *tu_group;
5062
5063   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5064                              struct type_unit_group);
5065   per_cu = &tu_group->per_cu;
5066   per_cu->objfile = objfile;
5067   per_cu->is_debug_types = 1;
5068   per_cu->type_unit_group = tu_group;
5069
5070   if (dwarf2_per_objfile->using_index)
5071     {
5072       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5073                                         struct dwarf2_per_cu_quick_data);
5074       tu_group->t.first_tu = cu->per_cu;
5075     }
5076   else
5077     {
5078       unsigned int line_offset = line_offset_struct.sect_off;
5079       struct partial_symtab *pst;
5080       char *name;
5081
5082       /* Give the symtab a useful name for debug purposes.  */
5083       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5084         name = xstrprintf ("<type_units_%d>",
5085                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5086       else
5087         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5088
5089       pst = create_partial_symtab (per_cu, name);
5090       pst->anonymous = 1;
5091
5092       xfree (name);
5093     }
5094
5095   tu_group->hash.dwo_unit = cu->dwo_unit;
5096   tu_group->hash.line_offset = line_offset_struct;
5097
5098   return tu_group;
5099 }
5100
5101 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5102    STMT_LIST is a DW_AT_stmt_list attribute.  */
5103
5104 static struct type_unit_group *
5105 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5106 {
5107   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5108   struct type_unit_group *tu_group;
5109   void **slot;
5110   unsigned int line_offset;
5111   struct type_unit_group type_unit_group_for_lookup;
5112
5113   if (dwarf2_per_objfile->type_unit_groups == NULL)
5114     {
5115       dwarf2_per_objfile->type_unit_groups =
5116         allocate_type_unit_groups_table ();
5117     }
5118
5119   /* Do we need to create a new group, or can we use an existing one?  */
5120
5121   if (stmt_list)
5122     {
5123       line_offset = DW_UNSND (stmt_list);
5124       ++tu_stats->nr_symtab_sharers;
5125     }
5126   else
5127     {
5128       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5129          We can do various things here like create one group per TU or
5130          spread them over multiple groups to split up the expansion work.
5131          To avoid worst case scenarios (too many groups or too large groups)
5132          we, umm, group them in bunches.  */
5133       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5134                      | (tu_stats->nr_stmt_less_type_units
5135                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5136       ++tu_stats->nr_stmt_less_type_units;
5137     }
5138
5139   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5140   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5141   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5142                          &type_unit_group_for_lookup, INSERT);
5143   if (*slot != NULL)
5144     {
5145       tu_group = *slot;
5146       gdb_assert (tu_group != NULL);
5147     }
5148   else
5149     {
5150       sect_offset line_offset_struct;
5151
5152       line_offset_struct.sect_off = line_offset;
5153       tu_group = create_type_unit_group (cu, line_offset_struct);
5154       *slot = tu_group;
5155       ++tu_stats->nr_symtabs;
5156     }
5157
5158   return tu_group;
5159 }
5160
5161 /* Struct used to sort TUs by their abbreviation table offset.  */
5162
5163 struct tu_abbrev_offset
5164 {
5165   struct signatured_type *sig_type;
5166   sect_offset abbrev_offset;
5167 };
5168
5169 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5170
5171 static int
5172 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5173 {
5174   const struct tu_abbrev_offset * const *a = ap;
5175   const struct tu_abbrev_offset * const *b = bp;
5176   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5177   unsigned int boff = (*b)->abbrev_offset.sect_off;
5178
5179   return (aoff > boff) - (aoff < boff);
5180 }
5181
5182 /* A helper function to add a type_unit_group to a table.  */
5183
5184 static int
5185 add_type_unit_group_to_table (void **slot, void *datum)
5186 {
5187   struct type_unit_group *tu_group = *slot;
5188   struct type_unit_group ***datap = datum;
5189
5190   **datap = tu_group;
5191   ++*datap;
5192
5193   return 1;
5194 }
5195
5196 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5197    each one passing FUNC,DATA.
5198
5199    The efficiency is because we sort TUs by the abbrev table they use and
5200    only read each abbrev table once.  In one program there are 200K TUs
5201    sharing 8K abbrev tables.
5202
5203    The main purpose of this function is to support building the
5204    dwarf2_per_objfile->type_unit_groups table.
5205    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5206    can collapse the search space by grouping them by stmt_list.
5207    The savings can be significant, in the same program from above the 200K TUs
5208    share 8K stmt_list tables.
5209
5210    FUNC is expected to call get_type_unit_group, which will create the
5211    struct type_unit_group if necessary and add it to
5212    dwarf2_per_objfile->type_unit_groups.  */
5213
5214 static void
5215 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5216 {
5217   struct objfile *objfile = dwarf2_per_objfile->objfile;
5218   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5219   struct cleanup *cleanups;
5220   struct abbrev_table *abbrev_table;
5221   sect_offset abbrev_offset;
5222   struct tu_abbrev_offset *sorted_by_abbrev;
5223   struct type_unit_group **iter;
5224   int i;
5225
5226   /* It's up to the caller to not call us multiple times.  */
5227   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5228
5229   if (dwarf2_per_objfile->n_type_units == 0)
5230     return;
5231
5232   /* TUs typically share abbrev tables, and there can be way more TUs than
5233      abbrev tables.  Sort by abbrev table to reduce the number of times we
5234      read each abbrev table in.
5235      Alternatives are to punt or to maintain a cache of abbrev tables.
5236      This is simpler and efficient enough for now.
5237
5238      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5239      symtab to use).  Typically TUs with the same abbrev offset have the same
5240      stmt_list value too so in practice this should work well.
5241
5242      The basic algorithm here is:
5243
5244       sort TUs by abbrev table
5245       for each TU with same abbrev table:
5246         read abbrev table if first user
5247         read TU top level DIE
5248           [IWBN if DWO skeletons had DW_AT_stmt_list]
5249         call FUNC  */
5250
5251   if (dwarf2_read_debug)
5252     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5253
5254   /* Sort in a separate table to maintain the order of all_type_units
5255      for .gdb_index: TU indices directly index all_type_units.  */
5256   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5257                               dwarf2_per_objfile->n_type_units);
5258   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5259     {
5260       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5261
5262       sorted_by_abbrev[i].sig_type = sig_type;
5263       sorted_by_abbrev[i].abbrev_offset =
5264         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
5265                             sig_type->per_cu.offset);
5266     }
5267   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5268   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5269          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5270
5271   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5272      called any number of times, so we don't reset tu_stats here.  */
5273
5274   abbrev_offset.sect_off = ~(unsigned) 0;
5275   abbrev_table = NULL;
5276   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5277
5278   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5279     {
5280       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5281
5282       /* Switch to the next abbrev table if necessary.  */
5283       if (abbrev_table == NULL
5284           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5285         {
5286           if (abbrev_table != NULL)
5287             {
5288               abbrev_table_free (abbrev_table);
5289               /* Reset to NULL in case abbrev_table_read_table throws
5290                  an error: abbrev_table_free_cleanup will get called.  */
5291               abbrev_table = NULL;
5292             }
5293           abbrev_offset = tu->abbrev_offset;
5294           abbrev_table =
5295             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5296                                      abbrev_offset);
5297           ++tu_stats->nr_uniq_abbrev_tables;
5298         }
5299
5300       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5301                                func, data);
5302     }
5303
5304   /* Create a vector of pointers to primary type units to make it easy to
5305      iterate over them and CUs.  See dw2_get_primary_cu.  */
5306   dwarf2_per_objfile->n_type_unit_groups =
5307     htab_elements (dwarf2_per_objfile->type_unit_groups);
5308   dwarf2_per_objfile->all_type_unit_groups =
5309     obstack_alloc (&objfile->objfile_obstack,
5310                    dwarf2_per_objfile->n_type_unit_groups
5311                    * sizeof (struct type_unit_group *));
5312   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5313   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5314                           add_type_unit_group_to_table, &iter);
5315   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5316               == dwarf2_per_objfile->n_type_unit_groups);
5317
5318   do_cleanups (cleanups);
5319
5320   if (dwarf2_read_debug)
5321     {
5322       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5323       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5324                           dwarf2_per_objfile->n_type_units);
5325       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5326                           tu_stats->nr_uniq_abbrev_tables);
5327       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5328                           tu_stats->nr_symtabs);
5329       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5330                           tu_stats->nr_symtab_sharers);
5331       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5332                           tu_stats->nr_stmt_less_type_units);
5333     }
5334 }
5335
5336 /* Reader function for build_type_psymtabs.  */
5337
5338 static void
5339 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5340                             gdb_byte *info_ptr,
5341                             struct die_info *type_unit_die,
5342                             int has_children,
5343                             void *data)
5344 {
5345   struct objfile *objfile = dwarf2_per_objfile->objfile;
5346   struct dwarf2_cu *cu = reader->cu;
5347   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5348   struct type_unit_group *tu_group;
5349   struct attribute *attr;
5350   struct partial_die_info *first_die;
5351   CORE_ADDR lowpc, highpc;
5352   struct partial_symtab *pst;
5353
5354   gdb_assert (data == NULL);
5355
5356   if (! has_children)
5357     return;
5358
5359   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5360   tu_group = get_type_unit_group (cu, attr);
5361
5362   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5363
5364   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5365   cu->list_in_scope = &file_symbols;
5366   pst = create_partial_symtab (per_cu, "");
5367   pst->anonymous = 1;
5368
5369   first_die = load_partial_dies (reader, info_ptr, 1);
5370
5371   lowpc = (CORE_ADDR) -1;
5372   highpc = (CORE_ADDR) 0;
5373   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5374
5375   pst->n_global_syms = objfile->global_psymbols.next -
5376     (objfile->global_psymbols.list + pst->globals_offset);
5377   pst->n_static_syms = objfile->static_psymbols.next -
5378     (objfile->static_psymbols.list + pst->statics_offset);
5379   sort_pst_symbols (objfile, pst);
5380 }
5381
5382 /* Traversal function for build_type_psymtabs.  */
5383
5384 static int
5385 build_type_psymtab_dependencies (void **slot, void *info)
5386 {
5387   struct objfile *objfile = dwarf2_per_objfile->objfile;
5388   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5389   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5390   struct partial_symtab *pst = per_cu->v.psymtab;
5391   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5392   struct dwarf2_per_cu_data *iter;
5393   int i;
5394
5395   gdb_assert (len > 0);
5396
5397   pst->number_of_dependencies = len;
5398   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5399                                      len * sizeof (struct psymtab *));
5400   for (i = 0;
5401        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5402        ++i)
5403     {
5404       pst->dependencies[i] = iter->v.psymtab;
5405       iter->type_unit_group = tu_group;
5406     }
5407
5408   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5409
5410   return 1;
5411 }
5412
5413 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5414    Build partial symbol tables for the .debug_types comp-units.  */
5415
5416 static void
5417 build_type_psymtabs (struct objfile *objfile)
5418 {
5419   if (! create_all_type_units (objfile))
5420     return;
5421
5422   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5423
5424   /* Now that all TUs have been processed we can fill in the dependencies.  */
5425   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5426                           build_type_psymtab_dependencies, NULL);
5427 }
5428
5429 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5430
5431 static void
5432 psymtabs_addrmap_cleanup (void *o)
5433 {
5434   struct objfile *objfile = o;
5435
5436   objfile->psymtabs_addrmap = NULL;
5437 }
5438
5439 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5440
5441 static void
5442 set_partial_user (struct objfile *objfile)
5443 {
5444   int i;
5445
5446   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5447     {
5448       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5449       struct partial_symtab *pst = per_cu->v.psymtab;
5450       int j;
5451
5452       if (pst == NULL)
5453         continue;
5454
5455       for (j = 0; j < pst->number_of_dependencies; ++j)
5456         {
5457           /* Set the 'user' field only if it is not already set.  */
5458           if (pst->dependencies[j]->user == NULL)
5459             pst->dependencies[j]->user = pst;
5460         }
5461     }
5462 }
5463
5464 /* Build the partial symbol table by doing a quick pass through the
5465    .debug_info and .debug_abbrev sections.  */
5466
5467 static void
5468 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5469 {
5470   struct cleanup *back_to, *addrmap_cleanup;
5471   struct obstack temp_obstack;
5472   int i;
5473
5474   if (dwarf2_read_debug)
5475     {
5476       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5477                           objfile->name);
5478     }
5479
5480   dwarf2_per_objfile->reading_partial_symbols = 1;
5481
5482   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5483
5484   /* Any cached compilation units will be linked by the per-objfile
5485      read_in_chain.  Make sure to free them when we're done.  */
5486   back_to = make_cleanup (free_cached_comp_units, NULL);
5487
5488   build_type_psymtabs (objfile);
5489
5490   create_all_comp_units (objfile);
5491
5492   /* Create a temporary address map on a temporary obstack.  We later
5493      copy this to the final obstack.  */
5494   obstack_init (&temp_obstack);
5495   make_cleanup_obstack_free (&temp_obstack);
5496   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5497   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5498
5499   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5500     {
5501       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5502
5503       process_psymtab_comp_unit (per_cu, 0);
5504     }
5505
5506   set_partial_user (objfile);
5507
5508   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5509                                                     &objfile->objfile_obstack);
5510   discard_cleanups (addrmap_cleanup);
5511
5512   do_cleanups (back_to);
5513
5514   if (dwarf2_read_debug)
5515     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5516                         objfile->name);
5517 }
5518
5519 /* die_reader_func for load_partial_comp_unit.  */
5520
5521 static void
5522 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5523                                gdb_byte *info_ptr,
5524                                struct die_info *comp_unit_die,
5525                                int has_children,
5526                                void *data)
5527 {
5528   struct dwarf2_cu *cu = reader->cu;
5529
5530   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5531
5532   /* Check if comp unit has_children.
5533      If so, read the rest of the partial symbols from this comp unit.
5534      If not, there's no more debug_info for this comp unit.  */
5535   if (has_children)
5536     load_partial_dies (reader, info_ptr, 0);
5537 }
5538
5539 /* Load the partial DIEs for a secondary CU into memory.
5540    This is also used when rereading a primary CU with load_all_dies.  */
5541
5542 static void
5543 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5544 {
5545   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5546                            load_partial_comp_unit_reader, NULL);
5547 }
5548
5549 static void
5550 read_comp_units_from_section (struct objfile *objfile,
5551                               struct dwarf2_section_info *section,
5552                               unsigned int is_dwz,
5553                               int *n_allocated,
5554                               int *n_comp_units,
5555                               struct dwarf2_per_cu_data ***all_comp_units)
5556 {
5557   gdb_byte *info_ptr;
5558   bfd *abfd = section->asection->owner;
5559
5560   dwarf2_read_section (objfile, section);
5561
5562   info_ptr = section->buffer;
5563
5564   while (info_ptr < section->buffer + section->size)
5565     {
5566       unsigned int length, initial_length_size;
5567       struct dwarf2_per_cu_data *this_cu;
5568       sect_offset offset;
5569
5570       offset.sect_off = info_ptr - section->buffer;
5571
5572       /* Read just enough information to find out where the next
5573          compilation unit is.  */
5574       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5575
5576       /* Save the compilation unit for later lookup.  */
5577       this_cu = obstack_alloc (&objfile->objfile_obstack,
5578                                sizeof (struct dwarf2_per_cu_data));
5579       memset (this_cu, 0, sizeof (*this_cu));
5580       this_cu->offset = offset;
5581       this_cu->length = length + initial_length_size;
5582       this_cu->is_dwz = is_dwz;
5583       this_cu->objfile = objfile;
5584       this_cu->info_or_types_section = section;
5585
5586       if (*n_comp_units == *n_allocated)
5587         {
5588           *n_allocated *= 2;
5589           *all_comp_units = xrealloc (*all_comp_units,
5590                                       *n_allocated
5591                                       * sizeof (struct dwarf2_per_cu_data *));
5592         }
5593       (*all_comp_units)[*n_comp_units] = this_cu;
5594       ++*n_comp_units;
5595
5596       info_ptr = info_ptr + this_cu->length;
5597     }
5598 }
5599
5600 /* Create a list of all compilation units in OBJFILE.
5601    This is only done for -readnow and building partial symtabs.  */
5602
5603 static void
5604 create_all_comp_units (struct objfile *objfile)
5605 {
5606   int n_allocated;
5607   int n_comp_units;
5608   struct dwarf2_per_cu_data **all_comp_units;
5609
5610   n_comp_units = 0;
5611   n_allocated = 10;
5612   all_comp_units = xmalloc (n_allocated
5613                             * sizeof (struct dwarf2_per_cu_data *));
5614
5615   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5616                                 &n_allocated, &n_comp_units, &all_comp_units);
5617
5618   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5619     {
5620       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5621
5622       read_comp_units_from_section (objfile, &dwz->info, 1,
5623                                     &n_allocated, &n_comp_units,
5624                                     &all_comp_units);
5625     }
5626
5627   dwarf2_per_objfile->all_comp_units
5628     = obstack_alloc (&objfile->objfile_obstack,
5629                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5630   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5631           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5632   xfree (all_comp_units);
5633   dwarf2_per_objfile->n_comp_units = n_comp_units;
5634 }
5635
5636 /* Process all loaded DIEs for compilation unit CU, starting at
5637    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5638    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5639    DW_AT_ranges).  If NEED_PC is set, then this function will set
5640    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5641    and record the covered ranges in the addrmap.  */
5642
5643 static void
5644 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5645                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5646 {
5647   struct partial_die_info *pdi;
5648
5649   /* Now, march along the PDI's, descending into ones which have
5650      interesting children but skipping the children of the other ones,
5651      until we reach the end of the compilation unit.  */
5652
5653   pdi = first_die;
5654
5655   while (pdi != NULL)
5656     {
5657       fixup_partial_die (pdi, cu);
5658
5659       /* Anonymous namespaces or modules have no name but have interesting
5660          children, so we need to look at them.  Ditto for anonymous
5661          enums.  */
5662
5663       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5664           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5665           || pdi->tag == DW_TAG_imported_unit)
5666         {
5667           switch (pdi->tag)
5668             {
5669             case DW_TAG_subprogram:
5670               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5671               break;
5672             case DW_TAG_constant:
5673             case DW_TAG_variable:
5674             case DW_TAG_typedef:
5675             case DW_TAG_union_type:
5676               if (!pdi->is_declaration)
5677                 {
5678                   add_partial_symbol (pdi, cu);
5679                 }
5680               break;
5681             case DW_TAG_class_type:
5682             case DW_TAG_interface_type:
5683             case DW_TAG_structure_type:
5684               if (!pdi->is_declaration)
5685                 {
5686                   add_partial_symbol (pdi, cu);
5687                 }
5688               break;
5689             case DW_TAG_enumeration_type:
5690               if (!pdi->is_declaration)
5691                 add_partial_enumeration (pdi, cu);
5692               break;
5693             case DW_TAG_base_type:
5694             case DW_TAG_subrange_type:
5695               /* File scope base type definitions are added to the partial
5696                  symbol table.  */
5697               add_partial_symbol (pdi, cu);
5698               break;
5699             case DW_TAG_namespace:
5700               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5701               break;
5702             case DW_TAG_module:
5703               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5704               break;
5705             case DW_TAG_imported_unit:
5706               {
5707                 struct dwarf2_per_cu_data *per_cu;
5708
5709                 /* For now we don't handle imported units in type units.  */
5710                 if (cu->per_cu->is_debug_types)
5711                   {
5712                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5713                              " supported in type units [in module %s]"),
5714                            cu->objfile->name);
5715                   }
5716
5717                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5718                                                            pdi->is_dwz,
5719                                                            cu->objfile);
5720
5721                 /* Go read the partial unit, if needed.  */
5722                 if (per_cu->v.psymtab == NULL)
5723                   process_psymtab_comp_unit (per_cu, 1);
5724
5725                 VEC_safe_push (dwarf2_per_cu_ptr,
5726                                cu->per_cu->imported_symtabs, per_cu);
5727               }
5728               break;
5729             default:
5730               break;
5731             }
5732         }
5733
5734       /* If the die has a sibling, skip to the sibling.  */
5735
5736       pdi = pdi->die_sibling;
5737     }
5738 }
5739
5740 /* Functions used to compute the fully scoped name of a partial DIE.
5741
5742    Normally, this is simple.  For C++, the parent DIE's fully scoped
5743    name is concatenated with "::" and the partial DIE's name.  For
5744    Java, the same thing occurs except that "." is used instead of "::".
5745    Enumerators are an exception; they use the scope of their parent
5746    enumeration type, i.e. the name of the enumeration type is not
5747    prepended to the enumerator.
5748
5749    There are two complexities.  One is DW_AT_specification; in this
5750    case "parent" means the parent of the target of the specification,
5751    instead of the direct parent of the DIE.  The other is compilers
5752    which do not emit DW_TAG_namespace; in this case we try to guess
5753    the fully qualified name of structure types from their members'
5754    linkage names.  This must be done using the DIE's children rather
5755    than the children of any DW_AT_specification target.  We only need
5756    to do this for structures at the top level, i.e. if the target of
5757    any DW_AT_specification (if any; otherwise the DIE itself) does not
5758    have a parent.  */
5759
5760 /* Compute the scope prefix associated with PDI's parent, in
5761    compilation unit CU.  The result will be allocated on CU's
5762    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5763    field.  NULL is returned if no prefix is necessary.  */
5764 static const char *
5765 partial_die_parent_scope (struct partial_die_info *pdi,
5766                           struct dwarf2_cu *cu)
5767 {
5768   const char *grandparent_scope;
5769   struct partial_die_info *parent, *real_pdi;
5770
5771   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5772      then this means the parent of the specification DIE.  */
5773
5774   real_pdi = pdi;
5775   while (real_pdi->has_specification)
5776     real_pdi = find_partial_die (real_pdi->spec_offset,
5777                                  real_pdi->spec_is_dwz, cu);
5778
5779   parent = real_pdi->die_parent;
5780   if (parent == NULL)
5781     return NULL;
5782
5783   if (parent->scope_set)
5784     return parent->scope;
5785
5786   fixup_partial_die (parent, cu);
5787
5788   grandparent_scope = partial_die_parent_scope (parent, cu);
5789
5790   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5791      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5792      Work around this problem here.  */
5793   if (cu->language == language_cplus
5794       && parent->tag == DW_TAG_namespace
5795       && strcmp (parent->name, "::") == 0
5796       && grandparent_scope == NULL)
5797     {
5798       parent->scope = NULL;
5799       parent->scope_set = 1;
5800       return NULL;
5801     }
5802
5803   if (pdi->tag == DW_TAG_enumerator)
5804     /* Enumerators should not get the name of the enumeration as a prefix.  */
5805     parent->scope = grandparent_scope;
5806   else if (parent->tag == DW_TAG_namespace
5807       || parent->tag == DW_TAG_module
5808       || parent->tag == DW_TAG_structure_type
5809       || parent->tag == DW_TAG_class_type
5810       || parent->tag == DW_TAG_interface_type
5811       || parent->tag == DW_TAG_union_type
5812       || parent->tag == DW_TAG_enumeration_type)
5813     {
5814       if (grandparent_scope == NULL)
5815         parent->scope = parent->name;
5816       else
5817         parent->scope = typename_concat (&cu->comp_unit_obstack,
5818                                          grandparent_scope,
5819                                          parent->name, 0, cu);
5820     }
5821   else
5822     {
5823       /* FIXME drow/2004-04-01: What should we be doing with
5824          function-local names?  For partial symbols, we should probably be
5825          ignoring them.  */
5826       complaint (&symfile_complaints,
5827                  _("unhandled containing DIE tag %d for DIE at %d"),
5828                  parent->tag, pdi->offset.sect_off);
5829       parent->scope = grandparent_scope;
5830     }
5831
5832   parent->scope_set = 1;
5833   return parent->scope;
5834 }
5835
5836 /* Return the fully scoped name associated with PDI, from compilation unit
5837    CU.  The result will be allocated with malloc.  */
5838
5839 static char *
5840 partial_die_full_name (struct partial_die_info *pdi,
5841                        struct dwarf2_cu *cu)
5842 {
5843   const char *parent_scope;
5844
5845   /* If this is a template instantiation, we can not work out the
5846      template arguments from partial DIEs.  So, unfortunately, we have
5847      to go through the full DIEs.  At least any work we do building
5848      types here will be reused if full symbols are loaded later.  */
5849   if (pdi->has_template_arguments)
5850     {
5851       fixup_partial_die (pdi, cu);
5852
5853       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5854         {
5855           struct die_info *die;
5856           struct attribute attr;
5857           struct dwarf2_cu *ref_cu = cu;
5858
5859           /* DW_FORM_ref_addr is using section offset.  */
5860           attr.name = 0;
5861           attr.form = DW_FORM_ref_addr;
5862           attr.u.unsnd = pdi->offset.sect_off;
5863           die = follow_die_ref (NULL, &attr, &ref_cu);
5864
5865           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5866         }
5867     }
5868
5869   parent_scope = partial_die_parent_scope (pdi, cu);
5870   if (parent_scope == NULL)
5871     return NULL;
5872   else
5873     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5874 }
5875
5876 static void
5877 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5878 {
5879   struct objfile *objfile = cu->objfile;
5880   CORE_ADDR addr = 0;
5881   const char *actual_name = NULL;
5882   CORE_ADDR baseaddr;
5883   char *built_actual_name;
5884
5885   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5886
5887   built_actual_name = partial_die_full_name (pdi, cu);
5888   if (built_actual_name != NULL)
5889     actual_name = built_actual_name;
5890
5891   if (actual_name == NULL)
5892     actual_name = pdi->name;
5893
5894   switch (pdi->tag)
5895     {
5896     case DW_TAG_subprogram:
5897       if (pdi->is_external || cu->language == language_ada)
5898         {
5899           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5900              of the global scope.  But in Ada, we want to be able to access
5901              nested procedures globally.  So all Ada subprograms are stored
5902              in the global scope.  */
5903           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5904              mst_text, objfile); */
5905           add_psymbol_to_list (actual_name, strlen (actual_name),
5906                                built_actual_name != NULL,
5907                                VAR_DOMAIN, LOC_BLOCK,
5908                                &objfile->global_psymbols,
5909                                0, pdi->lowpc + baseaddr,
5910                                cu->language, objfile);
5911         }
5912       else
5913         {
5914           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5915              mst_file_text, objfile); */
5916           add_psymbol_to_list (actual_name, strlen (actual_name),
5917                                built_actual_name != NULL,
5918                                VAR_DOMAIN, LOC_BLOCK,
5919                                &objfile->static_psymbols,
5920                                0, pdi->lowpc + baseaddr,
5921                                cu->language, objfile);
5922         }
5923       break;
5924     case DW_TAG_constant:
5925       {
5926         struct psymbol_allocation_list *list;
5927
5928         if (pdi->is_external)
5929           list = &objfile->global_psymbols;
5930         else
5931           list = &objfile->static_psymbols;
5932         add_psymbol_to_list (actual_name, strlen (actual_name),
5933                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
5934                              list, 0, 0, cu->language, objfile);
5935       }
5936       break;
5937     case DW_TAG_variable:
5938       if (pdi->d.locdesc)
5939         addr = decode_locdesc (pdi->d.locdesc, cu);
5940
5941       if (pdi->d.locdesc
5942           && addr == 0
5943           && !dwarf2_per_objfile->has_section_at_zero)
5944         {
5945           /* A global or static variable may also have been stripped
5946              out by the linker if unused, in which case its address
5947              will be nullified; do not add such variables into partial
5948              symbol table then.  */
5949         }
5950       else if (pdi->is_external)
5951         {
5952           /* Global Variable.
5953              Don't enter into the minimal symbol tables as there is
5954              a minimal symbol table entry from the ELF symbols already.
5955              Enter into partial symbol table if it has a location
5956              descriptor or a type.
5957              If the location descriptor is missing, new_symbol will create
5958              a LOC_UNRESOLVED symbol, the address of the variable will then
5959              be determined from the minimal symbol table whenever the variable
5960              is referenced.
5961              The address for the partial symbol table entry is not
5962              used by GDB, but it comes in handy for debugging partial symbol
5963              table building.  */
5964
5965           if (pdi->d.locdesc || pdi->has_type)
5966             add_psymbol_to_list (actual_name, strlen (actual_name),
5967                                  built_actual_name != NULL,
5968                                  VAR_DOMAIN, LOC_STATIC,
5969                                  &objfile->global_psymbols,
5970                                  0, addr + baseaddr,
5971                                  cu->language, objfile);
5972         }
5973       else
5974         {
5975           /* Static Variable.  Skip symbols without location descriptors.  */
5976           if (pdi->d.locdesc == NULL)
5977             {
5978               xfree (built_actual_name);
5979               return;
5980             }
5981           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
5982              mst_file_data, objfile); */
5983           add_psymbol_to_list (actual_name, strlen (actual_name),
5984                                built_actual_name != NULL,
5985                                VAR_DOMAIN, LOC_STATIC,
5986                                &objfile->static_psymbols,
5987                                0, addr + baseaddr,
5988                                cu->language, objfile);
5989         }
5990       break;
5991     case DW_TAG_typedef:
5992     case DW_TAG_base_type:
5993     case DW_TAG_subrange_type:
5994       add_psymbol_to_list (actual_name, strlen (actual_name),
5995                            built_actual_name != NULL,
5996                            VAR_DOMAIN, LOC_TYPEDEF,
5997                            &objfile->static_psymbols,
5998                            0, (CORE_ADDR) 0, cu->language, objfile);
5999       break;
6000     case DW_TAG_namespace:
6001       add_psymbol_to_list (actual_name, strlen (actual_name),
6002                            built_actual_name != NULL,
6003                            VAR_DOMAIN, LOC_TYPEDEF,
6004                            &objfile->global_psymbols,
6005                            0, (CORE_ADDR) 0, cu->language, objfile);
6006       break;
6007     case DW_TAG_class_type:
6008     case DW_TAG_interface_type:
6009     case DW_TAG_structure_type:
6010     case DW_TAG_union_type:
6011     case DW_TAG_enumeration_type:
6012       /* Skip external references.  The DWARF standard says in the section
6013          about "Structure, Union, and Class Type Entries": "An incomplete
6014          structure, union or class type is represented by a structure,
6015          union or class entry that does not have a byte size attribute
6016          and that has a DW_AT_declaration attribute."  */
6017       if (!pdi->has_byte_size && pdi->is_declaration)
6018         {
6019           xfree (built_actual_name);
6020           return;
6021         }
6022
6023       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6024          static vs. global.  */
6025       add_psymbol_to_list (actual_name, strlen (actual_name),
6026                            built_actual_name != NULL,
6027                            STRUCT_DOMAIN, LOC_TYPEDEF,
6028                            (cu->language == language_cplus
6029                             || cu->language == language_java)
6030                            ? &objfile->global_psymbols
6031                            : &objfile->static_psymbols,
6032                            0, (CORE_ADDR) 0, cu->language, objfile);
6033
6034       break;
6035     case DW_TAG_enumerator:
6036       add_psymbol_to_list (actual_name, strlen (actual_name),
6037                            built_actual_name != NULL,
6038                            VAR_DOMAIN, LOC_CONST,
6039                            (cu->language == language_cplus
6040                             || cu->language == language_java)
6041                            ? &objfile->global_psymbols
6042                            : &objfile->static_psymbols,
6043                            0, (CORE_ADDR) 0, cu->language, objfile);
6044       break;
6045     default:
6046       break;
6047     }
6048
6049   xfree (built_actual_name);
6050 }
6051
6052 /* Read a partial die corresponding to a namespace; also, add a symbol
6053    corresponding to that namespace to the symbol table.  NAMESPACE is
6054    the name of the enclosing namespace.  */
6055
6056 static void
6057 add_partial_namespace (struct partial_die_info *pdi,
6058                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6059                        int need_pc, struct dwarf2_cu *cu)
6060 {
6061   /* Add a symbol for the namespace.  */
6062
6063   add_partial_symbol (pdi, cu);
6064
6065   /* Now scan partial symbols in that namespace.  */
6066
6067   if (pdi->has_children)
6068     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6069 }
6070
6071 /* Read a partial die corresponding to a Fortran module.  */
6072
6073 static void
6074 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6075                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6076 {
6077   /* Now scan partial symbols in that module.  */
6078
6079   if (pdi->has_children)
6080     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6081 }
6082
6083 /* Read a partial die corresponding to a subprogram and create a partial
6084    symbol for that subprogram.  When the CU language allows it, this
6085    routine also defines a partial symbol for each nested subprogram
6086    that this subprogram contains.
6087
6088    DIE my also be a lexical block, in which case we simply search
6089    recursively for suprograms defined inside that lexical block.
6090    Again, this is only performed when the CU language allows this
6091    type of definitions.  */
6092
6093 static void
6094 add_partial_subprogram (struct partial_die_info *pdi,
6095                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6096                         int need_pc, struct dwarf2_cu *cu)
6097 {
6098   if (pdi->tag == DW_TAG_subprogram)
6099     {
6100       if (pdi->has_pc_info)
6101         {
6102           if (pdi->lowpc < *lowpc)
6103             *lowpc = pdi->lowpc;
6104           if (pdi->highpc > *highpc)
6105             *highpc = pdi->highpc;
6106           if (need_pc)
6107             {
6108               CORE_ADDR baseaddr;
6109               struct objfile *objfile = cu->objfile;
6110
6111               baseaddr = ANOFFSET (objfile->section_offsets,
6112                                    SECT_OFF_TEXT (objfile));
6113               addrmap_set_empty (objfile->psymtabs_addrmap,
6114                                  pdi->lowpc + baseaddr,
6115                                  pdi->highpc - 1 + baseaddr,
6116                                  cu->per_cu->v.psymtab);
6117             }
6118         }
6119
6120       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6121         {
6122           if (!pdi->is_declaration)
6123             /* Ignore subprogram DIEs that do not have a name, they are
6124                illegal.  Do not emit a complaint at this point, we will
6125                do so when we convert this psymtab into a symtab.  */
6126             if (pdi->name)
6127               add_partial_symbol (pdi, cu);
6128         }
6129     }
6130
6131   if (! pdi->has_children)
6132     return;
6133
6134   if (cu->language == language_ada)
6135     {
6136       pdi = pdi->die_child;
6137       while (pdi != NULL)
6138         {
6139           fixup_partial_die (pdi, cu);
6140           if (pdi->tag == DW_TAG_subprogram
6141               || pdi->tag == DW_TAG_lexical_block)
6142             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6143           pdi = pdi->die_sibling;
6144         }
6145     }
6146 }
6147
6148 /* Read a partial die corresponding to an enumeration type.  */
6149
6150 static void
6151 add_partial_enumeration (struct partial_die_info *enum_pdi,
6152                          struct dwarf2_cu *cu)
6153 {
6154   struct partial_die_info *pdi;
6155
6156   if (enum_pdi->name != NULL)
6157     add_partial_symbol (enum_pdi, cu);
6158
6159   pdi = enum_pdi->die_child;
6160   while (pdi)
6161     {
6162       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6163         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6164       else
6165         add_partial_symbol (pdi, cu);
6166       pdi = pdi->die_sibling;
6167     }
6168 }
6169
6170 /* Return the initial uleb128 in the die at INFO_PTR.  */
6171
6172 static unsigned int
6173 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
6174 {
6175   unsigned int bytes_read;
6176
6177   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6178 }
6179
6180 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6181    Return the corresponding abbrev, or NULL if the number is zero (indicating
6182    an empty DIE).  In either case *BYTES_READ will be set to the length of
6183    the initial number.  */
6184
6185 static struct abbrev_info *
6186 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
6187                  struct dwarf2_cu *cu)
6188 {
6189   bfd *abfd = cu->objfile->obfd;
6190   unsigned int abbrev_number;
6191   struct abbrev_info *abbrev;
6192
6193   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6194
6195   if (abbrev_number == 0)
6196     return NULL;
6197
6198   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6199   if (!abbrev)
6200     {
6201       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6202              abbrev_number, bfd_get_filename (abfd));
6203     }
6204
6205   return abbrev;
6206 }
6207
6208 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6209    Returns a pointer to the end of a series of DIEs, terminated by an empty
6210    DIE.  Any children of the skipped DIEs will also be skipped.  */
6211
6212 static gdb_byte *
6213 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
6214 {
6215   struct dwarf2_cu *cu = reader->cu;
6216   struct abbrev_info *abbrev;
6217   unsigned int bytes_read;
6218
6219   while (1)
6220     {
6221       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6222       if (abbrev == NULL)
6223         return info_ptr + bytes_read;
6224       else
6225         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6226     }
6227 }
6228
6229 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6230    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6231    abbrev corresponding to that skipped uleb128 should be passed in
6232    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6233    children.  */
6234
6235 static gdb_byte *
6236 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
6237               struct abbrev_info *abbrev)
6238 {
6239   unsigned int bytes_read;
6240   struct attribute attr;
6241   bfd *abfd = reader->abfd;
6242   struct dwarf2_cu *cu = reader->cu;
6243   gdb_byte *buffer = reader->buffer;
6244   const gdb_byte *buffer_end = reader->buffer_end;
6245   gdb_byte *start_info_ptr = info_ptr;
6246   unsigned int form, i;
6247
6248   for (i = 0; i < abbrev->num_attrs; i++)
6249     {
6250       /* The only abbrev we care about is DW_AT_sibling.  */
6251       if (abbrev->attrs[i].name == DW_AT_sibling)
6252         {
6253           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6254           if (attr.form == DW_FORM_ref_addr)
6255             complaint (&symfile_complaints,
6256                        _("ignoring absolute DW_AT_sibling"));
6257           else
6258             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6259         }
6260
6261       /* If it isn't DW_AT_sibling, skip this attribute.  */
6262       form = abbrev->attrs[i].form;
6263     skip_attribute:
6264       switch (form)
6265         {
6266         case DW_FORM_ref_addr:
6267           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6268              and later it is offset sized.  */
6269           if (cu->header.version == 2)
6270             info_ptr += cu->header.addr_size;
6271           else
6272             info_ptr += cu->header.offset_size;
6273           break;
6274         case DW_FORM_GNU_ref_alt:
6275           info_ptr += cu->header.offset_size;
6276           break;
6277         case DW_FORM_addr:
6278           info_ptr += cu->header.addr_size;
6279           break;
6280         case DW_FORM_data1:
6281         case DW_FORM_ref1:
6282         case DW_FORM_flag:
6283           info_ptr += 1;
6284           break;
6285         case DW_FORM_flag_present:
6286           break;
6287         case DW_FORM_data2:
6288         case DW_FORM_ref2:
6289           info_ptr += 2;
6290           break;
6291         case DW_FORM_data4:
6292         case DW_FORM_ref4:
6293           info_ptr += 4;
6294           break;
6295         case DW_FORM_data8:
6296         case DW_FORM_ref8:
6297         case DW_FORM_ref_sig8:
6298           info_ptr += 8;
6299           break;
6300         case DW_FORM_string:
6301           read_direct_string (abfd, info_ptr, &bytes_read);
6302           info_ptr += bytes_read;
6303           break;
6304         case DW_FORM_sec_offset:
6305         case DW_FORM_strp:
6306         case DW_FORM_GNU_strp_alt:
6307           info_ptr += cu->header.offset_size;
6308           break;
6309         case DW_FORM_exprloc:
6310         case DW_FORM_block:
6311           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6312           info_ptr += bytes_read;
6313           break;
6314         case DW_FORM_block1:
6315           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6316           break;
6317         case DW_FORM_block2:
6318           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6319           break;
6320         case DW_FORM_block4:
6321           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6322           break;
6323         case DW_FORM_sdata:
6324         case DW_FORM_udata:
6325         case DW_FORM_ref_udata:
6326         case DW_FORM_GNU_addr_index:
6327         case DW_FORM_GNU_str_index:
6328           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6329           break;
6330         case DW_FORM_indirect:
6331           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6332           info_ptr += bytes_read;
6333           /* We need to continue parsing from here, so just go back to
6334              the top.  */
6335           goto skip_attribute;
6336
6337         default:
6338           error (_("Dwarf Error: Cannot handle %s "
6339                    "in DWARF reader [in module %s]"),
6340                  dwarf_form_name (form),
6341                  bfd_get_filename (abfd));
6342         }
6343     }
6344
6345   if (abbrev->has_children)
6346     return skip_children (reader, info_ptr);
6347   else
6348     return info_ptr;
6349 }
6350
6351 /* Locate ORIG_PDI's sibling.
6352    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6353
6354 static gdb_byte *
6355 locate_pdi_sibling (const struct die_reader_specs *reader,
6356                     struct partial_die_info *orig_pdi,
6357                     gdb_byte *info_ptr)
6358 {
6359   /* Do we know the sibling already?  */
6360
6361   if (orig_pdi->sibling)
6362     return orig_pdi->sibling;
6363
6364   /* Are there any children to deal with?  */
6365
6366   if (!orig_pdi->has_children)
6367     return info_ptr;
6368
6369   /* Skip the children the long way.  */
6370
6371   return skip_children (reader, info_ptr);
6372 }
6373
6374 /* Expand this partial symbol table into a full symbol table.  SELF is
6375    not NULL.  */
6376
6377 static void
6378 dwarf2_read_symtab (struct partial_symtab *self,
6379                     struct objfile *objfile)
6380 {
6381   if (self->readin)
6382     {
6383       warning (_("bug: psymtab for %s is already read in."),
6384                self->filename);
6385     }
6386   else
6387     {
6388       if (info_verbose)
6389         {
6390           printf_filtered (_("Reading in symbols for %s..."),
6391                            self->filename);
6392           gdb_flush (gdb_stdout);
6393         }
6394
6395       /* Restore our global data.  */
6396       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6397
6398       /* If this psymtab is constructed from a debug-only objfile, the
6399          has_section_at_zero flag will not necessarily be correct.  We
6400          can get the correct value for this flag by looking at the data
6401          associated with the (presumably stripped) associated objfile.  */
6402       if (objfile->separate_debug_objfile_backlink)
6403         {
6404           struct dwarf2_per_objfile *dpo_backlink
6405             = objfile_data (objfile->separate_debug_objfile_backlink,
6406                             dwarf2_objfile_data_key);
6407
6408           dwarf2_per_objfile->has_section_at_zero
6409             = dpo_backlink->has_section_at_zero;
6410         }
6411
6412       dwarf2_per_objfile->reading_partial_symbols = 0;
6413
6414       psymtab_to_symtab_1 (self);
6415
6416       /* Finish up the debug error message.  */
6417       if (info_verbose)
6418         printf_filtered (_("done.\n"));
6419     }
6420
6421   process_cu_includes ();
6422 }
6423 \f
6424 /* Reading in full CUs.  */
6425
6426 /* Add PER_CU to the queue.  */
6427
6428 static void
6429 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6430                  enum language pretend_language)
6431 {
6432   struct dwarf2_queue_item *item;
6433
6434   per_cu->queued = 1;
6435   item = xmalloc (sizeof (*item));
6436   item->per_cu = per_cu;
6437   item->pretend_language = pretend_language;
6438   item->next = NULL;
6439
6440   if (dwarf2_queue == NULL)
6441     dwarf2_queue = item;
6442   else
6443     dwarf2_queue_tail->next = item;
6444
6445   dwarf2_queue_tail = item;
6446 }
6447
6448 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6449    unit and add it to our queue.
6450    The result is non-zero if PER_CU was queued, otherwise the result is zero
6451    meaning either PER_CU is already queued or it is already loaded.  */
6452
6453 static int
6454 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6455                        struct dwarf2_per_cu_data *per_cu,
6456                        enum language pretend_language)
6457 {
6458   /* We may arrive here during partial symbol reading, if we need full
6459      DIEs to process an unusual case (e.g. template arguments).  Do
6460      not queue PER_CU, just tell our caller to load its DIEs.  */
6461   if (dwarf2_per_objfile->reading_partial_symbols)
6462     {
6463       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6464         return 1;
6465       return 0;
6466     }
6467
6468   /* Mark the dependence relation so that we don't flush PER_CU
6469      too early.  */
6470   dwarf2_add_dependence (this_cu, per_cu);
6471
6472   /* If it's already on the queue, we have nothing to do.  */
6473   if (per_cu->queued)
6474     return 0;
6475
6476   /* If the compilation unit is already loaded, just mark it as
6477      used.  */
6478   if (per_cu->cu != NULL)
6479     {
6480       per_cu->cu->last_used = 0;
6481       return 0;
6482     }
6483
6484   /* Add it to the queue.  */
6485   queue_comp_unit (per_cu, pretend_language);
6486
6487   return 1;
6488 }
6489
6490 /* Process the queue.  */
6491
6492 static void
6493 process_queue (void)
6494 {
6495   struct dwarf2_queue_item *item, *next_item;
6496
6497   if (dwarf2_read_debug)
6498     {
6499       fprintf_unfiltered (gdb_stdlog,
6500                           "Expanding one or more symtabs of objfile %s ...\n",
6501                           dwarf2_per_objfile->objfile->name);
6502     }
6503
6504   /* The queue starts out with one item, but following a DIE reference
6505      may load a new CU, adding it to the end of the queue.  */
6506   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6507     {
6508       if (dwarf2_per_objfile->using_index
6509           ? !item->per_cu->v.quick->symtab
6510           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6511         {
6512           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6513
6514           if (dwarf2_read_debug)
6515             {
6516               fprintf_unfiltered (gdb_stdlog,
6517                                   "Expanding symtab of %s at offset 0x%x\n",
6518                                   per_cu->is_debug_types ? "TU" : "CU",
6519                                   per_cu->offset.sect_off);
6520             }
6521
6522           if (per_cu->is_debug_types)
6523             process_full_type_unit (per_cu, item->pretend_language);
6524           else
6525             process_full_comp_unit (per_cu, item->pretend_language);
6526
6527           if (dwarf2_read_debug)
6528             {
6529               fprintf_unfiltered (gdb_stdlog,
6530                                   "Done expanding %s at offset 0x%x\n",
6531                                   per_cu->is_debug_types ? "TU" : "CU",
6532                                   per_cu->offset.sect_off);
6533             }
6534         }
6535
6536       item->per_cu->queued = 0;
6537       next_item = item->next;
6538       xfree (item);
6539     }
6540
6541   dwarf2_queue_tail = NULL;
6542
6543   if (dwarf2_read_debug)
6544     {
6545       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6546                           dwarf2_per_objfile->objfile->name);
6547     }
6548 }
6549
6550 /* Free all allocated queue entries.  This function only releases anything if
6551    an error was thrown; if the queue was processed then it would have been
6552    freed as we went along.  */
6553
6554 static void
6555 dwarf2_release_queue (void *dummy)
6556 {
6557   struct dwarf2_queue_item *item, *last;
6558
6559   item = dwarf2_queue;
6560   while (item)
6561     {
6562       /* Anything still marked queued is likely to be in an
6563          inconsistent state, so discard it.  */
6564       if (item->per_cu->queued)
6565         {
6566           if (item->per_cu->cu != NULL)
6567             free_one_cached_comp_unit (item->per_cu);
6568           item->per_cu->queued = 0;
6569         }
6570
6571       last = item;
6572       item = item->next;
6573       xfree (last);
6574     }
6575
6576   dwarf2_queue = dwarf2_queue_tail = NULL;
6577 }
6578
6579 /* Read in full symbols for PST, and anything it depends on.  */
6580
6581 static void
6582 psymtab_to_symtab_1 (struct partial_symtab *pst)
6583 {
6584   struct dwarf2_per_cu_data *per_cu;
6585   int i;
6586
6587   if (pst->readin)
6588     return;
6589
6590   for (i = 0; i < pst->number_of_dependencies; i++)
6591     if (!pst->dependencies[i]->readin
6592         && pst->dependencies[i]->user == NULL)
6593       {
6594         /* Inform about additional files that need to be read in.  */
6595         if (info_verbose)
6596           {
6597             /* FIXME: i18n: Need to make this a single string.  */
6598             fputs_filtered (" ", gdb_stdout);
6599             wrap_here ("");
6600             fputs_filtered ("and ", gdb_stdout);
6601             wrap_here ("");
6602             printf_filtered ("%s...", pst->dependencies[i]->filename);
6603             wrap_here ("");     /* Flush output.  */
6604             gdb_flush (gdb_stdout);
6605           }
6606         psymtab_to_symtab_1 (pst->dependencies[i]);
6607       }
6608
6609   per_cu = pst->read_symtab_private;
6610
6611   if (per_cu == NULL)
6612     {
6613       /* It's an include file, no symbols to read for it.
6614          Everything is in the parent symtab.  */
6615       pst->readin = 1;
6616       return;
6617     }
6618
6619   dw2_do_instantiate_symtab (per_cu);
6620 }
6621
6622 /* Trivial hash function for die_info: the hash value of a DIE
6623    is its offset in .debug_info for this objfile.  */
6624
6625 static hashval_t
6626 die_hash (const void *item)
6627 {
6628   const struct die_info *die = item;
6629
6630   return die->offset.sect_off;
6631 }
6632
6633 /* Trivial comparison function for die_info structures: two DIEs
6634    are equal if they have the same offset.  */
6635
6636 static int
6637 die_eq (const void *item_lhs, const void *item_rhs)
6638 {
6639   const struct die_info *die_lhs = item_lhs;
6640   const struct die_info *die_rhs = item_rhs;
6641
6642   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6643 }
6644
6645 /* die_reader_func for load_full_comp_unit.
6646    This is identical to read_signatured_type_reader,
6647    but is kept separate for now.  */
6648
6649 static void
6650 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6651                             gdb_byte *info_ptr,
6652                             struct die_info *comp_unit_die,
6653                             int has_children,
6654                             void *data)
6655 {
6656   struct dwarf2_cu *cu = reader->cu;
6657   enum language *language_ptr = data;
6658
6659   gdb_assert (cu->die_hash == NULL);
6660   cu->die_hash =
6661     htab_create_alloc_ex (cu->header.length / 12,
6662                           die_hash,
6663                           die_eq,
6664                           NULL,
6665                           &cu->comp_unit_obstack,
6666                           hashtab_obstack_allocate,
6667                           dummy_obstack_deallocate);
6668
6669   if (has_children)
6670     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6671                                                   &info_ptr, comp_unit_die);
6672   cu->dies = comp_unit_die;
6673   /* comp_unit_die is not stored in die_hash, no need.  */
6674
6675   /* We try not to read any attributes in this function, because not
6676      all CUs needed for references have been loaded yet, and symbol
6677      table processing isn't initialized.  But we have to set the CU language,
6678      or we won't be able to build types correctly.
6679      Similarly, if we do not read the producer, we can not apply
6680      producer-specific interpretation.  */
6681   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6682 }
6683
6684 /* Load the DIEs associated with PER_CU into memory.  */
6685
6686 static void
6687 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6688                      enum language pretend_language)
6689 {
6690   gdb_assert (! this_cu->is_debug_types);
6691
6692   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6693                            load_full_comp_unit_reader, &pretend_language);
6694 }
6695
6696 /* Add a DIE to the delayed physname list.  */
6697
6698 static void
6699 add_to_method_list (struct type *type, int fnfield_index, int index,
6700                     const char *name, struct die_info *die,
6701                     struct dwarf2_cu *cu)
6702 {
6703   struct delayed_method_info mi;
6704   mi.type = type;
6705   mi.fnfield_index = fnfield_index;
6706   mi.index = index;
6707   mi.name = name;
6708   mi.die = die;
6709   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6710 }
6711
6712 /* A cleanup for freeing the delayed method list.  */
6713
6714 static void
6715 free_delayed_list (void *ptr)
6716 {
6717   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6718   if (cu->method_list != NULL)
6719     {
6720       VEC_free (delayed_method_info, cu->method_list);
6721       cu->method_list = NULL;
6722     }
6723 }
6724
6725 /* Compute the physnames of any methods on the CU's method list.
6726
6727    The computation of method physnames is delayed in order to avoid the
6728    (bad) condition that one of the method's formal parameters is of an as yet
6729    incomplete type.  */
6730
6731 static void
6732 compute_delayed_physnames (struct dwarf2_cu *cu)
6733 {
6734   int i;
6735   struct delayed_method_info *mi;
6736   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6737     {
6738       const char *physname;
6739       struct fn_fieldlist *fn_flp
6740         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6741       physname = dwarf2_physname (mi->name, mi->die, cu);
6742       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6743     }
6744 }
6745
6746 /* Go objects should be embedded in a DW_TAG_module DIE,
6747    and it's not clear if/how imported objects will appear.
6748    To keep Go support simple until that's worked out,
6749    go back through what we've read and create something usable.
6750    We could do this while processing each DIE, and feels kinda cleaner,
6751    but that way is more invasive.
6752    This is to, for example, allow the user to type "p var" or "b main"
6753    without having to specify the package name, and allow lookups
6754    of module.object to work in contexts that use the expression
6755    parser.  */
6756
6757 static void
6758 fixup_go_packaging (struct dwarf2_cu *cu)
6759 {
6760   char *package_name = NULL;
6761   struct pending *list;
6762   int i;
6763
6764   for (list = global_symbols; list != NULL; list = list->next)
6765     {
6766       for (i = 0; i < list->nsyms; ++i)
6767         {
6768           struct symbol *sym = list->symbol[i];
6769
6770           if (SYMBOL_LANGUAGE (sym) == language_go
6771               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6772             {
6773               char *this_package_name = go_symbol_package_name (sym);
6774
6775               if (this_package_name == NULL)
6776                 continue;
6777               if (package_name == NULL)
6778                 package_name = this_package_name;
6779               else
6780                 {
6781                   if (strcmp (package_name, this_package_name) != 0)
6782                     complaint (&symfile_complaints,
6783                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6784                                (SYMBOL_SYMTAB (sym)
6785                                 ? SYMBOL_SYMTAB (sym)->filename
6786                                 : cu->objfile->name),
6787                                this_package_name, package_name);
6788                   xfree (this_package_name);
6789                 }
6790             }
6791         }
6792     }
6793
6794   if (package_name != NULL)
6795     {
6796       struct objfile *objfile = cu->objfile;
6797       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6798                                                       package_name,
6799                                                       strlen (package_name));
6800       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6801                                      saved_package_name, objfile);
6802       struct symbol *sym;
6803
6804       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6805
6806       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6807       SYMBOL_SET_LANGUAGE (sym, language_go);
6808       SYMBOL_SET_NAMES (sym, saved_package_name,
6809                         strlen (saved_package_name), 0, objfile);
6810       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6811          e.g., "main" finds the "main" module and not C's main().  */
6812       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6813       SYMBOL_CLASS (sym) = LOC_TYPEDEF;
6814       SYMBOL_TYPE (sym) = type;
6815
6816       add_symbol_to_list (sym, &global_symbols);
6817
6818       xfree (package_name);
6819     }
6820 }
6821
6822 static void compute_symtab_includes (struct dwarf2_per_cu_data *per_cu);
6823
6824 /* Return the symtab for PER_CU.  This works properly regardless of
6825    whether we're using the index or psymtabs.  */
6826
6827 static struct symtab *
6828 get_symtab (struct dwarf2_per_cu_data *per_cu)
6829 {
6830   return (dwarf2_per_objfile->using_index
6831           ? per_cu->v.quick->symtab
6832           : per_cu->v.psymtab->symtab);
6833 }
6834
6835 /* A helper function for computing the list of all symbol tables
6836    included by PER_CU.  */
6837
6838 static void
6839 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6840                                 htab_t all_children,
6841                                 struct dwarf2_per_cu_data *per_cu)
6842 {
6843   void **slot;
6844   int ix;
6845   struct dwarf2_per_cu_data *iter;
6846
6847   slot = htab_find_slot (all_children, per_cu, INSERT);
6848   if (*slot != NULL)
6849     {
6850       /* This inclusion and its children have been processed.  */
6851       return;
6852     }
6853
6854   *slot = per_cu;
6855   /* Only add a CU if it has a symbol table.  */
6856   if (get_symtab (per_cu) != NULL)
6857     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6858
6859   for (ix = 0;
6860        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
6861        ++ix)
6862     recursively_compute_inclusions (result, all_children, iter);
6863 }
6864
6865 /* Compute the symtab 'includes' fields for the symtab related to
6866    PER_CU.  */
6867
6868 static void
6869 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6870 {
6871   gdb_assert (! per_cu->is_debug_types);
6872
6873   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
6874     {
6875       int ix, len;
6876       struct dwarf2_per_cu_data *iter;
6877       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6878       htab_t all_children;
6879       struct symtab *symtab = get_symtab (per_cu);
6880
6881       /* If we don't have a symtab, we can just skip this case.  */
6882       if (symtab == NULL)
6883         return;
6884
6885       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6886                                         NULL, xcalloc, xfree);
6887
6888       for (ix = 0;
6889            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
6890                         ix, iter);
6891            ++ix)
6892         recursively_compute_inclusions (&result_children, all_children, iter);
6893
6894       /* Now we have a transitive closure of all the included CUs, and
6895          for .gdb_index version 7 the included TUs, so we can convert it
6896          to a list of symtabs.  */
6897       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6898       symtab->includes
6899         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6900                          (len + 1) * sizeof (struct symtab *));
6901       for (ix = 0;
6902            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6903            ++ix)
6904         symtab->includes[ix] = get_symtab (iter);
6905       symtab->includes[len] = NULL;
6906
6907       VEC_free (dwarf2_per_cu_ptr, result_children);
6908       htab_delete (all_children);
6909     }
6910 }
6911
6912 /* Compute the 'includes' field for the symtabs of all the CUs we just
6913    read.  */
6914
6915 static void
6916 process_cu_includes (void)
6917 {
6918   int ix;
6919   struct dwarf2_per_cu_data *iter;
6920
6921   for (ix = 0;
6922        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6923                     ix, iter);
6924        ++ix)
6925     {
6926       if (! iter->is_debug_types)
6927         compute_symtab_includes (iter);
6928     }
6929
6930   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6931 }
6932
6933 /* Generate full symbol information for PER_CU, whose DIEs have
6934    already been loaded into memory.  */
6935
6936 static void
6937 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6938                         enum language pretend_language)
6939 {
6940   struct dwarf2_cu *cu = per_cu->cu;
6941   struct objfile *objfile = per_cu->objfile;
6942   CORE_ADDR lowpc, highpc;
6943   struct symtab *symtab;
6944   struct cleanup *back_to, *delayed_list_cleanup;
6945   CORE_ADDR baseaddr;
6946   struct block *static_block;
6947
6948   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6949
6950   buildsym_init ();
6951   back_to = make_cleanup (really_free_pendings, NULL);
6952   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6953
6954   cu->list_in_scope = &file_symbols;
6955
6956   cu->language = pretend_language;
6957   cu->language_defn = language_def (cu->language);
6958
6959   /* Do line number decoding in read_file_scope () */
6960   process_die (cu->dies, cu);
6961
6962   /* For now fudge the Go package.  */
6963   if (cu->language == language_go)
6964     fixup_go_packaging (cu);
6965
6966   /* Now that we have processed all the DIEs in the CU, all the types 
6967      should be complete, and it should now be safe to compute all of the
6968      physnames.  */
6969   compute_delayed_physnames (cu);
6970   do_cleanups (delayed_list_cleanup);
6971
6972   /* Some compilers don't define a DW_AT_high_pc attribute for the
6973      compilation unit.  If the DW_AT_high_pc is missing, synthesize
6974      it, by scanning the DIE's below the compilation unit.  */
6975   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
6976
6977   static_block
6978     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
6979                                    per_cu->imported_symtabs != NULL);
6980
6981   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
6982      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
6983      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
6984      addrmap to help ensure it has an accurate map of pc values belonging to
6985      this comp unit.  */
6986   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
6987
6988   symtab = end_symtab_from_static_block (static_block, objfile,
6989                                          SECT_OFF_TEXT (objfile), 0);
6990
6991   if (symtab != NULL)
6992     {
6993       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
6994
6995       /* Set symtab language to language from DW_AT_language.  If the
6996          compilation is from a C file generated by language preprocessors, do
6997          not set the language if it was already deduced by start_subfile.  */
6998       if (!(cu->language == language_c && symtab->language != language_c))
6999         symtab->language = cu->language;
7000
7001       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7002          produce DW_AT_location with location lists but it can be possibly
7003          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7004          there were bugs in prologue debug info, fixed later in GCC-4.5
7005          by "unwind info for epilogues" patch (which is not directly related).
7006
7007          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7008          needed, it would be wrong due to missing DW_AT_producer there.
7009
7010          Still one can confuse GDB by using non-standard GCC compilation
7011          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7012          */ 
7013       if (cu->has_loclist && gcc_4_minor >= 5)
7014         symtab->locations_valid = 1;
7015
7016       if (gcc_4_minor >= 5)
7017         symtab->epilogue_unwind_valid = 1;
7018
7019       symtab->call_site_htab = cu->call_site_htab;
7020     }
7021
7022   if (dwarf2_per_objfile->using_index)
7023     per_cu->v.quick->symtab = symtab;
7024   else
7025     {
7026       struct partial_symtab *pst = per_cu->v.psymtab;
7027       pst->symtab = symtab;
7028       pst->readin = 1;
7029     }
7030
7031   /* Push it for inclusion processing later.  */
7032   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7033
7034   do_cleanups (back_to);
7035 }
7036
7037 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7038    already been loaded into memory.  */
7039
7040 static void
7041 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7042                         enum language pretend_language)
7043 {
7044   struct dwarf2_cu *cu = per_cu->cu;
7045   struct objfile *objfile = per_cu->objfile;
7046   struct symtab *symtab;
7047   struct cleanup *back_to, *delayed_list_cleanup;
7048
7049   buildsym_init ();
7050   back_to = make_cleanup (really_free_pendings, NULL);
7051   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7052
7053   cu->list_in_scope = &file_symbols;
7054
7055   cu->language = pretend_language;
7056   cu->language_defn = language_def (cu->language);
7057
7058   /* The symbol tables are set up in read_type_unit_scope.  */
7059   process_die (cu->dies, cu);
7060
7061   /* For now fudge the Go package.  */
7062   if (cu->language == language_go)
7063     fixup_go_packaging (cu);
7064
7065   /* Now that we have processed all the DIEs in the CU, all the types 
7066      should be complete, and it should now be safe to compute all of the
7067      physnames.  */
7068   compute_delayed_physnames (cu);
7069   do_cleanups (delayed_list_cleanup);
7070
7071   /* TUs share symbol tables.
7072      If this is the first TU to use this symtab, complete the construction
7073      of it with end_expandable_symtab.  Otherwise, complete the addition of
7074      this TU's symbols to the existing symtab.  */
7075   if (per_cu->type_unit_group->primary_symtab == NULL)
7076     {
7077       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7078       per_cu->type_unit_group->primary_symtab = symtab;
7079
7080       if (symtab != NULL)
7081         {
7082           /* Set symtab language to language from DW_AT_language.  If the
7083              compilation is from a C file generated by language preprocessors,
7084              do not set the language if it was already deduced by
7085              start_subfile.  */
7086           if (!(cu->language == language_c && symtab->language != language_c))
7087             symtab->language = cu->language;
7088         }
7089     }
7090   else
7091     {
7092       augment_type_symtab (objfile,
7093                            per_cu->type_unit_group->primary_symtab);
7094       symtab = per_cu->type_unit_group->primary_symtab;
7095     }
7096
7097   if (dwarf2_per_objfile->using_index)
7098     per_cu->v.quick->symtab = symtab;
7099   else
7100     {
7101       struct partial_symtab *pst = per_cu->v.psymtab;
7102       pst->symtab = symtab;
7103       pst->readin = 1;
7104     }
7105
7106   do_cleanups (back_to);
7107 }
7108
7109 /* Process an imported unit DIE.  */
7110
7111 static void
7112 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7113 {
7114   struct attribute *attr;
7115
7116   /* For now we don't handle imported units in type units.  */
7117   if (cu->per_cu->is_debug_types)
7118     {
7119       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7120                " supported in type units [in module %s]"),
7121              cu->objfile->name);
7122     }
7123
7124   attr = dwarf2_attr (die, DW_AT_import, cu);
7125   if (attr != NULL)
7126     {
7127       struct dwarf2_per_cu_data *per_cu;
7128       struct symtab *imported_symtab;
7129       sect_offset offset;
7130       int is_dwz;
7131
7132       offset = dwarf2_get_ref_die_offset (attr);
7133       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7134       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7135
7136       /* Queue the unit, if needed.  */
7137       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7138         load_full_comp_unit (per_cu, cu->language);
7139
7140       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7141                      per_cu);
7142     }
7143 }
7144
7145 /* Process a die and its children.  */
7146
7147 static void
7148 process_die (struct die_info *die, struct dwarf2_cu *cu)
7149 {
7150   switch (die->tag)
7151     {
7152     case DW_TAG_padding:
7153       break;
7154     case DW_TAG_compile_unit:
7155     case DW_TAG_partial_unit:
7156       read_file_scope (die, cu);
7157       break;
7158     case DW_TAG_type_unit:
7159       read_type_unit_scope (die, cu);
7160       break;
7161     case DW_TAG_subprogram:
7162     case DW_TAG_inlined_subroutine:
7163       read_func_scope (die, cu);
7164       break;
7165     case DW_TAG_lexical_block:
7166     case DW_TAG_try_block:
7167     case DW_TAG_catch_block:
7168       read_lexical_block_scope (die, cu);
7169       break;
7170     case DW_TAG_GNU_call_site:
7171       read_call_site_scope (die, cu);
7172       break;
7173     case DW_TAG_class_type:
7174     case DW_TAG_interface_type:
7175     case DW_TAG_structure_type:
7176     case DW_TAG_union_type:
7177       process_structure_scope (die, cu);
7178       break;
7179     case DW_TAG_enumeration_type:
7180       process_enumeration_scope (die, cu);
7181       break;
7182
7183     /* These dies have a type, but processing them does not create
7184        a symbol or recurse to process the children.  Therefore we can
7185        read them on-demand through read_type_die.  */
7186     case DW_TAG_subroutine_type:
7187     case DW_TAG_set_type:
7188     case DW_TAG_array_type:
7189     case DW_TAG_pointer_type:
7190     case DW_TAG_ptr_to_member_type:
7191     case DW_TAG_reference_type:
7192     case DW_TAG_string_type:
7193       break;
7194
7195     case DW_TAG_base_type:
7196     case DW_TAG_subrange_type:
7197     case DW_TAG_typedef:
7198       /* Add a typedef symbol for the type definition, if it has a
7199          DW_AT_name.  */
7200       new_symbol (die, read_type_die (die, cu), cu);
7201       break;
7202     case DW_TAG_common_block:
7203       read_common_block (die, cu);
7204       break;
7205     case DW_TAG_common_inclusion:
7206       break;
7207     case DW_TAG_namespace:
7208       cu->processing_has_namespace_info = 1;
7209       read_namespace (die, cu);
7210       break;
7211     case DW_TAG_module:
7212       cu->processing_has_namespace_info = 1;
7213       read_module (die, cu);
7214       break;
7215     case DW_TAG_imported_declaration:
7216     case DW_TAG_imported_module:
7217       cu->processing_has_namespace_info = 1;
7218       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7219                                  || cu->language != language_fortran))
7220         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7221                    dwarf_tag_name (die->tag));
7222       read_import_statement (die, cu);
7223       break;
7224
7225     case DW_TAG_imported_unit:
7226       process_imported_unit_die (die, cu);
7227       break;
7228
7229     default:
7230       new_symbol (die, NULL, cu);
7231       break;
7232     }
7233 }
7234
7235 /* A helper function for dwarf2_compute_name which determines whether DIE
7236    needs to have the name of the scope prepended to the name listed in the
7237    die.  */
7238
7239 static int
7240 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7241 {
7242   struct attribute *attr;
7243
7244   switch (die->tag)
7245     {
7246     case DW_TAG_namespace:
7247     case DW_TAG_typedef:
7248     case DW_TAG_class_type:
7249     case DW_TAG_interface_type:
7250     case DW_TAG_structure_type:
7251     case DW_TAG_union_type:
7252     case DW_TAG_enumeration_type:
7253     case DW_TAG_enumerator:
7254     case DW_TAG_subprogram:
7255     case DW_TAG_member:
7256       return 1;
7257
7258     case DW_TAG_variable:
7259     case DW_TAG_constant:
7260       /* We only need to prefix "globally" visible variables.  These include
7261          any variable marked with DW_AT_external or any variable that
7262          lives in a namespace.  [Variables in anonymous namespaces
7263          require prefixing, but they are not DW_AT_external.]  */
7264
7265       if (dwarf2_attr (die, DW_AT_specification, cu))
7266         {
7267           struct dwarf2_cu *spec_cu = cu;
7268
7269           return die_needs_namespace (die_specification (die, &spec_cu),
7270                                       spec_cu);
7271         }
7272
7273       attr = dwarf2_attr (die, DW_AT_external, cu);
7274       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7275           && die->parent->tag != DW_TAG_module)
7276         return 0;
7277       /* A variable in a lexical block of some kind does not need a
7278          namespace, even though in C++ such variables may be external
7279          and have a mangled name.  */
7280       if (die->parent->tag ==  DW_TAG_lexical_block
7281           || die->parent->tag ==  DW_TAG_try_block
7282           || die->parent->tag ==  DW_TAG_catch_block
7283           || die->parent->tag == DW_TAG_subprogram)
7284         return 0;
7285       return 1;
7286
7287     default:
7288       return 0;
7289     }
7290 }
7291
7292 /* Retrieve the last character from a mem_file.  */
7293
7294 static void
7295 do_ui_file_peek_last (void *object, const char *buffer, long length)
7296 {
7297   char *last_char_p = (char *) object;
7298
7299   if (length > 0)
7300     *last_char_p = buffer[length - 1];
7301 }
7302
7303 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7304    compute the physname for the object, which include a method's:
7305    - formal parameters (C++/Java),
7306    - receiver type (Go),
7307    - return type (Java).
7308
7309    The term "physname" is a bit confusing.
7310    For C++, for example, it is the demangled name.
7311    For Go, for example, it's the mangled name.
7312
7313    For Ada, return the DIE's linkage name rather than the fully qualified
7314    name.  PHYSNAME is ignored..
7315
7316    The result is allocated on the objfile_obstack and canonicalized.  */
7317
7318 static const char *
7319 dwarf2_compute_name (const char *name,
7320                      struct die_info *die, struct dwarf2_cu *cu,
7321                      int physname)
7322 {
7323   struct objfile *objfile = cu->objfile;
7324
7325   if (name == NULL)
7326     name = dwarf2_name (die, cu);
7327
7328   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7329      compute it by typename_concat inside GDB.  */
7330   if (cu->language == language_ada
7331       || (cu->language == language_fortran && physname))
7332     {
7333       /* For Ada unit, we prefer the linkage name over the name, as
7334          the former contains the exported name, which the user expects
7335          to be able to reference.  Ideally, we want the user to be able
7336          to reference this entity using either natural or linkage name,
7337          but we haven't started looking at this enhancement yet.  */
7338       struct attribute *attr;
7339
7340       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7341       if (attr == NULL)
7342         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7343       if (attr && DW_STRING (attr))
7344         return DW_STRING (attr);
7345     }
7346
7347   /* These are the only languages we know how to qualify names in.  */
7348   if (name != NULL
7349       && (cu->language == language_cplus || cu->language == language_java
7350           || cu->language == language_fortran))
7351     {
7352       if (die_needs_namespace (die, cu))
7353         {
7354           long length;
7355           const char *prefix;
7356           struct ui_file *buf;
7357
7358           prefix = determine_prefix (die, cu);
7359           buf = mem_fileopen ();
7360           if (*prefix != '\0')
7361             {
7362               char *prefixed_name = typename_concat (NULL, prefix, name,
7363                                                      physname, cu);
7364
7365               fputs_unfiltered (prefixed_name, buf);
7366               xfree (prefixed_name);
7367             }
7368           else
7369             fputs_unfiltered (name, buf);
7370
7371           /* Template parameters may be specified in the DIE's DW_AT_name, or
7372              as children with DW_TAG_template_type_param or
7373              DW_TAG_value_type_param.  If the latter, add them to the name
7374              here.  If the name already has template parameters, then
7375              skip this step; some versions of GCC emit both, and
7376              it is more efficient to use the pre-computed name.
7377
7378              Something to keep in mind about this process: it is very
7379              unlikely, or in some cases downright impossible, to produce
7380              something that will match the mangled name of a function.
7381              If the definition of the function has the same debug info,
7382              we should be able to match up with it anyway.  But fallbacks
7383              using the minimal symbol, for instance to find a method
7384              implemented in a stripped copy of libstdc++, will not work.
7385              If we do not have debug info for the definition, we will have to
7386              match them up some other way.
7387
7388              When we do name matching there is a related problem with function
7389              templates; two instantiated function templates are allowed to
7390              differ only by their return types, which we do not add here.  */
7391
7392           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7393             {
7394               struct attribute *attr;
7395               struct die_info *child;
7396               int first = 1;
7397
7398               die->building_fullname = 1;
7399
7400               for (child = die->child; child != NULL; child = child->sibling)
7401                 {
7402                   struct type *type;
7403                   LONGEST value;
7404                   gdb_byte *bytes;
7405                   struct dwarf2_locexpr_baton *baton;
7406                   struct value *v;
7407
7408                   if (child->tag != DW_TAG_template_type_param
7409                       && child->tag != DW_TAG_template_value_param)
7410                     continue;
7411
7412                   if (first)
7413                     {
7414                       fputs_unfiltered ("<", buf);
7415                       first = 0;
7416                     }
7417                   else
7418                     fputs_unfiltered (", ", buf);
7419
7420                   attr = dwarf2_attr (child, DW_AT_type, cu);
7421                   if (attr == NULL)
7422                     {
7423                       complaint (&symfile_complaints,
7424                                  _("template parameter missing DW_AT_type"));
7425                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7426                       continue;
7427                     }
7428                   type = die_type (child, cu);
7429
7430                   if (child->tag == DW_TAG_template_type_param)
7431                     {
7432                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7433                       continue;
7434                     }
7435
7436                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7437                   if (attr == NULL)
7438                     {
7439                       complaint (&symfile_complaints,
7440                                  _("template parameter missing "
7441                                    "DW_AT_const_value"));
7442                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7443                       continue;
7444                     }
7445
7446                   dwarf2_const_value_attr (attr, type, name,
7447                                            &cu->comp_unit_obstack, cu,
7448                                            &value, &bytes, &baton);
7449
7450                   if (TYPE_NOSIGN (type))
7451                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7452                        changed, this can use value_print instead.  */
7453                     c_printchar (value, type, buf);
7454                   else
7455                     {
7456                       struct value_print_options opts;
7457
7458                       if (baton != NULL)
7459                         v = dwarf2_evaluate_loc_desc (type, NULL,
7460                                                       baton->data,
7461                                                       baton->size,
7462                                                       baton->per_cu);
7463                       else if (bytes != NULL)
7464                         {
7465                           v = allocate_value (type);
7466                           memcpy (value_contents_writeable (v), bytes,
7467                                   TYPE_LENGTH (type));
7468                         }
7469                       else
7470                         v = value_from_longest (type, value);
7471
7472                       /* Specify decimal so that we do not depend on
7473                          the radix.  */
7474                       get_formatted_print_options (&opts, 'd');
7475                       opts.raw = 1;
7476                       value_print (v, buf, &opts);
7477                       release_value (v);
7478                       value_free (v);
7479                     }
7480                 }
7481
7482               die->building_fullname = 0;
7483
7484               if (!first)
7485                 {
7486                   /* Close the argument list, with a space if necessary
7487                      (nested templates).  */
7488                   char last_char = '\0';
7489                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7490                   if (last_char == '>')
7491                     fputs_unfiltered (" >", buf);
7492                   else
7493                     fputs_unfiltered (">", buf);
7494                 }
7495             }
7496
7497           /* For Java and C++ methods, append formal parameter type
7498              information, if PHYSNAME.  */
7499
7500           if (physname && die->tag == DW_TAG_subprogram
7501               && (cu->language == language_cplus
7502                   || cu->language == language_java))
7503             {
7504               struct type *type = read_type_die (die, cu);
7505
7506               c_type_print_args (type, buf, 1, cu->language,
7507                                  &type_print_raw_options);
7508
7509               if (cu->language == language_java)
7510                 {
7511                   /* For java, we must append the return type to method
7512                      names.  */
7513                   if (die->tag == DW_TAG_subprogram)
7514                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7515                                      0, 0, &type_print_raw_options);
7516                 }
7517               else if (cu->language == language_cplus)
7518                 {
7519                   /* Assume that an artificial first parameter is
7520                      "this", but do not crash if it is not.  RealView
7521                      marks unnamed (and thus unused) parameters as
7522                      artificial; there is no way to differentiate
7523                      the two cases.  */
7524                   if (TYPE_NFIELDS (type) > 0
7525                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7526                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7527                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7528                                                                         0))))
7529                     fputs_unfiltered (" const", buf);
7530                 }
7531             }
7532
7533           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7534                                        &length);
7535           ui_file_delete (buf);
7536
7537           if (cu->language == language_cplus)
7538             {
7539               const char *cname
7540                 = dwarf2_canonicalize_name (name, cu,
7541                                             &objfile->objfile_obstack);
7542
7543               if (cname != NULL)
7544                 name = cname;
7545             }
7546         }
7547     }
7548
7549   return name;
7550 }
7551
7552 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7553    If scope qualifiers are appropriate they will be added.  The result
7554    will be allocated on the objfile_obstack, or NULL if the DIE does
7555    not have a name.  NAME may either be from a previous call to
7556    dwarf2_name or NULL.
7557
7558    The output string will be canonicalized (if C++/Java).  */
7559
7560 static const char *
7561 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7562 {
7563   return dwarf2_compute_name (name, die, cu, 0);
7564 }
7565
7566 /* Construct a physname for the given DIE in CU.  NAME may either be
7567    from a previous call to dwarf2_name or NULL.  The result will be
7568    allocated on the objfile_objstack or NULL if the DIE does not have a
7569    name.
7570
7571    The output string will be canonicalized (if C++/Java).  */
7572
7573 static const char *
7574 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7575 {
7576   struct objfile *objfile = cu->objfile;
7577   struct attribute *attr;
7578   const char *retval, *mangled = NULL, *canon = NULL;
7579   struct cleanup *back_to;
7580   int need_copy = 1;
7581
7582   /* In this case dwarf2_compute_name is just a shortcut not building anything
7583      on its own.  */
7584   if (!die_needs_namespace (die, cu))
7585     return dwarf2_compute_name (name, die, cu, 1);
7586
7587   back_to = make_cleanup (null_cleanup, NULL);
7588
7589   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7590   if (!attr)
7591     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7592
7593   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7594      has computed.  */
7595   if (attr && DW_STRING (attr))
7596     {
7597       char *demangled;
7598
7599       mangled = DW_STRING (attr);
7600
7601       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7602          type.  It is easier for GDB users to search for such functions as
7603          `name(params)' than `long name(params)'.  In such case the minimal
7604          symbol names do not match the full symbol names but for template
7605          functions there is never a need to look up their definition from their
7606          declaration so the only disadvantage remains the minimal symbol
7607          variant `long name(params)' does not have the proper inferior type.
7608          */
7609
7610       if (cu->language == language_go)
7611         {
7612           /* This is a lie, but we already lie to the caller new_symbol_full.
7613              new_symbol_full assumes we return the mangled name.
7614              This just undoes that lie until things are cleaned up.  */
7615           demangled = NULL;
7616         }
7617       else
7618         {
7619           demangled = cplus_demangle (mangled,
7620                                       (DMGL_PARAMS | DMGL_ANSI
7621                                        | (cu->language == language_java
7622                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7623                                           : DMGL_RET_DROP)));
7624         }
7625       if (demangled)
7626         {
7627           make_cleanup (xfree, demangled);
7628           canon = demangled;
7629         }
7630       else
7631         {
7632           canon = mangled;
7633           need_copy = 0;
7634         }
7635     }
7636
7637   if (canon == NULL || check_physname)
7638     {
7639       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7640
7641       if (canon != NULL && strcmp (physname, canon) != 0)
7642         {
7643           /* It may not mean a bug in GDB.  The compiler could also
7644              compute DW_AT_linkage_name incorrectly.  But in such case
7645              GDB would need to be bug-to-bug compatible.  */
7646
7647           complaint (&symfile_complaints,
7648                      _("Computed physname <%s> does not match demangled <%s> "
7649                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7650                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7651
7652           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7653              is available here - over computed PHYSNAME.  It is safer
7654              against both buggy GDB and buggy compilers.  */
7655
7656           retval = canon;
7657         }
7658       else
7659         {
7660           retval = physname;
7661           need_copy = 0;
7662         }
7663     }
7664   else
7665     retval = canon;
7666
7667   if (need_copy)
7668     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7669
7670   do_cleanups (back_to);
7671   return retval;
7672 }
7673
7674 /* Read the import statement specified by the given die and record it.  */
7675
7676 static void
7677 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7678 {
7679   struct objfile *objfile = cu->objfile;
7680   struct attribute *import_attr;
7681   struct die_info *imported_die, *child_die;
7682   struct dwarf2_cu *imported_cu;
7683   const char *imported_name;
7684   const char *imported_name_prefix;
7685   const char *canonical_name;
7686   const char *import_alias;
7687   const char *imported_declaration = NULL;
7688   const char *import_prefix;
7689   VEC (const_char_ptr) *excludes = NULL;
7690   struct cleanup *cleanups;
7691
7692   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7693   if (import_attr == NULL)
7694     {
7695       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7696                  dwarf_tag_name (die->tag));
7697       return;
7698     }
7699
7700   imported_cu = cu;
7701   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7702   imported_name = dwarf2_name (imported_die, imported_cu);
7703   if (imported_name == NULL)
7704     {
7705       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7706
7707         The import in the following code:
7708         namespace A
7709           {
7710             typedef int B;
7711           }
7712
7713         int main ()
7714           {
7715             using A::B;
7716             B b;
7717             return b;
7718           }
7719
7720         ...
7721          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7722             <52>   DW_AT_decl_file   : 1
7723             <53>   DW_AT_decl_line   : 6
7724             <54>   DW_AT_import      : <0x75>
7725          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7726             <59>   DW_AT_name        : B
7727             <5b>   DW_AT_decl_file   : 1
7728             <5c>   DW_AT_decl_line   : 2
7729             <5d>   DW_AT_type        : <0x6e>
7730         ...
7731          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7732             <76>   DW_AT_byte_size   : 4
7733             <77>   DW_AT_encoding    : 5        (signed)
7734
7735         imports the wrong die ( 0x75 instead of 0x58 ).
7736         This case will be ignored until the gcc bug is fixed.  */
7737       return;
7738     }
7739
7740   /* Figure out the local name after import.  */
7741   import_alias = dwarf2_name (die, cu);
7742
7743   /* Figure out where the statement is being imported to.  */
7744   import_prefix = determine_prefix (die, cu);
7745
7746   /* Figure out what the scope of the imported die is and prepend it
7747      to the name of the imported die.  */
7748   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7749
7750   if (imported_die->tag != DW_TAG_namespace
7751       && imported_die->tag != DW_TAG_module)
7752     {
7753       imported_declaration = imported_name;
7754       canonical_name = imported_name_prefix;
7755     }
7756   else if (strlen (imported_name_prefix) > 0)
7757     canonical_name = obconcat (&objfile->objfile_obstack,
7758                                imported_name_prefix, "::", imported_name,
7759                                (char *) NULL);
7760   else
7761     canonical_name = imported_name;
7762
7763   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7764
7765   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7766     for (child_die = die->child; child_die && child_die->tag;
7767          child_die = sibling_die (child_die))
7768       {
7769         /* DWARF-4: A Fortran use statement with a “rename list” may be
7770            represented by an imported module entry with an import attribute
7771            referring to the module and owned entries corresponding to those
7772            entities that are renamed as part of being imported.  */
7773
7774         if (child_die->tag != DW_TAG_imported_declaration)
7775           {
7776             complaint (&symfile_complaints,
7777                        _("child DW_TAG_imported_declaration expected "
7778                          "- DIE at 0x%x [in module %s]"),
7779                        child_die->offset.sect_off, objfile->name);
7780             continue;
7781           }
7782
7783         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7784         if (import_attr == NULL)
7785           {
7786             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7787                        dwarf_tag_name (child_die->tag));
7788             continue;
7789           }
7790
7791         imported_cu = cu;
7792         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7793                                               &imported_cu);
7794         imported_name = dwarf2_name (imported_die, imported_cu);
7795         if (imported_name == NULL)
7796           {
7797             complaint (&symfile_complaints,
7798                        _("child DW_TAG_imported_declaration has unknown "
7799                          "imported name - DIE at 0x%x [in module %s]"),
7800                        child_die->offset.sect_off, objfile->name);
7801             continue;
7802           }
7803
7804         VEC_safe_push (const_char_ptr, excludes, imported_name);
7805
7806         process_die (child_die, cu);
7807       }
7808
7809   cp_add_using_directive (import_prefix,
7810                           canonical_name,
7811                           import_alias,
7812                           imported_declaration,
7813                           excludes,
7814                           0,
7815                           &objfile->objfile_obstack);
7816
7817   do_cleanups (cleanups);
7818 }
7819
7820 /* Cleanup function for handle_DW_AT_stmt_list.  */
7821
7822 static void
7823 free_cu_line_header (void *arg)
7824 {
7825   struct dwarf2_cu *cu = arg;
7826
7827   free_line_header (cu->line_header);
7828   cu->line_header = NULL;
7829 }
7830
7831 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7832    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7833    this, it was first present in GCC release 4.3.0.  */
7834
7835 static int
7836 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7837 {
7838   if (!cu->checked_producer)
7839     check_producer (cu);
7840
7841   return cu->producer_is_gcc_lt_4_3;
7842 }
7843
7844 static void
7845 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7846                          const char **name, const char **comp_dir)
7847 {
7848   struct attribute *attr;
7849
7850   *name = NULL;
7851   *comp_dir = NULL;
7852
7853   /* Find the filename.  Do not use dwarf2_name here, since the filename
7854      is not a source language identifier.  */
7855   attr = dwarf2_attr (die, DW_AT_name, cu);
7856   if (attr)
7857     {
7858       *name = DW_STRING (attr);
7859     }
7860
7861   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7862   if (attr)
7863     *comp_dir = DW_STRING (attr);
7864   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
7865            && IS_ABSOLUTE_PATH (*name))
7866     {
7867       char *d = ldirname (*name);
7868
7869       *comp_dir = d;
7870       if (d != NULL)
7871         make_cleanup (xfree, d);
7872     }
7873   if (*comp_dir != NULL)
7874     {
7875       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7876          directory, get rid of it.  */
7877       char *cp = strchr (*comp_dir, ':');
7878
7879       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7880         *comp_dir = cp + 1;
7881     }
7882
7883   if (*name == NULL)
7884     *name = "<unknown>";
7885 }
7886
7887 /* Handle DW_AT_stmt_list for a compilation unit.
7888    DIE is the DW_TAG_compile_unit die for CU.
7889    COMP_DIR is the compilation directory.
7890    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7891
7892 static void
7893 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7894                         const char *comp_dir)
7895 {
7896   struct attribute *attr;
7897
7898   gdb_assert (! cu->per_cu->is_debug_types);
7899
7900   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7901   if (attr)
7902     {
7903       unsigned int line_offset = DW_UNSND (attr);
7904       struct line_header *line_header
7905         = dwarf_decode_line_header (line_offset, cu);
7906
7907       if (line_header)
7908         {
7909           cu->line_header = line_header;
7910           make_cleanup (free_cu_line_header, cu);
7911           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7912         }
7913     }
7914 }
7915
7916 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7917
7918 static void
7919 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7920 {
7921   struct objfile *objfile = dwarf2_per_objfile->objfile;
7922   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7923   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7924   CORE_ADDR highpc = ((CORE_ADDR) 0);
7925   struct attribute *attr;
7926   const char *name = NULL;
7927   const char *comp_dir = NULL;
7928   struct die_info *child_die;
7929   bfd *abfd = objfile->obfd;
7930   CORE_ADDR baseaddr;
7931
7932   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7933
7934   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7935
7936   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7937      from finish_block.  */
7938   if (lowpc == ((CORE_ADDR) -1))
7939     lowpc = highpc;
7940   lowpc += baseaddr;
7941   highpc += baseaddr;
7942
7943   find_file_and_directory (die, cu, &name, &comp_dir);
7944
7945   prepare_one_comp_unit (cu, die, cu->language);
7946
7947   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7948      standardised yet.  As a workaround for the language detection we fall
7949      back to the DW_AT_producer string.  */
7950   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7951     cu->language = language_opencl;
7952
7953   /* Similar hack for Go.  */
7954   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
7955     set_cu_language (DW_LANG_Go, cu);
7956
7957   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
7958
7959   /* Decode line number information if present.  We do this before
7960      processing child DIEs, so that the line header table is available
7961      for DW_AT_decl_file.  */
7962   handle_DW_AT_stmt_list (die, cu, comp_dir);
7963
7964   /* Process all dies in compilation unit.  */
7965   if (die->child != NULL)
7966     {
7967       child_die = die->child;
7968       while (child_die && child_die->tag)
7969         {
7970           process_die (child_die, cu);
7971           child_die = sibling_die (child_die);
7972         }
7973     }
7974
7975   /* Decode macro information, if present.  Dwarf 2 macro information
7976      refers to information in the line number info statement program
7977      header, so we can only read it if we've read the header
7978      successfully.  */
7979   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
7980   if (attr && cu->line_header)
7981     {
7982       if (dwarf2_attr (die, DW_AT_macro_info, cu))
7983         complaint (&symfile_complaints,
7984                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
7985
7986       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
7987     }
7988   else
7989     {
7990       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
7991       if (attr && cu->line_header)
7992         {
7993           unsigned int macro_offset = DW_UNSND (attr);
7994
7995           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
7996         }
7997     }
7998
7999   do_cleanups (back_to);
8000 }
8001
8002 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8003    Create the set of symtabs used by this TU, or if this TU is sharing
8004    symtabs with another TU and the symtabs have already been created
8005    then restore those symtabs in the line header.
8006    We don't need the pc/line-number mapping for type units.  */
8007
8008 static void
8009 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8010 {
8011   struct objfile *objfile = dwarf2_per_objfile->objfile;
8012   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8013   struct type_unit_group *tu_group;
8014   int first_time;
8015   struct line_header *lh;
8016   struct attribute *attr;
8017   unsigned int i, line_offset;
8018
8019   gdb_assert (per_cu->is_debug_types);
8020
8021   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8022
8023   /* If we're using .gdb_index (includes -readnow) then
8024      per_cu->s.type_unit_group may not have been set up yet.  */
8025   if (per_cu->type_unit_group == NULL)
8026     per_cu->type_unit_group = get_type_unit_group (cu, attr);
8027   tu_group = per_cu->type_unit_group;
8028
8029   /* If we've already processed this stmt_list there's no real need to
8030      do it again, we could fake it and just recreate the part we need
8031      (file name,index -> symtab mapping).  If data shows this optimization
8032      is useful we can do it then.  */
8033   first_time = tu_group->primary_symtab == NULL;
8034
8035   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8036      debug info.  */
8037   lh = NULL;
8038   if (attr != NULL)
8039     {
8040       line_offset = DW_UNSND (attr);
8041       lh = dwarf_decode_line_header (line_offset, cu);
8042     }
8043   if (lh == NULL)
8044     {
8045       if (first_time)
8046         dwarf2_start_symtab (cu, "", NULL, 0);
8047       else
8048         {
8049           gdb_assert (tu_group->symtabs == NULL);
8050           restart_symtab (0);
8051         }
8052       /* Note: The primary symtab will get allocated at the end.  */
8053       return;
8054     }
8055
8056   cu->line_header = lh;
8057   make_cleanup (free_cu_line_header, cu);
8058
8059   if (first_time)
8060     {
8061       dwarf2_start_symtab (cu, "", NULL, 0);
8062
8063       tu_group->num_symtabs = lh->num_file_names;
8064       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8065
8066       for (i = 0; i < lh->num_file_names; ++i)
8067         {
8068           char *dir = NULL;
8069           struct file_entry *fe = &lh->file_names[i];
8070
8071           if (fe->dir_index)
8072             dir = lh->include_dirs[fe->dir_index - 1];
8073           dwarf2_start_subfile (fe->name, dir, NULL);
8074
8075           /* Note: We don't have to watch for the main subfile here, type units
8076              don't have DW_AT_name.  */
8077
8078           if (current_subfile->symtab == NULL)
8079             {
8080               /* NOTE: start_subfile will recognize when it's been passed
8081                  a file it has already seen.  So we can't assume there's a
8082                  simple mapping from lh->file_names to subfiles,
8083                  lh->file_names may contain dups.  */
8084               current_subfile->symtab = allocate_symtab (current_subfile->name,
8085                                                          objfile);
8086             }
8087
8088           fe->symtab = current_subfile->symtab;
8089           tu_group->symtabs[i] = fe->symtab;
8090         }
8091     }
8092   else
8093     {
8094       restart_symtab (0);
8095
8096       for (i = 0; i < lh->num_file_names; ++i)
8097         {
8098           struct file_entry *fe = &lh->file_names[i];
8099
8100           fe->symtab = tu_group->symtabs[i];
8101         }
8102     }
8103
8104   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8105      so they don't have a "real" (so to speak) symtab anyway.
8106      There is later code that will assign the main symtab to all symbols
8107      that don't have one.  We need to handle the case of a symbol with a
8108      missing symtab (DW_AT_decl_file) anyway.  */
8109 }
8110
8111 /* Process DW_TAG_type_unit.
8112    For TUs we want to skip the first top level sibling if it's not the
8113    actual type being defined by this TU.  In this case the first top
8114    level sibling is there to provide context only.  */
8115
8116 static void
8117 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8118 {
8119   struct die_info *child_die;
8120
8121   prepare_one_comp_unit (cu, die, language_minimal);
8122
8123   /* Initialize (or reinitialize) the machinery for building symtabs.
8124      We do this before processing child DIEs, so that the line header table
8125      is available for DW_AT_decl_file.  */
8126   setup_type_unit_groups (die, cu);
8127
8128   if (die->child != NULL)
8129     {
8130       child_die = die->child;
8131       while (child_die && child_die->tag)
8132         {
8133           process_die (child_die, cu);
8134           child_die = sibling_die (child_die);
8135         }
8136     }
8137 }
8138 \f
8139 /* DWO/DWP files.
8140
8141    http://gcc.gnu.org/wiki/DebugFission
8142    http://gcc.gnu.org/wiki/DebugFissionDWP
8143
8144    To simplify handling of both DWO files ("object" files with the DWARF info)
8145    and DWP files (a file with the DWOs packaged up into one file), we treat
8146    DWP files as having a collection of virtual DWO files.  */
8147
8148 static hashval_t
8149 hash_dwo_file (const void *item)
8150 {
8151   const struct dwo_file *dwo_file = item;
8152
8153   return htab_hash_string (dwo_file->name);
8154 }
8155
8156 static int
8157 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8158 {
8159   const struct dwo_file *lhs = item_lhs;
8160   const struct dwo_file *rhs = item_rhs;
8161
8162   return strcmp (lhs->name, rhs->name) == 0;
8163 }
8164
8165 /* Allocate a hash table for DWO files.  */
8166
8167 static htab_t
8168 allocate_dwo_file_hash_table (void)
8169 {
8170   struct objfile *objfile = dwarf2_per_objfile->objfile;
8171
8172   return htab_create_alloc_ex (41,
8173                                hash_dwo_file,
8174                                eq_dwo_file,
8175                                NULL,
8176                                &objfile->objfile_obstack,
8177                                hashtab_obstack_allocate,
8178                                dummy_obstack_deallocate);
8179 }
8180
8181 /* Lookup DWO file DWO_NAME.  */
8182
8183 static void **
8184 lookup_dwo_file_slot (const char *dwo_name)
8185 {
8186   struct dwo_file find_entry;
8187   void **slot;
8188
8189   if (dwarf2_per_objfile->dwo_files == NULL)
8190     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8191
8192   memset (&find_entry, 0, sizeof (find_entry));
8193   find_entry.name = dwo_name;
8194   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8195
8196   return slot;
8197 }
8198
8199 static hashval_t
8200 hash_dwo_unit (const void *item)
8201 {
8202   const struct dwo_unit *dwo_unit = item;
8203
8204   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8205   return dwo_unit->signature;
8206 }
8207
8208 static int
8209 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8210 {
8211   const struct dwo_unit *lhs = item_lhs;
8212   const struct dwo_unit *rhs = item_rhs;
8213
8214   /* The signature is assumed to be unique within the DWO file.
8215      So while object file CU dwo_id's always have the value zero,
8216      that's OK, assuming each object file DWO file has only one CU,
8217      and that's the rule for now.  */
8218   return lhs->signature == rhs->signature;
8219 }
8220
8221 /* Allocate a hash table for DWO CUs,TUs.
8222    There is one of these tables for each of CUs,TUs for each DWO file.  */
8223
8224 static htab_t
8225 allocate_dwo_unit_table (struct objfile *objfile)
8226 {
8227   /* Start out with a pretty small number.
8228      Generally DWO files contain only one CU and maybe some TUs.  */
8229   return htab_create_alloc_ex (3,
8230                                hash_dwo_unit,
8231                                eq_dwo_unit,
8232                                NULL,
8233                                &objfile->objfile_obstack,
8234                                hashtab_obstack_allocate,
8235                                dummy_obstack_deallocate);
8236 }
8237
8238 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8239
8240 struct create_dwo_info_table_data
8241 {
8242   struct dwo_file *dwo_file;
8243   htab_t cu_htab;
8244 };
8245
8246 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8247
8248 static void
8249 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8250                                          gdb_byte *info_ptr,
8251                                          struct die_info *comp_unit_die,
8252                                          int has_children,
8253                                          void *datap)
8254 {
8255   struct dwarf2_cu *cu = reader->cu;
8256   struct objfile *objfile = dwarf2_per_objfile->objfile;
8257   sect_offset offset = cu->per_cu->offset;
8258   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
8259   struct create_dwo_info_table_data *data = datap;
8260   struct dwo_file *dwo_file = data->dwo_file;
8261   htab_t cu_htab = data->cu_htab;
8262   void **slot;
8263   struct attribute *attr;
8264   struct dwo_unit *dwo_unit;
8265
8266   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8267   if (attr == NULL)
8268     {
8269       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8270                " its dwo_id [in module %s]"),
8271              offset.sect_off, dwo_file->name);
8272       return;
8273     }
8274
8275   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8276   dwo_unit->dwo_file = dwo_file;
8277   dwo_unit->signature = DW_UNSND (attr);
8278   dwo_unit->info_or_types_section = section;
8279   dwo_unit->offset = offset;
8280   dwo_unit->length = cu->per_cu->length;
8281
8282   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8283   gdb_assert (slot != NULL);
8284   if (*slot != NULL)
8285     {
8286       const struct dwo_unit *dup_dwo_unit = *slot;
8287
8288       complaint (&symfile_complaints,
8289                  _("debug entry at offset 0x%x is duplicate to the entry at"
8290                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8291                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8292                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8293                  dwo_file->name);
8294     }
8295   else
8296     *slot = dwo_unit;
8297
8298   if (dwarf2_read_debug)
8299     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8300                         offset.sect_off,
8301                         phex (dwo_unit->signature,
8302                               sizeof (dwo_unit->signature)));
8303 }
8304
8305 /* Create a hash table to map DWO IDs to their CU entry in
8306    .debug_info.dwo in DWO_FILE.
8307    Note: This function processes DWO files only, not DWP files.  */
8308
8309 static htab_t
8310 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8311 {
8312   struct objfile *objfile = dwarf2_per_objfile->objfile;
8313   struct dwarf2_section_info *section = &dwo_file->sections.info;
8314   bfd *abfd;
8315   htab_t cu_htab;
8316   gdb_byte *info_ptr, *end_ptr;
8317   struct create_dwo_info_table_data create_dwo_info_table_data;
8318
8319   dwarf2_read_section (objfile, section);
8320   info_ptr = section->buffer;
8321
8322   if (info_ptr == NULL)
8323     return NULL;
8324
8325   /* We can't set abfd until now because the section may be empty or
8326      not present, in which case section->asection will be NULL.  */
8327   abfd = section->asection->owner;
8328
8329   if (dwarf2_read_debug)
8330     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8331                         bfd_get_filename (abfd));
8332
8333   cu_htab = allocate_dwo_unit_table (objfile);
8334
8335   create_dwo_info_table_data.dwo_file = dwo_file;
8336   create_dwo_info_table_data.cu_htab = cu_htab;
8337
8338   end_ptr = info_ptr + section->size;
8339   while (info_ptr < end_ptr)
8340     {
8341       struct dwarf2_per_cu_data per_cu;
8342
8343       memset (&per_cu, 0, sizeof (per_cu));
8344       per_cu.objfile = objfile;
8345       per_cu.is_debug_types = 0;
8346       per_cu.offset.sect_off = info_ptr - section->buffer;
8347       per_cu.info_or_types_section = section;
8348
8349       init_cutu_and_read_dies_no_follow (&per_cu,
8350                                          &dwo_file->sections.abbrev,
8351                                          dwo_file,
8352                                          create_dwo_debug_info_hash_table_reader,
8353                                          &create_dwo_info_table_data);
8354
8355       info_ptr += per_cu.length;
8356     }
8357
8358   return cu_htab;
8359 }
8360
8361 /* DWP file .debug_{cu,tu}_index section format:
8362    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8363
8364    Both index sections have the same format, and serve to map a 64-bit
8365    signature to a set of section numbers.  Each section begins with a header,
8366    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8367    indexes, and a pool of 32-bit section numbers.  The index sections will be
8368    aligned at 8-byte boundaries in the file.
8369
8370    The index section header contains two unsigned 32-bit values (using the
8371    byte order of the application binary):
8372
8373     N, the number of compilation units or type units in the index
8374     M, the number of slots in the hash table
8375
8376   (We assume that N and M will not exceed 2^32 - 1.)
8377
8378   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8379
8380   The hash table begins at offset 8 in the section, and consists of an array
8381   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8382   order of the application binary).  Unused slots in the hash table are 0.
8383   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8384
8385   The parallel table begins immediately after the hash table
8386   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8387   array of 32-bit indexes (using the byte order of the application binary),
8388   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8389   table contains a 32-bit index into the pool of section numbers.  For unused
8390   hash table slots, the corresponding entry in the parallel table will be 0.
8391
8392   Given a 64-bit compilation unit signature or a type signature S, an entry
8393   in the hash table is located as follows:
8394
8395   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8396      the low-order k bits all set to 1.
8397
8398   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8399
8400   3) If the hash table entry at index H matches the signature, use that
8401      entry.  If the hash table entry at index H is unused (all zeroes),
8402      terminate the search: the signature is not present in the table.
8403
8404   4) Let H = (H + H') modulo M. Repeat at Step 3.
8405
8406   Because M > N and H' and M are relatively prime, the search is guaranteed
8407   to stop at an unused slot or find the match.
8408
8409   The pool of section numbers begins immediately following the hash table
8410   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8411   section numbers consists of an array of 32-bit words (using the byte order
8412   of the application binary).  Each item in the array is indexed starting
8413   from 0.  The hash table entry provides the index of the first section
8414   number in the set.  Additional section numbers in the set follow, and the
8415   set is terminated by a 0 entry (section number 0 is not used in ELF).
8416
8417   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8418   section must be the first entry in the set, and the .debug_abbrev.dwo must
8419   be the second entry. Other members of the set may follow in any order.  */
8420
8421 /* Create a hash table to map DWO IDs to their CU/TU entry in
8422    .debug_{info,types}.dwo in DWP_FILE.
8423    Returns NULL if there isn't one.
8424    Note: This function processes DWP files only, not DWO files.  */
8425
8426 static struct dwp_hash_table *
8427 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8428 {
8429   struct objfile *objfile = dwarf2_per_objfile->objfile;
8430   bfd *dbfd = dwp_file->dbfd;
8431   char *index_ptr, *index_end;
8432   struct dwarf2_section_info *index;
8433   uint32_t version, nr_units, nr_slots;
8434   struct dwp_hash_table *htab;
8435
8436   if (is_debug_types)
8437     index = &dwp_file->sections.tu_index;
8438   else
8439     index = &dwp_file->sections.cu_index;
8440
8441   if (dwarf2_section_empty_p (index))
8442     return NULL;
8443   dwarf2_read_section (objfile, index);
8444
8445   index_ptr = index->buffer;
8446   index_end = index_ptr + index->size;
8447
8448   version = read_4_bytes (dbfd, index_ptr);
8449   index_ptr += 8; /* Skip the unused word.  */
8450   nr_units = read_4_bytes (dbfd, index_ptr);
8451   index_ptr += 4;
8452   nr_slots = read_4_bytes (dbfd, index_ptr);
8453   index_ptr += 4;
8454
8455   if (version != 1)
8456     {
8457       error (_("Dwarf Error: unsupported DWP file version (%u)"
8458                " [in module %s]"),
8459              version, dwp_file->name);
8460     }
8461   if (nr_slots != (nr_slots & -nr_slots))
8462     {
8463       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8464                " is not power of 2 [in module %s]"),
8465              nr_slots, dwp_file->name);
8466     }
8467
8468   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8469   htab->nr_units = nr_units;
8470   htab->nr_slots = nr_slots;
8471   htab->hash_table = index_ptr;
8472   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8473   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8474
8475   return htab;
8476 }
8477
8478 /* Update SECTIONS with the data from SECTP.
8479
8480    This function is like the other "locate" section routines that are
8481    passed to bfd_map_over_sections, but in this context the sections to
8482    read comes from the DWP hash table, not the full ELF section table.
8483
8484    The result is non-zero for success, or zero if an error was found.  */
8485
8486 static int
8487 locate_virtual_dwo_sections (asection *sectp,
8488                              struct virtual_dwo_sections *sections)
8489 {
8490   const struct dwop_section_names *names = &dwop_section_names;
8491
8492   if (section_is_p (sectp->name, &names->abbrev_dwo))
8493     {
8494       /* There can be only one.  */
8495       if (sections->abbrev.asection != NULL)
8496         return 0;
8497       sections->abbrev.asection = sectp;
8498       sections->abbrev.size = bfd_get_section_size (sectp);
8499     }
8500   else if (section_is_p (sectp->name, &names->info_dwo)
8501            || section_is_p (sectp->name, &names->types_dwo))
8502     {
8503       /* There can be only one.  */
8504       if (sections->info_or_types.asection != NULL)
8505         return 0;
8506       sections->info_or_types.asection = sectp;
8507       sections->info_or_types.size = bfd_get_section_size (sectp);
8508     }
8509   else if (section_is_p (sectp->name, &names->line_dwo))
8510     {
8511       /* There can be only one.  */
8512       if (sections->line.asection != NULL)
8513         return 0;
8514       sections->line.asection = sectp;
8515       sections->line.size = bfd_get_section_size (sectp);
8516     }
8517   else if (section_is_p (sectp->name, &names->loc_dwo))
8518     {
8519       /* There can be only one.  */
8520       if (sections->loc.asection != NULL)
8521         return 0;
8522       sections->loc.asection = sectp;
8523       sections->loc.size = bfd_get_section_size (sectp);
8524     }
8525   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8526     {
8527       /* There can be only one.  */
8528       if (sections->macinfo.asection != NULL)
8529         return 0;
8530       sections->macinfo.asection = sectp;
8531       sections->macinfo.size = bfd_get_section_size (sectp);
8532     }
8533   else if (section_is_p (sectp->name, &names->macro_dwo))
8534     {
8535       /* There can be only one.  */
8536       if (sections->macro.asection != NULL)
8537         return 0;
8538       sections->macro.asection = sectp;
8539       sections->macro.size = bfd_get_section_size (sectp);
8540     }
8541   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8542     {
8543       /* There can be only one.  */
8544       if (sections->str_offsets.asection != NULL)
8545         return 0;
8546       sections->str_offsets.asection = sectp;
8547       sections->str_offsets.size = bfd_get_section_size (sectp);
8548     }
8549   else
8550     {
8551       /* No other kind of section is valid.  */
8552       return 0;
8553     }
8554
8555   return 1;
8556 }
8557
8558 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8559    HTAB is the hash table from the DWP file.
8560    SECTION_INDEX is the index of the DWO in HTAB.  */
8561
8562 static struct dwo_unit *
8563 create_dwo_in_dwp (struct dwp_file *dwp_file,
8564                    const struct dwp_hash_table *htab,
8565                    uint32_t section_index,
8566                    ULONGEST signature, int is_debug_types)
8567 {
8568   struct objfile *objfile = dwarf2_per_objfile->objfile;
8569   bfd *dbfd = dwp_file->dbfd;
8570   const char *kind = is_debug_types ? "TU" : "CU";
8571   struct dwo_file *dwo_file;
8572   struct dwo_unit *dwo_unit;
8573   struct virtual_dwo_sections sections;
8574   void **dwo_file_slot;
8575   char *virtual_dwo_name;
8576   struct dwarf2_section_info *cutu;
8577   struct cleanup *cleanups;
8578   int i;
8579
8580   if (dwarf2_read_debug)
8581     {
8582       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8583                           kind,
8584                           section_index, phex (signature, sizeof (signature)),
8585                           dwp_file->name);
8586     }
8587
8588   /* Fetch the sections of this DWO.
8589      Put a limit on the number of sections we look for so that bad data
8590      doesn't cause us to loop forever.  */
8591
8592 #define MAX_NR_DWO_SECTIONS \
8593   (1 /* .debug_info or .debug_types */ \
8594    + 1 /* .debug_abbrev */ \
8595    + 1 /* .debug_line */ \
8596    + 1 /* .debug_loc */ \
8597    + 1 /* .debug_str_offsets */ \
8598    + 1 /* .debug_macro */ \
8599    + 1 /* .debug_macinfo */ \
8600    + 1 /* trailing zero */)
8601
8602   memset (&sections, 0, sizeof (sections));
8603   cleanups = make_cleanup (null_cleanup, 0);
8604
8605   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8606     {
8607       asection *sectp;
8608       uint32_t section_nr =
8609         read_4_bytes (dbfd,
8610                       htab->section_pool
8611                       + (section_index + i) * sizeof (uint32_t));
8612
8613       if (section_nr == 0)
8614         break;
8615       if (section_nr >= dwp_file->num_sections)
8616         {
8617           error (_("Dwarf Error: bad DWP hash table, section number too large"
8618                    " [in module %s]"),
8619                  dwp_file->name);
8620         }
8621
8622       sectp = dwp_file->elf_sections[section_nr];
8623       if (! locate_virtual_dwo_sections (sectp, &sections))
8624         {
8625           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8626                    " [in module %s]"),
8627                  dwp_file->name);
8628         }
8629     }
8630
8631   if (i < 2
8632       || sections.info_or_types.asection == NULL
8633       || sections.abbrev.asection == NULL)
8634     {
8635       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8636                " [in module %s]"),
8637              dwp_file->name);
8638     }
8639   if (i == MAX_NR_DWO_SECTIONS)
8640     {
8641       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8642                " [in module %s]"),
8643              dwp_file->name);
8644     }
8645
8646   /* It's easier for the rest of the code if we fake a struct dwo_file and
8647      have dwo_unit "live" in that.  At least for now.
8648
8649      The DWP file can be made up of a random collection of CUs and TUs.
8650      However, for each CU + set of TUs that came from the same original DWO
8651      file, we want to combine them back into a virtual DWO file to save space
8652      (fewer struct dwo_file objects to allocated).  Remember that for really
8653      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8654
8655   virtual_dwo_name =
8656     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8657                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8658                 sections.line.asection ? sections.line.asection->id : 0,
8659                 sections.loc.asection ? sections.loc.asection->id : 0,
8660                 (sections.str_offsets.asection
8661                 ? sections.str_offsets.asection->id
8662                 : 0));
8663   make_cleanup (xfree, virtual_dwo_name);
8664   /* Can we use an existing virtual DWO file?  */
8665   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name);
8666   /* Create one if necessary.  */
8667   if (*dwo_file_slot == NULL)
8668     {
8669       if (dwarf2_read_debug)
8670         {
8671           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8672                               virtual_dwo_name);
8673         }
8674       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8675       dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8676                                       virtual_dwo_name,
8677                                       strlen (virtual_dwo_name));
8678       dwo_file->sections.abbrev = sections.abbrev;
8679       dwo_file->sections.line = sections.line;
8680       dwo_file->sections.loc = sections.loc;
8681       dwo_file->sections.macinfo = sections.macinfo;
8682       dwo_file->sections.macro = sections.macro;
8683       dwo_file->sections.str_offsets = sections.str_offsets;
8684       /* The "str" section is global to the entire DWP file.  */
8685       dwo_file->sections.str = dwp_file->sections.str;
8686       /* The info or types section is assigned later to dwo_unit,
8687          there's no need to record it in dwo_file.
8688          Also, we can't simply record type sections in dwo_file because
8689          we record a pointer into the vector in dwo_unit.  As we collect more
8690          types we'll grow the vector and eventually have to reallocate space
8691          for it, invalidating all the pointers into the current copy.  */
8692       *dwo_file_slot = dwo_file;
8693     }
8694   else
8695     {
8696       if (dwarf2_read_debug)
8697         {
8698           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8699                               virtual_dwo_name);
8700         }
8701       dwo_file = *dwo_file_slot;
8702     }
8703   do_cleanups (cleanups);
8704
8705   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8706   dwo_unit->dwo_file = dwo_file;
8707   dwo_unit->signature = signature;
8708   dwo_unit->info_or_types_section =
8709     obstack_alloc (&objfile->objfile_obstack,
8710                    sizeof (struct dwarf2_section_info));
8711   *dwo_unit->info_or_types_section = sections.info_or_types;
8712   /* offset, length, type_offset_in_tu are set later.  */
8713
8714   return dwo_unit;
8715 }
8716
8717 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8718
8719 static struct dwo_unit *
8720 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8721                    const struct dwp_hash_table *htab,
8722                    ULONGEST signature, int is_debug_types)
8723 {
8724   bfd *dbfd = dwp_file->dbfd;
8725   uint32_t mask = htab->nr_slots - 1;
8726   uint32_t hash = signature & mask;
8727   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8728   unsigned int i;
8729   void **slot;
8730   struct dwo_unit find_dwo_cu, *dwo_cu;
8731
8732   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8733   find_dwo_cu.signature = signature;
8734   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8735
8736   if (*slot != NULL)
8737     return *slot;
8738
8739   /* Use a for loop so that we don't loop forever on bad debug info.  */
8740   for (i = 0; i < htab->nr_slots; ++i)
8741     {
8742       ULONGEST signature_in_table;
8743
8744       signature_in_table =
8745         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8746       if (signature_in_table == signature)
8747         {
8748           uint32_t section_index =
8749             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8750
8751           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8752                                      signature, is_debug_types);
8753           return *slot;
8754         }
8755       if (signature_in_table == 0)
8756         return NULL;
8757       hash = (hash + hash2) & mask;
8758     }
8759
8760   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8761            " [in module %s]"),
8762          dwp_file->name);
8763 }
8764
8765 /* Subroutine of open_dwop_file to simplify it.
8766    Open the file specified by FILE_NAME and hand it off to BFD for
8767    preliminary analysis.  Return a newly initialized bfd *, which
8768    includes a canonicalized copy of FILE_NAME.
8769    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8770    In case of trouble, return NULL.
8771    NOTE: This function is derived from symfile_bfd_open.  */
8772
8773 static bfd *
8774 try_open_dwop_file (const char *file_name, int is_dwp)
8775 {
8776   bfd *sym_bfd;
8777   int desc, flags;
8778   char *absolute_name;
8779
8780   flags = OPF_TRY_CWD_FIRST;
8781   if (is_dwp)
8782     flags |= OPF_SEARCH_IN_PATH;
8783   desc = openp (debug_file_directory, flags, file_name,
8784                 O_RDONLY | O_BINARY, &absolute_name);
8785   if (desc < 0)
8786     return NULL;
8787
8788   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8789   if (!sym_bfd)
8790     {
8791       xfree (absolute_name);
8792       return NULL;
8793     }
8794   xfree (absolute_name);
8795   bfd_set_cacheable (sym_bfd, 1);
8796
8797   if (!bfd_check_format (sym_bfd, bfd_object))
8798     {
8799       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8800       return NULL;
8801     }
8802
8803   return sym_bfd;
8804 }
8805
8806 /* Try to open DWO/DWP file FILE_NAME.
8807    COMP_DIR is the DW_AT_comp_dir attribute.
8808    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8809    The result is the bfd handle of the file.
8810    If there is a problem finding or opening the file, return NULL.
8811    Upon success, the canonicalized path of the file is stored in the bfd,
8812    same as symfile_bfd_open.  */
8813
8814 static bfd *
8815 open_dwop_file (const char *file_name, const char *comp_dir, int is_dwp)
8816 {
8817   bfd *abfd;
8818
8819   if (IS_ABSOLUTE_PATH (file_name))
8820     return try_open_dwop_file (file_name, is_dwp);
8821
8822   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8823
8824   if (comp_dir != NULL)
8825     {
8826       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8827
8828       /* NOTE: If comp_dir is a relative path, this will also try the
8829          search path, which seems useful.  */
8830       abfd = try_open_dwop_file (path_to_try, is_dwp);
8831       xfree (path_to_try);
8832       if (abfd != NULL)
8833         return abfd;
8834     }
8835
8836   /* That didn't work, try debug-file-directory, which, despite its name,
8837      is a list of paths.  */
8838
8839   if (*debug_file_directory == '\0')
8840     return NULL;
8841
8842   return try_open_dwop_file (file_name, is_dwp);
8843 }
8844
8845 /* This function is mapped across the sections and remembers the offset and
8846    size of each of the DWO debugging sections we are interested in.  */
8847
8848 static void
8849 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
8850 {
8851   struct dwo_sections *dwo_sections = dwo_sections_ptr;
8852   const struct dwop_section_names *names = &dwop_section_names;
8853
8854   if (section_is_p (sectp->name, &names->abbrev_dwo))
8855     {
8856       dwo_sections->abbrev.asection = sectp;
8857       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
8858     }
8859   else if (section_is_p (sectp->name, &names->info_dwo))
8860     {
8861       dwo_sections->info.asection = sectp;
8862       dwo_sections->info.size = bfd_get_section_size (sectp);
8863     }
8864   else if (section_is_p (sectp->name, &names->line_dwo))
8865     {
8866       dwo_sections->line.asection = sectp;
8867       dwo_sections->line.size = bfd_get_section_size (sectp);
8868     }
8869   else if (section_is_p (sectp->name, &names->loc_dwo))
8870     {
8871       dwo_sections->loc.asection = sectp;
8872       dwo_sections->loc.size = bfd_get_section_size (sectp);
8873     }
8874   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8875     {
8876       dwo_sections->macinfo.asection = sectp;
8877       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
8878     }
8879   else if (section_is_p (sectp->name, &names->macro_dwo))
8880     {
8881       dwo_sections->macro.asection = sectp;
8882       dwo_sections->macro.size = bfd_get_section_size (sectp);
8883     }
8884   else if (section_is_p (sectp->name, &names->str_dwo))
8885     {
8886       dwo_sections->str.asection = sectp;
8887       dwo_sections->str.size = bfd_get_section_size (sectp);
8888     }
8889   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8890     {
8891       dwo_sections->str_offsets.asection = sectp;
8892       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
8893     }
8894   else if (section_is_p (sectp->name, &names->types_dwo))
8895     {
8896       struct dwarf2_section_info type_section;
8897
8898       memset (&type_section, 0, sizeof (type_section));
8899       type_section.asection = sectp;
8900       type_section.size = bfd_get_section_size (sectp);
8901       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
8902                      &type_section);
8903     }
8904 }
8905
8906 /* Initialize the use of the DWO file specified by DWO_NAME.
8907    The result is NULL if DWO_NAME can't be found.  */
8908
8909 static struct dwo_file *
8910 open_and_init_dwo_file (const char *dwo_name, const char *comp_dir)
8911 {
8912   struct objfile *objfile = dwarf2_per_objfile->objfile;
8913   struct dwo_file *dwo_file;
8914   bfd *dbfd;
8915   struct cleanup *cleanups;
8916
8917   dbfd = open_dwop_file (dwo_name, comp_dir, 0);
8918   if (dbfd == NULL)
8919     {
8920       if (dwarf2_read_debug)
8921         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
8922       return NULL;
8923     }
8924   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8925   dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8926                                   dwo_name, strlen (dwo_name));
8927   dwo_file->dbfd = dbfd;
8928
8929   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8930
8931   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
8932
8933   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
8934
8935   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8936                                                  dwo_file->sections.types);
8937
8938   discard_cleanups (cleanups);
8939
8940   if (dwarf2_read_debug)
8941     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
8942
8943   return dwo_file;
8944 }
8945
8946 /* This function is mapped across the sections and remembers the offset and
8947    size of each of the DWP debugging sections we are interested in.  */
8948
8949 static void
8950 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
8951 {
8952   struct dwp_file *dwp_file = dwp_file_ptr;
8953   const struct dwop_section_names *names = &dwop_section_names;
8954   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
8955
8956   /* Record the ELF section number for later lookup: this is what the
8957      .debug_cu_index,.debug_tu_index tables use.  */
8958   gdb_assert (elf_section_nr < dwp_file->num_sections);
8959   dwp_file->elf_sections[elf_section_nr] = sectp;
8960
8961   /* Look for specific sections that we need.  */
8962   if (section_is_p (sectp->name, &names->str_dwo))
8963     {
8964       dwp_file->sections.str.asection = sectp;
8965       dwp_file->sections.str.size = bfd_get_section_size (sectp);
8966     }
8967   else if (section_is_p (sectp->name, &names->cu_index))
8968     {
8969       dwp_file->sections.cu_index.asection = sectp;
8970       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
8971     }
8972   else if (section_is_p (sectp->name, &names->tu_index))
8973     {
8974       dwp_file->sections.tu_index.asection = sectp;
8975       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
8976     }
8977 }
8978
8979 /* Hash function for dwp_file loaded CUs/TUs.  */
8980
8981 static hashval_t
8982 hash_dwp_loaded_cutus (const void *item)
8983 {
8984   const struct dwo_unit *dwo_unit = item;
8985
8986   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
8987   return dwo_unit->signature;
8988 }
8989
8990 /* Equality function for dwp_file loaded CUs/TUs.  */
8991
8992 static int
8993 eq_dwp_loaded_cutus (const void *a, const void *b)
8994 {
8995   const struct dwo_unit *dua = a;
8996   const struct dwo_unit *dub = b;
8997
8998   return dua->signature == dub->signature;
8999 }
9000
9001 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9002
9003 static htab_t
9004 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9005 {
9006   return htab_create_alloc_ex (3,
9007                                hash_dwp_loaded_cutus,
9008                                eq_dwp_loaded_cutus,
9009                                NULL,
9010                                &objfile->objfile_obstack,
9011                                hashtab_obstack_allocate,
9012                                dummy_obstack_deallocate);
9013 }
9014
9015 /* Initialize the use of the DWP file for the current objfile.
9016    By convention the name of the DWP file is ${objfile}.dwp.
9017    The result is NULL if it can't be found.  */
9018
9019 static struct dwp_file *
9020 open_and_init_dwp_file (const char *comp_dir)
9021 {
9022   struct objfile *objfile = dwarf2_per_objfile->objfile;
9023   struct dwp_file *dwp_file;
9024   char *dwp_name;
9025   bfd *dbfd;
9026   struct cleanup *cleanups;
9027
9028   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9029   cleanups = make_cleanup (xfree, dwp_name);
9030
9031   dbfd = open_dwop_file (dwp_name, comp_dir, 1);
9032   if (dbfd == NULL)
9033     {
9034       if (dwarf2_read_debug)
9035         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9036       do_cleanups (cleanups);
9037       return NULL;
9038     }
9039   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9040   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9041                                   dwp_name, strlen (dwp_name));
9042   dwp_file->dbfd = dbfd;
9043   do_cleanups (cleanups);
9044
9045   cleanups = make_cleanup (free_dwo_file_cleanup, dwp_file);
9046
9047   /* +1: section 0 is unused */
9048   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9049   dwp_file->elf_sections =
9050     OBSTACK_CALLOC (&objfile->objfile_obstack,
9051                     dwp_file->num_sections, asection *);
9052
9053   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9054
9055   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9056
9057   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9058
9059   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9060
9061   discard_cleanups (cleanups);
9062
9063   if (dwarf2_read_debug)
9064     {
9065       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9066       fprintf_unfiltered (gdb_stdlog,
9067                           "    %u CUs, %u TUs\n",
9068                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9069                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9070     }
9071
9072   return dwp_file;
9073 }
9074
9075 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9076    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9077    or in the DWP file for the objfile, referenced by THIS_UNIT.
9078    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9079    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9080
9081    This is called, for example, when wanting to read a variable with a
9082    complex location.  Therefore we don't want to do file i/o for every call.
9083    Therefore we don't want to look for a DWO file on every call.
9084    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9085    then we check if we've already seen DWO_NAME, and only THEN do we check
9086    for a DWO file.
9087
9088    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9089    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9090
9091 static struct dwo_unit *
9092 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9093                  const char *dwo_name, const char *comp_dir,
9094                  ULONGEST signature, int is_debug_types)
9095 {
9096   struct objfile *objfile = dwarf2_per_objfile->objfile;
9097   const char *kind = is_debug_types ? "TU" : "CU";
9098   void **dwo_file_slot;
9099   struct dwo_file *dwo_file;
9100   struct dwp_file *dwp_file;
9101
9102   /* Have we already read SIGNATURE from a DWP file?  */
9103
9104   if (! dwarf2_per_objfile->dwp_checked)
9105     {
9106       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file (comp_dir);
9107       dwarf2_per_objfile->dwp_checked = 1;
9108     }
9109   dwp_file = dwarf2_per_objfile->dwp_file;
9110
9111   if (dwp_file != NULL)
9112     {
9113       const struct dwp_hash_table *dwp_htab =
9114         is_debug_types ? dwp_file->tus : dwp_file->cus;
9115
9116       if (dwp_htab != NULL)
9117         {
9118           struct dwo_unit *dwo_cutu =
9119             lookup_dwo_in_dwp (dwp_file, dwp_htab, signature, is_debug_types);
9120
9121           if (dwo_cutu != NULL)
9122             {
9123               if (dwarf2_read_debug)
9124                 {
9125                   fprintf_unfiltered (gdb_stdlog,
9126                                       "Virtual DWO %s %s found: @%s\n",
9127                                       kind, hex_string (signature),
9128                                       host_address_to_string (dwo_cutu));
9129                 }
9130               return dwo_cutu;
9131             }
9132         }
9133     }
9134
9135   /* Have we already seen DWO_NAME?  */
9136
9137   dwo_file_slot = lookup_dwo_file_slot (dwo_name);
9138   if (*dwo_file_slot == NULL)
9139     {
9140       /* Read in the file and build a table of the DWOs it contains.  */
9141       *dwo_file_slot = open_and_init_dwo_file (dwo_name, comp_dir);
9142     }
9143   /* NOTE: This will be NULL if unable to open the file.  */
9144   dwo_file = *dwo_file_slot;
9145
9146   if (dwo_file != NULL)
9147     {
9148       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9149
9150       if (htab != NULL)
9151         {
9152           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9153
9154           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9155           find_dwo_cutu.signature = signature;
9156           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9157
9158           if (dwo_cutu != NULL)
9159             {
9160               if (dwarf2_read_debug)
9161                 {
9162                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9163                                       kind, dwo_name, hex_string (signature),
9164                                       host_address_to_string (dwo_cutu));
9165                 }
9166               return dwo_cutu;
9167             }
9168         }
9169     }
9170
9171   /* We didn't find it.  This could mean a dwo_id mismatch, or
9172      someone deleted the DWO/DWP file, or the search path isn't set up
9173      correctly to find the file.  */
9174
9175   if (dwarf2_read_debug)
9176     {
9177       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9178                           kind, dwo_name, hex_string (signature));
9179     }
9180
9181   complaint (&symfile_complaints,
9182              _("Could not find DWO CU referenced by CU at offset 0x%x"
9183                " [in module %s]"),
9184              this_unit->offset.sect_off, objfile->name);
9185   return NULL;
9186 }
9187
9188 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9189    See lookup_dwo_cutu_unit for details.  */
9190
9191 static struct dwo_unit *
9192 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9193                       const char *dwo_name, const char *comp_dir,
9194                       ULONGEST signature)
9195 {
9196   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9197 }
9198
9199 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9200    See lookup_dwo_cutu_unit for details.  */
9201
9202 static struct dwo_unit *
9203 lookup_dwo_type_unit (struct signatured_type *this_tu,
9204                       const char *dwo_name, const char *comp_dir)
9205 {
9206   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9207 }
9208
9209 /* Free all resources associated with DWO_FILE.
9210    Close the DWO file and munmap the sections.
9211    All memory should be on the objfile obstack.  */
9212
9213 static void
9214 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9215 {
9216   int ix;
9217   struct dwarf2_section_info *section;
9218
9219   gdb_bfd_unref (dwo_file->dbfd);
9220
9221   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9222 }
9223
9224 /* Wrapper for free_dwo_file for use in cleanups.  */
9225
9226 static void
9227 free_dwo_file_cleanup (void *arg)
9228 {
9229   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9230   struct objfile *objfile = dwarf2_per_objfile->objfile;
9231
9232   free_dwo_file (dwo_file, objfile);
9233 }
9234
9235 /* Traversal function for free_dwo_files.  */
9236
9237 static int
9238 free_dwo_file_from_slot (void **slot, void *info)
9239 {
9240   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9241   struct objfile *objfile = (struct objfile *) info;
9242
9243   free_dwo_file (dwo_file, objfile);
9244
9245   return 1;
9246 }
9247
9248 /* Free all resources associated with DWO_FILES.  */
9249
9250 static void
9251 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9252 {
9253   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9254 }
9255 \f
9256 /* Read in various DIEs.  */
9257
9258 /* qsort helper for inherit_abstract_dies.  */
9259
9260 static int
9261 unsigned_int_compar (const void *ap, const void *bp)
9262 {
9263   unsigned int a = *(unsigned int *) ap;
9264   unsigned int b = *(unsigned int *) bp;
9265
9266   return (a > b) - (b > a);
9267 }
9268
9269 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9270    Inherit only the children of the DW_AT_abstract_origin DIE not being
9271    already referenced by DW_AT_abstract_origin from the children of the
9272    current DIE.  */
9273
9274 static void
9275 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9276 {
9277   struct die_info *child_die;
9278   unsigned die_children_count;
9279   /* CU offsets which were referenced by children of the current DIE.  */
9280   sect_offset *offsets;
9281   sect_offset *offsets_end, *offsetp;
9282   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9283   struct die_info *origin_die;
9284   /* Iterator of the ORIGIN_DIE children.  */
9285   struct die_info *origin_child_die;
9286   struct cleanup *cleanups;
9287   struct attribute *attr;
9288   struct dwarf2_cu *origin_cu;
9289   struct pending **origin_previous_list_in_scope;
9290
9291   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9292   if (!attr)
9293     return;
9294
9295   /* Note that following die references may follow to a die in a
9296      different cu.  */
9297
9298   origin_cu = cu;
9299   origin_die = follow_die_ref (die, attr, &origin_cu);
9300
9301   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9302      symbols in.  */
9303   origin_previous_list_in_scope = origin_cu->list_in_scope;
9304   origin_cu->list_in_scope = cu->list_in_scope;
9305
9306   if (die->tag != origin_die->tag
9307       && !(die->tag == DW_TAG_inlined_subroutine
9308            && origin_die->tag == DW_TAG_subprogram))
9309     complaint (&symfile_complaints,
9310                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9311                die->offset.sect_off, origin_die->offset.sect_off);
9312
9313   child_die = die->child;
9314   die_children_count = 0;
9315   while (child_die && child_die->tag)
9316     {
9317       child_die = sibling_die (child_die);
9318       die_children_count++;
9319     }
9320   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9321   cleanups = make_cleanup (xfree, offsets);
9322
9323   offsets_end = offsets;
9324   child_die = die->child;
9325   while (child_die && child_die->tag)
9326     {
9327       /* For each CHILD_DIE, find the corresponding child of
9328          ORIGIN_DIE.  If there is more than one layer of
9329          DW_AT_abstract_origin, follow them all; there shouldn't be,
9330          but GCC versions at least through 4.4 generate this (GCC PR
9331          40573).  */
9332       struct die_info *child_origin_die = child_die;
9333       struct dwarf2_cu *child_origin_cu = cu;
9334
9335       while (1)
9336         {
9337           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9338                               child_origin_cu);
9339           if (attr == NULL)
9340             break;
9341           child_origin_die = follow_die_ref (child_origin_die, attr,
9342                                              &child_origin_cu);
9343         }
9344
9345       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9346          counterpart may exist.  */
9347       if (child_origin_die != child_die)
9348         {
9349           if (child_die->tag != child_origin_die->tag
9350               && !(child_die->tag == DW_TAG_inlined_subroutine
9351                    && child_origin_die->tag == DW_TAG_subprogram))
9352             complaint (&symfile_complaints,
9353                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9354                          "different tags"), child_die->offset.sect_off,
9355                        child_origin_die->offset.sect_off);
9356           if (child_origin_die->parent != origin_die)
9357             complaint (&symfile_complaints,
9358                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9359                          "different parents"), child_die->offset.sect_off,
9360                        child_origin_die->offset.sect_off);
9361           else
9362             *offsets_end++ = child_origin_die->offset;
9363         }
9364       child_die = sibling_die (child_die);
9365     }
9366   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9367          unsigned_int_compar);
9368   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9369     if (offsetp[-1].sect_off == offsetp->sect_off)
9370       complaint (&symfile_complaints,
9371                  _("Multiple children of DIE 0x%x refer "
9372                    "to DIE 0x%x as their abstract origin"),
9373                  die->offset.sect_off, offsetp->sect_off);
9374
9375   offsetp = offsets;
9376   origin_child_die = origin_die->child;
9377   while (origin_child_die && origin_child_die->tag)
9378     {
9379       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9380       while (offsetp < offsets_end
9381              && offsetp->sect_off < origin_child_die->offset.sect_off)
9382         offsetp++;
9383       if (offsetp >= offsets_end
9384           || offsetp->sect_off > origin_child_die->offset.sect_off)
9385         {
9386           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9387           process_die (origin_child_die, origin_cu);
9388         }
9389       origin_child_die = sibling_die (origin_child_die);
9390     }
9391   origin_cu->list_in_scope = origin_previous_list_in_scope;
9392
9393   do_cleanups (cleanups);
9394 }
9395
9396 static void
9397 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9398 {
9399   struct objfile *objfile = cu->objfile;
9400   struct context_stack *new;
9401   CORE_ADDR lowpc;
9402   CORE_ADDR highpc;
9403   struct die_info *child_die;
9404   struct attribute *attr, *call_line, *call_file;
9405   const char *name;
9406   CORE_ADDR baseaddr;
9407   struct block *block;
9408   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9409   VEC (symbolp) *template_args = NULL;
9410   struct template_symbol *templ_func = NULL;
9411
9412   if (inlined_func)
9413     {
9414       /* If we do not have call site information, we can't show the
9415          caller of this inlined function.  That's too confusing, so
9416          only use the scope for local variables.  */
9417       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9418       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9419       if (call_line == NULL || call_file == NULL)
9420         {
9421           read_lexical_block_scope (die, cu);
9422           return;
9423         }
9424     }
9425
9426   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9427
9428   name = dwarf2_name (die, cu);
9429
9430   /* Ignore functions with missing or empty names.  These are actually
9431      illegal according to the DWARF standard.  */
9432   if (name == NULL)
9433     {
9434       complaint (&symfile_complaints,
9435                  _("missing name for subprogram DIE at %d"),
9436                  die->offset.sect_off);
9437       return;
9438     }
9439
9440   /* Ignore functions with missing or invalid low and high pc attributes.  */
9441   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9442     {
9443       attr = dwarf2_attr (die, DW_AT_external, cu);
9444       if (!attr || !DW_UNSND (attr))
9445         complaint (&symfile_complaints,
9446                    _("cannot get low and high bounds "
9447                      "for subprogram DIE at %d"),
9448                    die->offset.sect_off);
9449       return;
9450     }
9451
9452   lowpc += baseaddr;
9453   highpc += baseaddr;
9454
9455   /* If we have any template arguments, then we must allocate a
9456      different sort of symbol.  */
9457   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9458     {
9459       if (child_die->tag == DW_TAG_template_type_param
9460           || child_die->tag == DW_TAG_template_value_param)
9461         {
9462           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9463                                        struct template_symbol);
9464           templ_func->base.is_cplus_template_function = 1;
9465           break;
9466         }
9467     }
9468
9469   new = push_context (0, lowpc);
9470   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9471                                (struct symbol *) templ_func);
9472
9473   /* If there is a location expression for DW_AT_frame_base, record
9474      it.  */
9475   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9476   if (attr)
9477     /* FIXME: cagney/2004-01-26: The DW_AT_frame_base's location
9478        expression is being recorded directly in the function's symbol
9479        and not in a separate frame-base object.  I guess this hack is
9480        to avoid adding some sort of frame-base adjunct/annex to the
9481        function's symbol :-(.  The problem with doing this is that it
9482        results in a function symbol with a location expression that
9483        has nothing to do with the location of the function, ouch!  The
9484        relationship should be: a function's symbol has-a frame base; a
9485        frame-base has-a location expression.  */
9486     dwarf2_symbol_mark_computed (attr, new->name, cu);
9487
9488   cu->list_in_scope = &local_symbols;
9489
9490   if (die->child != NULL)
9491     {
9492       child_die = die->child;
9493       while (child_die && child_die->tag)
9494         {
9495           if (child_die->tag == DW_TAG_template_type_param
9496               || child_die->tag == DW_TAG_template_value_param)
9497             {
9498               struct symbol *arg = new_symbol (child_die, NULL, cu);
9499
9500               if (arg != NULL)
9501                 VEC_safe_push (symbolp, template_args, arg);
9502             }
9503           else
9504             process_die (child_die, cu);
9505           child_die = sibling_die (child_die);
9506         }
9507     }
9508
9509   inherit_abstract_dies (die, cu);
9510
9511   /* If we have a DW_AT_specification, we might need to import using
9512      directives from the context of the specification DIE.  See the
9513      comment in determine_prefix.  */
9514   if (cu->language == language_cplus
9515       && dwarf2_attr (die, DW_AT_specification, cu))
9516     {
9517       struct dwarf2_cu *spec_cu = cu;
9518       struct die_info *spec_die = die_specification (die, &spec_cu);
9519
9520       while (spec_die)
9521         {
9522           child_die = spec_die->child;
9523           while (child_die && child_die->tag)
9524             {
9525               if (child_die->tag == DW_TAG_imported_module)
9526                 process_die (child_die, spec_cu);
9527               child_die = sibling_die (child_die);
9528             }
9529
9530           /* In some cases, GCC generates specification DIEs that
9531              themselves contain DW_AT_specification attributes.  */
9532           spec_die = die_specification (spec_die, &spec_cu);
9533         }
9534     }
9535
9536   new = pop_context ();
9537   /* Make a block for the local symbols within.  */
9538   block = finish_block (new->name, &local_symbols, new->old_blocks,
9539                         lowpc, highpc, objfile);
9540
9541   /* For C++, set the block's scope.  */
9542   if ((cu->language == language_cplus || cu->language == language_fortran)
9543       && cu->processing_has_namespace_info)
9544     block_set_scope (block, determine_prefix (die, cu),
9545                      &objfile->objfile_obstack);
9546
9547   /* If we have address ranges, record them.  */
9548   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9549
9550   /* Attach template arguments to function.  */
9551   if (! VEC_empty (symbolp, template_args))
9552     {
9553       gdb_assert (templ_func != NULL);
9554
9555       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9556       templ_func->template_arguments
9557         = obstack_alloc (&objfile->objfile_obstack,
9558                          (templ_func->n_template_arguments
9559                           * sizeof (struct symbol *)));
9560       memcpy (templ_func->template_arguments,
9561               VEC_address (symbolp, template_args),
9562               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9563       VEC_free (symbolp, template_args);
9564     }
9565
9566   /* In C++, we can have functions nested inside functions (e.g., when
9567      a function declares a class that has methods).  This means that
9568      when we finish processing a function scope, we may need to go
9569      back to building a containing block's symbol lists.  */
9570   local_symbols = new->locals;
9571   using_directives = new->using_directives;
9572
9573   /* If we've finished processing a top-level function, subsequent
9574      symbols go in the file symbol list.  */
9575   if (outermost_context_p ())
9576     cu->list_in_scope = &file_symbols;
9577 }
9578
9579 /* Process all the DIES contained within a lexical block scope.  Start
9580    a new scope, process the dies, and then close the scope.  */
9581
9582 static void
9583 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9584 {
9585   struct objfile *objfile = cu->objfile;
9586   struct context_stack *new;
9587   CORE_ADDR lowpc, highpc;
9588   struct die_info *child_die;
9589   CORE_ADDR baseaddr;
9590
9591   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9592
9593   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9594   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9595      as multiple lexical blocks?  Handling children in a sane way would
9596      be nasty.  Might be easier to properly extend generic blocks to
9597      describe ranges.  */
9598   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9599     return;
9600   lowpc += baseaddr;
9601   highpc += baseaddr;
9602
9603   push_context (0, lowpc);
9604   if (die->child != NULL)
9605     {
9606       child_die = die->child;
9607       while (child_die && child_die->tag)
9608         {
9609           process_die (child_die, cu);
9610           child_die = sibling_die (child_die);
9611         }
9612     }
9613   new = pop_context ();
9614
9615   if (local_symbols != NULL || using_directives != NULL)
9616     {
9617       struct block *block
9618         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9619                         highpc, objfile);
9620
9621       /* Note that recording ranges after traversing children, as we
9622          do here, means that recording a parent's ranges entails
9623          walking across all its children's ranges as they appear in
9624          the address map, which is quadratic behavior.
9625
9626          It would be nicer to record the parent's ranges before
9627          traversing its children, simply overriding whatever you find
9628          there.  But since we don't even decide whether to create a
9629          block until after we've traversed its children, that's hard
9630          to do.  */
9631       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9632     }
9633   local_symbols = new->locals;
9634   using_directives = new->using_directives;
9635 }
9636
9637 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9638
9639 static void
9640 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9641 {
9642   struct objfile *objfile = cu->objfile;
9643   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9644   CORE_ADDR pc, baseaddr;
9645   struct attribute *attr;
9646   struct call_site *call_site, call_site_local;
9647   void **slot;
9648   int nparams;
9649   struct die_info *child_die;
9650
9651   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9652
9653   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9654   if (!attr)
9655     {
9656       complaint (&symfile_complaints,
9657                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9658                    "DIE 0x%x [in module %s]"),
9659                  die->offset.sect_off, objfile->name);
9660       return;
9661     }
9662   pc = DW_ADDR (attr) + baseaddr;
9663
9664   if (cu->call_site_htab == NULL)
9665     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9666                                                NULL, &objfile->objfile_obstack,
9667                                                hashtab_obstack_allocate, NULL);
9668   call_site_local.pc = pc;
9669   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9670   if (*slot != NULL)
9671     {
9672       complaint (&symfile_complaints,
9673                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9674                    "DIE 0x%x [in module %s]"),
9675                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9676       return;
9677     }
9678
9679   /* Count parameters at the caller.  */
9680
9681   nparams = 0;
9682   for (child_die = die->child; child_die && child_die->tag;
9683        child_die = sibling_die (child_die))
9684     {
9685       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9686         {
9687           complaint (&symfile_complaints,
9688                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9689                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9690                      child_die->tag, child_die->offset.sect_off, objfile->name);
9691           continue;
9692         }
9693
9694       nparams++;
9695     }
9696
9697   call_site = obstack_alloc (&objfile->objfile_obstack,
9698                              (sizeof (*call_site)
9699                               + (sizeof (*call_site->parameter)
9700                                  * (nparams - 1))));
9701   *slot = call_site;
9702   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9703   call_site->pc = pc;
9704
9705   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9706     {
9707       struct die_info *func_die;
9708
9709       /* Skip also over DW_TAG_inlined_subroutine.  */
9710       for (func_die = die->parent;
9711            func_die && func_die->tag != DW_TAG_subprogram
9712            && func_die->tag != DW_TAG_subroutine_type;
9713            func_die = func_die->parent);
9714
9715       /* DW_AT_GNU_all_call_sites is a superset
9716          of DW_AT_GNU_all_tail_call_sites.  */
9717       if (func_die
9718           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9719           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9720         {
9721           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9722              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9723              both the initial caller containing the real return address PC and
9724              the final callee containing the current PC of a chain of tail
9725              calls do not need to have the tail call list complete.  But any
9726              function candidate for a virtual tail call frame searched via
9727              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9728              determined unambiguously.  */
9729         }
9730       else
9731         {
9732           struct type *func_type = NULL;
9733
9734           if (func_die)
9735             func_type = get_die_type (func_die, cu);
9736           if (func_type != NULL)
9737             {
9738               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9739
9740               /* Enlist this call site to the function.  */
9741               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9742               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9743             }
9744           else
9745             complaint (&symfile_complaints,
9746                        _("Cannot find function owning DW_TAG_GNU_call_site "
9747                          "DIE 0x%x [in module %s]"),
9748                        die->offset.sect_off, objfile->name);
9749         }
9750     }
9751
9752   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9753   if (attr == NULL)
9754     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9755   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9756   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9757     /* Keep NULL DWARF_BLOCK.  */;
9758   else if (attr_form_is_block (attr))
9759     {
9760       struct dwarf2_locexpr_baton *dlbaton;
9761
9762       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9763       dlbaton->data = DW_BLOCK (attr)->data;
9764       dlbaton->size = DW_BLOCK (attr)->size;
9765       dlbaton->per_cu = cu->per_cu;
9766
9767       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9768     }
9769   else if (is_ref_attr (attr))
9770     {
9771       struct dwarf2_cu *target_cu = cu;
9772       struct die_info *target_die;
9773
9774       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9775       gdb_assert (target_cu->objfile == objfile);
9776       if (die_is_declaration (target_die, target_cu))
9777         {
9778           const char *target_physname;
9779
9780           target_physname = dwarf2_physname (NULL, target_die, target_cu);
9781           if (target_physname == NULL)
9782             complaint (&symfile_complaints,
9783                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9784                          "physname, for referencing DIE 0x%x [in module %s]"),
9785                        die->offset.sect_off, objfile->name);
9786           else
9787             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9788         }
9789       else
9790         {
9791           CORE_ADDR lowpc;
9792
9793           /* DW_AT_entry_pc should be preferred.  */
9794           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9795             complaint (&symfile_complaints,
9796                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9797                          "low pc, for referencing DIE 0x%x [in module %s]"),
9798                        die->offset.sect_off, objfile->name);
9799           else
9800             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9801         }
9802     }
9803   else
9804     complaint (&symfile_complaints,
9805                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9806                  "block nor reference, for DIE 0x%x [in module %s]"),
9807                die->offset.sect_off, objfile->name);
9808
9809   call_site->per_cu = cu->per_cu;
9810
9811   for (child_die = die->child;
9812        child_die && child_die->tag;
9813        child_die = sibling_die (child_die))
9814     {
9815       struct call_site_parameter *parameter;
9816       struct attribute *loc, *origin;
9817
9818       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9819         {
9820           /* Already printed the complaint above.  */
9821           continue;
9822         }
9823
9824       gdb_assert (call_site->parameter_count < nparams);
9825       parameter = &call_site->parameter[call_site->parameter_count];
9826
9827       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
9828          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
9829          register is contained in DW_AT_GNU_call_site_value.  */
9830
9831       loc = dwarf2_attr (child_die, DW_AT_location, cu);
9832       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
9833       if (loc == NULL && origin != NULL && is_ref_attr (origin))
9834         {
9835           sect_offset offset;
9836
9837           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
9838           offset = dwarf2_get_ref_die_offset (origin);
9839           if (!offset_in_cu_p (&cu->header, offset))
9840             {
9841               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
9842                  binding can be done only inside one CU.  Such referenced DIE
9843                  therefore cannot be even moved to DW_TAG_partial_unit.  */
9844               complaint (&symfile_complaints,
9845                          _("DW_AT_abstract_origin offset is not in CU for "
9846                            "DW_TAG_GNU_call_site child DIE 0x%x "
9847                            "[in module %s]"),
9848                          child_die->offset.sect_off, objfile->name);
9849               continue;
9850             }
9851           parameter->u.param_offset.cu_off = (offset.sect_off
9852                                               - cu->header.offset.sect_off);
9853         }
9854       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
9855         {
9856           complaint (&symfile_complaints,
9857                      _("No DW_FORM_block* DW_AT_location for "
9858                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9859                      child_die->offset.sect_off, objfile->name);
9860           continue;
9861         }
9862       else
9863         {
9864           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
9865             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
9866           if (parameter->u.dwarf_reg != -1)
9867             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
9868           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
9869                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
9870                                              &parameter->u.fb_offset))
9871             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
9872           else
9873             {
9874               complaint (&symfile_complaints,
9875                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
9876                            "for DW_FORM_block* DW_AT_location is supported for "
9877                            "DW_TAG_GNU_call_site child DIE 0x%x "
9878                            "[in module %s]"),
9879                          child_die->offset.sect_off, objfile->name);
9880               continue;
9881             }
9882         }
9883
9884       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
9885       if (!attr_form_is_block (attr))
9886         {
9887           complaint (&symfile_complaints,
9888                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
9889                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9890                      child_die->offset.sect_off, objfile->name);
9891           continue;
9892         }
9893       parameter->value = DW_BLOCK (attr)->data;
9894       parameter->value_size = DW_BLOCK (attr)->size;
9895
9896       /* Parameters are not pre-cleared by memset above.  */
9897       parameter->data_value = NULL;
9898       parameter->data_value_size = 0;
9899       call_site->parameter_count++;
9900
9901       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
9902       if (attr)
9903         {
9904           if (!attr_form_is_block (attr))
9905             complaint (&symfile_complaints,
9906                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
9907                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9908                        child_die->offset.sect_off, objfile->name);
9909           else
9910             {
9911               parameter->data_value = DW_BLOCK (attr)->data;
9912               parameter->data_value_size = DW_BLOCK (attr)->size;
9913             }
9914         }
9915     }
9916 }
9917
9918 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
9919    Return 1 if the attributes are present and valid, otherwise, return 0.
9920    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
9921
9922 static int
9923 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
9924                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
9925                     struct partial_symtab *ranges_pst)
9926 {
9927   struct objfile *objfile = cu->objfile;
9928   struct comp_unit_head *cu_header = &cu->header;
9929   bfd *obfd = objfile->obfd;
9930   unsigned int addr_size = cu_header->addr_size;
9931   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9932   /* Base address selection entry.  */
9933   CORE_ADDR base;
9934   int found_base;
9935   unsigned int dummy;
9936   gdb_byte *buffer;
9937   CORE_ADDR marker;
9938   int low_set;
9939   CORE_ADDR low = 0;
9940   CORE_ADDR high = 0;
9941   CORE_ADDR baseaddr;
9942
9943   found_base = cu->base_known;
9944   base = cu->base_address;
9945
9946   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
9947   if (offset >= dwarf2_per_objfile->ranges.size)
9948     {
9949       complaint (&symfile_complaints,
9950                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
9951                  offset);
9952       return 0;
9953     }
9954   buffer = dwarf2_per_objfile->ranges.buffer + offset;
9955
9956   /* Read in the largest possible address.  */
9957   marker = read_address (obfd, buffer, cu, &dummy);
9958   if ((marker & mask) == mask)
9959     {
9960       /* If we found the largest possible address, then
9961          read the base address.  */
9962       base = read_address (obfd, buffer + addr_size, cu, &dummy);
9963       buffer += 2 * addr_size;
9964       offset += 2 * addr_size;
9965       found_base = 1;
9966     }
9967
9968   low_set = 0;
9969
9970   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9971
9972   while (1)
9973     {
9974       CORE_ADDR range_beginning, range_end;
9975
9976       range_beginning = read_address (obfd, buffer, cu, &dummy);
9977       buffer += addr_size;
9978       range_end = read_address (obfd, buffer, cu, &dummy);
9979       buffer += addr_size;
9980       offset += 2 * addr_size;
9981
9982       /* An end of list marker is a pair of zero addresses.  */
9983       if (range_beginning == 0 && range_end == 0)
9984         /* Found the end of list entry.  */
9985         break;
9986
9987       /* Each base address selection entry is a pair of 2 values.
9988          The first is the largest possible address, the second is
9989          the base address.  Check for a base address here.  */
9990       if ((range_beginning & mask) == mask)
9991         {
9992           /* If we found the largest possible address, then
9993              read the base address.  */
9994           base = read_address (obfd, buffer + addr_size, cu, &dummy);
9995           found_base = 1;
9996           continue;
9997         }
9998
9999       if (!found_base)
10000         {
10001           /* We have no valid base address for the ranges
10002              data.  */
10003           complaint (&symfile_complaints,
10004                      _("Invalid .debug_ranges data (no base address)"));
10005           return 0;
10006         }
10007
10008       if (range_beginning > range_end)
10009         {
10010           /* Inverted range entries are invalid.  */
10011           complaint (&symfile_complaints,
10012                      _("Invalid .debug_ranges data (inverted range)"));
10013           return 0;
10014         }
10015
10016       /* Empty range entries have no effect.  */
10017       if (range_beginning == range_end)
10018         continue;
10019
10020       range_beginning += base;
10021       range_end += base;
10022
10023       /* A not-uncommon case of bad debug info.
10024          Don't pollute the addrmap with bad data.  */
10025       if (range_beginning + baseaddr == 0
10026           && !dwarf2_per_objfile->has_section_at_zero)
10027         {
10028           complaint (&symfile_complaints,
10029                      _(".debug_ranges entry has start address of zero"
10030                        " [in module %s]"), objfile->name);
10031           continue;
10032         }
10033
10034       if (ranges_pst != NULL)
10035         addrmap_set_empty (objfile->psymtabs_addrmap,
10036                            range_beginning + baseaddr,
10037                            range_end - 1 + baseaddr,
10038                            ranges_pst);
10039
10040       /* FIXME: This is recording everything as a low-high
10041          segment of consecutive addresses.  We should have a
10042          data structure for discontiguous block ranges
10043          instead.  */
10044       if (! low_set)
10045         {
10046           low = range_beginning;
10047           high = range_end;
10048           low_set = 1;
10049         }
10050       else
10051         {
10052           if (range_beginning < low)
10053             low = range_beginning;
10054           if (range_end > high)
10055             high = range_end;
10056         }
10057     }
10058
10059   if (! low_set)
10060     /* If the first entry is an end-of-list marker, the range
10061        describes an empty scope, i.e. no instructions.  */
10062     return 0;
10063
10064   if (low_return)
10065     *low_return = low;
10066   if (high_return)
10067     *high_return = high;
10068   return 1;
10069 }
10070
10071 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10072    are present and valid, otherwise, return 0.  Return -1 if the range is
10073    discontinuous, i.e. derived from DW_AT_ranges information.  */
10074
10075 static int
10076 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10077                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10078                       struct partial_symtab *pst)
10079 {
10080   struct attribute *attr;
10081   struct attribute *attr_high;
10082   CORE_ADDR low = 0;
10083   CORE_ADDR high = 0;
10084   int ret = 0;
10085
10086   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10087   if (attr_high)
10088     {
10089       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10090       if (attr)
10091         {
10092           low = DW_ADDR (attr);
10093           if (attr_high->form == DW_FORM_addr
10094               || attr_high->form == DW_FORM_GNU_addr_index)
10095             high = DW_ADDR (attr_high);
10096           else
10097             high = low + DW_UNSND (attr_high);
10098         }
10099       else
10100         /* Found high w/o low attribute.  */
10101         return 0;
10102
10103       /* Found consecutive range of addresses.  */
10104       ret = 1;
10105     }
10106   else
10107     {
10108       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10109       if (attr != NULL)
10110         {
10111           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10112              We take advantage of the fact that DW_AT_ranges does not appear
10113              in DW_TAG_compile_unit of DWO files.  */
10114           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10115           unsigned int ranges_offset = (DW_UNSND (attr)
10116                                         + (need_ranges_base
10117                                            ? cu->ranges_base
10118                                            : 0));
10119
10120           /* Value of the DW_AT_ranges attribute is the offset in the
10121              .debug_ranges section.  */
10122           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10123             return 0;
10124           /* Found discontinuous range of addresses.  */
10125           ret = -1;
10126         }
10127     }
10128
10129   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10130   if (high <= low)
10131     return 0;
10132
10133   /* When using the GNU linker, .gnu.linkonce. sections are used to
10134      eliminate duplicate copies of functions and vtables and such.
10135      The linker will arbitrarily choose one and discard the others.
10136      The AT_*_pc values for such functions refer to local labels in
10137      these sections.  If the section from that file was discarded, the
10138      labels are not in the output, so the relocs get a value of 0.
10139      If this is a discarded function, mark the pc bounds as invalid,
10140      so that GDB will ignore it.  */
10141   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10142     return 0;
10143
10144   *lowpc = low;
10145   if (highpc)
10146     *highpc = high;
10147   return ret;
10148 }
10149
10150 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10151    its low and high PC addresses.  Do nothing if these addresses could not
10152    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10153    and HIGHPC to the high address if greater than HIGHPC.  */
10154
10155 static void
10156 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10157                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10158                                  struct dwarf2_cu *cu)
10159 {
10160   CORE_ADDR low, high;
10161   struct die_info *child = die->child;
10162
10163   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10164     {
10165       *lowpc = min (*lowpc, low);
10166       *highpc = max (*highpc, high);
10167     }
10168
10169   /* If the language does not allow nested subprograms (either inside
10170      subprograms or lexical blocks), we're done.  */
10171   if (cu->language != language_ada)
10172     return;
10173
10174   /* Check all the children of the given DIE.  If it contains nested
10175      subprograms, then check their pc bounds.  Likewise, we need to
10176      check lexical blocks as well, as they may also contain subprogram
10177      definitions.  */
10178   while (child && child->tag)
10179     {
10180       if (child->tag == DW_TAG_subprogram
10181           || child->tag == DW_TAG_lexical_block)
10182         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10183       child = sibling_die (child);
10184     }
10185 }
10186
10187 /* Get the low and high pc's represented by the scope DIE, and store
10188    them in *LOWPC and *HIGHPC.  If the correct values can't be
10189    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10190
10191 static void
10192 get_scope_pc_bounds (struct die_info *die,
10193                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10194                      struct dwarf2_cu *cu)
10195 {
10196   CORE_ADDR best_low = (CORE_ADDR) -1;
10197   CORE_ADDR best_high = (CORE_ADDR) 0;
10198   CORE_ADDR current_low, current_high;
10199
10200   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10201     {
10202       best_low = current_low;
10203       best_high = current_high;
10204     }
10205   else
10206     {
10207       struct die_info *child = die->child;
10208
10209       while (child && child->tag)
10210         {
10211           switch (child->tag) {
10212           case DW_TAG_subprogram:
10213             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10214             break;
10215           case DW_TAG_namespace:
10216           case DW_TAG_module:
10217             /* FIXME: carlton/2004-01-16: Should we do this for
10218                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10219                that current GCC's always emit the DIEs corresponding
10220                to definitions of methods of classes as children of a
10221                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10222                the DIEs giving the declarations, which could be
10223                anywhere).  But I don't see any reason why the
10224                standards says that they have to be there.  */
10225             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10226
10227             if (current_low != ((CORE_ADDR) -1))
10228               {
10229                 best_low = min (best_low, current_low);
10230                 best_high = max (best_high, current_high);
10231               }
10232             break;
10233           default:
10234             /* Ignore.  */
10235             break;
10236           }
10237
10238           child = sibling_die (child);
10239         }
10240     }
10241
10242   *lowpc = best_low;
10243   *highpc = best_high;
10244 }
10245
10246 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10247    in DIE.  */
10248
10249 static void
10250 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10251                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10252 {
10253   struct objfile *objfile = cu->objfile;
10254   struct attribute *attr;
10255   struct attribute *attr_high;
10256
10257   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10258   if (attr_high)
10259     {
10260       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10261       if (attr)
10262         {
10263           CORE_ADDR low = DW_ADDR (attr);
10264           CORE_ADDR high;
10265           if (attr_high->form == DW_FORM_addr
10266               || attr_high->form == DW_FORM_GNU_addr_index)
10267             high = DW_ADDR (attr_high);
10268           else
10269             high = low + DW_UNSND (attr_high);
10270
10271           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10272         }
10273     }
10274
10275   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10276   if (attr)
10277     {
10278       bfd *obfd = objfile->obfd;
10279       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10280          We take advantage of the fact that DW_AT_ranges does not appear
10281          in DW_TAG_compile_unit of DWO files.  */
10282       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10283
10284       /* The value of the DW_AT_ranges attribute is the offset of the
10285          address range list in the .debug_ranges section.  */
10286       unsigned long offset = (DW_UNSND (attr)
10287                               + (need_ranges_base ? cu->ranges_base : 0));
10288       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10289
10290       /* For some target architectures, but not others, the
10291          read_address function sign-extends the addresses it returns.
10292          To recognize base address selection entries, we need a
10293          mask.  */
10294       unsigned int addr_size = cu->header.addr_size;
10295       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10296
10297       /* The base address, to which the next pair is relative.  Note
10298          that this 'base' is a DWARF concept: most entries in a range
10299          list are relative, to reduce the number of relocs against the
10300          debugging information.  This is separate from this function's
10301          'baseaddr' argument, which GDB uses to relocate debugging
10302          information from a shared library based on the address at
10303          which the library was loaded.  */
10304       CORE_ADDR base = cu->base_address;
10305       int base_known = cu->base_known;
10306
10307       gdb_assert (dwarf2_per_objfile->ranges.readin);
10308       if (offset >= dwarf2_per_objfile->ranges.size)
10309         {
10310           complaint (&symfile_complaints,
10311                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10312                      offset);
10313           return;
10314         }
10315
10316       for (;;)
10317         {
10318           unsigned int bytes_read;
10319           CORE_ADDR start, end;
10320
10321           start = read_address (obfd, buffer, cu, &bytes_read);
10322           buffer += bytes_read;
10323           end = read_address (obfd, buffer, cu, &bytes_read);
10324           buffer += bytes_read;
10325
10326           /* Did we find the end of the range list?  */
10327           if (start == 0 && end == 0)
10328             break;
10329
10330           /* Did we find a base address selection entry?  */
10331           else if ((start & base_select_mask) == base_select_mask)
10332             {
10333               base = end;
10334               base_known = 1;
10335             }
10336
10337           /* We found an ordinary address range.  */
10338           else
10339             {
10340               if (!base_known)
10341                 {
10342                   complaint (&symfile_complaints,
10343                              _("Invalid .debug_ranges data "
10344                                "(no base address)"));
10345                   return;
10346                 }
10347
10348               if (start > end)
10349                 {
10350                   /* Inverted range entries are invalid.  */
10351                   complaint (&symfile_complaints,
10352                              _("Invalid .debug_ranges data "
10353                                "(inverted range)"));
10354                   return;
10355                 }
10356
10357               /* Empty range entries have no effect.  */
10358               if (start == end)
10359                 continue;
10360
10361               start += base + baseaddr;
10362               end += base + baseaddr;
10363
10364               /* A not-uncommon case of bad debug info.
10365                  Don't pollute the addrmap with bad data.  */
10366               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10367                 {
10368                   complaint (&symfile_complaints,
10369                              _(".debug_ranges entry has start address of zero"
10370                                " [in module %s]"), objfile->name);
10371                   continue;
10372                 }
10373
10374               record_block_range (block, start, end - 1);
10375             }
10376         }
10377     }
10378 }
10379
10380 /* Check whether the producer field indicates either of GCC < 4.6, or the
10381    Intel C/C++ compiler, and cache the result in CU.  */
10382
10383 static void
10384 check_producer (struct dwarf2_cu *cu)
10385 {
10386   const char *cs;
10387   int major, minor, release;
10388
10389   if (cu->producer == NULL)
10390     {
10391       /* For unknown compilers expect their behavior is DWARF version
10392          compliant.
10393
10394          GCC started to support .debug_types sections by -gdwarf-4 since
10395          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10396          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10397          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10398          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10399     }
10400   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10401     {
10402       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10403
10404       cs = &cu->producer[strlen ("GNU ")];
10405       while (*cs && !isdigit (*cs))
10406         cs++;
10407       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10408         {
10409           /* Not recognized as GCC.  */
10410         }
10411       else
10412         {
10413           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10414           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10415         }
10416     }
10417   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10418     cu->producer_is_icc = 1;
10419   else
10420     {
10421       /* For other non-GCC compilers, expect their behavior is DWARF version
10422          compliant.  */
10423     }
10424
10425   cu->checked_producer = 1;
10426 }
10427
10428 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10429    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10430    during 4.6.0 experimental.  */
10431
10432 static int
10433 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10434 {
10435   if (!cu->checked_producer)
10436     check_producer (cu);
10437
10438   return cu->producer_is_gxx_lt_4_6;
10439 }
10440
10441 /* Return the default accessibility type if it is not overriden by
10442    DW_AT_accessibility.  */
10443
10444 static enum dwarf_access_attribute
10445 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10446 {
10447   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10448     {
10449       /* The default DWARF 2 accessibility for members is public, the default
10450          accessibility for inheritance is private.  */
10451
10452       if (die->tag != DW_TAG_inheritance)
10453         return DW_ACCESS_public;
10454       else
10455         return DW_ACCESS_private;
10456     }
10457   else
10458     {
10459       /* DWARF 3+ defines the default accessibility a different way.  The same
10460          rules apply now for DW_TAG_inheritance as for the members and it only
10461          depends on the container kind.  */
10462
10463       if (die->parent->tag == DW_TAG_class_type)
10464         return DW_ACCESS_private;
10465       else
10466         return DW_ACCESS_public;
10467     }
10468 }
10469
10470 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10471    offset.  If the attribute was not found return 0, otherwise return
10472    1.  If it was found but could not properly be handled, set *OFFSET
10473    to 0.  */
10474
10475 static int
10476 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10477                              LONGEST *offset)
10478 {
10479   struct attribute *attr;
10480
10481   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10482   if (attr != NULL)
10483     {
10484       *offset = 0;
10485
10486       /* Note that we do not check for a section offset first here.
10487          This is because DW_AT_data_member_location is new in DWARF 4,
10488          so if we see it, we can assume that a constant form is really
10489          a constant and not a section offset.  */
10490       if (attr_form_is_constant (attr))
10491         *offset = dwarf2_get_attr_constant_value (attr, 0);
10492       else if (attr_form_is_section_offset (attr))
10493         dwarf2_complex_location_expr_complaint ();
10494       else if (attr_form_is_block (attr))
10495         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10496       else
10497         dwarf2_complex_location_expr_complaint ();
10498
10499       return 1;
10500     }
10501
10502   return 0;
10503 }
10504
10505 /* Add an aggregate field to the field list.  */
10506
10507 static void
10508 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10509                   struct dwarf2_cu *cu)
10510 {
10511   struct objfile *objfile = cu->objfile;
10512   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10513   struct nextfield *new_field;
10514   struct attribute *attr;
10515   struct field *fp;
10516   const char *fieldname = "";
10517
10518   /* Allocate a new field list entry and link it in.  */
10519   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10520   make_cleanup (xfree, new_field);
10521   memset (new_field, 0, sizeof (struct nextfield));
10522
10523   if (die->tag == DW_TAG_inheritance)
10524     {
10525       new_field->next = fip->baseclasses;
10526       fip->baseclasses = new_field;
10527     }
10528   else
10529     {
10530       new_field->next = fip->fields;
10531       fip->fields = new_field;
10532     }
10533   fip->nfields++;
10534
10535   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10536   if (attr)
10537     new_field->accessibility = DW_UNSND (attr);
10538   else
10539     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10540   if (new_field->accessibility != DW_ACCESS_public)
10541     fip->non_public_fields = 1;
10542
10543   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10544   if (attr)
10545     new_field->virtuality = DW_UNSND (attr);
10546   else
10547     new_field->virtuality = DW_VIRTUALITY_none;
10548
10549   fp = &new_field->field;
10550
10551   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10552     {
10553       LONGEST offset;
10554
10555       /* Data member other than a C++ static data member.  */
10556
10557       /* Get type of field.  */
10558       fp->type = die_type (die, cu);
10559
10560       SET_FIELD_BITPOS (*fp, 0);
10561
10562       /* Get bit size of field (zero if none).  */
10563       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10564       if (attr)
10565         {
10566           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10567         }
10568       else
10569         {
10570           FIELD_BITSIZE (*fp) = 0;
10571         }
10572
10573       /* Get bit offset of field.  */
10574       if (handle_data_member_location (die, cu, &offset))
10575         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10576       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10577       if (attr)
10578         {
10579           if (gdbarch_bits_big_endian (gdbarch))
10580             {
10581               /* For big endian bits, the DW_AT_bit_offset gives the
10582                  additional bit offset from the MSB of the containing
10583                  anonymous object to the MSB of the field.  We don't
10584                  have to do anything special since we don't need to
10585                  know the size of the anonymous object.  */
10586               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10587             }
10588           else
10589             {
10590               /* For little endian bits, compute the bit offset to the
10591                  MSB of the anonymous object, subtract off the number of
10592                  bits from the MSB of the field to the MSB of the
10593                  object, and then subtract off the number of bits of
10594                  the field itself.  The result is the bit offset of
10595                  the LSB of the field.  */
10596               int anonymous_size;
10597               int bit_offset = DW_UNSND (attr);
10598
10599               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10600               if (attr)
10601                 {
10602                   /* The size of the anonymous object containing
10603                      the bit field is explicit, so use the
10604                      indicated size (in bytes).  */
10605                   anonymous_size = DW_UNSND (attr);
10606                 }
10607               else
10608                 {
10609                   /* The size of the anonymous object containing
10610                      the bit field must be inferred from the type
10611                      attribute of the data member containing the
10612                      bit field.  */
10613                   anonymous_size = TYPE_LENGTH (fp->type);
10614                 }
10615               SET_FIELD_BITPOS (*fp,
10616                                 (FIELD_BITPOS (*fp)
10617                                  + anonymous_size * bits_per_byte
10618                                  - bit_offset - FIELD_BITSIZE (*fp)));
10619             }
10620         }
10621
10622       /* Get name of field.  */
10623       fieldname = dwarf2_name (die, cu);
10624       if (fieldname == NULL)
10625         fieldname = "";
10626
10627       /* The name is already allocated along with this objfile, so we don't
10628          need to duplicate it for the type.  */
10629       fp->name = fieldname;
10630
10631       /* Change accessibility for artificial fields (e.g. virtual table
10632          pointer or virtual base class pointer) to private.  */
10633       if (dwarf2_attr (die, DW_AT_artificial, cu))
10634         {
10635           FIELD_ARTIFICIAL (*fp) = 1;
10636           new_field->accessibility = DW_ACCESS_private;
10637           fip->non_public_fields = 1;
10638         }
10639     }
10640   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10641     {
10642       /* C++ static member.  */
10643
10644       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10645          is a declaration, but all versions of G++ as of this writing
10646          (so through at least 3.2.1) incorrectly generate
10647          DW_TAG_variable tags.  */
10648
10649       const char *physname;
10650
10651       /* Get name of field.  */
10652       fieldname = dwarf2_name (die, cu);
10653       if (fieldname == NULL)
10654         return;
10655
10656       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10657       if (attr
10658           /* Only create a symbol if this is an external value.
10659              new_symbol checks this and puts the value in the global symbol
10660              table, which we want.  If it is not external, new_symbol
10661              will try to put the value in cu->list_in_scope which is wrong.  */
10662           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10663         {
10664           /* A static const member, not much different than an enum as far as
10665              we're concerned, except that we can support more types.  */
10666           new_symbol (die, NULL, cu);
10667         }
10668
10669       /* Get physical name.  */
10670       physname = dwarf2_physname (fieldname, die, cu);
10671
10672       /* The name is already allocated along with this objfile, so we don't
10673          need to duplicate it for the type.  */
10674       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10675       FIELD_TYPE (*fp) = die_type (die, cu);
10676       FIELD_NAME (*fp) = fieldname;
10677     }
10678   else if (die->tag == DW_TAG_inheritance)
10679     {
10680       LONGEST offset;
10681
10682       /* C++ base class field.  */
10683       if (handle_data_member_location (die, cu, &offset))
10684         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10685       FIELD_BITSIZE (*fp) = 0;
10686       FIELD_TYPE (*fp) = die_type (die, cu);
10687       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10688       fip->nbaseclasses++;
10689     }
10690 }
10691
10692 /* Add a typedef defined in the scope of the FIP's class.  */
10693
10694 static void
10695 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10696                     struct dwarf2_cu *cu)
10697 {
10698   struct objfile *objfile = cu->objfile;
10699   struct typedef_field_list *new_field;
10700   struct attribute *attr;
10701   struct typedef_field *fp;
10702   char *fieldname = "";
10703
10704   /* Allocate a new field list entry and link it in.  */
10705   new_field = xzalloc (sizeof (*new_field));
10706   make_cleanup (xfree, new_field);
10707
10708   gdb_assert (die->tag == DW_TAG_typedef);
10709
10710   fp = &new_field->field;
10711
10712   /* Get name of field.  */
10713   fp->name = dwarf2_name (die, cu);
10714   if (fp->name == NULL)
10715     return;
10716
10717   fp->type = read_type_die (die, cu);
10718
10719   new_field->next = fip->typedef_field_list;
10720   fip->typedef_field_list = new_field;
10721   fip->typedef_field_list_count++;
10722 }
10723
10724 /* Create the vector of fields, and attach it to the type.  */
10725
10726 static void
10727 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10728                               struct dwarf2_cu *cu)
10729 {
10730   int nfields = fip->nfields;
10731
10732   /* Record the field count, allocate space for the array of fields,
10733      and create blank accessibility bitfields if necessary.  */
10734   TYPE_NFIELDS (type) = nfields;
10735   TYPE_FIELDS (type) = (struct field *)
10736     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10737   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10738
10739   if (fip->non_public_fields && cu->language != language_ada)
10740     {
10741       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10742
10743       TYPE_FIELD_PRIVATE_BITS (type) =
10744         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10745       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10746
10747       TYPE_FIELD_PROTECTED_BITS (type) =
10748         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10749       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10750
10751       TYPE_FIELD_IGNORE_BITS (type) =
10752         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10753       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10754     }
10755
10756   /* If the type has baseclasses, allocate and clear a bit vector for
10757      TYPE_FIELD_VIRTUAL_BITS.  */
10758   if (fip->nbaseclasses && cu->language != language_ada)
10759     {
10760       int num_bytes = B_BYTES (fip->nbaseclasses);
10761       unsigned char *pointer;
10762
10763       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10764       pointer = TYPE_ALLOC (type, num_bytes);
10765       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10766       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10767       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10768     }
10769
10770   /* Copy the saved-up fields into the field vector.  Start from the head of
10771      the list, adding to the tail of the field array, so that they end up in
10772      the same order in the array in which they were added to the list.  */
10773   while (nfields-- > 0)
10774     {
10775       struct nextfield *fieldp;
10776
10777       if (fip->fields)
10778         {
10779           fieldp = fip->fields;
10780           fip->fields = fieldp->next;
10781         }
10782       else
10783         {
10784           fieldp = fip->baseclasses;
10785           fip->baseclasses = fieldp->next;
10786         }
10787
10788       TYPE_FIELD (type, nfields) = fieldp->field;
10789       switch (fieldp->accessibility)
10790         {
10791         case DW_ACCESS_private:
10792           if (cu->language != language_ada)
10793             SET_TYPE_FIELD_PRIVATE (type, nfields);
10794           break;
10795
10796         case DW_ACCESS_protected:
10797           if (cu->language != language_ada)
10798             SET_TYPE_FIELD_PROTECTED (type, nfields);
10799           break;
10800
10801         case DW_ACCESS_public:
10802           break;
10803
10804         default:
10805           /* Unknown accessibility.  Complain and treat it as public.  */
10806           {
10807             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10808                        fieldp->accessibility);
10809           }
10810           break;
10811         }
10812       if (nfields < fip->nbaseclasses)
10813         {
10814           switch (fieldp->virtuality)
10815             {
10816             case DW_VIRTUALITY_virtual:
10817             case DW_VIRTUALITY_pure_virtual:
10818               if (cu->language == language_ada)
10819                 error (_("unexpected virtuality in component of Ada type"));
10820               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10821               break;
10822             }
10823         }
10824     }
10825 }
10826
10827 /* Return true if this member function is a constructor, false
10828    otherwise.  */
10829
10830 static int
10831 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
10832 {
10833   const char *fieldname;
10834   const char *typename;
10835   int len;
10836
10837   if (die->parent == NULL)
10838     return 0;
10839
10840   if (die->parent->tag != DW_TAG_structure_type
10841       && die->parent->tag != DW_TAG_union_type
10842       && die->parent->tag != DW_TAG_class_type)
10843     return 0;
10844
10845   fieldname = dwarf2_name (die, cu);
10846   typename = dwarf2_name (die->parent, cu);
10847   if (fieldname == NULL || typename == NULL)
10848     return 0;
10849
10850   len = strlen (fieldname);
10851   return (strncmp (fieldname, typename, len) == 0
10852           && (typename[len] == '\0' || typename[len] == '<'));
10853 }
10854
10855 /* Add a member function to the proper fieldlist.  */
10856
10857 static void
10858 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
10859                       struct type *type, struct dwarf2_cu *cu)
10860 {
10861   struct objfile *objfile = cu->objfile;
10862   struct attribute *attr;
10863   struct fnfieldlist *flp;
10864   int i;
10865   struct fn_field *fnp;
10866   const char *fieldname;
10867   struct nextfnfield *new_fnfield;
10868   struct type *this_type;
10869   enum dwarf_access_attribute accessibility;
10870
10871   if (cu->language == language_ada)
10872     error (_("unexpected member function in Ada type"));
10873
10874   /* Get name of member function.  */
10875   fieldname = dwarf2_name (die, cu);
10876   if (fieldname == NULL)
10877     return;
10878
10879   /* Look up member function name in fieldlist.  */
10880   for (i = 0; i < fip->nfnfields; i++)
10881     {
10882       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
10883         break;
10884     }
10885
10886   /* Create new list element if necessary.  */
10887   if (i < fip->nfnfields)
10888     flp = &fip->fnfieldlists[i];
10889   else
10890     {
10891       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
10892         {
10893           fip->fnfieldlists = (struct fnfieldlist *)
10894             xrealloc (fip->fnfieldlists,
10895                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
10896                       * sizeof (struct fnfieldlist));
10897           if (fip->nfnfields == 0)
10898             make_cleanup (free_current_contents, &fip->fnfieldlists);
10899         }
10900       flp = &fip->fnfieldlists[fip->nfnfields];
10901       flp->name = fieldname;
10902       flp->length = 0;
10903       flp->head = NULL;
10904       i = fip->nfnfields++;
10905     }
10906
10907   /* Create a new member function field and chain it to the field list
10908      entry.  */
10909   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
10910   make_cleanup (xfree, new_fnfield);
10911   memset (new_fnfield, 0, sizeof (struct nextfnfield));
10912   new_fnfield->next = flp->head;
10913   flp->head = new_fnfield;
10914   flp->length++;
10915
10916   /* Fill in the member function field info.  */
10917   fnp = &new_fnfield->fnfield;
10918
10919   /* Delay processing of the physname until later.  */
10920   if (cu->language == language_cplus || cu->language == language_java)
10921     {
10922       add_to_method_list (type, i, flp->length - 1, fieldname,
10923                           die, cu);
10924     }
10925   else
10926     {
10927       const char *physname = dwarf2_physname (fieldname, die, cu);
10928       fnp->physname = physname ? physname : "";
10929     }
10930
10931   fnp->type = alloc_type (objfile);
10932   this_type = read_type_die (die, cu);
10933   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
10934     {
10935       int nparams = TYPE_NFIELDS (this_type);
10936
10937       /* TYPE is the domain of this method, and THIS_TYPE is the type
10938            of the method itself (TYPE_CODE_METHOD).  */
10939       smash_to_method_type (fnp->type, type,
10940                             TYPE_TARGET_TYPE (this_type),
10941                             TYPE_FIELDS (this_type),
10942                             TYPE_NFIELDS (this_type),
10943                             TYPE_VARARGS (this_type));
10944
10945       /* Handle static member functions.
10946          Dwarf2 has no clean way to discern C++ static and non-static
10947          member functions.  G++ helps GDB by marking the first
10948          parameter for non-static member functions (which is the this
10949          pointer) as artificial.  We obtain this information from
10950          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
10951       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
10952         fnp->voffset = VOFFSET_STATIC;
10953     }
10954   else
10955     complaint (&symfile_complaints, _("member function type missing for '%s'"),
10956                dwarf2_full_name (fieldname, die, cu));
10957
10958   /* Get fcontext from DW_AT_containing_type if present.  */
10959   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
10960     fnp->fcontext = die_containing_type (die, cu);
10961
10962   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
10963      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
10964
10965   /* Get accessibility.  */
10966   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10967   if (attr)
10968     accessibility = DW_UNSND (attr);
10969   else
10970     accessibility = dwarf2_default_access_attribute (die, cu);
10971   switch (accessibility)
10972     {
10973     case DW_ACCESS_private:
10974       fnp->is_private = 1;
10975       break;
10976     case DW_ACCESS_protected:
10977       fnp->is_protected = 1;
10978       break;
10979     }
10980
10981   /* Check for artificial methods.  */
10982   attr = dwarf2_attr (die, DW_AT_artificial, cu);
10983   if (attr && DW_UNSND (attr) != 0)
10984     fnp->is_artificial = 1;
10985
10986   fnp->is_constructor = dwarf2_is_constructor (die, cu);
10987
10988   /* Get index in virtual function table if it is a virtual member
10989      function.  For older versions of GCC, this is an offset in the
10990      appropriate virtual table, as specified by DW_AT_containing_type.
10991      For everyone else, it is an expression to be evaluated relative
10992      to the object address.  */
10993
10994   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
10995   if (attr)
10996     {
10997       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
10998         {
10999           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11000             {
11001               /* Old-style GCC.  */
11002               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11003             }
11004           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11005                    || (DW_BLOCK (attr)->size > 1
11006                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11007                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11008             {
11009               struct dwarf_block blk;
11010               int offset;
11011
11012               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11013                         ? 1 : 2);
11014               blk.size = DW_BLOCK (attr)->size - offset;
11015               blk.data = DW_BLOCK (attr)->data + offset;
11016               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11017               if ((fnp->voffset % cu->header.addr_size) != 0)
11018                 dwarf2_complex_location_expr_complaint ();
11019               else
11020                 fnp->voffset /= cu->header.addr_size;
11021               fnp->voffset += 2;
11022             }
11023           else
11024             dwarf2_complex_location_expr_complaint ();
11025
11026           if (!fnp->fcontext)
11027             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11028         }
11029       else if (attr_form_is_section_offset (attr))
11030         {
11031           dwarf2_complex_location_expr_complaint ();
11032         }
11033       else
11034         {
11035           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11036                                                  fieldname);
11037         }
11038     }
11039   else
11040     {
11041       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11042       if (attr && DW_UNSND (attr))
11043         {
11044           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11045           complaint (&symfile_complaints,
11046                      _("Member function \"%s\" (offset %d) is virtual "
11047                        "but the vtable offset is not specified"),
11048                      fieldname, die->offset.sect_off);
11049           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11050           TYPE_CPLUS_DYNAMIC (type) = 1;
11051         }
11052     }
11053 }
11054
11055 /* Create the vector of member function fields, and attach it to the type.  */
11056
11057 static void
11058 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11059                                  struct dwarf2_cu *cu)
11060 {
11061   struct fnfieldlist *flp;
11062   int i;
11063
11064   if (cu->language == language_ada)
11065     error (_("unexpected member functions in Ada type"));
11066
11067   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11068   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11069     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11070
11071   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11072     {
11073       struct nextfnfield *nfp = flp->head;
11074       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11075       int k;
11076
11077       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11078       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11079       fn_flp->fn_fields = (struct fn_field *)
11080         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11081       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11082         fn_flp->fn_fields[k] = nfp->fnfield;
11083     }
11084
11085   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11086 }
11087
11088 /* Returns non-zero if NAME is the name of a vtable member in CU's
11089    language, zero otherwise.  */
11090 static int
11091 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11092 {
11093   static const char vptr[] = "_vptr";
11094   static const char vtable[] = "vtable";
11095
11096   /* Look for the C++ and Java forms of the vtable.  */
11097   if ((cu->language == language_java
11098        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11099        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11100        && is_cplus_marker (name[sizeof (vptr) - 1])))
11101     return 1;
11102
11103   return 0;
11104 }
11105
11106 /* GCC outputs unnamed structures that are really pointers to member
11107    functions, with the ABI-specified layout.  If TYPE describes
11108    such a structure, smash it into a member function type.
11109
11110    GCC shouldn't do this; it should just output pointer to member DIEs.
11111    This is GCC PR debug/28767.  */
11112
11113 static void
11114 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11115 {
11116   struct type *pfn_type, *domain_type, *new_type;
11117
11118   /* Check for a structure with no name and two children.  */
11119   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11120     return;
11121
11122   /* Check for __pfn and __delta members.  */
11123   if (TYPE_FIELD_NAME (type, 0) == NULL
11124       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11125       || TYPE_FIELD_NAME (type, 1) == NULL
11126       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11127     return;
11128
11129   /* Find the type of the method.  */
11130   pfn_type = TYPE_FIELD_TYPE (type, 0);
11131   if (pfn_type == NULL
11132       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11133       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11134     return;
11135
11136   /* Look for the "this" argument.  */
11137   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11138   if (TYPE_NFIELDS (pfn_type) == 0
11139       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11140       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11141     return;
11142
11143   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11144   new_type = alloc_type (objfile);
11145   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11146                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11147                         TYPE_VARARGS (pfn_type));
11148   smash_to_methodptr_type (type, new_type);
11149 }
11150
11151 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11152    (icc).  */
11153
11154 static int
11155 producer_is_icc (struct dwarf2_cu *cu)
11156 {
11157   if (!cu->checked_producer)
11158     check_producer (cu);
11159
11160   return cu->producer_is_icc;
11161 }
11162
11163 /* Called when we find the DIE that starts a structure or union scope
11164    (definition) to create a type for the structure or union.  Fill in
11165    the type's name and general properties; the members will not be
11166    processed until process_structure_type.
11167
11168    NOTE: we need to call these functions regardless of whether or not the
11169    DIE has a DW_AT_name attribute, since it might be an anonymous
11170    structure or union.  This gets the type entered into our set of
11171    user defined types.
11172
11173    However, if the structure is incomplete (an opaque struct/union)
11174    then suppress creating a symbol table entry for it since gdb only
11175    wants to find the one with the complete definition.  Note that if
11176    it is complete, we just call new_symbol, which does it's own
11177    checking about whether the struct/union is anonymous or not (and
11178    suppresses creating a symbol table entry itself).  */
11179
11180 static struct type *
11181 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11182 {
11183   struct objfile *objfile = cu->objfile;
11184   struct type *type;
11185   struct attribute *attr;
11186   const char *name;
11187
11188   /* If the definition of this type lives in .debug_types, read that type.
11189      Don't follow DW_AT_specification though, that will take us back up
11190      the chain and we want to go down.  */
11191   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11192   if (attr)
11193     {
11194       struct dwarf2_cu *type_cu = cu;
11195       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11196
11197       /* We could just recurse on read_structure_type, but we need to call
11198          get_die_type to ensure only one type for this DIE is created.
11199          This is important, for example, because for c++ classes we need
11200          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11201       type = read_type_die (type_die, type_cu);
11202
11203       /* TYPE_CU may not be the same as CU.
11204          Ensure TYPE is recorded in CU's type_hash table.  */
11205       return set_die_type (die, type, cu);
11206     }
11207
11208   type = alloc_type (objfile);
11209   INIT_CPLUS_SPECIFIC (type);
11210
11211   name = dwarf2_name (die, cu);
11212   if (name != NULL)
11213     {
11214       if (cu->language == language_cplus
11215           || cu->language == language_java)
11216         {
11217           const char *full_name = dwarf2_full_name (name, die, cu);
11218
11219           /* dwarf2_full_name might have already finished building the DIE's
11220              type.  If so, there is no need to continue.  */
11221           if (get_die_type (die, cu) != NULL)
11222             return get_die_type (die, cu);
11223
11224           TYPE_TAG_NAME (type) = full_name;
11225           if (die->tag == DW_TAG_structure_type
11226               || die->tag == DW_TAG_class_type)
11227             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11228         }
11229       else
11230         {
11231           /* The name is already allocated along with this objfile, so
11232              we don't need to duplicate it for the type.  */
11233           TYPE_TAG_NAME (type) = name;
11234           if (die->tag == DW_TAG_class_type)
11235             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11236         }
11237     }
11238
11239   if (die->tag == DW_TAG_structure_type)
11240     {
11241       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11242     }
11243   else if (die->tag == DW_TAG_union_type)
11244     {
11245       TYPE_CODE (type) = TYPE_CODE_UNION;
11246     }
11247   else
11248     {
11249       TYPE_CODE (type) = TYPE_CODE_CLASS;
11250     }
11251
11252   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11253     TYPE_DECLARED_CLASS (type) = 1;
11254
11255   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11256   if (attr)
11257     {
11258       TYPE_LENGTH (type) = DW_UNSND (attr);
11259     }
11260   else
11261     {
11262       TYPE_LENGTH (type) = 0;
11263     }
11264
11265   if (producer_is_icc (cu))
11266     {
11267       /* ICC does not output the required DW_AT_declaration
11268          on incomplete types, but gives them a size of zero.  */
11269     }
11270   else
11271     TYPE_STUB_SUPPORTED (type) = 1;
11272
11273   if (die_is_declaration (die, cu))
11274     TYPE_STUB (type) = 1;
11275   else if (attr == NULL && die->child == NULL
11276            && producer_is_realview (cu->producer))
11277     /* RealView does not output the required DW_AT_declaration
11278        on incomplete types.  */
11279     TYPE_STUB (type) = 1;
11280
11281   /* We need to add the type field to the die immediately so we don't
11282      infinitely recurse when dealing with pointers to the structure
11283      type within the structure itself.  */
11284   set_die_type (die, type, cu);
11285
11286   /* set_die_type should be already done.  */
11287   set_descriptive_type (type, die, cu);
11288
11289   return type;
11290 }
11291
11292 /* Finish creating a structure or union type, including filling in
11293    its members and creating a symbol for it.  */
11294
11295 static void
11296 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11297 {
11298   struct objfile *objfile = cu->objfile;
11299   struct die_info *child_die = die->child;
11300   struct type *type;
11301
11302   type = get_die_type (die, cu);
11303   if (type == NULL)
11304     type = read_structure_type (die, cu);
11305
11306   if (die->child != NULL && ! die_is_declaration (die, cu))
11307     {
11308       struct field_info fi;
11309       struct die_info *child_die;
11310       VEC (symbolp) *template_args = NULL;
11311       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11312
11313       memset (&fi, 0, sizeof (struct field_info));
11314
11315       child_die = die->child;
11316
11317       while (child_die && child_die->tag)
11318         {
11319           if (child_die->tag == DW_TAG_member
11320               || child_die->tag == DW_TAG_variable)
11321             {
11322               /* NOTE: carlton/2002-11-05: A C++ static data member
11323                  should be a DW_TAG_member that is a declaration, but
11324                  all versions of G++ as of this writing (so through at
11325                  least 3.2.1) incorrectly generate DW_TAG_variable
11326                  tags for them instead.  */
11327               dwarf2_add_field (&fi, child_die, cu);
11328             }
11329           else if (child_die->tag == DW_TAG_subprogram)
11330             {
11331               /* C++ member function.  */
11332               dwarf2_add_member_fn (&fi, child_die, type, cu);
11333             }
11334           else if (child_die->tag == DW_TAG_inheritance)
11335             {
11336               /* C++ base class field.  */
11337               dwarf2_add_field (&fi, child_die, cu);
11338             }
11339           else if (child_die->tag == DW_TAG_typedef)
11340             dwarf2_add_typedef (&fi, child_die, cu);
11341           else if (child_die->tag == DW_TAG_template_type_param
11342                    || child_die->tag == DW_TAG_template_value_param)
11343             {
11344               struct symbol *arg = new_symbol (child_die, NULL, cu);
11345
11346               if (arg != NULL)
11347                 VEC_safe_push (symbolp, template_args, arg);
11348             }
11349
11350           child_die = sibling_die (child_die);
11351         }
11352
11353       /* Attach template arguments to type.  */
11354       if (! VEC_empty (symbolp, template_args))
11355         {
11356           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11357           TYPE_N_TEMPLATE_ARGUMENTS (type)
11358             = VEC_length (symbolp, template_args);
11359           TYPE_TEMPLATE_ARGUMENTS (type)
11360             = obstack_alloc (&objfile->objfile_obstack,
11361                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11362                               * sizeof (struct symbol *)));
11363           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11364                   VEC_address (symbolp, template_args),
11365                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11366                    * sizeof (struct symbol *)));
11367           VEC_free (symbolp, template_args);
11368         }
11369
11370       /* Attach fields and member functions to the type.  */
11371       if (fi.nfields)
11372         dwarf2_attach_fields_to_type (&fi, type, cu);
11373       if (fi.nfnfields)
11374         {
11375           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11376
11377           /* Get the type which refers to the base class (possibly this
11378              class itself) which contains the vtable pointer for the current
11379              class from the DW_AT_containing_type attribute.  This use of
11380              DW_AT_containing_type is a GNU extension.  */
11381
11382           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11383             {
11384               struct type *t = die_containing_type (die, cu);
11385
11386               TYPE_VPTR_BASETYPE (type) = t;
11387               if (type == t)
11388                 {
11389                   int i;
11390
11391                   /* Our own class provides vtbl ptr.  */
11392                   for (i = TYPE_NFIELDS (t) - 1;
11393                        i >= TYPE_N_BASECLASSES (t);
11394                        --i)
11395                     {
11396                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11397
11398                       if (is_vtable_name (fieldname, cu))
11399                         {
11400                           TYPE_VPTR_FIELDNO (type) = i;
11401                           break;
11402                         }
11403                     }
11404
11405                   /* Complain if virtual function table field not found.  */
11406                   if (i < TYPE_N_BASECLASSES (t))
11407                     complaint (&symfile_complaints,
11408                                _("virtual function table pointer "
11409                                  "not found when defining class '%s'"),
11410                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11411                                "");
11412                 }
11413               else
11414                 {
11415                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11416                 }
11417             }
11418           else if (cu->producer
11419                    && strncmp (cu->producer,
11420                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11421             {
11422               /* The IBM XLC compiler does not provide direct indication
11423                  of the containing type, but the vtable pointer is
11424                  always named __vfp.  */
11425
11426               int i;
11427
11428               for (i = TYPE_NFIELDS (type) - 1;
11429                    i >= TYPE_N_BASECLASSES (type);
11430                    --i)
11431                 {
11432                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11433                     {
11434                       TYPE_VPTR_FIELDNO (type) = i;
11435                       TYPE_VPTR_BASETYPE (type) = type;
11436                       break;
11437                     }
11438                 }
11439             }
11440         }
11441
11442       /* Copy fi.typedef_field_list linked list elements content into the
11443          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11444       if (fi.typedef_field_list)
11445         {
11446           int i = fi.typedef_field_list_count;
11447
11448           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11449           TYPE_TYPEDEF_FIELD_ARRAY (type)
11450             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11451           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11452
11453           /* Reverse the list order to keep the debug info elements order.  */
11454           while (--i >= 0)
11455             {
11456               struct typedef_field *dest, *src;
11457
11458               dest = &TYPE_TYPEDEF_FIELD (type, i);
11459               src = &fi.typedef_field_list->field;
11460               fi.typedef_field_list = fi.typedef_field_list->next;
11461               *dest = *src;
11462             }
11463         }
11464
11465       do_cleanups (back_to);
11466
11467       if (HAVE_CPLUS_STRUCT (type))
11468         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11469     }
11470
11471   quirk_gcc_member_function_pointer (type, objfile);
11472
11473   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11474      snapshots) has been known to create a die giving a declaration
11475      for a class that has, as a child, a die giving a definition for a
11476      nested class.  So we have to process our children even if the
11477      current die is a declaration.  Normally, of course, a declaration
11478      won't have any children at all.  */
11479
11480   while (child_die != NULL && child_die->tag)
11481     {
11482       if (child_die->tag == DW_TAG_member
11483           || child_die->tag == DW_TAG_variable
11484           || child_die->tag == DW_TAG_inheritance
11485           || child_die->tag == DW_TAG_template_value_param
11486           || child_die->tag == DW_TAG_template_type_param)
11487         {
11488           /* Do nothing.  */
11489         }
11490       else
11491         process_die (child_die, cu);
11492
11493       child_die = sibling_die (child_die);
11494     }
11495
11496   /* Do not consider external references.  According to the DWARF standard,
11497      these DIEs are identified by the fact that they have no byte_size
11498      attribute, and a declaration attribute.  */
11499   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11500       || !die_is_declaration (die, cu))
11501     new_symbol (die, type, cu);
11502 }
11503
11504 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11505    complete the type's fields yet, or create any symbols.  */
11506
11507 static struct type *
11508 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11509 {
11510   struct objfile *objfile = cu->objfile;
11511   struct type *type;
11512   struct attribute *attr;
11513   const char *name;
11514
11515   /* If the definition of this type lives in .debug_types, read that type.
11516      Don't follow DW_AT_specification though, that will take us back up
11517      the chain and we want to go down.  */
11518   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11519   if (attr)
11520     {
11521       struct dwarf2_cu *type_cu = cu;
11522       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11523
11524       type = read_type_die (type_die, type_cu);
11525
11526       /* TYPE_CU may not be the same as CU.
11527          Ensure TYPE is recorded in CU's type_hash table.  */
11528       return set_die_type (die, type, cu);
11529     }
11530
11531   type = alloc_type (objfile);
11532
11533   TYPE_CODE (type) = TYPE_CODE_ENUM;
11534   name = dwarf2_full_name (NULL, die, cu);
11535   if (name != NULL)
11536     TYPE_TAG_NAME (type) = name;
11537
11538   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11539   if (attr)
11540     {
11541       TYPE_LENGTH (type) = DW_UNSND (attr);
11542     }
11543   else
11544     {
11545       TYPE_LENGTH (type) = 0;
11546     }
11547
11548   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11549      declared as private in the package spec, and then defined only
11550      inside the package body.  Such types are known as Taft Amendment
11551      Types.  When another package uses such a type, an incomplete DIE
11552      may be generated by the compiler.  */
11553   if (die_is_declaration (die, cu))
11554     TYPE_STUB (type) = 1;
11555
11556   return set_die_type (die, type, cu);
11557 }
11558
11559 /* Given a pointer to a die which begins an enumeration, process all
11560    the dies that define the members of the enumeration, and create the
11561    symbol for the enumeration type.
11562
11563    NOTE: We reverse the order of the element list.  */
11564
11565 static void
11566 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11567 {
11568   struct type *this_type;
11569
11570   this_type = get_die_type (die, cu);
11571   if (this_type == NULL)
11572     this_type = read_enumeration_type (die, cu);
11573
11574   if (die->child != NULL)
11575     {
11576       struct die_info *child_die;
11577       struct symbol *sym;
11578       struct field *fields = NULL;
11579       int num_fields = 0;
11580       int unsigned_enum = 1;
11581       const char *name;
11582       int flag_enum = 1;
11583       ULONGEST mask = 0;
11584
11585       child_die = die->child;
11586       while (child_die && child_die->tag)
11587         {
11588           if (child_die->tag != DW_TAG_enumerator)
11589             {
11590               process_die (child_die, cu);
11591             }
11592           else
11593             {
11594               name = dwarf2_name (child_die, cu);
11595               if (name)
11596                 {
11597                   sym = new_symbol (child_die, this_type, cu);
11598                   if (SYMBOL_VALUE (sym) < 0)
11599                     {
11600                       unsigned_enum = 0;
11601                       flag_enum = 0;
11602                     }
11603                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11604                     flag_enum = 0;
11605                   else
11606                     mask |= SYMBOL_VALUE (sym);
11607
11608                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11609                     {
11610                       fields = (struct field *)
11611                         xrealloc (fields,
11612                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11613                                   * sizeof (struct field));
11614                     }
11615
11616                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11617                   FIELD_TYPE (fields[num_fields]) = NULL;
11618                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11619                   FIELD_BITSIZE (fields[num_fields]) = 0;
11620
11621                   num_fields++;
11622                 }
11623             }
11624
11625           child_die = sibling_die (child_die);
11626         }
11627
11628       if (num_fields)
11629         {
11630           TYPE_NFIELDS (this_type) = num_fields;
11631           TYPE_FIELDS (this_type) = (struct field *)
11632             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11633           memcpy (TYPE_FIELDS (this_type), fields,
11634                   sizeof (struct field) * num_fields);
11635           xfree (fields);
11636         }
11637       if (unsigned_enum)
11638         TYPE_UNSIGNED (this_type) = 1;
11639       if (flag_enum)
11640         TYPE_FLAG_ENUM (this_type) = 1;
11641     }
11642
11643   /* If we are reading an enum from a .debug_types unit, and the enum
11644      is a declaration, and the enum is not the signatured type in the
11645      unit, then we do not want to add a symbol for it.  Adding a
11646      symbol would in some cases obscure the true definition of the
11647      enum, giving users an incomplete type when the definition is
11648      actually available.  Note that we do not want to do this for all
11649      enums which are just declarations, because C++0x allows forward
11650      enum declarations.  */
11651   if (cu->per_cu->is_debug_types
11652       && die_is_declaration (die, cu))
11653     {
11654       struct signatured_type *sig_type;
11655
11656       sig_type
11657         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
11658                                             cu->per_cu->info_or_types_section,
11659                                             cu->per_cu->offset);
11660       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11661       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11662         return;
11663     }
11664
11665   new_symbol (die, this_type, cu);
11666 }
11667
11668 /* Extract all information from a DW_TAG_array_type DIE and put it in
11669    the DIE's type field.  For now, this only handles one dimensional
11670    arrays.  */
11671
11672 static struct type *
11673 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11674 {
11675   struct objfile *objfile = cu->objfile;
11676   struct die_info *child_die;
11677   struct type *type;
11678   struct type *element_type, *range_type, *index_type;
11679   struct type **range_types = NULL;
11680   struct attribute *attr;
11681   int ndim = 0;
11682   struct cleanup *back_to;
11683   const char *name;
11684
11685   element_type = die_type (die, cu);
11686
11687   /* The die_type call above may have already set the type for this DIE.  */
11688   type = get_die_type (die, cu);
11689   if (type)
11690     return type;
11691
11692   /* Irix 6.2 native cc creates array types without children for
11693      arrays with unspecified length.  */
11694   if (die->child == NULL)
11695     {
11696       index_type = objfile_type (objfile)->builtin_int;
11697       range_type = create_range_type (NULL, index_type, 0, -1);
11698       type = create_array_type (NULL, element_type, range_type);
11699       return set_die_type (die, type, cu);
11700     }
11701
11702   back_to = make_cleanup (null_cleanup, NULL);
11703   child_die = die->child;
11704   while (child_die && child_die->tag)
11705     {
11706       if (child_die->tag == DW_TAG_subrange_type)
11707         {
11708           struct type *child_type = read_type_die (child_die, cu);
11709
11710           if (child_type != NULL)
11711             {
11712               /* The range type was succesfully read.  Save it for the
11713                  array type creation.  */
11714               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11715                 {
11716                   range_types = (struct type **)
11717                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11718                               * sizeof (struct type *));
11719                   if (ndim == 0)
11720                     make_cleanup (free_current_contents, &range_types);
11721                 }
11722               range_types[ndim++] = child_type;
11723             }
11724         }
11725       child_die = sibling_die (child_die);
11726     }
11727
11728   /* Dwarf2 dimensions are output from left to right, create the
11729      necessary array types in backwards order.  */
11730
11731   type = element_type;
11732
11733   if (read_array_order (die, cu) == DW_ORD_col_major)
11734     {
11735       int i = 0;
11736
11737       while (i < ndim)
11738         type = create_array_type (NULL, type, range_types[i++]);
11739     }
11740   else
11741     {
11742       while (ndim-- > 0)
11743         type = create_array_type (NULL, type, range_types[ndim]);
11744     }
11745
11746   /* Understand Dwarf2 support for vector types (like they occur on
11747      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11748      array type.  This is not part of the Dwarf2/3 standard yet, but a
11749      custom vendor extension.  The main difference between a regular
11750      array and the vector variant is that vectors are passed by value
11751      to functions.  */
11752   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11753   if (attr)
11754     make_vector_type (type);
11755
11756   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11757      implementation may choose to implement triple vectors using this
11758      attribute.  */
11759   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11760   if (attr)
11761     {
11762       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11763         TYPE_LENGTH (type) = DW_UNSND (attr);
11764       else
11765         complaint (&symfile_complaints,
11766                    _("DW_AT_byte_size for array type smaller "
11767                      "than the total size of elements"));
11768     }
11769
11770   name = dwarf2_name (die, cu);
11771   if (name)
11772     TYPE_NAME (type) = name;
11773
11774   /* Install the type in the die.  */
11775   set_die_type (die, type, cu);
11776
11777   /* set_die_type should be already done.  */
11778   set_descriptive_type (type, die, cu);
11779
11780   do_cleanups (back_to);
11781
11782   return type;
11783 }
11784
11785 static enum dwarf_array_dim_ordering
11786 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11787 {
11788   struct attribute *attr;
11789
11790   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11791
11792   if (attr) return DW_SND (attr);
11793
11794   /* GNU F77 is a special case, as at 08/2004 array type info is the
11795      opposite order to the dwarf2 specification, but data is still
11796      laid out as per normal fortran.
11797
11798      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11799      version checking.  */
11800
11801   if (cu->language == language_fortran
11802       && cu->producer && strstr (cu->producer, "GNU F77"))
11803     {
11804       return DW_ORD_row_major;
11805     }
11806
11807   switch (cu->language_defn->la_array_ordering)
11808     {
11809     case array_column_major:
11810       return DW_ORD_col_major;
11811     case array_row_major:
11812     default:
11813       return DW_ORD_row_major;
11814     };
11815 }
11816
11817 /* Extract all information from a DW_TAG_set_type DIE and put it in
11818    the DIE's type field.  */
11819
11820 static struct type *
11821 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11822 {
11823   struct type *domain_type, *set_type;
11824   struct attribute *attr;
11825
11826   domain_type = die_type (die, cu);
11827
11828   /* The die_type call above may have already set the type for this DIE.  */
11829   set_type = get_die_type (die, cu);
11830   if (set_type)
11831     return set_type;
11832
11833   set_type = create_set_type (NULL, domain_type);
11834
11835   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11836   if (attr)
11837     TYPE_LENGTH (set_type) = DW_UNSND (attr);
11838
11839   return set_die_type (die, set_type, cu);
11840 }
11841
11842 /* A helper for read_common_block that creates a locexpr baton.
11843    SYM is the symbol which we are marking as computed.
11844    COMMON_DIE is the DIE for the common block.
11845    COMMON_LOC is the location expression attribute for the common
11846    block itself.
11847    MEMBER_LOC is the location expression attribute for the particular
11848    member of the common block that we are processing.
11849    CU is the CU from which the above come.  */
11850
11851 static void
11852 mark_common_block_symbol_computed (struct symbol *sym,
11853                                    struct die_info *common_die,
11854                                    struct attribute *common_loc,
11855                                    struct attribute *member_loc,
11856                                    struct dwarf2_cu *cu)
11857 {
11858   struct objfile *objfile = dwarf2_per_objfile->objfile;
11859   struct dwarf2_locexpr_baton *baton;
11860   gdb_byte *ptr;
11861   unsigned int cu_off;
11862   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
11863   LONGEST offset = 0;
11864
11865   gdb_assert (common_loc && member_loc);
11866   gdb_assert (attr_form_is_block (common_loc));
11867   gdb_assert (attr_form_is_block (member_loc)
11868               || attr_form_is_constant (member_loc));
11869
11870   baton = obstack_alloc (&objfile->objfile_obstack,
11871                          sizeof (struct dwarf2_locexpr_baton));
11872   baton->per_cu = cu->per_cu;
11873   gdb_assert (baton->per_cu);
11874
11875   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
11876
11877   if (attr_form_is_constant (member_loc))
11878     {
11879       offset = dwarf2_get_attr_constant_value (member_loc, 0);
11880       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
11881     }
11882   else
11883     baton->size += DW_BLOCK (member_loc)->size;
11884
11885   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
11886   baton->data = ptr;
11887
11888   *ptr++ = DW_OP_call4;
11889   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
11890   store_unsigned_integer (ptr, 4, byte_order, cu_off);
11891   ptr += 4;
11892
11893   if (attr_form_is_constant (member_loc))
11894     {
11895       *ptr++ = DW_OP_addr;
11896       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
11897       ptr += cu->header.addr_size;
11898     }
11899   else
11900     {
11901       /* We have to copy the data here, because DW_OP_call4 will only
11902          use a DW_AT_location attribute.  */
11903       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
11904       ptr += DW_BLOCK (member_loc)->size;
11905     }
11906
11907   *ptr++ = DW_OP_plus;
11908   gdb_assert (ptr - baton->data == baton->size);
11909
11910   SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
11911   SYMBOL_LOCATION_BATON (sym) = baton;
11912   SYMBOL_CLASS (sym) = LOC_COMPUTED;
11913 }
11914
11915 /* Create appropriate locally-scoped variables for all the
11916    DW_TAG_common_block entries.  Also create a struct common_block
11917    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
11918    is used to sepate the common blocks name namespace from regular
11919    variable names.  */
11920
11921 static void
11922 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
11923 {
11924   struct attribute *attr;
11925
11926   attr = dwarf2_attr (die, DW_AT_location, cu);
11927   if (attr)
11928     {
11929       /* Support the .debug_loc offsets.  */
11930       if (attr_form_is_block (attr))
11931         {
11932           /* Ok.  */
11933         }
11934       else if (attr_form_is_section_offset (attr))
11935         {
11936           dwarf2_complex_location_expr_complaint ();
11937           attr = NULL;
11938         }
11939       else
11940         {
11941           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11942                                                  "common block member");
11943           attr = NULL;
11944         }
11945     }
11946
11947   if (die->child != NULL)
11948     {
11949       struct objfile *objfile = cu->objfile;
11950       struct die_info *child_die;
11951       size_t n_entries = 0, size;
11952       struct common_block *common_block;
11953       struct symbol *sym;
11954
11955       for (child_die = die->child;
11956            child_die && child_die->tag;
11957            child_die = sibling_die (child_die))
11958         ++n_entries;
11959
11960       size = (sizeof (struct common_block)
11961               + (n_entries - 1) * sizeof (struct symbol *));
11962       common_block = obstack_alloc (&objfile->objfile_obstack, size);
11963       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
11964       common_block->n_entries = 0;
11965
11966       for (child_die = die->child;
11967            child_die && child_die->tag;
11968            child_die = sibling_die (child_die))
11969         {
11970           /* Create the symbol in the DW_TAG_common_block block in the current
11971              symbol scope.  */
11972           sym = new_symbol (child_die, NULL, cu);
11973           if (sym != NULL)
11974             {
11975               struct attribute *member_loc;
11976
11977               common_block->contents[common_block->n_entries++] = sym;
11978
11979               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
11980                                         cu);
11981               if (member_loc)
11982                 {
11983                   /* GDB has handled this for a long time, but it is
11984                      not specified by DWARF.  It seems to have been
11985                      emitted by gfortran at least as recently as:
11986                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
11987                   complaint (&symfile_complaints,
11988                              _("Variable in common block has "
11989                                "DW_AT_data_member_location "
11990                                "- DIE at 0x%x [in module %s]"),
11991                              child_die->offset.sect_off, cu->objfile->name);
11992
11993                   if (attr_form_is_section_offset (member_loc))
11994                     dwarf2_complex_location_expr_complaint ();
11995                   else if (attr_form_is_constant (member_loc)
11996                            || attr_form_is_block (member_loc))
11997                     {
11998                       if (attr)
11999                         mark_common_block_symbol_computed (sym, die, attr,
12000                                                            member_loc, cu);
12001                     }
12002                   else
12003                     dwarf2_complex_location_expr_complaint ();
12004                 }
12005             }
12006         }
12007
12008       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12009       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12010     }
12011 }
12012
12013 /* Create a type for a C++ namespace.  */
12014
12015 static struct type *
12016 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12017 {
12018   struct objfile *objfile = cu->objfile;
12019   const char *previous_prefix, *name;
12020   int is_anonymous;
12021   struct type *type;
12022
12023   /* For extensions, reuse the type of the original namespace.  */
12024   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12025     {
12026       struct die_info *ext_die;
12027       struct dwarf2_cu *ext_cu = cu;
12028
12029       ext_die = dwarf2_extension (die, &ext_cu);
12030       type = read_type_die (ext_die, ext_cu);
12031
12032       /* EXT_CU may not be the same as CU.
12033          Ensure TYPE is recorded in CU's type_hash table.  */
12034       return set_die_type (die, type, cu);
12035     }
12036
12037   name = namespace_name (die, &is_anonymous, cu);
12038
12039   /* Now build the name of the current namespace.  */
12040
12041   previous_prefix = determine_prefix (die, cu);
12042   if (previous_prefix[0] != '\0')
12043     name = typename_concat (&objfile->objfile_obstack,
12044                             previous_prefix, name, 0, cu);
12045
12046   /* Create the type.  */
12047   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12048                     objfile);
12049   TYPE_NAME (type) = name;
12050   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12051
12052   return set_die_type (die, type, cu);
12053 }
12054
12055 /* Read a C++ namespace.  */
12056
12057 static void
12058 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12059 {
12060   struct objfile *objfile = cu->objfile;
12061   int is_anonymous;
12062
12063   /* Add a symbol associated to this if we haven't seen the namespace
12064      before.  Also, add a using directive if it's an anonymous
12065      namespace.  */
12066
12067   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12068     {
12069       struct type *type;
12070
12071       type = read_type_die (die, cu);
12072       new_symbol (die, type, cu);
12073
12074       namespace_name (die, &is_anonymous, cu);
12075       if (is_anonymous)
12076         {
12077           const char *previous_prefix = determine_prefix (die, cu);
12078
12079           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12080                                   NULL, NULL, 0, &objfile->objfile_obstack);
12081         }
12082     }
12083
12084   if (die->child != NULL)
12085     {
12086       struct die_info *child_die = die->child;
12087
12088       while (child_die && child_die->tag)
12089         {
12090           process_die (child_die, cu);
12091           child_die = sibling_die (child_die);
12092         }
12093     }
12094 }
12095
12096 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12097    imported module.  Still we need that type as local Fortran "use ... only"
12098    declaration imports depend on the created type in determine_prefix.  */
12099
12100 static struct type *
12101 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12102 {
12103   struct objfile *objfile = cu->objfile;
12104   const char *module_name;
12105   struct type *type;
12106
12107   module_name = dwarf2_name (die, cu);
12108   if (!module_name)
12109     complaint (&symfile_complaints,
12110                _("DW_TAG_module has no name, offset 0x%x"),
12111                die->offset.sect_off);
12112   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12113
12114   /* determine_prefix uses TYPE_TAG_NAME.  */
12115   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12116
12117   return set_die_type (die, type, cu);
12118 }
12119
12120 /* Read a Fortran module.  */
12121
12122 static void
12123 read_module (struct die_info *die, struct dwarf2_cu *cu)
12124 {
12125   struct die_info *child_die = die->child;
12126
12127   while (child_die && child_die->tag)
12128     {
12129       process_die (child_die, cu);
12130       child_die = sibling_die (child_die);
12131     }
12132 }
12133
12134 /* Return the name of the namespace represented by DIE.  Set
12135    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12136    namespace.  */
12137
12138 static const char *
12139 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12140 {
12141   struct die_info *current_die;
12142   const char *name = NULL;
12143
12144   /* Loop through the extensions until we find a name.  */
12145
12146   for (current_die = die;
12147        current_die != NULL;
12148        current_die = dwarf2_extension (die, &cu))
12149     {
12150       name = dwarf2_name (current_die, cu);
12151       if (name != NULL)
12152         break;
12153     }
12154
12155   /* Is it an anonymous namespace?  */
12156
12157   *is_anonymous = (name == NULL);
12158   if (*is_anonymous)
12159     name = CP_ANONYMOUS_NAMESPACE_STR;
12160
12161   return name;
12162 }
12163
12164 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12165    the user defined type vector.  */
12166
12167 static struct type *
12168 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12169 {
12170   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12171   struct comp_unit_head *cu_header = &cu->header;
12172   struct type *type;
12173   struct attribute *attr_byte_size;
12174   struct attribute *attr_address_class;
12175   int byte_size, addr_class;
12176   struct type *target_type;
12177
12178   target_type = die_type (die, cu);
12179
12180   /* The die_type call above may have already set the type for this DIE.  */
12181   type = get_die_type (die, cu);
12182   if (type)
12183     return type;
12184
12185   type = lookup_pointer_type (target_type);
12186
12187   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12188   if (attr_byte_size)
12189     byte_size = DW_UNSND (attr_byte_size);
12190   else
12191     byte_size = cu_header->addr_size;
12192
12193   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12194   if (attr_address_class)
12195     addr_class = DW_UNSND (attr_address_class);
12196   else
12197     addr_class = DW_ADDR_none;
12198
12199   /* If the pointer size or address class is different than the
12200      default, create a type variant marked as such and set the
12201      length accordingly.  */
12202   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12203     {
12204       if (gdbarch_address_class_type_flags_p (gdbarch))
12205         {
12206           int type_flags;
12207
12208           type_flags = gdbarch_address_class_type_flags
12209                          (gdbarch, byte_size, addr_class);
12210           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12211                       == 0);
12212           type = make_type_with_address_space (type, type_flags);
12213         }
12214       else if (TYPE_LENGTH (type) != byte_size)
12215         {
12216           complaint (&symfile_complaints,
12217                      _("invalid pointer size %d"), byte_size);
12218         }
12219       else
12220         {
12221           /* Should we also complain about unhandled address classes?  */
12222         }
12223     }
12224
12225   TYPE_LENGTH (type) = byte_size;
12226   return set_die_type (die, type, cu);
12227 }
12228
12229 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12230    the user defined type vector.  */
12231
12232 static struct type *
12233 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12234 {
12235   struct type *type;
12236   struct type *to_type;
12237   struct type *domain;
12238
12239   to_type = die_type (die, cu);
12240   domain = die_containing_type (die, cu);
12241
12242   /* The calls above may have already set the type for this DIE.  */
12243   type = get_die_type (die, cu);
12244   if (type)
12245     return type;
12246
12247   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12248     type = lookup_methodptr_type (to_type);
12249   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12250     {
12251       struct type *new_type = alloc_type (cu->objfile);
12252
12253       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12254                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12255                             TYPE_VARARGS (to_type));
12256       type = lookup_methodptr_type (new_type);
12257     }
12258   else
12259     type = lookup_memberptr_type (to_type, domain);
12260
12261   return set_die_type (die, type, cu);
12262 }
12263
12264 /* Extract all information from a DW_TAG_reference_type DIE and add to
12265    the user defined type vector.  */
12266
12267 static struct type *
12268 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12269 {
12270   struct comp_unit_head *cu_header = &cu->header;
12271   struct type *type, *target_type;
12272   struct attribute *attr;
12273
12274   target_type = die_type (die, cu);
12275
12276   /* The die_type call above may have already set the type for this DIE.  */
12277   type = get_die_type (die, cu);
12278   if (type)
12279     return type;
12280
12281   type = lookup_reference_type (target_type);
12282   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12283   if (attr)
12284     {
12285       TYPE_LENGTH (type) = DW_UNSND (attr);
12286     }
12287   else
12288     {
12289       TYPE_LENGTH (type) = cu_header->addr_size;
12290     }
12291   return set_die_type (die, type, cu);
12292 }
12293
12294 static struct type *
12295 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12296 {
12297   struct type *base_type, *cv_type;
12298
12299   base_type = die_type (die, cu);
12300
12301   /* The die_type call above may have already set the type for this DIE.  */
12302   cv_type = get_die_type (die, cu);
12303   if (cv_type)
12304     return cv_type;
12305
12306   /* In case the const qualifier is applied to an array type, the element type
12307      is so qualified, not the array type (section 6.7.3 of C99).  */
12308   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12309     {
12310       struct type *el_type, *inner_array;
12311
12312       base_type = copy_type (base_type);
12313       inner_array = base_type;
12314
12315       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12316         {
12317           TYPE_TARGET_TYPE (inner_array) =
12318             copy_type (TYPE_TARGET_TYPE (inner_array));
12319           inner_array = TYPE_TARGET_TYPE (inner_array);
12320         }
12321
12322       el_type = TYPE_TARGET_TYPE (inner_array);
12323       TYPE_TARGET_TYPE (inner_array) =
12324         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12325
12326       return set_die_type (die, base_type, cu);
12327     }
12328
12329   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12330   return set_die_type (die, cv_type, cu);
12331 }
12332
12333 static struct type *
12334 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12335 {
12336   struct type *base_type, *cv_type;
12337
12338   base_type = die_type (die, cu);
12339
12340   /* The die_type call above may have already set the type for this DIE.  */
12341   cv_type = get_die_type (die, cu);
12342   if (cv_type)
12343     return cv_type;
12344
12345   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12346   return set_die_type (die, cv_type, cu);
12347 }
12348
12349 /* Handle DW_TAG_restrict_type.  */
12350
12351 static struct type *
12352 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12353 {
12354   struct type *base_type, *cv_type;
12355
12356   base_type = die_type (die, cu);
12357
12358   /* The die_type call above may have already set the type for this DIE.  */
12359   cv_type = get_die_type (die, cu);
12360   if (cv_type)
12361     return cv_type;
12362
12363   cv_type = make_restrict_type (base_type);
12364   return set_die_type (die, cv_type, cu);
12365 }
12366
12367 /* Extract all information from a DW_TAG_string_type DIE and add to
12368    the user defined type vector.  It isn't really a user defined type,
12369    but it behaves like one, with other DIE's using an AT_user_def_type
12370    attribute to reference it.  */
12371
12372 static struct type *
12373 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12374 {
12375   struct objfile *objfile = cu->objfile;
12376   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12377   struct type *type, *range_type, *index_type, *char_type;
12378   struct attribute *attr;
12379   unsigned int length;
12380
12381   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12382   if (attr)
12383     {
12384       length = DW_UNSND (attr);
12385     }
12386   else
12387     {
12388       /* Check for the DW_AT_byte_size attribute.  */
12389       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12390       if (attr)
12391         {
12392           length = DW_UNSND (attr);
12393         }
12394       else
12395         {
12396           length = 1;
12397         }
12398     }
12399
12400   index_type = objfile_type (objfile)->builtin_int;
12401   range_type = create_range_type (NULL, index_type, 1, length);
12402   char_type = language_string_char_type (cu->language_defn, gdbarch);
12403   type = create_string_type (NULL, char_type, range_type);
12404
12405   return set_die_type (die, type, cu);
12406 }
12407
12408 /* Handle DIES due to C code like:
12409
12410    struct foo
12411    {
12412    int (*funcp)(int a, long l);
12413    int b;
12414    };
12415
12416    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12417
12418 static struct type *
12419 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12420 {
12421   struct objfile *objfile = cu->objfile;
12422   struct type *type;            /* Type that this function returns.  */
12423   struct type *ftype;           /* Function that returns above type.  */
12424   struct attribute *attr;
12425
12426   type = die_type (die, cu);
12427
12428   /* The die_type call above may have already set the type for this DIE.  */
12429   ftype = get_die_type (die, cu);
12430   if (ftype)
12431     return ftype;
12432
12433   ftype = lookup_function_type (type);
12434
12435   /* All functions in C++, Pascal and Java have prototypes.  */
12436   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12437   if ((attr && (DW_UNSND (attr) != 0))
12438       || cu->language == language_cplus
12439       || cu->language == language_java
12440       || cu->language == language_pascal)
12441     TYPE_PROTOTYPED (ftype) = 1;
12442   else if (producer_is_realview (cu->producer))
12443     /* RealView does not emit DW_AT_prototyped.  We can not
12444        distinguish prototyped and unprototyped functions; default to
12445        prototyped, since that is more common in modern code (and
12446        RealView warns about unprototyped functions).  */
12447     TYPE_PROTOTYPED (ftype) = 1;
12448
12449   /* Store the calling convention in the type if it's available in
12450      the subroutine die.  Otherwise set the calling convention to
12451      the default value DW_CC_normal.  */
12452   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12453   if (attr)
12454     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12455   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12456     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12457   else
12458     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12459
12460   /* We need to add the subroutine type to the die immediately so
12461      we don't infinitely recurse when dealing with parameters
12462      declared as the same subroutine type.  */
12463   set_die_type (die, ftype, cu);
12464
12465   if (die->child != NULL)
12466     {
12467       struct type *void_type = objfile_type (objfile)->builtin_void;
12468       struct die_info *child_die;
12469       int nparams, iparams;
12470
12471       /* Count the number of parameters.
12472          FIXME: GDB currently ignores vararg functions, but knows about
12473          vararg member functions.  */
12474       nparams = 0;
12475       child_die = die->child;
12476       while (child_die && child_die->tag)
12477         {
12478           if (child_die->tag == DW_TAG_formal_parameter)
12479             nparams++;
12480           else if (child_die->tag == DW_TAG_unspecified_parameters)
12481             TYPE_VARARGS (ftype) = 1;
12482           child_die = sibling_die (child_die);
12483         }
12484
12485       /* Allocate storage for parameters and fill them in.  */
12486       TYPE_NFIELDS (ftype) = nparams;
12487       TYPE_FIELDS (ftype) = (struct field *)
12488         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12489
12490       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12491          even if we error out during the parameters reading below.  */
12492       for (iparams = 0; iparams < nparams; iparams++)
12493         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12494
12495       iparams = 0;
12496       child_die = die->child;
12497       while (child_die && child_die->tag)
12498         {
12499           if (child_die->tag == DW_TAG_formal_parameter)
12500             {
12501               struct type *arg_type;
12502
12503               /* DWARF version 2 has no clean way to discern C++
12504                  static and non-static member functions.  G++ helps
12505                  GDB by marking the first parameter for non-static
12506                  member functions (which is the this pointer) as
12507                  artificial.  We pass this information to
12508                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12509
12510                  DWARF version 3 added DW_AT_object_pointer, which GCC
12511                  4.5 does not yet generate.  */
12512               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12513               if (attr)
12514                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12515               else
12516                 {
12517                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12518
12519                   /* GCC/43521: In java, the formal parameter
12520                      "this" is sometimes not marked with DW_AT_artificial.  */
12521                   if (cu->language == language_java)
12522                     {
12523                       const char *name = dwarf2_name (child_die, cu);
12524
12525                       if (name && !strcmp (name, "this"))
12526                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12527                     }
12528                 }
12529               arg_type = die_type (child_die, cu);
12530
12531               /* RealView does not mark THIS as const, which the testsuite
12532                  expects.  GCC marks THIS as const in method definitions,
12533                  but not in the class specifications (GCC PR 43053).  */
12534               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12535                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12536                 {
12537                   int is_this = 0;
12538                   struct dwarf2_cu *arg_cu = cu;
12539                   const char *name = dwarf2_name (child_die, cu);
12540
12541                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12542                   if (attr)
12543                     {
12544                       /* If the compiler emits this, use it.  */
12545                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12546                         is_this = 1;
12547                     }
12548                   else if (name && strcmp (name, "this") == 0)
12549                     /* Function definitions will have the argument names.  */
12550                     is_this = 1;
12551                   else if (name == NULL && iparams == 0)
12552                     /* Declarations may not have the names, so like
12553                        elsewhere in GDB, assume an artificial first
12554                        argument is "this".  */
12555                     is_this = 1;
12556
12557                   if (is_this)
12558                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12559                                              arg_type, 0);
12560                 }
12561
12562               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12563               iparams++;
12564             }
12565           child_die = sibling_die (child_die);
12566         }
12567     }
12568
12569   return ftype;
12570 }
12571
12572 static struct type *
12573 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12574 {
12575   struct objfile *objfile = cu->objfile;
12576   const char *name = NULL;
12577   struct type *this_type, *target_type;
12578
12579   name = dwarf2_full_name (NULL, die, cu);
12580   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12581                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12582   TYPE_NAME (this_type) = name;
12583   set_die_type (die, this_type, cu);
12584   target_type = die_type (die, cu);
12585   if (target_type != this_type)
12586     TYPE_TARGET_TYPE (this_type) = target_type;
12587   else
12588     {
12589       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12590          spec and cause infinite loops in GDB.  */
12591       complaint (&symfile_complaints,
12592                  _("Self-referential DW_TAG_typedef "
12593                    "- DIE at 0x%x [in module %s]"),
12594                  die->offset.sect_off, objfile->name);
12595       TYPE_TARGET_TYPE (this_type) = NULL;
12596     }
12597   return this_type;
12598 }
12599
12600 /* Find a representation of a given base type and install
12601    it in the TYPE field of the die.  */
12602
12603 static struct type *
12604 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12605 {
12606   struct objfile *objfile = cu->objfile;
12607   struct type *type;
12608   struct attribute *attr;
12609   int encoding = 0, size = 0;
12610   const char *name;
12611   enum type_code code = TYPE_CODE_INT;
12612   int type_flags = 0;
12613   struct type *target_type = NULL;
12614
12615   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12616   if (attr)
12617     {
12618       encoding = DW_UNSND (attr);
12619     }
12620   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12621   if (attr)
12622     {
12623       size = DW_UNSND (attr);
12624     }
12625   name = dwarf2_name (die, cu);
12626   if (!name)
12627     {
12628       complaint (&symfile_complaints,
12629                  _("DW_AT_name missing from DW_TAG_base_type"));
12630     }
12631
12632   switch (encoding)
12633     {
12634       case DW_ATE_address:
12635         /* Turn DW_ATE_address into a void * pointer.  */
12636         code = TYPE_CODE_PTR;
12637         type_flags |= TYPE_FLAG_UNSIGNED;
12638         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12639         break;
12640       case DW_ATE_boolean:
12641         code = TYPE_CODE_BOOL;
12642         type_flags |= TYPE_FLAG_UNSIGNED;
12643         break;
12644       case DW_ATE_complex_float:
12645         code = TYPE_CODE_COMPLEX;
12646         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12647         break;
12648       case DW_ATE_decimal_float:
12649         code = TYPE_CODE_DECFLOAT;
12650         break;
12651       case DW_ATE_float:
12652         code = TYPE_CODE_FLT;
12653         break;
12654       case DW_ATE_signed:
12655         break;
12656       case DW_ATE_unsigned:
12657         type_flags |= TYPE_FLAG_UNSIGNED;
12658         if (cu->language == language_fortran
12659             && name
12660             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12661           code = TYPE_CODE_CHAR;
12662         break;
12663       case DW_ATE_signed_char:
12664         if (cu->language == language_ada || cu->language == language_m2
12665             || cu->language == language_pascal
12666             || cu->language == language_fortran)
12667           code = TYPE_CODE_CHAR;
12668         break;
12669       case DW_ATE_unsigned_char:
12670         if (cu->language == language_ada || cu->language == language_m2
12671             || cu->language == language_pascal
12672             || cu->language == language_fortran)
12673           code = TYPE_CODE_CHAR;
12674         type_flags |= TYPE_FLAG_UNSIGNED;
12675         break;
12676       case DW_ATE_UTF:
12677         /* We just treat this as an integer and then recognize the
12678            type by name elsewhere.  */
12679         break;
12680
12681       default:
12682         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12683                    dwarf_type_encoding_name (encoding));
12684         break;
12685     }
12686
12687   type = init_type (code, size, type_flags, NULL, objfile);
12688   TYPE_NAME (type) = name;
12689   TYPE_TARGET_TYPE (type) = target_type;
12690
12691   if (name && strcmp (name, "char") == 0)
12692     TYPE_NOSIGN (type) = 1;
12693
12694   return set_die_type (die, type, cu);
12695 }
12696
12697 /* Read the given DW_AT_subrange DIE.  */
12698
12699 static struct type *
12700 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12701 {
12702   struct type *base_type;
12703   struct type *range_type;
12704   struct attribute *attr;
12705   LONGEST low, high;
12706   int low_default_is_valid;
12707   const char *name;
12708   LONGEST negative_mask;
12709
12710   base_type = die_type (die, cu);
12711   /* Preserve BASE_TYPE's original type, just set its LENGTH.  */
12712   check_typedef (base_type);
12713
12714   /* The die_type call above may have already set the type for this DIE.  */
12715   range_type = get_die_type (die, cu);
12716   if (range_type)
12717     return range_type;
12718
12719   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12720      omitting DW_AT_lower_bound.  */
12721   switch (cu->language)
12722     {
12723     case language_c:
12724     case language_cplus:
12725       low = 0;
12726       low_default_is_valid = 1;
12727       break;
12728     case language_fortran:
12729       low = 1;
12730       low_default_is_valid = 1;
12731       break;
12732     case language_d:
12733     case language_java:
12734     case language_objc:
12735       low = 0;
12736       low_default_is_valid = (cu->header.version >= 4);
12737       break;
12738     case language_ada:
12739     case language_m2:
12740     case language_pascal:
12741       low = 1;
12742       low_default_is_valid = (cu->header.version >= 4);
12743       break;
12744     default:
12745       low = 0;
12746       low_default_is_valid = 0;
12747       break;
12748     }
12749
12750   /* FIXME: For variable sized arrays either of these could be
12751      a variable rather than a constant value.  We'll allow it,
12752      but we don't know how to handle it.  */
12753   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12754   if (attr)
12755     low = dwarf2_get_attr_constant_value (attr, low);
12756   else if (!low_default_is_valid)
12757     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12758                                       "- DIE at 0x%x [in module %s]"),
12759                die->offset.sect_off, cu->objfile->name);
12760
12761   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12762   if (attr)
12763     {
12764       if (attr_form_is_block (attr) || is_ref_attr (attr))
12765         {
12766           /* GCC encodes arrays with unspecified or dynamic length
12767              with a DW_FORM_block1 attribute or a reference attribute.
12768              FIXME: GDB does not yet know how to handle dynamic
12769              arrays properly, treat them as arrays with unspecified
12770              length for now.
12771
12772              FIXME: jimb/2003-09-22: GDB does not really know
12773              how to handle arrays of unspecified length
12774              either; we just represent them as zero-length
12775              arrays.  Choose an appropriate upper bound given
12776              the lower bound we've computed above.  */
12777           high = low - 1;
12778         }
12779       else
12780         high = dwarf2_get_attr_constant_value (attr, 1);
12781     }
12782   else
12783     {
12784       attr = dwarf2_attr (die, DW_AT_count, cu);
12785       if (attr)
12786         {
12787           int count = dwarf2_get_attr_constant_value (attr, 1);
12788           high = low + count - 1;
12789         }
12790       else
12791         {
12792           /* Unspecified array length.  */
12793           high = low - 1;
12794         }
12795     }
12796
12797   /* Dwarf-2 specifications explicitly allows to create subrange types
12798      without specifying a base type.
12799      In that case, the base type must be set to the type of
12800      the lower bound, upper bound or count, in that order, if any of these
12801      three attributes references an object that has a type.
12802      If no base type is found, the Dwarf-2 specifications say that
12803      a signed integer type of size equal to the size of an address should
12804      be used.
12805      For the following C code: `extern char gdb_int [];'
12806      GCC produces an empty range DIE.
12807      FIXME: muller/2010-05-28: Possible references to object for low bound,
12808      high bound or count are not yet handled by this code.  */
12809   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12810     {
12811       struct objfile *objfile = cu->objfile;
12812       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12813       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12814       struct type *int_type = objfile_type (objfile)->builtin_int;
12815
12816       /* Test "int", "long int", and "long long int" objfile types,
12817          and select the first one having a size above or equal to the
12818          architecture address size.  */
12819       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12820         base_type = int_type;
12821       else
12822         {
12823           int_type = objfile_type (objfile)->builtin_long;
12824           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12825             base_type = int_type;
12826           else
12827             {
12828               int_type = objfile_type (objfile)->builtin_long_long;
12829               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12830                 base_type = int_type;
12831             }
12832         }
12833     }
12834
12835   negative_mask =
12836     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
12837   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
12838     low |= negative_mask;
12839   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
12840     high |= negative_mask;
12841
12842   range_type = create_range_type (NULL, base_type, low, high);
12843
12844   /* Mark arrays with dynamic length at least as an array of unspecified
12845      length.  GDB could check the boundary but before it gets implemented at
12846      least allow accessing the array elements.  */
12847   if (attr && attr_form_is_block (attr))
12848     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12849
12850   /* Ada expects an empty array on no boundary attributes.  */
12851   if (attr == NULL && cu->language != language_ada)
12852     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12853
12854   name = dwarf2_name (die, cu);
12855   if (name)
12856     TYPE_NAME (range_type) = name;
12857
12858   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12859   if (attr)
12860     TYPE_LENGTH (range_type) = DW_UNSND (attr);
12861
12862   set_die_type (die, range_type, cu);
12863
12864   /* set_die_type should be already done.  */
12865   set_descriptive_type (range_type, die, cu);
12866
12867   return range_type;
12868 }
12869
12870 static struct type *
12871 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
12872 {
12873   struct type *type;
12874
12875   /* For now, we only support the C meaning of an unspecified type: void.  */
12876
12877   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
12878   TYPE_NAME (type) = dwarf2_name (die, cu);
12879
12880   return set_die_type (die, type, cu);
12881 }
12882
12883 /* Read a single die and all its descendents.  Set the die's sibling
12884    field to NULL; set other fields in the die correctly, and set all
12885    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
12886    location of the info_ptr after reading all of those dies.  PARENT
12887    is the parent of the die in question.  */
12888
12889 static struct die_info *
12890 read_die_and_children (const struct die_reader_specs *reader,
12891                        gdb_byte *info_ptr,
12892                        gdb_byte **new_info_ptr,
12893                        struct die_info *parent)
12894 {
12895   struct die_info *die;
12896   gdb_byte *cur_ptr;
12897   int has_children;
12898
12899   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
12900   if (die == NULL)
12901     {
12902       *new_info_ptr = cur_ptr;
12903       return NULL;
12904     }
12905   store_in_ref_table (die, reader->cu);
12906
12907   if (has_children)
12908     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
12909   else
12910     {
12911       die->child = NULL;
12912       *new_info_ptr = cur_ptr;
12913     }
12914
12915   die->sibling = NULL;
12916   die->parent = parent;
12917   return die;
12918 }
12919
12920 /* Read a die, all of its descendents, and all of its siblings; set
12921    all of the fields of all of the dies correctly.  Arguments are as
12922    in read_die_and_children.  */
12923
12924 static struct die_info *
12925 read_die_and_siblings (const struct die_reader_specs *reader,
12926                        gdb_byte *info_ptr,
12927                        gdb_byte **new_info_ptr,
12928                        struct die_info *parent)
12929 {
12930   struct die_info *first_die, *last_sibling;
12931   gdb_byte *cur_ptr;
12932
12933   cur_ptr = info_ptr;
12934   first_die = last_sibling = NULL;
12935
12936   while (1)
12937     {
12938       struct die_info *die
12939         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
12940
12941       if (die == NULL)
12942         {
12943           *new_info_ptr = cur_ptr;
12944           return first_die;
12945         }
12946
12947       if (!first_die)
12948         first_die = die;
12949       else
12950         last_sibling->sibling = die;
12951
12952       last_sibling = die;
12953     }
12954 }
12955
12956 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
12957    attributes.
12958    The caller is responsible for filling in the extra attributes
12959    and updating (*DIEP)->num_attrs.
12960    Set DIEP to point to a newly allocated die with its information,
12961    except for its child, sibling, and parent fields.
12962    Set HAS_CHILDREN to tell whether the die has children or not.  */
12963
12964 static gdb_byte *
12965 read_full_die_1 (const struct die_reader_specs *reader,
12966                  struct die_info **diep, gdb_byte *info_ptr,
12967                  int *has_children, int num_extra_attrs)
12968 {
12969   unsigned int abbrev_number, bytes_read, i;
12970   sect_offset offset;
12971   struct abbrev_info *abbrev;
12972   struct die_info *die;
12973   struct dwarf2_cu *cu = reader->cu;
12974   bfd *abfd = reader->abfd;
12975
12976   offset.sect_off = info_ptr - reader->buffer;
12977   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
12978   info_ptr += bytes_read;
12979   if (!abbrev_number)
12980     {
12981       *diep = NULL;
12982       *has_children = 0;
12983       return info_ptr;
12984     }
12985
12986   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
12987   if (!abbrev)
12988     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
12989            abbrev_number,
12990            bfd_get_filename (abfd));
12991
12992   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
12993   die->offset = offset;
12994   die->tag = abbrev->tag;
12995   die->abbrev = abbrev_number;
12996
12997   /* Make the result usable.
12998      The caller needs to update num_attrs after adding the extra
12999      attributes.  */
13000   die->num_attrs = abbrev->num_attrs;
13001
13002   for (i = 0; i < abbrev->num_attrs; ++i)
13003     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13004                                info_ptr);
13005
13006   *diep = die;
13007   *has_children = abbrev->has_children;
13008   return info_ptr;
13009 }
13010
13011 /* Read a die and all its attributes.
13012    Set DIEP to point to a newly allocated die with its information,
13013    except for its child, sibling, and parent fields.
13014    Set HAS_CHILDREN to tell whether the die has children or not.  */
13015
13016 static gdb_byte *
13017 read_full_die (const struct die_reader_specs *reader,
13018                struct die_info **diep, gdb_byte *info_ptr,
13019                int *has_children)
13020 {
13021   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13022 }
13023 \f
13024 /* Abbreviation tables.
13025
13026    In DWARF version 2, the description of the debugging information is
13027    stored in a separate .debug_abbrev section.  Before we read any
13028    dies from a section we read in all abbreviations and install them
13029    in a hash table.  */
13030
13031 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13032
13033 static struct abbrev_info *
13034 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13035 {
13036   struct abbrev_info *abbrev;
13037
13038   abbrev = (struct abbrev_info *)
13039     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13040   memset (abbrev, 0, sizeof (struct abbrev_info));
13041   return abbrev;
13042 }
13043
13044 /* Add an abbreviation to the table.  */
13045
13046 static void
13047 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13048                          unsigned int abbrev_number,
13049                          struct abbrev_info *abbrev)
13050 {
13051   unsigned int hash_number;
13052
13053   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13054   abbrev->next = abbrev_table->abbrevs[hash_number];
13055   abbrev_table->abbrevs[hash_number] = abbrev;
13056 }
13057
13058 /* Look up an abbrev in the table.
13059    Returns NULL if the abbrev is not found.  */
13060
13061 static struct abbrev_info *
13062 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13063                             unsigned int abbrev_number)
13064 {
13065   unsigned int hash_number;
13066   struct abbrev_info *abbrev;
13067
13068   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13069   abbrev = abbrev_table->abbrevs[hash_number];
13070
13071   while (abbrev)
13072     {
13073       if (abbrev->number == abbrev_number)
13074         return abbrev;
13075       abbrev = abbrev->next;
13076     }
13077   return NULL;
13078 }
13079
13080 /* Read in an abbrev table.  */
13081
13082 static struct abbrev_table *
13083 abbrev_table_read_table (struct dwarf2_section_info *section,
13084                          sect_offset offset)
13085 {
13086   struct objfile *objfile = dwarf2_per_objfile->objfile;
13087   bfd *abfd = section->asection->owner;
13088   struct abbrev_table *abbrev_table;
13089   gdb_byte *abbrev_ptr;
13090   struct abbrev_info *cur_abbrev;
13091   unsigned int abbrev_number, bytes_read, abbrev_name;
13092   unsigned int abbrev_form;
13093   struct attr_abbrev *cur_attrs;
13094   unsigned int allocated_attrs;
13095
13096   abbrev_table = XMALLOC (struct abbrev_table);
13097   abbrev_table->offset = offset;
13098   obstack_init (&abbrev_table->abbrev_obstack);
13099   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13100                                          (ABBREV_HASH_SIZE
13101                                           * sizeof (struct abbrev_info *)));
13102   memset (abbrev_table->abbrevs, 0,
13103           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13104
13105   dwarf2_read_section (objfile, section);
13106   abbrev_ptr = section->buffer + offset.sect_off;
13107   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13108   abbrev_ptr += bytes_read;
13109
13110   allocated_attrs = ATTR_ALLOC_CHUNK;
13111   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13112
13113   /* Loop until we reach an abbrev number of 0.  */
13114   while (abbrev_number)
13115     {
13116       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13117
13118       /* read in abbrev header */
13119       cur_abbrev->number = abbrev_number;
13120       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13121       abbrev_ptr += bytes_read;
13122       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13123       abbrev_ptr += 1;
13124
13125       /* now read in declarations */
13126       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13127       abbrev_ptr += bytes_read;
13128       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13129       abbrev_ptr += bytes_read;
13130       while (abbrev_name)
13131         {
13132           if (cur_abbrev->num_attrs == allocated_attrs)
13133             {
13134               allocated_attrs += ATTR_ALLOC_CHUNK;
13135               cur_attrs
13136                 = xrealloc (cur_attrs, (allocated_attrs
13137                                         * sizeof (struct attr_abbrev)));
13138             }
13139
13140           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13141           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13142           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13143           abbrev_ptr += bytes_read;
13144           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13145           abbrev_ptr += bytes_read;
13146         }
13147
13148       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13149                                          (cur_abbrev->num_attrs
13150                                           * sizeof (struct attr_abbrev)));
13151       memcpy (cur_abbrev->attrs, cur_attrs,
13152               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13153
13154       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13155
13156       /* Get next abbreviation.
13157          Under Irix6 the abbreviations for a compilation unit are not
13158          always properly terminated with an abbrev number of 0.
13159          Exit loop if we encounter an abbreviation which we have
13160          already read (which means we are about to read the abbreviations
13161          for the next compile unit) or if the end of the abbreviation
13162          table is reached.  */
13163       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13164         break;
13165       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13166       abbrev_ptr += bytes_read;
13167       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13168         break;
13169     }
13170
13171   xfree (cur_attrs);
13172   return abbrev_table;
13173 }
13174
13175 /* Free the resources held by ABBREV_TABLE.  */
13176
13177 static void
13178 abbrev_table_free (struct abbrev_table *abbrev_table)
13179 {
13180   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13181   xfree (abbrev_table);
13182 }
13183
13184 /* Same as abbrev_table_free but as a cleanup.
13185    We pass in a pointer to the pointer to the table so that we can
13186    set the pointer to NULL when we're done.  It also simplifies
13187    build_type_unit_groups.  */
13188
13189 static void
13190 abbrev_table_free_cleanup (void *table_ptr)
13191 {
13192   struct abbrev_table **abbrev_table_ptr = table_ptr;
13193
13194   if (*abbrev_table_ptr != NULL)
13195     abbrev_table_free (*abbrev_table_ptr);
13196   *abbrev_table_ptr = NULL;
13197 }
13198
13199 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13200
13201 static void
13202 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13203                      struct dwarf2_section_info *abbrev_section)
13204 {
13205   cu->abbrev_table =
13206     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13207 }
13208
13209 /* Release the memory used by the abbrev table for a compilation unit.  */
13210
13211 static void
13212 dwarf2_free_abbrev_table (void *ptr_to_cu)
13213 {
13214   struct dwarf2_cu *cu = ptr_to_cu;
13215
13216   abbrev_table_free (cu->abbrev_table);
13217   /* Set this to NULL so that we SEGV if we try to read it later,
13218      and also because free_comp_unit verifies this is NULL.  */
13219   cu->abbrev_table = NULL;
13220 }
13221 \f
13222 /* Returns nonzero if TAG represents a type that we might generate a partial
13223    symbol for.  */
13224
13225 static int
13226 is_type_tag_for_partial (int tag)
13227 {
13228   switch (tag)
13229     {
13230 #if 0
13231     /* Some types that would be reasonable to generate partial symbols for,
13232        that we don't at present.  */
13233     case DW_TAG_array_type:
13234     case DW_TAG_file_type:
13235     case DW_TAG_ptr_to_member_type:
13236     case DW_TAG_set_type:
13237     case DW_TAG_string_type:
13238     case DW_TAG_subroutine_type:
13239 #endif
13240     case DW_TAG_base_type:
13241     case DW_TAG_class_type:
13242     case DW_TAG_interface_type:
13243     case DW_TAG_enumeration_type:
13244     case DW_TAG_structure_type:
13245     case DW_TAG_subrange_type:
13246     case DW_TAG_typedef:
13247     case DW_TAG_union_type:
13248       return 1;
13249     default:
13250       return 0;
13251     }
13252 }
13253
13254 /* Load all DIEs that are interesting for partial symbols into memory.  */
13255
13256 static struct partial_die_info *
13257 load_partial_dies (const struct die_reader_specs *reader,
13258                    gdb_byte *info_ptr, int building_psymtab)
13259 {
13260   struct dwarf2_cu *cu = reader->cu;
13261   struct objfile *objfile = cu->objfile;
13262   struct partial_die_info *part_die;
13263   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13264   struct abbrev_info *abbrev;
13265   unsigned int bytes_read;
13266   unsigned int load_all = 0;
13267   int nesting_level = 1;
13268
13269   parent_die = NULL;
13270   last_die = NULL;
13271
13272   gdb_assert (cu->per_cu != NULL);
13273   if (cu->per_cu->load_all_dies)
13274     load_all = 1;
13275
13276   cu->partial_dies
13277     = htab_create_alloc_ex (cu->header.length / 12,
13278                             partial_die_hash,
13279                             partial_die_eq,
13280                             NULL,
13281                             &cu->comp_unit_obstack,
13282                             hashtab_obstack_allocate,
13283                             dummy_obstack_deallocate);
13284
13285   part_die = obstack_alloc (&cu->comp_unit_obstack,
13286                             sizeof (struct partial_die_info));
13287
13288   while (1)
13289     {
13290       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13291
13292       /* A NULL abbrev means the end of a series of children.  */
13293       if (abbrev == NULL)
13294         {
13295           if (--nesting_level == 0)
13296             {
13297               /* PART_DIE was probably the last thing allocated on the
13298                  comp_unit_obstack, so we could call obstack_free
13299                  here.  We don't do that because the waste is small,
13300                  and will be cleaned up when we're done with this
13301                  compilation unit.  This way, we're also more robust
13302                  against other users of the comp_unit_obstack.  */
13303               return first_die;
13304             }
13305           info_ptr += bytes_read;
13306           last_die = parent_die;
13307           parent_die = parent_die->die_parent;
13308           continue;
13309         }
13310
13311       /* Check for template arguments.  We never save these; if
13312          they're seen, we just mark the parent, and go on our way.  */
13313       if (parent_die != NULL
13314           && cu->language == language_cplus
13315           && (abbrev->tag == DW_TAG_template_type_param
13316               || abbrev->tag == DW_TAG_template_value_param))
13317         {
13318           parent_die->has_template_arguments = 1;
13319
13320           if (!load_all)
13321             {
13322               /* We don't need a partial DIE for the template argument.  */
13323               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13324               continue;
13325             }
13326         }
13327
13328       /* We only recurse into c++ subprograms looking for template arguments.
13329          Skip their other children.  */
13330       if (!load_all
13331           && cu->language == language_cplus
13332           && parent_die != NULL
13333           && parent_die->tag == DW_TAG_subprogram)
13334         {
13335           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13336           continue;
13337         }
13338
13339       /* Check whether this DIE is interesting enough to save.  Normally
13340          we would not be interested in members here, but there may be
13341          later variables referencing them via DW_AT_specification (for
13342          static members).  */
13343       if (!load_all
13344           && !is_type_tag_for_partial (abbrev->tag)
13345           && abbrev->tag != DW_TAG_constant
13346           && abbrev->tag != DW_TAG_enumerator
13347           && abbrev->tag != DW_TAG_subprogram
13348           && abbrev->tag != DW_TAG_lexical_block
13349           && abbrev->tag != DW_TAG_variable
13350           && abbrev->tag != DW_TAG_namespace
13351           && abbrev->tag != DW_TAG_module
13352           && abbrev->tag != DW_TAG_member
13353           && abbrev->tag != DW_TAG_imported_unit)
13354         {
13355           /* Otherwise we skip to the next sibling, if any.  */
13356           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13357           continue;
13358         }
13359
13360       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13361                                    info_ptr);
13362
13363       /* This two-pass algorithm for processing partial symbols has a
13364          high cost in cache pressure.  Thus, handle some simple cases
13365          here which cover the majority of C partial symbols.  DIEs
13366          which neither have specification tags in them, nor could have
13367          specification tags elsewhere pointing at them, can simply be
13368          processed and discarded.
13369
13370          This segment is also optional; scan_partial_symbols and
13371          add_partial_symbol will handle these DIEs if we chain
13372          them in normally.  When compilers which do not emit large
13373          quantities of duplicate debug information are more common,
13374          this code can probably be removed.  */
13375
13376       /* Any complete simple types at the top level (pretty much all
13377          of them, for a language without namespaces), can be processed
13378          directly.  */
13379       if (parent_die == NULL
13380           && part_die->has_specification == 0
13381           && part_die->is_declaration == 0
13382           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13383               || part_die->tag == DW_TAG_base_type
13384               || part_die->tag == DW_TAG_subrange_type))
13385         {
13386           if (building_psymtab && part_die->name != NULL)
13387             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13388                                  VAR_DOMAIN, LOC_TYPEDEF,
13389                                  &objfile->static_psymbols,
13390                                  0, (CORE_ADDR) 0, cu->language, objfile);
13391           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13392           continue;
13393         }
13394
13395       /* The exception for DW_TAG_typedef with has_children above is
13396          a workaround of GCC PR debug/47510.  In the case of this complaint
13397          type_name_no_tag_or_error will error on such types later.
13398
13399          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13400          it could not find the child DIEs referenced later, this is checked
13401          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13402
13403       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13404         complaint (&symfile_complaints,
13405                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13406                      "- DIE at 0x%x [in module %s]"),
13407                    part_die->offset.sect_off, objfile->name);
13408
13409       /* If we're at the second level, and we're an enumerator, and
13410          our parent has no specification (meaning possibly lives in a
13411          namespace elsewhere), then we can add the partial symbol now
13412          instead of queueing it.  */
13413       if (part_die->tag == DW_TAG_enumerator
13414           && parent_die != NULL
13415           && parent_die->die_parent == NULL
13416           && parent_die->tag == DW_TAG_enumeration_type
13417           && parent_die->has_specification == 0)
13418         {
13419           if (part_die->name == NULL)
13420             complaint (&symfile_complaints,
13421                        _("malformed enumerator DIE ignored"));
13422           else if (building_psymtab)
13423             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13424                                  VAR_DOMAIN, LOC_CONST,
13425                                  (cu->language == language_cplus
13426                                   || cu->language == language_java)
13427                                  ? &objfile->global_psymbols
13428                                  : &objfile->static_psymbols,
13429                                  0, (CORE_ADDR) 0, cu->language, objfile);
13430
13431           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13432           continue;
13433         }
13434
13435       /* We'll save this DIE so link it in.  */
13436       part_die->die_parent = parent_die;
13437       part_die->die_sibling = NULL;
13438       part_die->die_child = NULL;
13439
13440       if (last_die && last_die == parent_die)
13441         last_die->die_child = part_die;
13442       else if (last_die)
13443         last_die->die_sibling = part_die;
13444
13445       last_die = part_die;
13446
13447       if (first_die == NULL)
13448         first_die = part_die;
13449
13450       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13451          find interesting need to be in the hash table, because we
13452          also have the parent/sibling/child chains; only those that we
13453          might refer to by offset later during partial symbol reading.
13454
13455          For now this means things that might have be the target of a
13456          DW_AT_specification, DW_AT_abstract_origin, or
13457          DW_AT_extension.  DW_AT_extension will refer only to
13458          namespaces; DW_AT_abstract_origin refers to functions (and
13459          many things under the function DIE, but we do not recurse
13460          into function DIEs during partial symbol reading) and
13461          possibly variables as well; DW_AT_specification refers to
13462          declarations.  Declarations ought to have the DW_AT_declaration
13463          flag.  It happens that GCC forgets to put it in sometimes, but
13464          only for functions, not for types.
13465
13466          Adding more things than necessary to the hash table is harmless
13467          except for the performance cost.  Adding too few will result in
13468          wasted time in find_partial_die, when we reread the compilation
13469          unit with load_all_dies set.  */
13470
13471       if (load_all
13472           || abbrev->tag == DW_TAG_constant
13473           || abbrev->tag == DW_TAG_subprogram
13474           || abbrev->tag == DW_TAG_variable
13475           || abbrev->tag == DW_TAG_namespace
13476           || part_die->is_declaration)
13477         {
13478           void **slot;
13479
13480           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13481                                            part_die->offset.sect_off, INSERT);
13482           *slot = part_die;
13483         }
13484
13485       part_die = obstack_alloc (&cu->comp_unit_obstack,
13486                                 sizeof (struct partial_die_info));
13487
13488       /* For some DIEs we want to follow their children (if any).  For C
13489          we have no reason to follow the children of structures; for other
13490          languages we have to, so that we can get at method physnames
13491          to infer fully qualified class names, for DW_AT_specification,
13492          and for C++ template arguments.  For C++, we also look one level
13493          inside functions to find template arguments (if the name of the
13494          function does not already contain the template arguments).
13495
13496          For Ada, we need to scan the children of subprograms and lexical
13497          blocks as well because Ada allows the definition of nested
13498          entities that could be interesting for the debugger, such as
13499          nested subprograms for instance.  */
13500       if (last_die->has_children
13501           && (load_all
13502               || last_die->tag == DW_TAG_namespace
13503               || last_die->tag == DW_TAG_module
13504               || last_die->tag == DW_TAG_enumeration_type
13505               || (cu->language == language_cplus
13506                   && last_die->tag == DW_TAG_subprogram
13507                   && (last_die->name == NULL
13508                       || strchr (last_die->name, '<') == NULL))
13509               || (cu->language != language_c
13510                   && (last_die->tag == DW_TAG_class_type
13511                       || last_die->tag == DW_TAG_interface_type
13512                       || last_die->tag == DW_TAG_structure_type
13513                       || last_die->tag == DW_TAG_union_type))
13514               || (cu->language == language_ada
13515                   && (last_die->tag == DW_TAG_subprogram
13516                       || last_die->tag == DW_TAG_lexical_block))))
13517         {
13518           nesting_level++;
13519           parent_die = last_die;
13520           continue;
13521         }
13522
13523       /* Otherwise we skip to the next sibling, if any.  */
13524       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13525
13526       /* Back to the top, do it again.  */
13527     }
13528 }
13529
13530 /* Read a minimal amount of information into the minimal die structure.  */
13531
13532 static gdb_byte *
13533 read_partial_die (const struct die_reader_specs *reader,
13534                   struct partial_die_info *part_die,
13535                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13536                   gdb_byte *info_ptr)
13537 {
13538   struct dwarf2_cu *cu = reader->cu;
13539   struct objfile *objfile = cu->objfile;
13540   gdb_byte *buffer = reader->buffer;
13541   unsigned int i;
13542   struct attribute attr;
13543   int has_low_pc_attr = 0;
13544   int has_high_pc_attr = 0;
13545   int high_pc_relative = 0;
13546
13547   memset (part_die, 0, sizeof (struct partial_die_info));
13548
13549   part_die->offset.sect_off = info_ptr - buffer;
13550
13551   info_ptr += abbrev_len;
13552
13553   if (abbrev == NULL)
13554     return info_ptr;
13555
13556   part_die->tag = abbrev->tag;
13557   part_die->has_children = abbrev->has_children;
13558
13559   for (i = 0; i < abbrev->num_attrs; ++i)
13560     {
13561       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13562
13563       /* Store the data if it is of an attribute we want to keep in a
13564          partial symbol table.  */
13565       switch (attr.name)
13566         {
13567         case DW_AT_name:
13568           switch (part_die->tag)
13569             {
13570             case DW_TAG_compile_unit:
13571             case DW_TAG_partial_unit:
13572             case DW_TAG_type_unit:
13573               /* Compilation units have a DW_AT_name that is a filename, not
13574                  a source language identifier.  */
13575             case DW_TAG_enumeration_type:
13576             case DW_TAG_enumerator:
13577               /* These tags always have simple identifiers already; no need
13578                  to canonicalize them.  */
13579               part_die->name = DW_STRING (&attr);
13580               break;
13581             default:
13582               part_die->name
13583                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13584                                             &objfile->objfile_obstack);
13585               break;
13586             }
13587           break;
13588         case DW_AT_linkage_name:
13589         case DW_AT_MIPS_linkage_name:
13590           /* Note that both forms of linkage name might appear.  We
13591              assume they will be the same, and we only store the last
13592              one we see.  */
13593           if (cu->language == language_ada)
13594             part_die->name = DW_STRING (&attr);
13595           part_die->linkage_name = DW_STRING (&attr);
13596           break;
13597         case DW_AT_low_pc:
13598           has_low_pc_attr = 1;
13599           part_die->lowpc = DW_ADDR (&attr);
13600           break;
13601         case DW_AT_high_pc:
13602           has_high_pc_attr = 1;
13603           if (attr.form == DW_FORM_addr
13604               || attr.form == DW_FORM_GNU_addr_index)
13605             part_die->highpc = DW_ADDR (&attr);
13606           else
13607             {
13608               high_pc_relative = 1;
13609               part_die->highpc = DW_UNSND (&attr);
13610             }
13611           break;
13612         case DW_AT_location:
13613           /* Support the .debug_loc offsets.  */
13614           if (attr_form_is_block (&attr))
13615             {
13616                part_die->d.locdesc = DW_BLOCK (&attr);
13617             }
13618           else if (attr_form_is_section_offset (&attr))
13619             {
13620               dwarf2_complex_location_expr_complaint ();
13621             }
13622           else
13623             {
13624               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13625                                                      "partial symbol information");
13626             }
13627           break;
13628         case DW_AT_external:
13629           part_die->is_external = DW_UNSND (&attr);
13630           break;
13631         case DW_AT_declaration:
13632           part_die->is_declaration = DW_UNSND (&attr);
13633           break;
13634         case DW_AT_type:
13635           part_die->has_type = 1;
13636           break;
13637         case DW_AT_abstract_origin:
13638         case DW_AT_specification:
13639         case DW_AT_extension:
13640           part_die->has_specification = 1;
13641           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13642           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13643                                    || cu->per_cu->is_dwz);
13644           break;
13645         case DW_AT_sibling:
13646           /* Ignore absolute siblings, they might point outside of
13647              the current compile unit.  */
13648           if (attr.form == DW_FORM_ref_addr)
13649             complaint (&symfile_complaints,
13650                        _("ignoring absolute DW_AT_sibling"));
13651           else
13652             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13653           break;
13654         case DW_AT_byte_size:
13655           part_die->has_byte_size = 1;
13656           break;
13657         case DW_AT_calling_convention:
13658           /* DWARF doesn't provide a way to identify a program's source-level
13659              entry point.  DW_AT_calling_convention attributes are only meant
13660              to describe functions' calling conventions.
13661
13662              However, because it's a necessary piece of information in
13663              Fortran, and because DW_CC_program is the only piece of debugging
13664              information whose definition refers to a 'main program' at all,
13665              several compilers have begun marking Fortran main programs with
13666              DW_CC_program --- even when those functions use the standard
13667              calling conventions.
13668
13669              So until DWARF specifies a way to provide this information and
13670              compilers pick up the new representation, we'll support this
13671              practice.  */
13672           if (DW_UNSND (&attr) == DW_CC_program
13673               && cu->language == language_fortran)
13674             {
13675               set_main_name (part_die->name);
13676
13677               /* As this DIE has a static linkage the name would be difficult
13678                  to look up later.  */
13679               language_of_main = language_fortran;
13680             }
13681           break;
13682         case DW_AT_inline:
13683           if (DW_UNSND (&attr) == DW_INL_inlined
13684               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13685             part_die->may_be_inlined = 1;
13686           break;
13687
13688         case DW_AT_import:
13689           if (part_die->tag == DW_TAG_imported_unit)
13690             {
13691               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13692               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13693                                   || cu->per_cu->is_dwz);
13694             }
13695           break;
13696
13697         default:
13698           break;
13699         }
13700     }
13701
13702   if (high_pc_relative)
13703     part_die->highpc += part_die->lowpc;
13704
13705   if (has_low_pc_attr && has_high_pc_attr)
13706     {
13707       /* When using the GNU linker, .gnu.linkonce. sections are used to
13708          eliminate duplicate copies of functions and vtables and such.
13709          The linker will arbitrarily choose one and discard the others.
13710          The AT_*_pc values for such functions refer to local labels in
13711          these sections.  If the section from that file was discarded, the
13712          labels are not in the output, so the relocs get a value of 0.
13713          If this is a discarded function, mark the pc bounds as invalid,
13714          so that GDB will ignore it.  */
13715       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13716         {
13717           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13718
13719           complaint (&symfile_complaints,
13720                      _("DW_AT_low_pc %s is zero "
13721                        "for DIE at 0x%x [in module %s]"),
13722                      paddress (gdbarch, part_die->lowpc),
13723                      part_die->offset.sect_off, objfile->name);
13724         }
13725       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13726       else if (part_die->lowpc >= part_die->highpc)
13727         {
13728           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13729
13730           complaint (&symfile_complaints,
13731                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13732                        "for DIE at 0x%x [in module %s]"),
13733                      paddress (gdbarch, part_die->lowpc),
13734                      paddress (gdbarch, part_die->highpc),
13735                      part_die->offset.sect_off, objfile->name);
13736         }
13737       else
13738         part_die->has_pc_info = 1;
13739     }
13740
13741   return info_ptr;
13742 }
13743
13744 /* Find a cached partial DIE at OFFSET in CU.  */
13745
13746 static struct partial_die_info *
13747 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13748 {
13749   struct partial_die_info *lookup_die = NULL;
13750   struct partial_die_info part_die;
13751
13752   part_die.offset = offset;
13753   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13754                                     offset.sect_off);
13755
13756   return lookup_die;
13757 }
13758
13759 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13760    except in the case of .debug_types DIEs which do not reference
13761    outside their CU (they do however referencing other types via
13762    DW_FORM_ref_sig8).  */
13763
13764 static struct partial_die_info *
13765 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13766 {
13767   struct objfile *objfile = cu->objfile;
13768   struct dwarf2_per_cu_data *per_cu = NULL;
13769   struct partial_die_info *pd = NULL;
13770
13771   if (offset_in_dwz == cu->per_cu->is_dwz
13772       && offset_in_cu_p (&cu->header, offset))
13773     {
13774       pd = find_partial_die_in_comp_unit (offset, cu);
13775       if (pd != NULL)
13776         return pd;
13777       /* We missed recording what we needed.
13778          Load all dies and try again.  */
13779       per_cu = cu->per_cu;
13780     }
13781   else
13782     {
13783       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13784       if (cu->per_cu->is_debug_types)
13785         {
13786           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13787                    " external reference to offset 0x%lx [in module %s].\n"),
13788                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
13789                  bfd_get_filename (objfile->obfd));
13790         }
13791       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
13792                                                  objfile);
13793
13794       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
13795         load_partial_comp_unit (per_cu);
13796
13797       per_cu->cu->last_used = 0;
13798       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13799     }
13800
13801   /* If we didn't find it, and not all dies have been loaded,
13802      load them all and try again.  */
13803
13804   if (pd == NULL && per_cu->load_all_dies == 0)
13805     {
13806       per_cu->load_all_dies = 1;
13807
13808       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
13809          THIS_CU->cu may already be in use.  So we can't just free it and
13810          replace its DIEs with the ones we read in.  Instead, we leave those
13811          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
13812          and clobber THIS_CU->cu->partial_dies with the hash table for the new
13813          set.  */
13814       load_partial_comp_unit (per_cu);
13815
13816       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13817     }
13818
13819   if (pd == NULL)
13820     internal_error (__FILE__, __LINE__,
13821                     _("could not find partial DIE 0x%x "
13822                       "in cache [from module %s]\n"),
13823                     offset.sect_off, bfd_get_filename (objfile->obfd));
13824   return pd;
13825 }
13826
13827 /* See if we can figure out if the class lives in a namespace.  We do
13828    this by looking for a member function; its demangled name will
13829    contain namespace info, if there is any.  */
13830
13831 static void
13832 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
13833                                   struct dwarf2_cu *cu)
13834 {
13835   /* NOTE: carlton/2003-10-07: Getting the info this way changes
13836      what template types look like, because the demangler
13837      frequently doesn't give the same name as the debug info.  We
13838      could fix this by only using the demangled name to get the
13839      prefix (but see comment in read_structure_type).  */
13840
13841   struct partial_die_info *real_pdi;
13842   struct partial_die_info *child_pdi;
13843
13844   /* If this DIE (this DIE's specification, if any) has a parent, then
13845      we should not do this.  We'll prepend the parent's fully qualified
13846      name when we create the partial symbol.  */
13847
13848   real_pdi = struct_pdi;
13849   while (real_pdi->has_specification)
13850     real_pdi = find_partial_die (real_pdi->spec_offset,
13851                                  real_pdi->spec_is_dwz, cu);
13852
13853   if (real_pdi->die_parent != NULL)
13854     return;
13855
13856   for (child_pdi = struct_pdi->die_child;
13857        child_pdi != NULL;
13858        child_pdi = child_pdi->die_sibling)
13859     {
13860       if (child_pdi->tag == DW_TAG_subprogram
13861           && child_pdi->linkage_name != NULL)
13862         {
13863           char *actual_class_name
13864             = language_class_name_from_physname (cu->language_defn,
13865                                                  child_pdi->linkage_name);
13866           if (actual_class_name != NULL)
13867             {
13868               struct_pdi->name
13869                 = obstack_copy0 (&cu->objfile->objfile_obstack,
13870                                  actual_class_name,
13871                                  strlen (actual_class_name));
13872               xfree (actual_class_name);
13873             }
13874           break;
13875         }
13876     }
13877 }
13878
13879 /* Adjust PART_DIE before generating a symbol for it.  This function
13880    may set the is_external flag or change the DIE's name.  */
13881
13882 static void
13883 fixup_partial_die (struct partial_die_info *part_die,
13884                    struct dwarf2_cu *cu)
13885 {
13886   /* Once we've fixed up a die, there's no point in doing so again.
13887      This also avoids a memory leak if we were to call
13888      guess_partial_die_structure_name multiple times.  */
13889   if (part_die->fixup_called)
13890     return;
13891
13892   /* If we found a reference attribute and the DIE has no name, try
13893      to find a name in the referred to DIE.  */
13894
13895   if (part_die->name == NULL && part_die->has_specification)
13896     {
13897       struct partial_die_info *spec_die;
13898
13899       spec_die = find_partial_die (part_die->spec_offset,
13900                                    part_die->spec_is_dwz, cu);
13901
13902       fixup_partial_die (spec_die, cu);
13903
13904       if (spec_die->name)
13905         {
13906           part_die->name = spec_die->name;
13907
13908           /* Copy DW_AT_external attribute if it is set.  */
13909           if (spec_die->is_external)
13910             part_die->is_external = spec_die->is_external;
13911         }
13912     }
13913
13914   /* Set default names for some unnamed DIEs.  */
13915
13916   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
13917     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
13918
13919   /* If there is no parent die to provide a namespace, and there are
13920      children, see if we can determine the namespace from their linkage
13921      name.  */
13922   if (cu->language == language_cplus
13923       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
13924       && part_die->die_parent == NULL
13925       && part_die->has_children
13926       && (part_die->tag == DW_TAG_class_type
13927           || part_die->tag == DW_TAG_structure_type
13928           || part_die->tag == DW_TAG_union_type))
13929     guess_partial_die_structure_name (part_die, cu);
13930
13931   /* GCC might emit a nameless struct or union that has a linkage
13932      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
13933   if (part_die->name == NULL
13934       && (part_die->tag == DW_TAG_class_type
13935           || part_die->tag == DW_TAG_interface_type
13936           || part_die->tag == DW_TAG_structure_type
13937           || part_die->tag == DW_TAG_union_type)
13938       && part_die->linkage_name != NULL)
13939     {
13940       char *demangled;
13941
13942       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
13943       if (demangled)
13944         {
13945           const char *base;
13946
13947           /* Strip any leading namespaces/classes, keep only the base name.
13948              DW_AT_name for named DIEs does not contain the prefixes.  */
13949           base = strrchr (demangled, ':');
13950           if (base && base > demangled && base[-1] == ':')
13951             base++;
13952           else
13953             base = demangled;
13954
13955           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
13956                                           base, strlen (base));
13957           xfree (demangled);
13958         }
13959     }
13960
13961   part_die->fixup_called = 1;
13962 }
13963
13964 /* Read an attribute value described by an attribute form.  */
13965
13966 static gdb_byte *
13967 read_attribute_value (const struct die_reader_specs *reader,
13968                       struct attribute *attr, unsigned form,
13969                       gdb_byte *info_ptr)
13970 {
13971   struct dwarf2_cu *cu = reader->cu;
13972   bfd *abfd = reader->abfd;
13973   struct comp_unit_head *cu_header = &cu->header;
13974   unsigned int bytes_read;
13975   struct dwarf_block *blk;
13976
13977   attr->form = form;
13978   switch (form)
13979     {
13980     case DW_FORM_ref_addr:
13981       if (cu->header.version == 2)
13982         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
13983       else
13984         DW_UNSND (attr) = read_offset (abfd, info_ptr,
13985                                        &cu->header, &bytes_read);
13986       info_ptr += bytes_read;
13987       break;
13988     case DW_FORM_GNU_ref_alt:
13989       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
13990       info_ptr += bytes_read;
13991       break;
13992     case DW_FORM_addr:
13993       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
13994       info_ptr += bytes_read;
13995       break;
13996     case DW_FORM_block2:
13997       blk = dwarf_alloc_block (cu);
13998       blk->size = read_2_bytes (abfd, info_ptr);
13999       info_ptr += 2;
14000       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14001       info_ptr += blk->size;
14002       DW_BLOCK (attr) = blk;
14003       break;
14004     case DW_FORM_block4:
14005       blk = dwarf_alloc_block (cu);
14006       blk->size = read_4_bytes (abfd, info_ptr);
14007       info_ptr += 4;
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_data2:
14013       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14014       info_ptr += 2;
14015       break;
14016     case DW_FORM_data4:
14017       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14018       info_ptr += 4;
14019       break;
14020     case DW_FORM_data8:
14021       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14022       info_ptr += 8;
14023       break;
14024     case DW_FORM_sec_offset:
14025       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14026       info_ptr += bytes_read;
14027       break;
14028     case DW_FORM_string:
14029       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14030       DW_STRING_IS_CANONICAL (attr) = 0;
14031       info_ptr += bytes_read;
14032       break;
14033     case DW_FORM_strp:
14034       if (!cu->per_cu->is_dwz)
14035         {
14036           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14037                                                    &bytes_read);
14038           DW_STRING_IS_CANONICAL (attr) = 0;
14039           info_ptr += bytes_read;
14040           break;
14041         }
14042       /* FALLTHROUGH */
14043     case DW_FORM_GNU_strp_alt:
14044       {
14045         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14046         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14047                                           &bytes_read);
14048
14049         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14050         DW_STRING_IS_CANONICAL (attr) = 0;
14051         info_ptr += bytes_read;
14052       }
14053       break;
14054     case DW_FORM_exprloc:
14055     case DW_FORM_block:
14056       blk = dwarf_alloc_block (cu);
14057       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14058       info_ptr += bytes_read;
14059       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14060       info_ptr += blk->size;
14061       DW_BLOCK (attr) = blk;
14062       break;
14063     case DW_FORM_block1:
14064       blk = dwarf_alloc_block (cu);
14065       blk->size = read_1_byte (abfd, info_ptr);
14066       info_ptr += 1;
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_data1:
14072       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14073       info_ptr += 1;
14074       break;
14075     case DW_FORM_flag:
14076       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14077       info_ptr += 1;
14078       break;
14079     case DW_FORM_flag_present:
14080       DW_UNSND (attr) = 1;
14081       break;
14082     case DW_FORM_sdata:
14083       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14084       info_ptr += bytes_read;
14085       break;
14086     case DW_FORM_udata:
14087       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14088       info_ptr += bytes_read;
14089       break;
14090     case DW_FORM_ref1:
14091       DW_UNSND (attr) = (cu->header.offset.sect_off
14092                          + read_1_byte (abfd, info_ptr));
14093       info_ptr += 1;
14094       break;
14095     case DW_FORM_ref2:
14096       DW_UNSND (attr) = (cu->header.offset.sect_off
14097                          + read_2_bytes (abfd, info_ptr));
14098       info_ptr += 2;
14099       break;
14100     case DW_FORM_ref4:
14101       DW_UNSND (attr) = (cu->header.offset.sect_off
14102                          + read_4_bytes (abfd, info_ptr));
14103       info_ptr += 4;
14104       break;
14105     case DW_FORM_ref8:
14106       DW_UNSND (attr) = (cu->header.offset.sect_off
14107                          + read_8_bytes (abfd, info_ptr));
14108       info_ptr += 8;
14109       break;
14110     case DW_FORM_ref_sig8:
14111       /* Convert the signature to something we can record in DW_UNSND
14112          for later lookup.
14113          NOTE: This is NULL if the type wasn't found.  */
14114       DW_SIGNATURED_TYPE (attr) =
14115         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14116       info_ptr += 8;
14117       break;
14118     case DW_FORM_ref_udata:
14119       DW_UNSND (attr) = (cu->header.offset.sect_off
14120                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14121       info_ptr += bytes_read;
14122       break;
14123     case DW_FORM_indirect:
14124       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14125       info_ptr += bytes_read;
14126       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14127       break;
14128     case DW_FORM_GNU_addr_index:
14129       if (reader->dwo_file == NULL)
14130         {
14131           /* For now flag a hard error.
14132              Later we can turn this into a complaint.  */
14133           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14134                  dwarf_form_name (form),
14135                  bfd_get_filename (abfd));
14136         }
14137       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14138       info_ptr += bytes_read;
14139       break;
14140     case DW_FORM_GNU_str_index:
14141       if (reader->dwo_file == NULL)
14142         {
14143           /* For now flag a hard error.
14144              Later we can turn this into a complaint if warranted.  */
14145           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14146                  dwarf_form_name (form),
14147                  bfd_get_filename (abfd));
14148         }
14149       {
14150         ULONGEST str_index =
14151           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14152
14153         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14154         DW_STRING_IS_CANONICAL (attr) = 0;
14155         info_ptr += bytes_read;
14156       }
14157       break;
14158     default:
14159       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14160              dwarf_form_name (form),
14161              bfd_get_filename (abfd));
14162     }
14163
14164   /* Super hack.  */
14165   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14166     attr->form = DW_FORM_GNU_ref_alt;
14167
14168   /* We have seen instances where the compiler tried to emit a byte
14169      size attribute of -1 which ended up being encoded as an unsigned
14170      0xffffffff.  Although 0xffffffff is technically a valid size value,
14171      an object of this size seems pretty unlikely so we can relatively
14172      safely treat these cases as if the size attribute was invalid and
14173      treat them as zero by default.  */
14174   if (attr->name == DW_AT_byte_size
14175       && form == DW_FORM_data4
14176       && DW_UNSND (attr) >= 0xffffffff)
14177     {
14178       complaint
14179         (&symfile_complaints,
14180          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14181          hex_string (DW_UNSND (attr)));
14182       DW_UNSND (attr) = 0;
14183     }
14184
14185   return info_ptr;
14186 }
14187
14188 /* Read an attribute described by an abbreviated attribute.  */
14189
14190 static gdb_byte *
14191 read_attribute (const struct die_reader_specs *reader,
14192                 struct attribute *attr, struct attr_abbrev *abbrev,
14193                 gdb_byte *info_ptr)
14194 {
14195   attr->name = abbrev->name;
14196   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14197 }
14198
14199 /* Read dwarf information from a buffer.  */
14200
14201 static unsigned int
14202 read_1_byte (bfd *abfd, const gdb_byte *buf)
14203 {
14204   return bfd_get_8 (abfd, buf);
14205 }
14206
14207 static int
14208 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14209 {
14210   return bfd_get_signed_8 (abfd, buf);
14211 }
14212
14213 static unsigned int
14214 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14215 {
14216   return bfd_get_16 (abfd, buf);
14217 }
14218
14219 static int
14220 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14221 {
14222   return bfd_get_signed_16 (abfd, buf);
14223 }
14224
14225 static unsigned int
14226 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14227 {
14228   return bfd_get_32 (abfd, buf);
14229 }
14230
14231 static int
14232 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14233 {
14234   return bfd_get_signed_32 (abfd, buf);
14235 }
14236
14237 static ULONGEST
14238 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14239 {
14240   return bfd_get_64 (abfd, buf);
14241 }
14242
14243 static CORE_ADDR
14244 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
14245               unsigned int *bytes_read)
14246 {
14247   struct comp_unit_head *cu_header = &cu->header;
14248   CORE_ADDR retval = 0;
14249
14250   if (cu_header->signed_addr_p)
14251     {
14252       switch (cu_header->addr_size)
14253         {
14254         case 2:
14255           retval = bfd_get_signed_16 (abfd, buf);
14256           break;
14257         case 4:
14258           retval = bfd_get_signed_32 (abfd, buf);
14259           break;
14260         case 8:
14261           retval = bfd_get_signed_64 (abfd, buf);
14262           break;
14263         default:
14264           internal_error (__FILE__, __LINE__,
14265                           _("read_address: bad switch, signed [in module %s]"),
14266                           bfd_get_filename (abfd));
14267         }
14268     }
14269   else
14270     {
14271       switch (cu_header->addr_size)
14272         {
14273         case 2:
14274           retval = bfd_get_16 (abfd, buf);
14275           break;
14276         case 4:
14277           retval = bfd_get_32 (abfd, buf);
14278           break;
14279         case 8:
14280           retval = bfd_get_64 (abfd, buf);
14281           break;
14282         default:
14283           internal_error (__FILE__, __LINE__,
14284                           _("read_address: bad switch, "
14285                             "unsigned [in module %s]"),
14286                           bfd_get_filename (abfd));
14287         }
14288     }
14289
14290   *bytes_read = cu_header->addr_size;
14291   return retval;
14292 }
14293
14294 /* Read the initial length from a section.  The (draft) DWARF 3
14295    specification allows the initial length to take up either 4 bytes
14296    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14297    bytes describe the length and all offsets will be 8 bytes in length
14298    instead of 4.
14299
14300    An older, non-standard 64-bit format is also handled by this
14301    function.  The older format in question stores the initial length
14302    as an 8-byte quantity without an escape value.  Lengths greater
14303    than 2^32 aren't very common which means that the initial 4 bytes
14304    is almost always zero.  Since a length value of zero doesn't make
14305    sense for the 32-bit format, this initial zero can be considered to
14306    be an escape value which indicates the presence of the older 64-bit
14307    format.  As written, the code can't detect (old format) lengths
14308    greater than 4GB.  If it becomes necessary to handle lengths
14309    somewhat larger than 4GB, we could allow other small values (such
14310    as the non-sensical values of 1, 2, and 3) to also be used as
14311    escape values indicating the presence of the old format.
14312
14313    The value returned via bytes_read should be used to increment the
14314    relevant pointer after calling read_initial_length().
14315
14316    [ Note:  read_initial_length() and read_offset() are based on the
14317      document entitled "DWARF Debugging Information Format", revision
14318      3, draft 8, dated November 19, 2001.  This document was obtained
14319      from:
14320
14321         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14322
14323      This document is only a draft and is subject to change.  (So beware.)
14324
14325      Details regarding the older, non-standard 64-bit format were
14326      determined empirically by examining 64-bit ELF files produced by
14327      the SGI toolchain on an IRIX 6.5 machine.
14328
14329      - Kevin, July 16, 2002
14330    ] */
14331
14332 static LONGEST
14333 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
14334 {
14335   LONGEST length = bfd_get_32 (abfd, buf);
14336
14337   if (length == 0xffffffff)
14338     {
14339       length = bfd_get_64 (abfd, buf + 4);
14340       *bytes_read = 12;
14341     }
14342   else if (length == 0)
14343     {
14344       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14345       length = bfd_get_64 (abfd, buf);
14346       *bytes_read = 8;
14347     }
14348   else
14349     {
14350       *bytes_read = 4;
14351     }
14352
14353   return length;
14354 }
14355
14356 /* Cover function for read_initial_length.
14357    Returns the length of the object at BUF, and stores the size of the
14358    initial length in *BYTES_READ and stores the size that offsets will be in
14359    *OFFSET_SIZE.
14360    If the initial length size is not equivalent to that specified in
14361    CU_HEADER then issue a complaint.
14362    This is useful when reading non-comp-unit headers.  */
14363
14364 static LONGEST
14365 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
14366                                         const struct comp_unit_head *cu_header,
14367                                         unsigned int *bytes_read,
14368                                         unsigned int *offset_size)
14369 {
14370   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14371
14372   gdb_assert (cu_header->initial_length_size == 4
14373               || cu_header->initial_length_size == 8
14374               || cu_header->initial_length_size == 12);
14375
14376   if (cu_header->initial_length_size != *bytes_read)
14377     complaint (&symfile_complaints,
14378                _("intermixed 32-bit and 64-bit DWARF sections"));
14379
14380   *offset_size = (*bytes_read == 4) ? 4 : 8;
14381   return length;
14382 }
14383
14384 /* Read an offset from the data stream.  The size of the offset is
14385    given by cu_header->offset_size.  */
14386
14387 static LONGEST
14388 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
14389              unsigned int *bytes_read)
14390 {
14391   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14392
14393   *bytes_read = cu_header->offset_size;
14394   return offset;
14395 }
14396
14397 /* Read an offset from the data stream.  */
14398
14399 static LONGEST
14400 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
14401 {
14402   LONGEST retval = 0;
14403
14404   switch (offset_size)
14405     {
14406     case 4:
14407       retval = bfd_get_32 (abfd, buf);
14408       break;
14409     case 8:
14410       retval = bfd_get_64 (abfd, buf);
14411       break;
14412     default:
14413       internal_error (__FILE__, __LINE__,
14414                       _("read_offset_1: bad switch [in module %s]"),
14415                       bfd_get_filename (abfd));
14416     }
14417
14418   return retval;
14419 }
14420
14421 static gdb_byte *
14422 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
14423 {
14424   /* If the size of a host char is 8 bits, we can return a pointer
14425      to the buffer, otherwise we have to copy the data to a buffer
14426      allocated on the temporary obstack.  */
14427   gdb_assert (HOST_CHAR_BIT == 8);
14428   return buf;
14429 }
14430
14431 static char *
14432 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14433 {
14434   /* If the size of a host char is 8 bits, we can return a pointer
14435      to the string, otherwise we have to copy the string to a buffer
14436      allocated on the temporary obstack.  */
14437   gdb_assert (HOST_CHAR_BIT == 8);
14438   if (*buf == '\0')
14439     {
14440       *bytes_read_ptr = 1;
14441       return NULL;
14442     }
14443   *bytes_read_ptr = strlen ((char *) buf) + 1;
14444   return (char *) buf;
14445 }
14446
14447 static char *
14448 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14449 {
14450   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14451   if (dwarf2_per_objfile->str.buffer == NULL)
14452     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14453            bfd_get_filename (abfd));
14454   if (str_offset >= dwarf2_per_objfile->str.size)
14455     error (_("DW_FORM_strp pointing outside of "
14456              ".debug_str section [in module %s]"),
14457            bfd_get_filename (abfd));
14458   gdb_assert (HOST_CHAR_BIT == 8);
14459   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14460     return NULL;
14461   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
14462 }
14463
14464 /* Read a string at offset STR_OFFSET in the .debug_str section from
14465    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14466    the string consists of a single NUL byte, return NULL; otherwise
14467    return a pointer to the string.  */
14468
14469 static char *
14470 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14471 {
14472   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14473
14474   if (dwz->str.buffer == NULL)
14475     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14476              "section [in module %s]"),
14477            bfd_get_filename (dwz->dwz_bfd));
14478   if (str_offset >= dwz->str.size)
14479     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14480              ".debug_str section [in module %s]"),
14481            bfd_get_filename (dwz->dwz_bfd));
14482   gdb_assert (HOST_CHAR_BIT == 8);
14483   if (dwz->str.buffer[str_offset] == '\0')
14484     return NULL;
14485   return (char *) (dwz->str.buffer + str_offset);
14486 }
14487
14488 static char *
14489 read_indirect_string (bfd *abfd, gdb_byte *buf,
14490                       const struct comp_unit_head *cu_header,
14491                       unsigned int *bytes_read_ptr)
14492 {
14493   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14494
14495   return read_indirect_string_at_offset (abfd, str_offset);
14496 }
14497
14498 static ULONGEST
14499 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14500 {
14501   ULONGEST result;
14502   unsigned int num_read;
14503   int i, shift;
14504   unsigned char byte;
14505
14506   result = 0;
14507   shift = 0;
14508   num_read = 0;
14509   i = 0;
14510   while (1)
14511     {
14512       byte = bfd_get_8 (abfd, buf);
14513       buf++;
14514       num_read++;
14515       result |= ((ULONGEST) (byte & 127) << shift);
14516       if ((byte & 128) == 0)
14517         {
14518           break;
14519         }
14520       shift += 7;
14521     }
14522   *bytes_read_ptr = num_read;
14523   return result;
14524 }
14525
14526 static LONGEST
14527 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14528 {
14529   LONGEST result;
14530   int i, shift, num_read;
14531   unsigned char byte;
14532
14533   result = 0;
14534   shift = 0;
14535   num_read = 0;
14536   i = 0;
14537   while (1)
14538     {
14539       byte = bfd_get_8 (abfd, buf);
14540       buf++;
14541       num_read++;
14542       result |= ((LONGEST) (byte & 127) << shift);
14543       shift += 7;
14544       if ((byte & 128) == 0)
14545         {
14546           break;
14547         }
14548     }
14549   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14550     result |= -(((LONGEST) 1) << shift);
14551   *bytes_read_ptr = num_read;
14552   return result;
14553 }
14554
14555 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14556    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14557    ADDR_SIZE is the size of addresses from the CU header.  */
14558
14559 static CORE_ADDR
14560 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14561 {
14562   struct objfile *objfile = dwarf2_per_objfile->objfile;
14563   bfd *abfd = objfile->obfd;
14564   const gdb_byte *info_ptr;
14565
14566   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14567   if (dwarf2_per_objfile->addr.buffer == NULL)
14568     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14569            objfile->name);
14570   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14571     error (_("DW_FORM_addr_index pointing outside of "
14572              ".debug_addr section [in module %s]"),
14573            objfile->name);
14574   info_ptr = (dwarf2_per_objfile->addr.buffer
14575               + addr_base + addr_index * addr_size);
14576   if (addr_size == 4)
14577     return bfd_get_32 (abfd, info_ptr);
14578   else
14579     return bfd_get_64 (abfd, info_ptr);
14580 }
14581
14582 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14583
14584 static CORE_ADDR
14585 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14586 {
14587   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14588 }
14589
14590 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14591
14592 static CORE_ADDR
14593 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
14594                              unsigned int *bytes_read)
14595 {
14596   bfd *abfd = cu->objfile->obfd;
14597   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14598
14599   return read_addr_index (cu, addr_index);
14600 }
14601
14602 /* Data structure to pass results from dwarf2_read_addr_index_reader
14603    back to dwarf2_read_addr_index.  */
14604
14605 struct dwarf2_read_addr_index_data
14606 {
14607   ULONGEST addr_base;
14608   int addr_size;
14609 };
14610
14611 /* die_reader_func for dwarf2_read_addr_index.  */
14612
14613 static void
14614 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14615                                gdb_byte *info_ptr,
14616                                struct die_info *comp_unit_die,
14617                                int has_children,
14618                                void *data)
14619 {
14620   struct dwarf2_cu *cu = reader->cu;
14621   struct dwarf2_read_addr_index_data *aidata =
14622     (struct dwarf2_read_addr_index_data *) data;
14623
14624   aidata->addr_base = cu->addr_base;
14625   aidata->addr_size = cu->header.addr_size;
14626 }
14627
14628 /* Given an index in .debug_addr, fetch the value.
14629    NOTE: This can be called during dwarf expression evaluation,
14630    long after the debug information has been read, and thus per_cu->cu
14631    may no longer exist.  */
14632
14633 CORE_ADDR
14634 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14635                         unsigned int addr_index)
14636 {
14637   struct objfile *objfile = per_cu->objfile;
14638   struct dwarf2_cu *cu = per_cu->cu;
14639   ULONGEST addr_base;
14640   int addr_size;
14641
14642   /* This is intended to be called from outside this file.  */
14643   dw2_setup (objfile);
14644
14645   /* We need addr_base and addr_size.
14646      If we don't have PER_CU->cu, we have to get it.
14647      Nasty, but the alternative is storing the needed info in PER_CU,
14648      which at this point doesn't seem justified: it's not clear how frequently
14649      it would get used and it would increase the size of every PER_CU.
14650      Entry points like dwarf2_per_cu_addr_size do a similar thing
14651      so we're not in uncharted territory here.
14652      Alas we need to be a bit more complicated as addr_base is contained
14653      in the DIE.
14654
14655      We don't need to read the entire CU(/TU).
14656      We just need the header and top level die.
14657
14658      IWBN to use the aging mechanism to let us lazily later discard the CU.
14659      For now we skip this optimization.  */
14660
14661   if (cu != NULL)
14662     {
14663       addr_base = cu->addr_base;
14664       addr_size = cu->header.addr_size;
14665     }
14666   else
14667     {
14668       struct dwarf2_read_addr_index_data aidata;
14669
14670       /* Note: We can't use init_cutu_and_read_dies_simple here,
14671          we need addr_base.  */
14672       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14673                                dwarf2_read_addr_index_reader, &aidata);
14674       addr_base = aidata.addr_base;
14675       addr_size = aidata.addr_size;
14676     }
14677
14678   return read_addr_index_1 (addr_index, addr_base, addr_size);
14679 }
14680
14681 /* Given a DW_AT_str_index, fetch the string.  */
14682
14683 static char *
14684 read_str_index (const struct die_reader_specs *reader,
14685                 struct dwarf2_cu *cu, ULONGEST str_index)
14686 {
14687   struct objfile *objfile = dwarf2_per_objfile->objfile;
14688   const char *dwo_name = objfile->name;
14689   bfd *abfd = objfile->obfd;
14690   struct dwo_sections *sections = &reader->dwo_file->sections;
14691   gdb_byte *info_ptr;
14692   ULONGEST str_offset;
14693
14694   dwarf2_read_section (objfile, &sections->str);
14695   dwarf2_read_section (objfile, &sections->str_offsets);
14696   if (sections->str.buffer == NULL)
14697     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14698              " in CU at offset 0x%lx [in module %s]"),
14699            (long) cu->header.offset.sect_off, dwo_name);
14700   if (sections->str_offsets.buffer == NULL)
14701     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14702              " in CU at offset 0x%lx [in module %s]"),
14703            (long) cu->header.offset.sect_off, dwo_name);
14704   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14705     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14706              " section in CU at offset 0x%lx [in module %s]"),
14707            (long) cu->header.offset.sect_off, dwo_name);
14708   info_ptr = (sections->str_offsets.buffer
14709               + str_index * cu->header.offset_size);
14710   if (cu->header.offset_size == 4)
14711     str_offset = bfd_get_32 (abfd, info_ptr);
14712   else
14713     str_offset = bfd_get_64 (abfd, info_ptr);
14714   if (str_offset >= sections->str.size)
14715     error (_("Offset from DW_FORM_str_index pointing outside of"
14716              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14717            (long) cu->header.offset.sect_off, dwo_name);
14718   return (char *) (sections->str.buffer + str_offset);
14719 }
14720
14721 /* Return the length of an LEB128 number in BUF.  */
14722
14723 static int
14724 leb128_size (const gdb_byte *buf)
14725 {
14726   const gdb_byte *begin = buf;
14727   gdb_byte byte;
14728
14729   while (1)
14730     {
14731       byte = *buf++;
14732       if ((byte & 128) == 0)
14733         return buf - begin;
14734     }
14735 }
14736
14737 static void
14738 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14739 {
14740   switch (lang)
14741     {
14742     case DW_LANG_C89:
14743     case DW_LANG_C99:
14744     case DW_LANG_C:
14745       cu->language = language_c;
14746       break;
14747     case DW_LANG_C_plus_plus:
14748       cu->language = language_cplus;
14749       break;
14750     case DW_LANG_D:
14751       cu->language = language_d;
14752       break;
14753     case DW_LANG_Fortran77:
14754     case DW_LANG_Fortran90:
14755     case DW_LANG_Fortran95:
14756       cu->language = language_fortran;
14757       break;
14758     case DW_LANG_Go:
14759       cu->language = language_go;
14760       break;
14761     case DW_LANG_Mips_Assembler:
14762       cu->language = language_asm;
14763       break;
14764     case DW_LANG_Java:
14765       cu->language = language_java;
14766       break;
14767     case DW_LANG_Ada83:
14768     case DW_LANG_Ada95:
14769       cu->language = language_ada;
14770       break;
14771     case DW_LANG_Modula2:
14772       cu->language = language_m2;
14773       break;
14774     case DW_LANG_Pascal83:
14775       cu->language = language_pascal;
14776       break;
14777     case DW_LANG_ObjC:
14778       cu->language = language_objc;
14779       break;
14780     case DW_LANG_Cobol74:
14781     case DW_LANG_Cobol85:
14782     default:
14783       cu->language = language_minimal;
14784       break;
14785     }
14786   cu->language_defn = language_def (cu->language);
14787 }
14788
14789 /* Return the named attribute or NULL if not there.  */
14790
14791 static struct attribute *
14792 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
14793 {
14794   for (;;)
14795     {
14796       unsigned int i;
14797       struct attribute *spec = NULL;
14798
14799       for (i = 0; i < die->num_attrs; ++i)
14800         {
14801           if (die->attrs[i].name == name)
14802             return &die->attrs[i];
14803           if (die->attrs[i].name == DW_AT_specification
14804               || die->attrs[i].name == DW_AT_abstract_origin)
14805             spec = &die->attrs[i];
14806         }
14807
14808       if (!spec)
14809         break;
14810
14811       die = follow_die_ref (die, spec, &cu);
14812     }
14813
14814   return NULL;
14815 }
14816
14817 /* Return the named attribute or NULL if not there,
14818    but do not follow DW_AT_specification, etc.
14819    This is for use in contexts where we're reading .debug_types dies.
14820    Following DW_AT_specification, DW_AT_abstract_origin will take us
14821    back up the chain, and we want to go down.  */
14822
14823 static struct attribute *
14824 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
14825 {
14826   unsigned int i;
14827
14828   for (i = 0; i < die->num_attrs; ++i)
14829     if (die->attrs[i].name == name)
14830       return &die->attrs[i];
14831
14832   return NULL;
14833 }
14834
14835 /* Return non-zero iff the attribute NAME is defined for the given DIE,
14836    and holds a non-zero value.  This function should only be used for
14837    DW_FORM_flag or DW_FORM_flag_present attributes.  */
14838
14839 static int
14840 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
14841 {
14842   struct attribute *attr = dwarf2_attr (die, name, cu);
14843
14844   return (attr && DW_UNSND (attr));
14845 }
14846
14847 static int
14848 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
14849 {
14850   /* A DIE is a declaration if it has a DW_AT_declaration attribute
14851      which value is non-zero.  However, we have to be careful with
14852      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
14853      (via dwarf2_flag_true_p) follows this attribute.  So we may
14854      end up accidently finding a declaration attribute that belongs
14855      to a different DIE referenced by the specification attribute,
14856      even though the given DIE does not have a declaration attribute.  */
14857   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
14858           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
14859 }
14860
14861 /* Return the die giving the specification for DIE, if there is
14862    one.  *SPEC_CU is the CU containing DIE on input, and the CU
14863    containing the return value on output.  If there is no
14864    specification, but there is an abstract origin, that is
14865    returned.  */
14866
14867 static struct die_info *
14868 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
14869 {
14870   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
14871                                              *spec_cu);
14872
14873   if (spec_attr == NULL)
14874     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
14875
14876   if (spec_attr == NULL)
14877     return NULL;
14878   else
14879     return follow_die_ref (die, spec_attr, spec_cu);
14880 }
14881
14882 /* Free the line_header structure *LH, and any arrays and strings it
14883    refers to.
14884    NOTE: This is also used as a "cleanup" function.  */
14885
14886 static void
14887 free_line_header (struct line_header *lh)
14888 {
14889   if (lh->standard_opcode_lengths)
14890     xfree (lh->standard_opcode_lengths);
14891
14892   /* Remember that all the lh->file_names[i].name pointers are
14893      pointers into debug_line_buffer, and don't need to be freed.  */
14894   if (lh->file_names)
14895     xfree (lh->file_names);
14896
14897   /* Similarly for the include directory names.  */
14898   if (lh->include_dirs)
14899     xfree (lh->include_dirs);
14900
14901   xfree (lh);
14902 }
14903
14904 /* Add an entry to LH's include directory table.  */
14905
14906 static void
14907 add_include_dir (struct line_header *lh, char *include_dir)
14908 {
14909   /* Grow the array if necessary.  */
14910   if (lh->include_dirs_size == 0)
14911     {
14912       lh->include_dirs_size = 1; /* for testing */
14913       lh->include_dirs = xmalloc (lh->include_dirs_size
14914                                   * sizeof (*lh->include_dirs));
14915     }
14916   else if (lh->num_include_dirs >= lh->include_dirs_size)
14917     {
14918       lh->include_dirs_size *= 2;
14919       lh->include_dirs = xrealloc (lh->include_dirs,
14920                                    (lh->include_dirs_size
14921                                     * sizeof (*lh->include_dirs)));
14922     }
14923
14924   lh->include_dirs[lh->num_include_dirs++] = include_dir;
14925 }
14926
14927 /* Add an entry to LH's file name table.  */
14928
14929 static void
14930 add_file_name (struct line_header *lh,
14931                char *name,
14932                unsigned int dir_index,
14933                unsigned int mod_time,
14934                unsigned int length)
14935 {
14936   struct file_entry *fe;
14937
14938   /* Grow the array if necessary.  */
14939   if (lh->file_names_size == 0)
14940     {
14941       lh->file_names_size = 1; /* for testing */
14942       lh->file_names = xmalloc (lh->file_names_size
14943                                 * sizeof (*lh->file_names));
14944     }
14945   else if (lh->num_file_names >= lh->file_names_size)
14946     {
14947       lh->file_names_size *= 2;
14948       lh->file_names = xrealloc (lh->file_names,
14949                                  (lh->file_names_size
14950                                   * sizeof (*lh->file_names)));
14951     }
14952
14953   fe = &lh->file_names[lh->num_file_names++];
14954   fe->name = name;
14955   fe->dir_index = dir_index;
14956   fe->mod_time = mod_time;
14957   fe->length = length;
14958   fe->included_p = 0;
14959   fe->symtab = NULL;
14960 }
14961
14962 /* A convenience function to find the proper .debug_line section for a
14963    CU.  */
14964
14965 static struct dwarf2_section_info *
14966 get_debug_line_section (struct dwarf2_cu *cu)
14967 {
14968   struct dwarf2_section_info *section;
14969
14970   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
14971      DWO file.  */
14972   if (cu->dwo_unit && cu->per_cu->is_debug_types)
14973     section = &cu->dwo_unit->dwo_file->sections.line;
14974   else if (cu->per_cu->is_dwz)
14975     {
14976       struct dwz_file *dwz = dwarf2_get_dwz_file ();
14977
14978       section = &dwz->line;
14979     }
14980   else
14981     section = &dwarf2_per_objfile->line;
14982
14983   return section;
14984 }
14985
14986 /* Read the statement program header starting at OFFSET in
14987    .debug_line, or .debug_line.dwo.  Return a pointer
14988    to a struct line_header, allocated using xmalloc.
14989
14990    NOTE: the strings in the include directory and file name tables of
14991    the returned object point into the dwarf line section buffer,
14992    and must not be freed.  */
14993
14994 static struct line_header *
14995 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
14996 {
14997   struct cleanup *back_to;
14998   struct line_header *lh;
14999   gdb_byte *line_ptr;
15000   unsigned int bytes_read, offset_size;
15001   int i;
15002   char *cur_dir, *cur_file;
15003   struct dwarf2_section_info *section;
15004   bfd *abfd;
15005
15006   section = get_debug_line_section (cu);
15007   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15008   if (section->buffer == NULL)
15009     {
15010       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15011         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15012       else
15013         complaint (&symfile_complaints, _("missing .debug_line section"));
15014       return 0;
15015     }
15016
15017   /* We can't do this until we know the section is non-empty.
15018      Only then do we know we have such a section.  */
15019   abfd = section->asection->owner;
15020
15021   /* Make sure that at least there's room for the total_length field.
15022      That could be 12 bytes long, but we're just going to fudge that.  */
15023   if (offset + 4 >= section->size)
15024     {
15025       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15026       return 0;
15027     }
15028
15029   lh = xmalloc (sizeof (*lh));
15030   memset (lh, 0, sizeof (*lh));
15031   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15032                           (void *) lh);
15033
15034   line_ptr = section->buffer + offset;
15035
15036   /* Read in the header.  */
15037   lh->total_length =
15038     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15039                                             &bytes_read, &offset_size);
15040   line_ptr += bytes_read;
15041   if (line_ptr + lh->total_length > (section->buffer + section->size))
15042     {
15043       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15044       return 0;
15045     }
15046   lh->statement_program_end = line_ptr + lh->total_length;
15047   lh->version = read_2_bytes (abfd, line_ptr);
15048   line_ptr += 2;
15049   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15050   line_ptr += offset_size;
15051   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15052   line_ptr += 1;
15053   if (lh->version >= 4)
15054     {
15055       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15056       line_ptr += 1;
15057     }
15058   else
15059     lh->maximum_ops_per_instruction = 1;
15060
15061   if (lh->maximum_ops_per_instruction == 0)
15062     {
15063       lh->maximum_ops_per_instruction = 1;
15064       complaint (&symfile_complaints,
15065                  _("invalid maximum_ops_per_instruction "
15066                    "in `.debug_line' section"));
15067     }
15068
15069   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15070   line_ptr += 1;
15071   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15072   line_ptr += 1;
15073   lh->line_range = read_1_byte (abfd, line_ptr);
15074   line_ptr += 1;
15075   lh->opcode_base = read_1_byte (abfd, line_ptr);
15076   line_ptr += 1;
15077   lh->standard_opcode_lengths
15078     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15079
15080   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15081   for (i = 1; i < lh->opcode_base; ++i)
15082     {
15083       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15084       line_ptr += 1;
15085     }
15086
15087   /* Read directory table.  */
15088   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15089     {
15090       line_ptr += bytes_read;
15091       add_include_dir (lh, cur_dir);
15092     }
15093   line_ptr += bytes_read;
15094
15095   /* Read file name table.  */
15096   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15097     {
15098       unsigned int dir_index, mod_time, length;
15099
15100       line_ptr += bytes_read;
15101       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15102       line_ptr += bytes_read;
15103       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15104       line_ptr += bytes_read;
15105       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15106       line_ptr += bytes_read;
15107
15108       add_file_name (lh, cur_file, dir_index, mod_time, length);
15109     }
15110   line_ptr += bytes_read;
15111   lh->statement_program_start = line_ptr;
15112
15113   if (line_ptr > (section->buffer + section->size))
15114     complaint (&symfile_complaints,
15115                _("line number info header doesn't "
15116                  "fit in `.debug_line' section"));
15117
15118   discard_cleanups (back_to);
15119   return lh;
15120 }
15121
15122 /* Subroutine of dwarf_decode_lines to simplify it.
15123    Return the file name of the psymtab for included file FILE_INDEX
15124    in line header LH of PST.
15125    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15126    If space for the result is malloc'd, it will be freed by a cleanup.
15127    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15128
15129    The function creates dangling cleanup registration.  */
15130
15131 static char *
15132 psymtab_include_file_name (const struct line_header *lh, int file_index,
15133                            const struct partial_symtab *pst,
15134                            const char *comp_dir)
15135 {
15136   const struct file_entry fe = lh->file_names [file_index];
15137   char *include_name = fe.name;
15138   char *include_name_to_compare = include_name;
15139   char *dir_name = NULL;
15140   const char *pst_filename;
15141   char *copied_name = NULL;
15142   int file_is_pst;
15143
15144   if (fe.dir_index)
15145     dir_name = lh->include_dirs[fe.dir_index - 1];
15146
15147   if (!IS_ABSOLUTE_PATH (include_name)
15148       && (dir_name != NULL || comp_dir != NULL))
15149     {
15150       /* Avoid creating a duplicate psymtab for PST.
15151          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15152          Before we do the comparison, however, we need to account
15153          for DIR_NAME and COMP_DIR.
15154          First prepend dir_name (if non-NULL).  If we still don't
15155          have an absolute path prepend comp_dir (if non-NULL).
15156          However, the directory we record in the include-file's
15157          psymtab does not contain COMP_DIR (to match the
15158          corresponding symtab(s)).
15159
15160          Example:
15161
15162          bash$ cd /tmp
15163          bash$ gcc -g ./hello.c
15164          include_name = "hello.c"
15165          dir_name = "."
15166          DW_AT_comp_dir = comp_dir = "/tmp"
15167          DW_AT_name = "./hello.c"  */
15168
15169       if (dir_name != NULL)
15170         {
15171           include_name = concat (dir_name, SLASH_STRING,
15172                                  include_name, (char *)NULL);
15173           include_name_to_compare = include_name;
15174           make_cleanup (xfree, include_name);
15175         }
15176       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15177         {
15178           include_name_to_compare = concat (comp_dir, SLASH_STRING,
15179                                             include_name, (char *)NULL);
15180         }
15181     }
15182
15183   pst_filename = pst->filename;
15184   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15185     {
15186       copied_name = concat (pst->dirname, SLASH_STRING,
15187                             pst_filename, (char *)NULL);
15188       pst_filename = copied_name;
15189     }
15190
15191   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15192
15193   if (include_name_to_compare != include_name)
15194     xfree (include_name_to_compare);
15195   if (copied_name != NULL)
15196     xfree (copied_name);
15197
15198   if (file_is_pst)
15199     return NULL;
15200   return include_name;
15201 }
15202
15203 /* Ignore this record_line request.  */
15204
15205 static void
15206 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15207 {
15208   return;
15209 }
15210
15211 /* Subroutine of dwarf_decode_lines to simplify it.
15212    Process the line number information in LH.  */
15213
15214 static void
15215 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15216                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15217 {
15218   gdb_byte *line_ptr, *extended_end;
15219   gdb_byte *line_end;
15220   unsigned int bytes_read, extended_len;
15221   unsigned char op_code, extended_op, adj_opcode;
15222   CORE_ADDR baseaddr;
15223   struct objfile *objfile = cu->objfile;
15224   bfd *abfd = objfile->obfd;
15225   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15226   const int decode_for_pst_p = (pst != NULL);
15227   struct subfile *last_subfile = NULL;
15228   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15229     = record_line;
15230
15231   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15232
15233   line_ptr = lh->statement_program_start;
15234   line_end = lh->statement_program_end;
15235
15236   /* Read the statement sequences until there's nothing left.  */
15237   while (line_ptr < line_end)
15238     {
15239       /* state machine registers  */
15240       CORE_ADDR address = 0;
15241       unsigned int file = 1;
15242       unsigned int line = 1;
15243       unsigned int column = 0;
15244       int is_stmt = lh->default_is_stmt;
15245       int basic_block = 0;
15246       int end_sequence = 0;
15247       CORE_ADDR addr;
15248       unsigned char op_index = 0;
15249
15250       if (!decode_for_pst_p && lh->num_file_names >= file)
15251         {
15252           /* Start a subfile for the current file of the state machine.  */
15253           /* lh->include_dirs and lh->file_names are 0-based, but the
15254              directory and file name numbers in the statement program
15255              are 1-based.  */
15256           struct file_entry *fe = &lh->file_names[file - 1];
15257           char *dir = NULL;
15258
15259           if (fe->dir_index)
15260             dir = lh->include_dirs[fe->dir_index - 1];
15261
15262           dwarf2_start_subfile (fe->name, dir, comp_dir);
15263         }
15264
15265       /* Decode the table.  */
15266       while (!end_sequence)
15267         {
15268           op_code = read_1_byte (abfd, line_ptr);
15269           line_ptr += 1;
15270           if (line_ptr > line_end)
15271             {
15272               dwarf2_debug_line_missing_end_sequence_complaint ();
15273               break;
15274             }
15275
15276           if (op_code >= lh->opcode_base)
15277             {
15278               /* Special operand.  */
15279               adj_opcode = op_code - lh->opcode_base;
15280               address += (((op_index + (adj_opcode / lh->line_range))
15281                            / lh->maximum_ops_per_instruction)
15282                           * lh->minimum_instruction_length);
15283               op_index = ((op_index + (adj_opcode / lh->line_range))
15284                           % lh->maximum_ops_per_instruction);
15285               line += lh->line_base + (adj_opcode % lh->line_range);
15286               if (lh->num_file_names < file || file == 0)
15287                 dwarf2_debug_line_missing_file_complaint ();
15288               /* For now we ignore lines not starting on an
15289                  instruction boundary.  */
15290               else if (op_index == 0)
15291                 {
15292                   lh->file_names[file - 1].included_p = 1;
15293                   if (!decode_for_pst_p && is_stmt)
15294                     {
15295                       if (last_subfile != current_subfile)
15296                         {
15297                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15298                           if (last_subfile)
15299                             (*p_record_line) (last_subfile, 0, addr);
15300                           last_subfile = current_subfile;
15301                         }
15302                       /* Append row to matrix using current values.  */
15303                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15304                       (*p_record_line) (current_subfile, line, addr);
15305                     }
15306                 }
15307               basic_block = 0;
15308             }
15309           else switch (op_code)
15310             {
15311             case DW_LNS_extended_op:
15312               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15313                                                    &bytes_read);
15314               line_ptr += bytes_read;
15315               extended_end = line_ptr + extended_len;
15316               extended_op = read_1_byte (abfd, line_ptr);
15317               line_ptr += 1;
15318               switch (extended_op)
15319                 {
15320                 case DW_LNE_end_sequence:
15321                   p_record_line = record_line;
15322                   end_sequence = 1;
15323                   break;
15324                 case DW_LNE_set_address:
15325                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15326
15327                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15328                     {
15329                       /* This line table is for a function which has been
15330                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15331
15332                       long line_offset
15333                         = line_ptr - get_debug_line_section (cu)->buffer;
15334
15335                       complaint (&symfile_complaints,
15336                                  _(".debug_line address at offset 0x%lx is 0 "
15337                                    "[in module %s]"),
15338                                  line_offset, objfile->name);
15339                       p_record_line = noop_record_line;
15340                     }
15341
15342                   op_index = 0;
15343                   line_ptr += bytes_read;
15344                   address += baseaddr;
15345                   break;
15346                 case DW_LNE_define_file:
15347                   {
15348                     char *cur_file;
15349                     unsigned int dir_index, mod_time, length;
15350
15351                     cur_file = read_direct_string (abfd, line_ptr,
15352                                                    &bytes_read);
15353                     line_ptr += bytes_read;
15354                     dir_index =
15355                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15356                     line_ptr += bytes_read;
15357                     mod_time =
15358                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15359                     line_ptr += bytes_read;
15360                     length =
15361                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15362                     line_ptr += bytes_read;
15363                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15364                   }
15365                   break;
15366                 case DW_LNE_set_discriminator:
15367                   /* The discriminator is not interesting to the debugger;
15368                      just ignore it.  */
15369                   line_ptr = extended_end;
15370                   break;
15371                 default:
15372                   complaint (&symfile_complaints,
15373                              _("mangled .debug_line section"));
15374                   return;
15375                 }
15376               /* Make sure that we parsed the extended op correctly.  If e.g.
15377                  we expected a different address size than the producer used,
15378                  we may have read the wrong number of bytes.  */
15379               if (line_ptr != extended_end)
15380                 {
15381                   complaint (&symfile_complaints,
15382                              _("mangled .debug_line section"));
15383                   return;
15384                 }
15385               break;
15386             case DW_LNS_copy:
15387               if (lh->num_file_names < file || file == 0)
15388                 dwarf2_debug_line_missing_file_complaint ();
15389               else
15390                 {
15391                   lh->file_names[file - 1].included_p = 1;
15392                   if (!decode_for_pst_p && is_stmt)
15393                     {
15394                       if (last_subfile != current_subfile)
15395                         {
15396                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15397                           if (last_subfile)
15398                             (*p_record_line) (last_subfile, 0, addr);
15399                           last_subfile = current_subfile;
15400                         }
15401                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15402                       (*p_record_line) (current_subfile, line, addr);
15403                     }
15404                 }
15405               basic_block = 0;
15406               break;
15407             case DW_LNS_advance_pc:
15408               {
15409                 CORE_ADDR adjust
15410                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15411
15412                 address += (((op_index + adjust)
15413                              / lh->maximum_ops_per_instruction)
15414                             * lh->minimum_instruction_length);
15415                 op_index = ((op_index + adjust)
15416                             % lh->maximum_ops_per_instruction);
15417                 line_ptr += bytes_read;
15418               }
15419               break;
15420             case DW_LNS_advance_line:
15421               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15422               line_ptr += bytes_read;
15423               break;
15424             case DW_LNS_set_file:
15425               {
15426                 /* The arrays lh->include_dirs and lh->file_names are
15427                    0-based, but the directory and file name numbers in
15428                    the statement program are 1-based.  */
15429                 struct file_entry *fe;
15430                 char *dir = NULL;
15431
15432                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15433                 line_ptr += bytes_read;
15434                 if (lh->num_file_names < file || file == 0)
15435                   dwarf2_debug_line_missing_file_complaint ();
15436                 else
15437                   {
15438                     fe = &lh->file_names[file - 1];
15439                     if (fe->dir_index)
15440                       dir = lh->include_dirs[fe->dir_index - 1];
15441                     if (!decode_for_pst_p)
15442                       {
15443                         last_subfile = current_subfile;
15444                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15445                       }
15446                   }
15447               }
15448               break;
15449             case DW_LNS_set_column:
15450               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15451               line_ptr += bytes_read;
15452               break;
15453             case DW_LNS_negate_stmt:
15454               is_stmt = (!is_stmt);
15455               break;
15456             case DW_LNS_set_basic_block:
15457               basic_block = 1;
15458               break;
15459             /* Add to the address register of the state machine the
15460                address increment value corresponding to special opcode
15461                255.  I.e., this value is scaled by the minimum
15462                instruction length since special opcode 255 would have
15463                scaled the increment.  */
15464             case DW_LNS_const_add_pc:
15465               {
15466                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15467
15468                 address += (((op_index + adjust)
15469                              / lh->maximum_ops_per_instruction)
15470                             * lh->minimum_instruction_length);
15471                 op_index = ((op_index + adjust)
15472                             % lh->maximum_ops_per_instruction);
15473               }
15474               break;
15475             case DW_LNS_fixed_advance_pc:
15476               address += read_2_bytes (abfd, line_ptr);
15477               op_index = 0;
15478               line_ptr += 2;
15479               break;
15480             default:
15481               {
15482                 /* Unknown standard opcode, ignore it.  */
15483                 int i;
15484
15485                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15486                   {
15487                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15488                     line_ptr += bytes_read;
15489                   }
15490               }
15491             }
15492         }
15493       if (lh->num_file_names < file || file == 0)
15494         dwarf2_debug_line_missing_file_complaint ();
15495       else
15496         {
15497           lh->file_names[file - 1].included_p = 1;
15498           if (!decode_for_pst_p)
15499             {
15500               addr = gdbarch_addr_bits_remove (gdbarch, address);
15501               (*p_record_line) (current_subfile, 0, addr);
15502             }
15503         }
15504     }
15505 }
15506
15507 /* Decode the Line Number Program (LNP) for the given line_header
15508    structure and CU.  The actual information extracted and the type
15509    of structures created from the LNP depends on the value of PST.
15510
15511    1. If PST is NULL, then this procedure uses the data from the program
15512       to create all necessary symbol tables, and their linetables.
15513
15514    2. If PST is not NULL, this procedure reads the program to determine
15515       the list of files included by the unit represented by PST, and
15516       builds all the associated partial symbol tables.
15517
15518    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15519    It is used for relative paths in the line table.
15520    NOTE: When processing partial symtabs (pst != NULL),
15521    comp_dir == pst->dirname.
15522
15523    NOTE: It is important that psymtabs have the same file name (via strcmp)
15524    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15525    symtab we don't use it in the name of the psymtabs we create.
15526    E.g. expand_line_sal requires this when finding psymtabs to expand.
15527    A good testcase for this is mb-inline.exp.  */
15528
15529 static void
15530 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15531                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15532                     int want_line_info)
15533 {
15534   struct objfile *objfile = cu->objfile;
15535   const int decode_for_pst_p = (pst != NULL);
15536   struct subfile *first_subfile = current_subfile;
15537
15538   if (want_line_info)
15539     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15540
15541   if (decode_for_pst_p)
15542     {
15543       int file_index;
15544
15545       /* Now that we're done scanning the Line Header Program, we can
15546          create the psymtab of each included file.  */
15547       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15548         if (lh->file_names[file_index].included_p == 1)
15549           {
15550             char *include_name =
15551               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15552             if (include_name != NULL)
15553               dwarf2_create_include_psymtab (include_name, pst, objfile);
15554           }
15555     }
15556   else
15557     {
15558       /* Make sure a symtab is created for every file, even files
15559          which contain only variables (i.e. no code with associated
15560          line numbers).  */
15561       int i;
15562
15563       for (i = 0; i < lh->num_file_names; i++)
15564         {
15565           char *dir = NULL;
15566           struct file_entry *fe;
15567
15568           fe = &lh->file_names[i];
15569           if (fe->dir_index)
15570             dir = lh->include_dirs[fe->dir_index - 1];
15571           dwarf2_start_subfile (fe->name, dir, comp_dir);
15572
15573           /* Skip the main file; we don't need it, and it must be
15574              allocated last, so that it will show up before the
15575              non-primary symtabs in the objfile's symtab list.  */
15576           if (current_subfile == first_subfile)
15577             continue;
15578
15579           if (current_subfile->symtab == NULL)
15580             current_subfile->symtab = allocate_symtab (current_subfile->name,
15581                                                        objfile);
15582           fe->symtab = current_subfile->symtab;
15583         }
15584     }
15585 }
15586
15587 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15588    DIRNAME the name of the source directory which contains FILENAME
15589    or NULL if not known.  COMP_DIR is the compilation directory for the
15590    linetable's compilation unit or NULL if not known.
15591    This routine tries to keep line numbers from identical absolute and
15592    relative file names in a common subfile.
15593
15594    Using the `list' example from the GDB testsuite, which resides in
15595    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15596    of /srcdir/list0.c yields the following debugging information for list0.c:
15597
15598    DW_AT_name:          /srcdir/list0.c
15599    DW_AT_comp_dir:              /compdir
15600    files.files[0].name: list0.h
15601    files.files[0].dir:  /srcdir
15602    files.files[1].name: list0.c
15603    files.files[1].dir:  /srcdir
15604
15605    The line number information for list0.c has to end up in a single
15606    subfile, so that `break /srcdir/list0.c:1' works as expected.
15607    start_subfile will ensure that this happens provided that we pass the
15608    concatenation of files.files[1].dir and files.files[1].name as the
15609    subfile's name.  */
15610
15611 static void
15612 dwarf2_start_subfile (char *filename, const char *dirname,
15613                       const char *comp_dir)
15614 {
15615   char *fullname;
15616
15617   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15618      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15619      second argument to start_subfile.  To be consistent, we do the
15620      same here.  In order not to lose the line information directory,
15621      we concatenate it to the filename when it makes sense.
15622      Note that the Dwarf3 standard says (speaking of filenames in line
15623      information): ``The directory index is ignored for file names
15624      that represent full path names''.  Thus ignoring dirname in the
15625      `else' branch below isn't an issue.  */
15626
15627   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15628     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15629   else
15630     fullname = filename;
15631
15632   start_subfile (fullname, comp_dir);
15633
15634   if (fullname != filename)
15635     xfree (fullname);
15636 }
15637
15638 /* Start a symtab for DWARF.
15639    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15640
15641 static void
15642 dwarf2_start_symtab (struct dwarf2_cu *cu,
15643                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15644 {
15645   start_symtab (name, comp_dir, low_pc);
15646   record_debugformat ("DWARF 2");
15647   record_producer (cu->producer);
15648
15649   /* We assume that we're processing GCC output.  */
15650   processing_gcc_compilation = 2;
15651
15652   cu->processing_has_namespace_info = 0;
15653 }
15654
15655 static void
15656 var_decode_location (struct attribute *attr, struct symbol *sym,
15657                      struct dwarf2_cu *cu)
15658 {
15659   struct objfile *objfile = cu->objfile;
15660   struct comp_unit_head *cu_header = &cu->header;
15661
15662   /* NOTE drow/2003-01-30: There used to be a comment and some special
15663      code here to turn a symbol with DW_AT_external and a
15664      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15665      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15666      with some versions of binutils) where shared libraries could have
15667      relocations against symbols in their debug information - the
15668      minimal symbol would have the right address, but the debug info
15669      would not.  It's no longer necessary, because we will explicitly
15670      apply relocations when we read in the debug information now.  */
15671
15672   /* A DW_AT_location attribute with no contents indicates that a
15673      variable has been optimized away.  */
15674   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15675     {
15676       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15677       return;
15678     }
15679
15680   /* Handle one degenerate form of location expression specially, to
15681      preserve GDB's previous behavior when section offsets are
15682      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15683      then mark this symbol as LOC_STATIC.  */
15684
15685   if (attr_form_is_block (attr)
15686       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15687            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15688           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15689               && (DW_BLOCK (attr)->size
15690                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15691     {
15692       unsigned int dummy;
15693
15694       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15695         SYMBOL_VALUE_ADDRESS (sym) =
15696           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15697       else
15698         SYMBOL_VALUE_ADDRESS (sym) =
15699           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15700       SYMBOL_CLASS (sym) = LOC_STATIC;
15701       fixup_symbol_section (sym, objfile);
15702       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15703                                               SYMBOL_SECTION (sym));
15704       return;
15705     }
15706
15707   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15708      expression evaluator, and use LOC_COMPUTED only when necessary
15709      (i.e. when the value of a register or memory location is
15710      referenced, or a thread-local block, etc.).  Then again, it might
15711      not be worthwhile.  I'm assuming that it isn't unless performance
15712      or memory numbers show me otherwise.  */
15713
15714   dwarf2_symbol_mark_computed (attr, sym, cu);
15715   SYMBOL_CLASS (sym) = LOC_COMPUTED;
15716
15717   if (SYMBOL_COMPUTED_OPS (sym) == &dwarf2_loclist_funcs)
15718     cu->has_loclist = 1;
15719 }
15720
15721 /* Given a pointer to a DWARF information entry, figure out if we need
15722    to make a symbol table entry for it, and if so, create a new entry
15723    and return a pointer to it.
15724    If TYPE is NULL, determine symbol type from the die, otherwise
15725    used the passed type.
15726    If SPACE is not NULL, use it to hold the new symbol.  If it is
15727    NULL, allocate a new symbol on the objfile's obstack.  */
15728
15729 static struct symbol *
15730 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15731                  struct symbol *space)
15732 {
15733   struct objfile *objfile = cu->objfile;
15734   struct symbol *sym = NULL;
15735   const char *name;
15736   struct attribute *attr = NULL;
15737   struct attribute *attr2 = NULL;
15738   CORE_ADDR baseaddr;
15739   struct pending **list_to_add = NULL;
15740
15741   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15742
15743   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15744
15745   name = dwarf2_name (die, cu);
15746   if (name)
15747     {
15748       const char *linkagename;
15749       int suppress_add = 0;
15750
15751       if (space)
15752         sym = space;
15753       else
15754         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
15755       OBJSTAT (objfile, n_syms++);
15756
15757       /* Cache this symbol's name and the name's demangled form (if any).  */
15758       SYMBOL_SET_LANGUAGE (sym, cu->language);
15759       linkagename = dwarf2_physname (name, die, cu);
15760       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15761
15762       /* Fortran does not have mangling standard and the mangling does differ
15763          between gfortran, iFort etc.  */
15764       if (cu->language == language_fortran
15765           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15766         symbol_set_demangled_name (&(sym->ginfo),
15767                                    dwarf2_full_name (name, die, cu),
15768                                    NULL);
15769
15770       /* Default assumptions.
15771          Use the passed type or decode it from the die.  */
15772       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15773       SYMBOL_CLASS (sym) = LOC_OPTIMIZED_OUT;
15774       if (type != NULL)
15775         SYMBOL_TYPE (sym) = type;
15776       else
15777         SYMBOL_TYPE (sym) = die_type (die, cu);
15778       attr = dwarf2_attr (die,
15779                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15780                           cu);
15781       if (attr)
15782         {
15783           SYMBOL_LINE (sym) = DW_UNSND (attr);
15784         }
15785
15786       attr = dwarf2_attr (die,
15787                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
15788                           cu);
15789       if (attr)
15790         {
15791           int file_index = DW_UNSND (attr);
15792
15793           if (cu->line_header == NULL
15794               || file_index > cu->line_header->num_file_names)
15795             complaint (&symfile_complaints,
15796                        _("file index out of range"));
15797           else if (file_index > 0)
15798             {
15799               struct file_entry *fe;
15800
15801               fe = &cu->line_header->file_names[file_index - 1];
15802               SYMBOL_SYMTAB (sym) = fe->symtab;
15803             }
15804         }
15805
15806       switch (die->tag)
15807         {
15808         case DW_TAG_label:
15809           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15810           if (attr)
15811             {
15812               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
15813             }
15814           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
15815           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
15816           SYMBOL_CLASS (sym) = LOC_LABEL;
15817           add_symbol_to_list (sym, cu->list_in_scope);
15818           break;
15819         case DW_TAG_subprogram:
15820           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15821              finish_block.  */
15822           SYMBOL_CLASS (sym) = LOC_BLOCK;
15823           attr2 = dwarf2_attr (die, DW_AT_external, cu);
15824           if ((attr2 && (DW_UNSND (attr2) != 0))
15825               || cu->language == language_ada)
15826             {
15827               /* Subprograms marked external are stored as a global symbol.
15828                  Ada subprograms, whether marked external or not, are always
15829                  stored as a global symbol, because we want to be able to
15830                  access them globally.  For instance, we want to be able
15831                  to break on a nested subprogram without having to
15832                  specify the context.  */
15833               list_to_add = &global_symbols;
15834             }
15835           else
15836             {
15837               list_to_add = cu->list_in_scope;
15838             }
15839           break;
15840         case DW_TAG_inlined_subroutine:
15841           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15842              finish_block.  */
15843           SYMBOL_CLASS (sym) = LOC_BLOCK;
15844           SYMBOL_INLINED (sym) = 1;
15845           list_to_add = cu->list_in_scope;
15846           break;
15847         case DW_TAG_template_value_param:
15848           suppress_add = 1;
15849           /* Fall through.  */
15850         case DW_TAG_constant:
15851         case DW_TAG_variable:
15852         case DW_TAG_member:
15853           /* Compilation with minimal debug info may result in
15854              variables with missing type entries.  Change the
15855              misleading `void' type to something sensible.  */
15856           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
15857             SYMBOL_TYPE (sym)
15858               = objfile_type (objfile)->nodebug_data_symbol;
15859
15860           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15861           /* In the case of DW_TAG_member, we should only be called for
15862              static const members.  */
15863           if (die->tag == DW_TAG_member)
15864             {
15865               /* dwarf2_add_field uses die_is_declaration,
15866                  so we do the same.  */
15867               gdb_assert (die_is_declaration (die, cu));
15868               gdb_assert (attr);
15869             }
15870           if (attr)
15871             {
15872               dwarf2_const_value (attr, sym, cu);
15873               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15874               if (!suppress_add)
15875                 {
15876                   if (attr2 && (DW_UNSND (attr2) != 0))
15877                     list_to_add = &global_symbols;
15878                   else
15879                     list_to_add = cu->list_in_scope;
15880                 }
15881               break;
15882             }
15883           attr = dwarf2_attr (die, DW_AT_location, cu);
15884           if (attr)
15885             {
15886               var_decode_location (attr, sym, cu);
15887               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15888
15889               /* Fortran explicitly imports any global symbols to the local
15890                  scope by DW_TAG_common_block.  */
15891               if (cu->language == language_fortran && die->parent
15892                   && die->parent->tag == DW_TAG_common_block)
15893                 attr2 = NULL;
15894
15895               if (SYMBOL_CLASS (sym) == LOC_STATIC
15896                   && SYMBOL_VALUE_ADDRESS (sym) == 0
15897                   && !dwarf2_per_objfile->has_section_at_zero)
15898                 {
15899                   /* When a static variable is eliminated by the linker,
15900                      the corresponding debug information is not stripped
15901                      out, but the variable address is set to null;
15902                      do not add such variables into symbol table.  */
15903                 }
15904               else if (attr2 && (DW_UNSND (attr2) != 0))
15905                 {
15906                   /* Workaround gfortran PR debug/40040 - it uses
15907                      DW_AT_location for variables in -fPIC libraries which may
15908                      get overriden by other libraries/executable and get
15909                      a different address.  Resolve it by the minimal symbol
15910                      which may come from inferior's executable using copy
15911                      relocation.  Make this workaround only for gfortran as for
15912                      other compilers GDB cannot guess the minimal symbol
15913                      Fortran mangling kind.  */
15914                   if (cu->language == language_fortran && die->parent
15915                       && die->parent->tag == DW_TAG_module
15916                       && cu->producer
15917                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
15918                     SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15919
15920                   /* A variable with DW_AT_external is never static,
15921                      but it may be block-scoped.  */
15922                   list_to_add = (cu->list_in_scope == &file_symbols
15923                                  ? &global_symbols : cu->list_in_scope);
15924                 }
15925               else
15926                 list_to_add = cu->list_in_scope;
15927             }
15928           else
15929             {
15930               /* We do not know the address of this symbol.
15931                  If it is an external symbol and we have type information
15932                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
15933                  The address of the variable will then be determined from
15934                  the minimal symbol table whenever the variable is
15935                  referenced.  */
15936               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15937
15938               /* Fortran explicitly imports any global symbols to the local
15939                  scope by DW_TAG_common_block.  */
15940               if (cu->language == language_fortran && die->parent
15941                   && die->parent->tag == DW_TAG_common_block)
15942                 {
15943                   /* SYMBOL_CLASS doesn't matter here because
15944                      read_common_block is going to reset it.  */
15945                   if (!suppress_add)
15946                     list_to_add = cu->list_in_scope;
15947                 }
15948               else if (attr2 && (DW_UNSND (attr2) != 0)
15949                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
15950                 {
15951                   /* A variable with DW_AT_external is never static, but it
15952                      may be block-scoped.  */
15953                   list_to_add = (cu->list_in_scope == &file_symbols
15954                                  ? &global_symbols : cu->list_in_scope);
15955
15956                   SYMBOL_CLASS (sym) = LOC_UNRESOLVED;
15957                 }
15958               else if (!die_is_declaration (die, cu))
15959                 {
15960                   /* Use the default LOC_OPTIMIZED_OUT class.  */
15961                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
15962                   if (!suppress_add)
15963                     list_to_add = cu->list_in_scope;
15964                 }
15965             }
15966           break;
15967         case DW_TAG_formal_parameter:
15968           /* If we are inside a function, mark this as an argument.  If
15969              not, we might be looking at an argument to an inlined function
15970              when we do not have enough information to show inlined frames;
15971              pretend it's a local variable in that case so that the user can
15972              still see it.  */
15973           if (context_stack_depth > 0
15974               && context_stack[context_stack_depth - 1].name != NULL)
15975             SYMBOL_IS_ARGUMENT (sym) = 1;
15976           attr = dwarf2_attr (die, DW_AT_location, cu);
15977           if (attr)
15978             {
15979               var_decode_location (attr, sym, cu);
15980             }
15981           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15982           if (attr)
15983             {
15984               dwarf2_const_value (attr, sym, cu);
15985             }
15986
15987           list_to_add = cu->list_in_scope;
15988           break;
15989         case DW_TAG_unspecified_parameters:
15990           /* From varargs functions; gdb doesn't seem to have any
15991              interest in this information, so just ignore it for now.
15992              (FIXME?) */
15993           break;
15994         case DW_TAG_template_type_param:
15995           suppress_add = 1;
15996           /* Fall through.  */
15997         case DW_TAG_class_type:
15998         case DW_TAG_interface_type:
15999         case DW_TAG_structure_type:
16000         case DW_TAG_union_type:
16001         case DW_TAG_set_type:
16002         case DW_TAG_enumeration_type:
16003           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16004           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16005
16006           {
16007             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16008                really ever be static objects: otherwise, if you try
16009                to, say, break of a class's method and you're in a file
16010                which doesn't mention that class, it won't work unless
16011                the check for all static symbols in lookup_symbol_aux
16012                saves you.  See the OtherFileClass tests in
16013                gdb.c++/namespace.exp.  */
16014
16015             if (!suppress_add)
16016               {
16017                 list_to_add = (cu->list_in_scope == &file_symbols
16018                                && (cu->language == language_cplus
16019                                    || cu->language == language_java)
16020                                ? &global_symbols : cu->list_in_scope);
16021
16022                 /* The semantics of C++ state that "struct foo {
16023                    ... }" also defines a typedef for "foo".  A Java
16024                    class declaration also defines a typedef for the
16025                    class.  */
16026                 if (cu->language == language_cplus
16027                     || cu->language == language_java
16028                     || cu->language == language_ada)
16029                   {
16030                     /* The symbol's name is already allocated along
16031                        with this objfile, so we don't need to
16032                        duplicate it for the type.  */
16033                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16034                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16035                   }
16036               }
16037           }
16038           break;
16039         case DW_TAG_typedef:
16040           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16041           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16042           list_to_add = cu->list_in_scope;
16043           break;
16044         case DW_TAG_base_type:
16045         case DW_TAG_subrange_type:
16046           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16047           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16048           list_to_add = cu->list_in_scope;
16049           break;
16050         case DW_TAG_enumerator:
16051           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16052           if (attr)
16053             {
16054               dwarf2_const_value (attr, sym, cu);
16055             }
16056           {
16057             /* NOTE: carlton/2003-11-10: See comment above in the
16058                DW_TAG_class_type, etc. block.  */
16059
16060             list_to_add = (cu->list_in_scope == &file_symbols
16061                            && (cu->language == language_cplus
16062                                || cu->language == language_java)
16063                            ? &global_symbols : cu->list_in_scope);
16064           }
16065           break;
16066         case DW_TAG_namespace:
16067           SYMBOL_CLASS (sym) = LOC_TYPEDEF;
16068           list_to_add = &global_symbols;
16069           break;
16070         case DW_TAG_common_block:
16071           SYMBOL_CLASS (sym) = LOC_COMMON_BLOCK;
16072           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16073           add_symbol_to_list (sym, cu->list_in_scope);
16074           break;
16075         default:
16076           /* Not a tag we recognize.  Hopefully we aren't processing
16077              trash data, but since we must specifically ignore things
16078              we don't recognize, there is nothing else we should do at
16079              this point.  */
16080           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16081                      dwarf_tag_name (die->tag));
16082           break;
16083         }
16084
16085       if (suppress_add)
16086         {
16087           sym->hash_next = objfile->template_symbols;
16088           objfile->template_symbols = sym;
16089           list_to_add = NULL;
16090         }
16091
16092       if (list_to_add != NULL)
16093         add_symbol_to_list (sym, list_to_add);
16094
16095       /* For the benefit of old versions of GCC, check for anonymous
16096          namespaces based on the demangled name.  */
16097       if (!cu->processing_has_namespace_info
16098           && cu->language == language_cplus)
16099         cp_scan_for_anonymous_namespaces (sym, objfile);
16100     }
16101   return (sym);
16102 }
16103
16104 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16105
16106 static struct symbol *
16107 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16108 {
16109   return new_symbol_full (die, type, cu, NULL);
16110 }
16111
16112 /* Given an attr with a DW_FORM_dataN value in host byte order,
16113    zero-extend it as appropriate for the symbol's type.  The DWARF
16114    standard (v4) is not entirely clear about the meaning of using
16115    DW_FORM_dataN for a constant with a signed type, where the type is
16116    wider than the data.  The conclusion of a discussion on the DWARF
16117    list was that this is unspecified.  We choose to always zero-extend
16118    because that is the interpretation long in use by GCC.  */
16119
16120 static gdb_byte *
16121 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16122                          const char *name, struct obstack *obstack,
16123                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16124 {
16125   struct objfile *objfile = cu->objfile;
16126   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16127                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16128   LONGEST l = DW_UNSND (attr);
16129
16130   if (bits < sizeof (*value) * 8)
16131     {
16132       l &= ((LONGEST) 1 << bits) - 1;
16133       *value = l;
16134     }
16135   else if (bits == sizeof (*value) * 8)
16136     *value = l;
16137   else
16138     {
16139       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16140       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16141       return bytes;
16142     }
16143
16144   return NULL;
16145 }
16146
16147 /* Read a constant value from an attribute.  Either set *VALUE, or if
16148    the value does not fit in *VALUE, set *BYTES - either already
16149    allocated on the objfile obstack, or newly allocated on OBSTACK,
16150    or, set *BATON, if we translated the constant to a location
16151    expression.  */
16152
16153 static void
16154 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16155                          const char *name, struct obstack *obstack,
16156                          struct dwarf2_cu *cu,
16157                          LONGEST *value, gdb_byte **bytes,
16158                          struct dwarf2_locexpr_baton **baton)
16159 {
16160   struct objfile *objfile = cu->objfile;
16161   struct comp_unit_head *cu_header = &cu->header;
16162   struct dwarf_block *blk;
16163   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16164                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16165
16166   *value = 0;
16167   *bytes = NULL;
16168   *baton = NULL;
16169
16170   switch (attr->form)
16171     {
16172     case DW_FORM_addr:
16173     case DW_FORM_GNU_addr_index:
16174       {
16175         gdb_byte *data;
16176
16177         if (TYPE_LENGTH (type) != cu_header->addr_size)
16178           dwarf2_const_value_length_mismatch_complaint (name,
16179                                                         cu_header->addr_size,
16180                                                         TYPE_LENGTH (type));
16181         /* Symbols of this form are reasonably rare, so we just
16182            piggyback on the existing location code rather than writing
16183            a new implementation of symbol_computed_ops.  */
16184         *baton = obstack_alloc (&objfile->objfile_obstack,
16185                                 sizeof (struct dwarf2_locexpr_baton));
16186         (*baton)->per_cu = cu->per_cu;
16187         gdb_assert ((*baton)->per_cu);
16188
16189         (*baton)->size = 2 + cu_header->addr_size;
16190         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16191         (*baton)->data = data;
16192
16193         data[0] = DW_OP_addr;
16194         store_unsigned_integer (&data[1], cu_header->addr_size,
16195                                 byte_order, DW_ADDR (attr));
16196         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16197       }
16198       break;
16199     case DW_FORM_string:
16200     case DW_FORM_strp:
16201     case DW_FORM_GNU_str_index:
16202     case DW_FORM_GNU_strp_alt:
16203       /* DW_STRING is already allocated on the objfile obstack, point
16204          directly to it.  */
16205       *bytes = (gdb_byte *) DW_STRING (attr);
16206       break;
16207     case DW_FORM_block1:
16208     case DW_FORM_block2:
16209     case DW_FORM_block4:
16210     case DW_FORM_block:
16211     case DW_FORM_exprloc:
16212       blk = DW_BLOCK (attr);
16213       if (TYPE_LENGTH (type) != blk->size)
16214         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16215                                                       TYPE_LENGTH (type));
16216       *bytes = blk->data;
16217       break;
16218
16219       /* The DW_AT_const_value attributes are supposed to carry the
16220          symbol's value "represented as it would be on the target
16221          architecture."  By the time we get here, it's already been
16222          converted to host endianness, so we just need to sign- or
16223          zero-extend it as appropriate.  */
16224     case DW_FORM_data1:
16225       *bytes = dwarf2_const_value_data (attr, type, name,
16226                                         obstack, cu, value, 8);
16227       break;
16228     case DW_FORM_data2:
16229       *bytes = dwarf2_const_value_data (attr, type, name,
16230                                         obstack, cu, value, 16);
16231       break;
16232     case DW_FORM_data4:
16233       *bytes = dwarf2_const_value_data (attr, type, name,
16234                                         obstack, cu, value, 32);
16235       break;
16236     case DW_FORM_data8:
16237       *bytes = dwarf2_const_value_data (attr, type, name,
16238                                         obstack, cu, value, 64);
16239       break;
16240
16241     case DW_FORM_sdata:
16242       *value = DW_SND (attr);
16243       break;
16244
16245     case DW_FORM_udata:
16246       *value = DW_UNSND (attr);
16247       break;
16248
16249     default:
16250       complaint (&symfile_complaints,
16251                  _("unsupported const value attribute form: '%s'"),
16252                  dwarf_form_name (attr->form));
16253       *value = 0;
16254       break;
16255     }
16256 }
16257
16258
16259 /* Copy constant value from an attribute to a symbol.  */
16260
16261 static void
16262 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16263                     struct dwarf2_cu *cu)
16264 {
16265   struct objfile *objfile = cu->objfile;
16266   struct comp_unit_head *cu_header = &cu->header;
16267   LONGEST value;
16268   gdb_byte *bytes;
16269   struct dwarf2_locexpr_baton *baton;
16270
16271   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16272                            SYMBOL_PRINT_NAME (sym),
16273                            &objfile->objfile_obstack, cu,
16274                            &value, &bytes, &baton);
16275
16276   if (baton != NULL)
16277     {
16278       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
16279       SYMBOL_LOCATION_BATON (sym) = baton;
16280       SYMBOL_CLASS (sym) = LOC_COMPUTED;
16281     }
16282   else if (bytes != NULL)
16283      {
16284       SYMBOL_VALUE_BYTES (sym) = bytes;
16285       SYMBOL_CLASS (sym) = LOC_CONST_BYTES;
16286     }
16287   else
16288     {
16289       SYMBOL_VALUE (sym) = value;
16290       SYMBOL_CLASS (sym) = LOC_CONST;
16291     }
16292 }
16293
16294 /* Return the type of the die in question using its DW_AT_type attribute.  */
16295
16296 static struct type *
16297 die_type (struct die_info *die, struct dwarf2_cu *cu)
16298 {
16299   struct attribute *type_attr;
16300
16301   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16302   if (!type_attr)
16303     {
16304       /* A missing DW_AT_type represents a void type.  */
16305       return objfile_type (cu->objfile)->builtin_void;
16306     }
16307
16308   return lookup_die_type (die, type_attr, cu);
16309 }
16310
16311 /* True iff CU's producer generates GNAT Ada auxiliary information
16312    that allows to find parallel types through that information instead
16313    of having to do expensive parallel lookups by type name.  */
16314
16315 static int
16316 need_gnat_info (struct dwarf2_cu *cu)
16317 {
16318   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16319      of GNAT produces this auxiliary information, without any indication
16320      that it is produced.  Part of enhancing the FSF version of GNAT
16321      to produce that information will be to put in place an indicator
16322      that we can use in order to determine whether the descriptive type
16323      info is available or not.  One suggestion that has been made is
16324      to use a new attribute, attached to the CU die.  For now, assume
16325      that the descriptive type info is not available.  */
16326   return 0;
16327 }
16328
16329 /* Return the auxiliary type of the die in question using its
16330    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16331    attribute is not present.  */
16332
16333 static struct type *
16334 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16335 {
16336   struct attribute *type_attr;
16337
16338   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16339   if (!type_attr)
16340     return NULL;
16341
16342   return lookup_die_type (die, type_attr, cu);
16343 }
16344
16345 /* If DIE has a descriptive_type attribute, then set the TYPE's
16346    descriptive type accordingly.  */
16347
16348 static void
16349 set_descriptive_type (struct type *type, struct die_info *die,
16350                       struct dwarf2_cu *cu)
16351 {
16352   struct type *descriptive_type = die_descriptive_type (die, cu);
16353
16354   if (descriptive_type)
16355     {
16356       ALLOCATE_GNAT_AUX_TYPE (type);
16357       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16358     }
16359 }
16360
16361 /* Return the containing type of the die in question using its
16362    DW_AT_containing_type attribute.  */
16363
16364 static struct type *
16365 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16366 {
16367   struct attribute *type_attr;
16368
16369   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16370   if (!type_attr)
16371     error (_("Dwarf Error: Problem turning containing type into gdb type "
16372              "[in module %s]"), cu->objfile->name);
16373
16374   return lookup_die_type (die, type_attr, cu);
16375 }
16376
16377 /* Look up the type of DIE in CU using its type attribute ATTR.
16378    If there is no type substitute an error marker.  */
16379
16380 static struct type *
16381 lookup_die_type (struct die_info *die, struct attribute *attr,
16382                  struct dwarf2_cu *cu)
16383 {
16384   struct objfile *objfile = cu->objfile;
16385   struct type *this_type;
16386
16387   /* First see if we have it cached.  */
16388
16389   if (attr->form == DW_FORM_GNU_ref_alt)
16390     {
16391       struct dwarf2_per_cu_data *per_cu;
16392       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16393
16394       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16395       this_type = get_die_type_at_offset (offset, per_cu);
16396     }
16397   else if (is_ref_attr (attr))
16398     {
16399       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16400
16401       this_type = get_die_type_at_offset (offset, cu->per_cu);
16402     }
16403   else if (attr->form == DW_FORM_ref_sig8)
16404     {
16405       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16406
16407       /* sig_type will be NULL if the signatured type is missing from
16408          the debug info.  */
16409       if (sig_type == NULL)
16410         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16411                  "at 0x%x [in module %s]"),
16412                die->offset.sect_off, objfile->name);
16413
16414       gdb_assert (sig_type->per_cu.is_debug_types);
16415       /* If we haven't filled in type_offset_in_section yet, then we
16416          haven't read the type in yet.  */
16417       this_type = NULL;
16418       if (sig_type->type_offset_in_section.sect_off != 0)
16419         {
16420           this_type =
16421             get_die_type_at_offset (sig_type->type_offset_in_section,
16422                                     &sig_type->per_cu);
16423         }
16424     }
16425   else
16426     {
16427       dump_die_for_error (die);
16428       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16429              dwarf_attr_name (attr->name), objfile->name);
16430     }
16431
16432   /* If not cached we need to read it in.  */
16433
16434   if (this_type == NULL)
16435     {
16436       struct die_info *type_die;
16437       struct dwarf2_cu *type_cu = cu;
16438
16439       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16440       /* If we found the type now, it's probably because the type came
16441          from an inter-CU reference and the type's CU got expanded before
16442          ours.  */
16443       this_type = get_die_type (type_die, type_cu);
16444       if (this_type == NULL)
16445         this_type = read_type_die_1 (type_die, type_cu);
16446     }
16447
16448   /* If we still don't have a type use an error marker.  */
16449
16450   if (this_type == NULL)
16451     {
16452       char *message, *saved;
16453
16454       /* read_type_die already issued a complaint.  */
16455       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16456                             objfile->name,
16457                             cu->header.offset.sect_off,
16458                             die->offset.sect_off);
16459       saved = obstack_copy0 (&objfile->objfile_obstack,
16460                              message, strlen (message));
16461       xfree (message);
16462
16463       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16464     }
16465
16466   return this_type;
16467 }
16468
16469 /* Return the type in DIE, CU.
16470    Returns NULL for invalid types.
16471
16472    This first does a lookup in the appropriate type_hash table,
16473    and only reads the die in if necessary.
16474
16475    NOTE: This can be called when reading in partial or full symbols.  */
16476
16477 static struct type *
16478 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16479 {
16480   struct type *this_type;
16481
16482   this_type = get_die_type (die, cu);
16483   if (this_type)
16484     return this_type;
16485
16486   return read_type_die_1 (die, cu);
16487 }
16488
16489 /* Read the type in DIE, CU.
16490    Returns NULL for invalid types.  */
16491
16492 static struct type *
16493 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16494 {
16495   struct type *this_type = NULL;
16496
16497   switch (die->tag)
16498     {
16499     case DW_TAG_class_type:
16500     case DW_TAG_interface_type:
16501     case DW_TAG_structure_type:
16502     case DW_TAG_union_type:
16503       this_type = read_structure_type (die, cu);
16504       break;
16505     case DW_TAG_enumeration_type:
16506       this_type = read_enumeration_type (die, cu);
16507       break;
16508     case DW_TAG_subprogram:
16509     case DW_TAG_subroutine_type:
16510     case DW_TAG_inlined_subroutine:
16511       this_type = read_subroutine_type (die, cu);
16512       break;
16513     case DW_TAG_array_type:
16514       this_type = read_array_type (die, cu);
16515       break;
16516     case DW_TAG_set_type:
16517       this_type = read_set_type (die, cu);
16518       break;
16519     case DW_TAG_pointer_type:
16520       this_type = read_tag_pointer_type (die, cu);
16521       break;
16522     case DW_TAG_ptr_to_member_type:
16523       this_type = read_tag_ptr_to_member_type (die, cu);
16524       break;
16525     case DW_TAG_reference_type:
16526       this_type = read_tag_reference_type (die, cu);
16527       break;
16528     case DW_TAG_const_type:
16529       this_type = read_tag_const_type (die, cu);
16530       break;
16531     case DW_TAG_volatile_type:
16532       this_type = read_tag_volatile_type (die, cu);
16533       break;
16534     case DW_TAG_restrict_type:
16535       this_type = read_tag_restrict_type (die, cu);
16536       break;
16537     case DW_TAG_string_type:
16538       this_type = read_tag_string_type (die, cu);
16539       break;
16540     case DW_TAG_typedef:
16541       this_type = read_typedef (die, cu);
16542       break;
16543     case DW_TAG_subrange_type:
16544       this_type = read_subrange_type (die, cu);
16545       break;
16546     case DW_TAG_base_type:
16547       this_type = read_base_type (die, cu);
16548       break;
16549     case DW_TAG_unspecified_type:
16550       this_type = read_unspecified_type (die, cu);
16551       break;
16552     case DW_TAG_namespace:
16553       this_type = read_namespace_type (die, cu);
16554       break;
16555     case DW_TAG_module:
16556       this_type = read_module_type (die, cu);
16557       break;
16558     default:
16559       complaint (&symfile_complaints,
16560                  _("unexpected tag in read_type_die: '%s'"),
16561                  dwarf_tag_name (die->tag));
16562       break;
16563     }
16564
16565   return this_type;
16566 }
16567
16568 /* See if we can figure out if the class lives in a namespace.  We do
16569    this by looking for a member function; its demangled name will
16570    contain namespace info, if there is any.
16571    Return the computed name or NULL.
16572    Space for the result is allocated on the objfile's obstack.
16573    This is the full-die version of guess_partial_die_structure_name.
16574    In this case we know DIE has no useful parent.  */
16575
16576 static char *
16577 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16578 {
16579   struct die_info *spec_die;
16580   struct dwarf2_cu *spec_cu;
16581   struct die_info *child;
16582
16583   spec_cu = cu;
16584   spec_die = die_specification (die, &spec_cu);
16585   if (spec_die != NULL)
16586     {
16587       die = spec_die;
16588       cu = spec_cu;
16589     }
16590
16591   for (child = die->child;
16592        child != NULL;
16593        child = child->sibling)
16594     {
16595       if (child->tag == DW_TAG_subprogram)
16596         {
16597           struct attribute *attr;
16598
16599           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16600           if (attr == NULL)
16601             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16602           if (attr != NULL)
16603             {
16604               char *actual_name
16605                 = language_class_name_from_physname (cu->language_defn,
16606                                                      DW_STRING (attr));
16607               char *name = NULL;
16608
16609               if (actual_name != NULL)
16610                 {
16611                   const char *die_name = dwarf2_name (die, cu);
16612
16613                   if (die_name != NULL
16614                       && strcmp (die_name, actual_name) != 0)
16615                     {
16616                       /* Strip off the class name from the full name.
16617                          We want the prefix.  */
16618                       int die_name_len = strlen (die_name);
16619                       int actual_name_len = strlen (actual_name);
16620
16621                       /* Test for '::' as a sanity check.  */
16622                       if (actual_name_len > die_name_len + 2
16623                           && actual_name[actual_name_len
16624                                          - die_name_len - 1] == ':')
16625                         name =
16626                           obstack_copy0 (&cu->objfile->objfile_obstack,
16627                                          actual_name,
16628                                          actual_name_len - die_name_len - 2);
16629                     }
16630                 }
16631               xfree (actual_name);
16632               return name;
16633             }
16634         }
16635     }
16636
16637   return NULL;
16638 }
16639
16640 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16641    prefix part in such case.  See
16642    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16643
16644 static char *
16645 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16646 {
16647   struct attribute *attr;
16648   char *base;
16649
16650   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16651       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16652     return NULL;
16653
16654   attr = dwarf2_attr (die, DW_AT_name, cu);
16655   if (attr != NULL && DW_STRING (attr) != NULL)
16656     return NULL;
16657
16658   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16659   if (attr == NULL)
16660     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16661   if (attr == NULL || DW_STRING (attr) == NULL)
16662     return NULL;
16663
16664   /* dwarf2_name had to be already called.  */
16665   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16666
16667   /* Strip the base name, keep any leading namespaces/classes.  */
16668   base = strrchr (DW_STRING (attr), ':');
16669   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16670     return "";
16671
16672   return obstack_copy0 (&cu->objfile->objfile_obstack,
16673                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16674 }
16675
16676 /* Return the name of the namespace/class that DIE is defined within,
16677    or "" if we can't tell.  The caller should not xfree the result.
16678
16679    For example, if we're within the method foo() in the following
16680    code:
16681
16682    namespace N {
16683      class C {
16684        void foo () {
16685        }
16686      };
16687    }
16688
16689    then determine_prefix on foo's die will return "N::C".  */
16690
16691 static const char *
16692 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16693 {
16694   struct die_info *parent, *spec_die;
16695   struct dwarf2_cu *spec_cu;
16696   struct type *parent_type;
16697   char *retval;
16698
16699   if (cu->language != language_cplus && cu->language != language_java
16700       && cu->language != language_fortran)
16701     return "";
16702
16703   retval = anonymous_struct_prefix (die, cu);
16704   if (retval)
16705     return retval;
16706
16707   /* We have to be careful in the presence of DW_AT_specification.
16708      For example, with GCC 3.4, given the code
16709
16710      namespace N {
16711        void foo() {
16712          // Definition of N::foo.
16713        }
16714      }
16715
16716      then we'll have a tree of DIEs like this:
16717
16718      1: DW_TAG_compile_unit
16719        2: DW_TAG_namespace        // N
16720          3: DW_TAG_subprogram     // declaration of N::foo
16721        4: DW_TAG_subprogram       // definition of N::foo
16722             DW_AT_specification   // refers to die #3
16723
16724      Thus, when processing die #4, we have to pretend that we're in
16725      the context of its DW_AT_specification, namely the contex of die
16726      #3.  */
16727   spec_cu = cu;
16728   spec_die = die_specification (die, &spec_cu);
16729   if (spec_die == NULL)
16730     parent = die->parent;
16731   else
16732     {
16733       parent = spec_die->parent;
16734       cu = spec_cu;
16735     }
16736
16737   if (parent == NULL)
16738     return "";
16739   else if (parent->building_fullname)
16740     {
16741       const char *name;
16742       const char *parent_name;
16743
16744       /* It has been seen on RealView 2.2 built binaries,
16745          DW_TAG_template_type_param types actually _defined_ as
16746          children of the parent class:
16747
16748          enum E {};
16749          template class <class Enum> Class{};
16750          Class<enum E> class_e;
16751
16752          1: DW_TAG_class_type (Class)
16753            2: DW_TAG_enumeration_type (E)
16754              3: DW_TAG_enumerator (enum1:0)
16755              3: DW_TAG_enumerator (enum2:1)
16756              ...
16757            2: DW_TAG_template_type_param
16758               DW_AT_type  DW_FORM_ref_udata (E)
16759
16760          Besides being broken debug info, it can put GDB into an
16761          infinite loop.  Consider:
16762
16763          When we're building the full name for Class<E>, we'll start
16764          at Class, and go look over its template type parameters,
16765          finding E.  We'll then try to build the full name of E, and
16766          reach here.  We're now trying to build the full name of E,
16767          and look over the parent DIE for containing scope.  In the
16768          broken case, if we followed the parent DIE of E, we'd again
16769          find Class, and once again go look at its template type
16770          arguments, etc., etc.  Simply don't consider such parent die
16771          as source-level parent of this die (it can't be, the language
16772          doesn't allow it), and break the loop here.  */
16773       name = dwarf2_name (die, cu);
16774       parent_name = dwarf2_name (parent, cu);
16775       complaint (&symfile_complaints,
16776                  _("template param type '%s' defined within parent '%s'"),
16777                  name ? name : "<unknown>",
16778                  parent_name ? parent_name : "<unknown>");
16779       return "";
16780     }
16781   else
16782     switch (parent->tag)
16783       {
16784       case DW_TAG_namespace:
16785         parent_type = read_type_die (parent, cu);
16786         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
16787            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
16788            Work around this problem here.  */
16789         if (cu->language == language_cplus
16790             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
16791           return "";
16792         /* We give a name to even anonymous namespaces.  */
16793         return TYPE_TAG_NAME (parent_type);
16794       case DW_TAG_class_type:
16795       case DW_TAG_interface_type:
16796       case DW_TAG_structure_type:
16797       case DW_TAG_union_type:
16798       case DW_TAG_module:
16799         parent_type = read_type_die (parent, cu);
16800         if (TYPE_TAG_NAME (parent_type) != NULL)
16801           return TYPE_TAG_NAME (parent_type);
16802         else
16803           /* An anonymous structure is only allowed non-static data
16804              members; no typedefs, no member functions, et cetera.
16805              So it does not need a prefix.  */
16806           return "";
16807       case DW_TAG_compile_unit:
16808       case DW_TAG_partial_unit:
16809         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
16810         if (cu->language == language_cplus
16811             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16812             && die->child != NULL
16813             && (die->tag == DW_TAG_class_type
16814                 || die->tag == DW_TAG_structure_type
16815                 || die->tag == DW_TAG_union_type))
16816           {
16817             char *name = guess_full_die_structure_name (die, cu);
16818             if (name != NULL)
16819               return name;
16820           }
16821         return "";
16822       default:
16823         return determine_prefix (parent, cu);
16824       }
16825 }
16826
16827 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
16828    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
16829    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
16830    an obconcat, otherwise allocate storage for the result.  The CU argument is
16831    used to determine the language and hence, the appropriate separator.  */
16832
16833 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
16834
16835 static char *
16836 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
16837                  int physname, struct dwarf2_cu *cu)
16838 {
16839   const char *lead = "";
16840   const char *sep;
16841
16842   if (suffix == NULL || suffix[0] == '\0'
16843       || prefix == NULL || prefix[0] == '\0')
16844     sep = "";
16845   else if (cu->language == language_java)
16846     sep = ".";
16847   else if (cu->language == language_fortran && physname)
16848     {
16849       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
16850          DW_AT_MIPS_linkage_name is preferred and used instead.  */
16851
16852       lead = "__";
16853       sep = "_MOD_";
16854     }
16855   else
16856     sep = "::";
16857
16858   if (prefix == NULL)
16859     prefix = "";
16860   if (suffix == NULL)
16861     suffix = "";
16862
16863   if (obs == NULL)
16864     {
16865       char *retval
16866         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
16867
16868       strcpy (retval, lead);
16869       strcat (retval, prefix);
16870       strcat (retval, sep);
16871       strcat (retval, suffix);
16872       return retval;
16873     }
16874   else
16875     {
16876       /* We have an obstack.  */
16877       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
16878     }
16879 }
16880
16881 /* Return sibling of die, NULL if no sibling.  */
16882
16883 static struct die_info *
16884 sibling_die (struct die_info *die)
16885 {
16886   return die->sibling;
16887 }
16888
16889 /* Get name of a die, return NULL if not found.  */
16890
16891 static const char *
16892 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
16893                           struct obstack *obstack)
16894 {
16895   if (name && cu->language == language_cplus)
16896     {
16897       char *canon_name = cp_canonicalize_string (name);
16898
16899       if (canon_name != NULL)
16900         {
16901           if (strcmp (canon_name, name) != 0)
16902             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
16903           xfree (canon_name);
16904         }
16905     }
16906
16907   return name;
16908 }
16909
16910 /* Get name of a die, return NULL if not found.  */
16911
16912 static const char *
16913 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
16914 {
16915   struct attribute *attr;
16916
16917   attr = dwarf2_attr (die, DW_AT_name, cu);
16918   if ((!attr || !DW_STRING (attr))
16919       && die->tag != DW_TAG_class_type
16920       && die->tag != DW_TAG_interface_type
16921       && die->tag != DW_TAG_structure_type
16922       && die->tag != DW_TAG_union_type)
16923     return NULL;
16924
16925   switch (die->tag)
16926     {
16927     case DW_TAG_compile_unit:
16928     case DW_TAG_partial_unit:
16929       /* Compilation units have a DW_AT_name that is a filename, not
16930          a source language identifier.  */
16931     case DW_TAG_enumeration_type:
16932     case DW_TAG_enumerator:
16933       /* These tags always have simple identifiers already; no need
16934          to canonicalize them.  */
16935       return DW_STRING (attr);
16936
16937     case DW_TAG_subprogram:
16938       /* Java constructors will all be named "<init>", so return
16939          the class name when we see this special case.  */
16940       if (cu->language == language_java
16941           && DW_STRING (attr) != NULL
16942           && strcmp (DW_STRING (attr), "<init>") == 0)
16943         {
16944           struct dwarf2_cu *spec_cu = cu;
16945           struct die_info *spec_die;
16946
16947           /* GCJ will output '<init>' for Java constructor names.
16948              For this special case, return the name of the parent class.  */
16949
16950           /* GCJ may output suprogram DIEs with AT_specification set.
16951              If so, use the name of the specified DIE.  */
16952           spec_die = die_specification (die, &spec_cu);
16953           if (spec_die != NULL)
16954             return dwarf2_name (spec_die, spec_cu);
16955
16956           do
16957             {
16958               die = die->parent;
16959               if (die->tag == DW_TAG_class_type)
16960                 return dwarf2_name (die, cu);
16961             }
16962           while (die->tag != DW_TAG_compile_unit
16963                  && die->tag != DW_TAG_partial_unit);
16964         }
16965       break;
16966
16967     case DW_TAG_class_type:
16968     case DW_TAG_interface_type:
16969     case DW_TAG_structure_type:
16970     case DW_TAG_union_type:
16971       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
16972          structures or unions.  These were of the form "._%d" in GCC 4.1,
16973          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
16974          and GCC 4.4.  We work around this problem by ignoring these.  */
16975       if (attr && DW_STRING (attr)
16976           && (strncmp (DW_STRING (attr), "._", 2) == 0
16977               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
16978         return NULL;
16979
16980       /* GCC might emit a nameless typedef that has a linkage name.  See
16981          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16982       if (!attr || DW_STRING (attr) == NULL)
16983         {
16984           char *demangled = NULL;
16985
16986           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16987           if (attr == NULL)
16988             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16989
16990           if (attr == NULL || DW_STRING (attr) == NULL)
16991             return NULL;
16992
16993           /* Avoid demangling DW_STRING (attr) the second time on a second
16994              call for the same DIE.  */
16995           if (!DW_STRING_IS_CANONICAL (attr))
16996             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
16997
16998           if (demangled)
16999             {
17000               char *base;
17001
17002               /* FIXME: we already did this for the partial symbol... */
17003               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17004                                                 demangled, strlen (demangled));
17005               DW_STRING_IS_CANONICAL (attr) = 1;
17006               xfree (demangled);
17007
17008               /* Strip any leading namespaces/classes, keep only the base name.
17009                  DW_AT_name for named DIEs does not contain the prefixes.  */
17010               base = strrchr (DW_STRING (attr), ':');
17011               if (base && base > DW_STRING (attr) && base[-1] == ':')
17012                 return &base[1];
17013               else
17014                 return DW_STRING (attr);
17015             }
17016         }
17017       break;
17018
17019     default:
17020       break;
17021     }
17022
17023   if (!DW_STRING_IS_CANONICAL (attr))
17024     {
17025       DW_STRING (attr)
17026         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17027                                     &cu->objfile->objfile_obstack);
17028       DW_STRING_IS_CANONICAL (attr) = 1;
17029     }
17030   return DW_STRING (attr);
17031 }
17032
17033 /* Return the die that this die in an extension of, or NULL if there
17034    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17035    containing the return value on output.  */
17036
17037 static struct die_info *
17038 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17039 {
17040   struct attribute *attr;
17041
17042   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17043   if (attr == NULL)
17044     return NULL;
17045
17046   return follow_die_ref (die, attr, ext_cu);
17047 }
17048
17049 /* Convert a DIE tag into its string name.  */
17050
17051 static const char *
17052 dwarf_tag_name (unsigned tag)
17053 {
17054   const char *name = get_DW_TAG_name (tag);
17055
17056   if (name == NULL)
17057     return "DW_TAG_<unknown>";
17058
17059   return name;
17060 }
17061
17062 /* Convert a DWARF attribute code into its string name.  */
17063
17064 static const char *
17065 dwarf_attr_name (unsigned attr)
17066 {
17067   const char *name;
17068
17069 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17070   if (attr == DW_AT_MIPS_fde)
17071     return "DW_AT_MIPS_fde";
17072 #else
17073   if (attr == DW_AT_HP_block_index)
17074     return "DW_AT_HP_block_index";
17075 #endif
17076
17077   name = get_DW_AT_name (attr);
17078
17079   if (name == NULL)
17080     return "DW_AT_<unknown>";
17081
17082   return name;
17083 }
17084
17085 /* Convert a DWARF value form code into its string name.  */
17086
17087 static const char *
17088 dwarf_form_name (unsigned form)
17089 {
17090   const char *name = get_DW_FORM_name (form);
17091
17092   if (name == NULL)
17093     return "DW_FORM_<unknown>";
17094
17095   return name;
17096 }
17097
17098 static char *
17099 dwarf_bool_name (unsigned mybool)
17100 {
17101   if (mybool)
17102     return "TRUE";
17103   else
17104     return "FALSE";
17105 }
17106
17107 /* Convert a DWARF type code into its string name.  */
17108
17109 static const char *
17110 dwarf_type_encoding_name (unsigned enc)
17111 {
17112   const char *name = get_DW_ATE_name (enc);
17113
17114   if (name == NULL)
17115     return "DW_ATE_<unknown>";
17116
17117   return name;
17118 }
17119
17120 static void
17121 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17122 {
17123   unsigned int i;
17124
17125   print_spaces (indent, f);
17126   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17127            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17128
17129   if (die->parent != NULL)
17130     {
17131       print_spaces (indent, f);
17132       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17133                           die->parent->offset.sect_off);
17134     }
17135
17136   print_spaces (indent, f);
17137   fprintf_unfiltered (f, "  has children: %s\n",
17138            dwarf_bool_name (die->child != NULL));
17139
17140   print_spaces (indent, f);
17141   fprintf_unfiltered (f, "  attributes:\n");
17142
17143   for (i = 0; i < die->num_attrs; ++i)
17144     {
17145       print_spaces (indent, f);
17146       fprintf_unfiltered (f, "    %s (%s) ",
17147                dwarf_attr_name (die->attrs[i].name),
17148                dwarf_form_name (die->attrs[i].form));
17149
17150       switch (die->attrs[i].form)
17151         {
17152         case DW_FORM_addr:
17153         case DW_FORM_GNU_addr_index:
17154           fprintf_unfiltered (f, "address: ");
17155           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17156           break;
17157         case DW_FORM_block2:
17158         case DW_FORM_block4:
17159         case DW_FORM_block:
17160         case DW_FORM_block1:
17161           fprintf_unfiltered (f, "block: size %s",
17162                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17163           break;
17164         case DW_FORM_exprloc:
17165           fprintf_unfiltered (f, "expression: size %s",
17166                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17167           break;
17168         case DW_FORM_ref_addr:
17169           fprintf_unfiltered (f, "ref address: ");
17170           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17171           break;
17172         case DW_FORM_GNU_ref_alt:
17173           fprintf_unfiltered (f, "alt ref address: ");
17174           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17175           break;
17176         case DW_FORM_ref1:
17177         case DW_FORM_ref2:
17178         case DW_FORM_ref4:
17179         case DW_FORM_ref8:
17180         case DW_FORM_ref_udata:
17181           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17182                               (long) (DW_UNSND (&die->attrs[i])));
17183           break;
17184         case DW_FORM_data1:
17185         case DW_FORM_data2:
17186         case DW_FORM_data4:
17187         case DW_FORM_data8:
17188         case DW_FORM_udata:
17189         case DW_FORM_sdata:
17190           fprintf_unfiltered (f, "constant: %s",
17191                               pulongest (DW_UNSND (&die->attrs[i])));
17192           break;
17193         case DW_FORM_sec_offset:
17194           fprintf_unfiltered (f, "section offset: %s",
17195                               pulongest (DW_UNSND (&die->attrs[i])));
17196           break;
17197         case DW_FORM_ref_sig8:
17198           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17199             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
17200                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
17201           else
17202             fprintf_unfiltered (f, "signatured type, offset: unknown");
17203           break;
17204         case DW_FORM_string:
17205         case DW_FORM_strp:
17206         case DW_FORM_GNU_str_index:
17207         case DW_FORM_GNU_strp_alt:
17208           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17209                    DW_STRING (&die->attrs[i])
17210                    ? DW_STRING (&die->attrs[i]) : "",
17211                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17212           break;
17213         case DW_FORM_flag:
17214           if (DW_UNSND (&die->attrs[i]))
17215             fprintf_unfiltered (f, "flag: TRUE");
17216           else
17217             fprintf_unfiltered (f, "flag: FALSE");
17218           break;
17219         case DW_FORM_flag_present:
17220           fprintf_unfiltered (f, "flag: TRUE");
17221           break;
17222         case DW_FORM_indirect:
17223           /* The reader will have reduced the indirect form to
17224              the "base form" so this form should not occur.  */
17225           fprintf_unfiltered (f, 
17226                               "unexpected attribute form: DW_FORM_indirect");
17227           break;
17228         default:
17229           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17230                    die->attrs[i].form);
17231           break;
17232         }
17233       fprintf_unfiltered (f, "\n");
17234     }
17235 }
17236
17237 static void
17238 dump_die_for_error (struct die_info *die)
17239 {
17240   dump_die_shallow (gdb_stderr, 0, die);
17241 }
17242
17243 static void
17244 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17245 {
17246   int indent = level * 4;
17247
17248   gdb_assert (die != NULL);
17249
17250   if (level >= max_level)
17251     return;
17252
17253   dump_die_shallow (f, indent, die);
17254
17255   if (die->child != NULL)
17256     {
17257       print_spaces (indent, f);
17258       fprintf_unfiltered (f, "  Children:");
17259       if (level + 1 < max_level)
17260         {
17261           fprintf_unfiltered (f, "\n");
17262           dump_die_1 (f, level + 1, max_level, die->child);
17263         }
17264       else
17265         {
17266           fprintf_unfiltered (f,
17267                               " [not printed, max nesting level reached]\n");
17268         }
17269     }
17270
17271   if (die->sibling != NULL && level > 0)
17272     {
17273       dump_die_1 (f, level, max_level, die->sibling);
17274     }
17275 }
17276
17277 /* This is called from the pdie macro in gdbinit.in.
17278    It's not static so gcc will keep a copy callable from gdb.  */
17279
17280 void
17281 dump_die (struct die_info *die, int max_level)
17282 {
17283   dump_die_1 (gdb_stdlog, 0, max_level, die);
17284 }
17285
17286 static void
17287 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17288 {
17289   void **slot;
17290
17291   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17292                                    INSERT);
17293
17294   *slot = die;
17295 }
17296
17297 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17298    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17299
17300 static int
17301 is_ref_attr (struct attribute *attr)
17302 {
17303   switch (attr->form)
17304     {
17305     case DW_FORM_ref_addr:
17306     case DW_FORM_ref1:
17307     case DW_FORM_ref2:
17308     case DW_FORM_ref4:
17309     case DW_FORM_ref8:
17310     case DW_FORM_ref_udata:
17311     case DW_FORM_GNU_ref_alt:
17312       return 1;
17313     default:
17314       return 0;
17315     }
17316 }
17317
17318 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17319    required kind.  */
17320
17321 static sect_offset
17322 dwarf2_get_ref_die_offset (struct attribute *attr)
17323 {
17324   sect_offset retval = { DW_UNSND (attr) };
17325
17326   if (is_ref_attr (attr))
17327     return retval;
17328
17329   retval.sect_off = 0;
17330   complaint (&symfile_complaints,
17331              _("unsupported die ref attribute form: '%s'"),
17332              dwarf_form_name (attr->form));
17333   return retval;
17334 }
17335
17336 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17337  * the value held by the attribute is not constant.  */
17338
17339 static LONGEST
17340 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17341 {
17342   if (attr->form == DW_FORM_sdata)
17343     return DW_SND (attr);
17344   else if (attr->form == DW_FORM_udata
17345            || attr->form == DW_FORM_data1
17346            || attr->form == DW_FORM_data2
17347            || attr->form == DW_FORM_data4
17348            || attr->form == DW_FORM_data8)
17349     return DW_UNSND (attr);
17350   else
17351     {
17352       complaint (&symfile_complaints,
17353                  _("Attribute value is not a constant (%s)"),
17354                  dwarf_form_name (attr->form));
17355       return default_value;
17356     }
17357 }
17358
17359 /* Follow reference or signature attribute ATTR of SRC_DIE.
17360    On entry *REF_CU is the CU of SRC_DIE.
17361    On exit *REF_CU is the CU of the result.  */
17362
17363 static struct die_info *
17364 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17365                        struct dwarf2_cu **ref_cu)
17366 {
17367   struct die_info *die;
17368
17369   if (is_ref_attr (attr))
17370     die = follow_die_ref (src_die, attr, ref_cu);
17371   else if (attr->form == DW_FORM_ref_sig8)
17372     die = follow_die_sig (src_die, attr, ref_cu);
17373   else
17374     {
17375       dump_die_for_error (src_die);
17376       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17377              (*ref_cu)->objfile->name);
17378     }
17379
17380   return die;
17381 }
17382
17383 /* Follow reference OFFSET.
17384    On entry *REF_CU is the CU of the source die referencing OFFSET.
17385    On exit *REF_CU is the CU of the result.
17386    Returns NULL if OFFSET is invalid.  */
17387
17388 static struct die_info *
17389 follow_die_offset (sect_offset offset, int offset_in_dwz,
17390                    struct dwarf2_cu **ref_cu)
17391 {
17392   struct die_info temp_die;
17393   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17394
17395   gdb_assert (cu->per_cu != NULL);
17396
17397   target_cu = cu;
17398
17399   if (cu->per_cu->is_debug_types)
17400     {
17401       /* .debug_types CUs cannot reference anything outside their CU.
17402          If they need to, they have to reference a signatured type via
17403          DW_FORM_ref_sig8.  */
17404       if (! offset_in_cu_p (&cu->header, offset))
17405         return NULL;
17406     }
17407   else if (offset_in_dwz != cu->per_cu->is_dwz
17408            || ! offset_in_cu_p (&cu->header, offset))
17409     {
17410       struct dwarf2_per_cu_data *per_cu;
17411
17412       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17413                                                  cu->objfile);
17414
17415       /* If necessary, add it to the queue and load its DIEs.  */
17416       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17417         load_full_comp_unit (per_cu, cu->language);
17418
17419       target_cu = per_cu->cu;
17420     }
17421   else if (cu->dies == NULL)
17422     {
17423       /* We're loading full DIEs during partial symbol reading.  */
17424       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17425       load_full_comp_unit (cu->per_cu, language_minimal);
17426     }
17427
17428   *ref_cu = target_cu;
17429   temp_die.offset = offset;
17430   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17431 }
17432
17433 /* Follow reference attribute ATTR of SRC_DIE.
17434    On entry *REF_CU is the CU of SRC_DIE.
17435    On exit *REF_CU is the CU of the result.  */
17436
17437 static struct die_info *
17438 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17439                 struct dwarf2_cu **ref_cu)
17440 {
17441   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17442   struct dwarf2_cu *cu = *ref_cu;
17443   struct die_info *die;
17444
17445   die = follow_die_offset (offset,
17446                            (attr->form == DW_FORM_GNU_ref_alt
17447                             || cu->per_cu->is_dwz),
17448                            ref_cu);
17449   if (!die)
17450     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17451            "at 0x%x [in module %s]"),
17452            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17453
17454   return die;
17455 }
17456
17457 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17458    Returned value is intended for DW_OP_call*.  Returned
17459    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17460
17461 struct dwarf2_locexpr_baton
17462 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17463                                struct dwarf2_per_cu_data *per_cu,
17464                                CORE_ADDR (*get_frame_pc) (void *baton),
17465                                void *baton)
17466 {
17467   struct dwarf2_cu *cu;
17468   struct die_info *die;
17469   struct attribute *attr;
17470   struct dwarf2_locexpr_baton retval;
17471
17472   dw2_setup (per_cu->objfile);
17473
17474   if (per_cu->cu == NULL)
17475     load_cu (per_cu);
17476   cu = per_cu->cu;
17477
17478   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17479   if (!die)
17480     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17481            offset.sect_off, per_cu->objfile->name);
17482
17483   attr = dwarf2_attr (die, DW_AT_location, cu);
17484   if (!attr)
17485     {
17486       /* DWARF: "If there is no such attribute, then there is no effect.".
17487          DATA is ignored if SIZE is 0.  */
17488
17489       retval.data = NULL;
17490       retval.size = 0;
17491     }
17492   else if (attr_form_is_section_offset (attr))
17493     {
17494       struct dwarf2_loclist_baton loclist_baton;
17495       CORE_ADDR pc = (*get_frame_pc) (baton);
17496       size_t size;
17497
17498       fill_in_loclist_baton (cu, &loclist_baton, attr);
17499
17500       retval.data = dwarf2_find_location_expression (&loclist_baton,
17501                                                      &size, pc);
17502       retval.size = size;
17503     }
17504   else
17505     {
17506       if (!attr_form_is_block (attr))
17507         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17508                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17509                offset.sect_off, per_cu->objfile->name);
17510
17511       retval.data = DW_BLOCK (attr)->data;
17512       retval.size = DW_BLOCK (attr)->size;
17513     }
17514   retval.per_cu = cu->per_cu;
17515
17516   age_cached_comp_units ();
17517
17518   return retval;
17519 }
17520
17521 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17522    offset.  */
17523
17524 struct dwarf2_locexpr_baton
17525 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17526                              struct dwarf2_per_cu_data *per_cu,
17527                              CORE_ADDR (*get_frame_pc) (void *baton),
17528                              void *baton)
17529 {
17530   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17531
17532   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17533 }
17534
17535 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17536    PER_CU.  */
17537
17538 struct type *
17539 dwarf2_get_die_type (cu_offset die_offset,
17540                      struct dwarf2_per_cu_data *per_cu)
17541 {
17542   sect_offset die_offset_sect;
17543
17544   dw2_setup (per_cu->objfile);
17545
17546   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17547   return get_die_type_at_offset (die_offset_sect, per_cu);
17548 }
17549
17550 /* Follow the signature attribute ATTR in SRC_DIE.
17551    On entry *REF_CU is the CU of SRC_DIE.
17552    On exit *REF_CU is the CU of the result.  */
17553
17554 static struct die_info *
17555 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17556                 struct dwarf2_cu **ref_cu)
17557 {
17558   struct objfile *objfile = (*ref_cu)->objfile;
17559   struct die_info temp_die;
17560   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17561   struct dwarf2_cu *sig_cu;
17562   struct die_info *die;
17563
17564   /* sig_type will be NULL if the signatured type is missing from
17565      the debug info.  */
17566   if (sig_type == NULL)
17567     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17568              "at 0x%x [in module %s]"),
17569            src_die->offset.sect_off, objfile->name);
17570
17571   /* If necessary, add it to the queue and load its DIEs.  */
17572
17573   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17574     read_signatured_type (sig_type);
17575
17576   gdb_assert (sig_type->per_cu.cu != NULL);
17577
17578   sig_cu = sig_type->per_cu.cu;
17579   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17580   temp_die.offset = sig_type->type_offset_in_section;
17581   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17582                              temp_die.offset.sect_off);
17583   if (die)
17584     {
17585       /* For .gdb_index version 7 keep track of included TUs.
17586          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17587       if (dwarf2_per_objfile->index_table != NULL
17588           && dwarf2_per_objfile->index_table->version <= 7)
17589         {
17590           VEC_safe_push (dwarf2_per_cu_ptr,
17591                          (*ref_cu)->per_cu->imported_symtabs,
17592                          sig_cu->per_cu);
17593         }
17594
17595       *ref_cu = sig_cu;
17596       return die;
17597     }
17598
17599   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17600          "from DIE at 0x%x [in module %s]"),
17601          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17602 }
17603
17604 /* Given an offset of a signatured type, return its signatured_type.  */
17605
17606 static struct signatured_type *
17607 lookup_signatured_type_at_offset (struct objfile *objfile,
17608                                   struct dwarf2_section_info *section,
17609                                   sect_offset offset)
17610 {
17611   gdb_byte *info_ptr = section->buffer + offset.sect_off;
17612   unsigned int length, initial_length_size;
17613   unsigned int sig_offset;
17614   struct signatured_type find_entry, *sig_type;
17615
17616   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
17617   sig_offset = (initial_length_size
17618                 + 2 /*version*/
17619                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
17620                 + 1 /*address_size*/);
17621   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
17622   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
17623
17624   /* This is only used to lookup previously recorded types.
17625      If we didn't find it, it's our bug.  */
17626   gdb_assert (sig_type != NULL);
17627   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
17628
17629   return sig_type;
17630 }
17631
17632 /* Load the DIEs associated with type unit PER_CU into memory.  */
17633
17634 static void
17635 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17636 {
17637   struct signatured_type *sig_type;
17638
17639   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17640   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17641
17642   /* We have the per_cu, but we need the signatured_type.
17643      Fortunately this is an easy translation.  */
17644   gdb_assert (per_cu->is_debug_types);
17645   sig_type = (struct signatured_type *) per_cu;
17646
17647   gdb_assert (per_cu->cu == NULL);
17648
17649   read_signatured_type (sig_type);
17650
17651   gdb_assert (per_cu->cu != NULL);
17652 }
17653
17654 /* die_reader_func for read_signatured_type.
17655    This is identical to load_full_comp_unit_reader,
17656    but is kept separate for now.  */
17657
17658 static void
17659 read_signatured_type_reader (const struct die_reader_specs *reader,
17660                              gdb_byte *info_ptr,
17661                              struct die_info *comp_unit_die,
17662                              int has_children,
17663                              void *data)
17664 {
17665   struct dwarf2_cu *cu = reader->cu;
17666
17667   gdb_assert (cu->die_hash == NULL);
17668   cu->die_hash =
17669     htab_create_alloc_ex (cu->header.length / 12,
17670                           die_hash,
17671                           die_eq,
17672                           NULL,
17673                           &cu->comp_unit_obstack,
17674                           hashtab_obstack_allocate,
17675                           dummy_obstack_deallocate);
17676
17677   if (has_children)
17678     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17679                                                   &info_ptr, comp_unit_die);
17680   cu->dies = comp_unit_die;
17681   /* comp_unit_die is not stored in die_hash, no need.  */
17682
17683   /* We try not to read any attributes in this function, because not
17684      all CUs needed for references have been loaded yet, and symbol
17685      table processing isn't initialized.  But we have to set the CU language,
17686      or we won't be able to build types correctly.
17687      Similarly, if we do not read the producer, we can not apply
17688      producer-specific interpretation.  */
17689   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17690 }
17691
17692 /* Read in a signatured type and build its CU and DIEs.
17693    If the type is a stub for the real type in a DWO file,
17694    read in the real type from the DWO file as well.  */
17695
17696 static void
17697 read_signatured_type (struct signatured_type *sig_type)
17698 {
17699   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17700
17701   gdb_assert (per_cu->is_debug_types);
17702   gdb_assert (per_cu->cu == NULL);
17703
17704   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17705                            read_signatured_type_reader, NULL);
17706 }
17707
17708 /* Decode simple location descriptions.
17709    Given a pointer to a dwarf block that defines a location, compute
17710    the location and return the value.
17711
17712    NOTE drow/2003-11-18: This function is called in two situations
17713    now: for the address of static or global variables (partial symbols
17714    only) and for offsets into structures which are expected to be
17715    (more or less) constant.  The partial symbol case should go away,
17716    and only the constant case should remain.  That will let this
17717    function complain more accurately.  A few special modes are allowed
17718    without complaint for global variables (for instance, global
17719    register values and thread-local values).
17720
17721    A location description containing no operations indicates that the
17722    object is optimized out.  The return value is 0 for that case.
17723    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17724    callers will only want a very basic result and this can become a
17725    complaint.
17726
17727    Note that stack[0] is unused except as a default error return.  */
17728
17729 static CORE_ADDR
17730 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17731 {
17732   struct objfile *objfile = cu->objfile;
17733   size_t i;
17734   size_t size = blk->size;
17735   gdb_byte *data = blk->data;
17736   CORE_ADDR stack[64];
17737   int stacki;
17738   unsigned int bytes_read, unsnd;
17739   gdb_byte op;
17740
17741   i = 0;
17742   stacki = 0;
17743   stack[stacki] = 0;
17744   stack[++stacki] = 0;
17745
17746   while (i < size)
17747     {
17748       op = data[i++];
17749       switch (op)
17750         {
17751         case DW_OP_lit0:
17752         case DW_OP_lit1:
17753         case DW_OP_lit2:
17754         case DW_OP_lit3:
17755         case DW_OP_lit4:
17756         case DW_OP_lit5:
17757         case DW_OP_lit6:
17758         case DW_OP_lit7:
17759         case DW_OP_lit8:
17760         case DW_OP_lit9:
17761         case DW_OP_lit10:
17762         case DW_OP_lit11:
17763         case DW_OP_lit12:
17764         case DW_OP_lit13:
17765         case DW_OP_lit14:
17766         case DW_OP_lit15:
17767         case DW_OP_lit16:
17768         case DW_OP_lit17:
17769         case DW_OP_lit18:
17770         case DW_OP_lit19:
17771         case DW_OP_lit20:
17772         case DW_OP_lit21:
17773         case DW_OP_lit22:
17774         case DW_OP_lit23:
17775         case DW_OP_lit24:
17776         case DW_OP_lit25:
17777         case DW_OP_lit26:
17778         case DW_OP_lit27:
17779         case DW_OP_lit28:
17780         case DW_OP_lit29:
17781         case DW_OP_lit30:
17782         case DW_OP_lit31:
17783           stack[++stacki] = op - DW_OP_lit0;
17784           break;
17785
17786         case DW_OP_reg0:
17787         case DW_OP_reg1:
17788         case DW_OP_reg2:
17789         case DW_OP_reg3:
17790         case DW_OP_reg4:
17791         case DW_OP_reg5:
17792         case DW_OP_reg6:
17793         case DW_OP_reg7:
17794         case DW_OP_reg8:
17795         case DW_OP_reg9:
17796         case DW_OP_reg10:
17797         case DW_OP_reg11:
17798         case DW_OP_reg12:
17799         case DW_OP_reg13:
17800         case DW_OP_reg14:
17801         case DW_OP_reg15:
17802         case DW_OP_reg16:
17803         case DW_OP_reg17:
17804         case DW_OP_reg18:
17805         case DW_OP_reg19:
17806         case DW_OP_reg20:
17807         case DW_OP_reg21:
17808         case DW_OP_reg22:
17809         case DW_OP_reg23:
17810         case DW_OP_reg24:
17811         case DW_OP_reg25:
17812         case DW_OP_reg26:
17813         case DW_OP_reg27:
17814         case DW_OP_reg28:
17815         case DW_OP_reg29:
17816         case DW_OP_reg30:
17817         case DW_OP_reg31:
17818           stack[++stacki] = op - DW_OP_reg0;
17819           if (i < size)
17820             dwarf2_complex_location_expr_complaint ();
17821           break;
17822
17823         case DW_OP_regx:
17824           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
17825           i += bytes_read;
17826           stack[++stacki] = unsnd;
17827           if (i < size)
17828             dwarf2_complex_location_expr_complaint ();
17829           break;
17830
17831         case DW_OP_addr:
17832           stack[++stacki] = read_address (objfile->obfd, &data[i],
17833                                           cu, &bytes_read);
17834           i += bytes_read;
17835           break;
17836
17837         case DW_OP_const1u:
17838           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
17839           i += 1;
17840           break;
17841
17842         case DW_OP_const1s:
17843           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
17844           i += 1;
17845           break;
17846
17847         case DW_OP_const2u:
17848           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
17849           i += 2;
17850           break;
17851
17852         case DW_OP_const2s:
17853           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
17854           i += 2;
17855           break;
17856
17857         case DW_OP_const4u:
17858           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
17859           i += 4;
17860           break;
17861
17862         case DW_OP_const4s:
17863           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
17864           i += 4;
17865           break;
17866
17867         case DW_OP_const8u:
17868           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
17869           i += 8;
17870           break;
17871
17872         case DW_OP_constu:
17873           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
17874                                                   &bytes_read);
17875           i += bytes_read;
17876           break;
17877
17878         case DW_OP_consts:
17879           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
17880           i += bytes_read;
17881           break;
17882
17883         case DW_OP_dup:
17884           stack[stacki + 1] = stack[stacki];
17885           stacki++;
17886           break;
17887
17888         case DW_OP_plus:
17889           stack[stacki - 1] += stack[stacki];
17890           stacki--;
17891           break;
17892
17893         case DW_OP_plus_uconst:
17894           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
17895                                                  &bytes_read);
17896           i += bytes_read;
17897           break;
17898
17899         case DW_OP_minus:
17900           stack[stacki - 1] -= stack[stacki];
17901           stacki--;
17902           break;
17903
17904         case DW_OP_deref:
17905           /* If we're not the last op, then we definitely can't encode
17906              this using GDB's address_class enum.  This is valid for partial
17907              global symbols, although the variable's address will be bogus
17908              in the psymtab.  */
17909           if (i < size)
17910             dwarf2_complex_location_expr_complaint ();
17911           break;
17912
17913         case DW_OP_GNU_push_tls_address:
17914           /* The top of the stack has the offset from the beginning
17915              of the thread control block at which the variable is located.  */
17916           /* Nothing should follow this operator, so the top of stack would
17917              be returned.  */
17918           /* This is valid for partial global symbols, but the variable's
17919              address will be bogus in the psymtab.  Make it always at least
17920              non-zero to not look as a variable garbage collected by linker
17921              which have DW_OP_addr 0.  */
17922           if (i < size)
17923             dwarf2_complex_location_expr_complaint ();
17924           stack[stacki]++;
17925           break;
17926
17927         case DW_OP_GNU_uninit:
17928           break;
17929
17930         case DW_OP_GNU_addr_index:
17931         case DW_OP_GNU_const_index:
17932           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
17933                                                          &bytes_read);
17934           i += bytes_read;
17935           break;
17936
17937         default:
17938           {
17939             const char *name = get_DW_OP_name (op);
17940
17941             if (name)
17942               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
17943                          name);
17944             else
17945               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
17946                          op);
17947           }
17948
17949           return (stack[stacki]);
17950         }
17951
17952       /* Enforce maximum stack depth of SIZE-1 to avoid writing
17953          outside of the allocated space.  Also enforce minimum>0.  */
17954       if (stacki >= ARRAY_SIZE (stack) - 1)
17955         {
17956           complaint (&symfile_complaints,
17957                      _("location description stack overflow"));
17958           return 0;
17959         }
17960
17961       if (stacki <= 0)
17962         {
17963           complaint (&symfile_complaints,
17964                      _("location description stack underflow"));
17965           return 0;
17966         }
17967     }
17968   return (stack[stacki]);
17969 }
17970
17971 /* memory allocation interface */
17972
17973 static struct dwarf_block *
17974 dwarf_alloc_block (struct dwarf2_cu *cu)
17975 {
17976   struct dwarf_block *blk;
17977
17978   blk = (struct dwarf_block *)
17979     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
17980   return (blk);
17981 }
17982
17983 static struct die_info *
17984 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
17985 {
17986   struct die_info *die;
17987   size_t size = sizeof (struct die_info);
17988
17989   if (num_attrs > 1)
17990     size += (num_attrs - 1) * sizeof (struct attribute);
17991
17992   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
17993   memset (die, 0, sizeof (struct die_info));
17994   return (die);
17995 }
17996
17997 \f
17998 /* Macro support.  */
17999
18000 /* Return the full name of file number I in *LH's file name table.
18001    Use COMP_DIR as the name of the current directory of the
18002    compilation.  The result is allocated using xmalloc; the caller is
18003    responsible for freeing it.  */
18004 static char *
18005 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18006 {
18007   /* Is the file number a valid index into the line header's file name
18008      table?  Remember that file numbers start with one, not zero.  */
18009   if (1 <= file && file <= lh->num_file_names)
18010     {
18011       struct file_entry *fe = &lh->file_names[file - 1];
18012
18013       if (IS_ABSOLUTE_PATH (fe->name))
18014         return xstrdup (fe->name);
18015       else
18016         {
18017           const char *dir;
18018           int dir_len;
18019           char *full_name;
18020
18021           if (fe->dir_index)
18022             dir = lh->include_dirs[fe->dir_index - 1];
18023           else
18024             dir = comp_dir;
18025
18026           if (dir)
18027             {
18028               dir_len = strlen (dir);
18029               full_name = xmalloc (dir_len + 1 + strlen (fe->name) + 1);
18030               strcpy (full_name, dir);
18031               full_name[dir_len] = '/';
18032               strcpy (full_name + dir_len + 1, fe->name);
18033               return full_name;
18034             }
18035           else
18036             return xstrdup (fe->name);
18037         }
18038     }
18039   else
18040     {
18041       /* The compiler produced a bogus file number.  We can at least
18042          record the macro definitions made in the file, even if we
18043          won't be able to find the file by name.  */
18044       char fake_name[80];
18045
18046       xsnprintf (fake_name, sizeof (fake_name),
18047                  "<bad macro file number %d>", file);
18048
18049       complaint (&symfile_complaints,
18050                  _("bad file number in macro information (%d)"),
18051                  file);
18052
18053       return xstrdup (fake_name);
18054     }
18055 }
18056
18057
18058 static struct macro_source_file *
18059 macro_start_file (int file, int line,
18060                   struct macro_source_file *current_file,
18061                   const char *comp_dir,
18062                   struct line_header *lh, struct objfile *objfile)
18063 {
18064   /* The full name of this source file.  */
18065   char *full_name = file_full_name (file, lh, comp_dir);
18066
18067   /* We don't create a macro table for this compilation unit
18068      at all until we actually get a filename.  */
18069   if (! pending_macros)
18070     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18071                                       objfile->per_bfd->macro_cache);
18072
18073   if (! current_file)
18074     {
18075       /* If we have no current file, then this must be the start_file
18076          directive for the compilation unit's main source file.  */
18077       current_file = macro_set_main (pending_macros, full_name);
18078       macro_define_special (pending_macros);
18079     }
18080   else
18081     current_file = macro_include (current_file, line, full_name);
18082
18083   xfree (full_name);
18084
18085   return current_file;
18086 }
18087
18088
18089 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18090    followed by a null byte.  */
18091 static char *
18092 copy_string (const char *buf, int len)
18093 {
18094   char *s = xmalloc (len + 1);
18095
18096   memcpy (s, buf, len);
18097   s[len] = '\0';
18098   return s;
18099 }
18100
18101
18102 static const char *
18103 consume_improper_spaces (const char *p, const char *body)
18104 {
18105   if (*p == ' ')
18106     {
18107       complaint (&symfile_complaints,
18108                  _("macro definition contains spaces "
18109                    "in formal argument list:\n`%s'"),
18110                  body);
18111
18112       while (*p == ' ')
18113         p++;
18114     }
18115
18116   return p;
18117 }
18118
18119
18120 static void
18121 parse_macro_definition (struct macro_source_file *file, int line,
18122                         const char *body)
18123 {
18124   const char *p;
18125
18126   /* The body string takes one of two forms.  For object-like macro
18127      definitions, it should be:
18128
18129         <macro name> " " <definition>
18130
18131      For function-like macro definitions, it should be:
18132
18133         <macro name> "() " <definition>
18134      or
18135         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18136
18137      Spaces may appear only where explicitly indicated, and in the
18138      <definition>.
18139
18140      The Dwarf 2 spec says that an object-like macro's name is always
18141      followed by a space, but versions of GCC around March 2002 omit
18142      the space when the macro's definition is the empty string.
18143
18144      The Dwarf 2 spec says that there should be no spaces between the
18145      formal arguments in a function-like macro's formal argument list,
18146      but versions of GCC around March 2002 include spaces after the
18147      commas.  */
18148
18149
18150   /* Find the extent of the macro name.  The macro name is terminated
18151      by either a space or null character (for an object-like macro) or
18152      an opening paren (for a function-like macro).  */
18153   for (p = body; *p; p++)
18154     if (*p == ' ' || *p == '(')
18155       break;
18156
18157   if (*p == ' ' || *p == '\0')
18158     {
18159       /* It's an object-like macro.  */
18160       int name_len = p - body;
18161       char *name = copy_string (body, name_len);
18162       const char *replacement;
18163
18164       if (*p == ' ')
18165         replacement = body + name_len + 1;
18166       else
18167         {
18168           dwarf2_macro_malformed_definition_complaint (body);
18169           replacement = body + name_len;
18170         }
18171
18172       macro_define_object (file, line, name, replacement);
18173
18174       xfree (name);
18175     }
18176   else if (*p == '(')
18177     {
18178       /* It's a function-like macro.  */
18179       char *name = copy_string (body, p - body);
18180       int argc = 0;
18181       int argv_size = 1;
18182       char **argv = xmalloc (argv_size * sizeof (*argv));
18183
18184       p++;
18185
18186       p = consume_improper_spaces (p, body);
18187
18188       /* Parse the formal argument list.  */
18189       while (*p && *p != ')')
18190         {
18191           /* Find the extent of the current argument name.  */
18192           const char *arg_start = p;
18193
18194           while (*p && *p != ',' && *p != ')' && *p != ' ')
18195             p++;
18196
18197           if (! *p || p == arg_start)
18198             dwarf2_macro_malformed_definition_complaint (body);
18199           else
18200             {
18201               /* Make sure argv has room for the new argument.  */
18202               if (argc >= argv_size)
18203                 {
18204                   argv_size *= 2;
18205                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18206                 }
18207
18208               argv[argc++] = copy_string (arg_start, p - arg_start);
18209             }
18210
18211           p = consume_improper_spaces (p, body);
18212
18213           /* Consume the comma, if present.  */
18214           if (*p == ',')
18215             {
18216               p++;
18217
18218               p = consume_improper_spaces (p, body);
18219             }
18220         }
18221
18222       if (*p == ')')
18223         {
18224           p++;
18225
18226           if (*p == ' ')
18227             /* Perfectly formed definition, no complaints.  */
18228             macro_define_function (file, line, name,
18229                                    argc, (const char **) argv,
18230                                    p + 1);
18231           else if (*p == '\0')
18232             {
18233               /* Complain, but do define it.  */
18234               dwarf2_macro_malformed_definition_complaint (body);
18235               macro_define_function (file, line, name,
18236                                      argc, (const char **) argv,
18237                                      p);
18238             }
18239           else
18240             /* Just complain.  */
18241             dwarf2_macro_malformed_definition_complaint (body);
18242         }
18243       else
18244         /* Just complain.  */
18245         dwarf2_macro_malformed_definition_complaint (body);
18246
18247       xfree (name);
18248       {
18249         int i;
18250
18251         for (i = 0; i < argc; i++)
18252           xfree (argv[i]);
18253       }
18254       xfree (argv);
18255     }
18256   else
18257     dwarf2_macro_malformed_definition_complaint (body);
18258 }
18259
18260 /* Skip some bytes from BYTES according to the form given in FORM.
18261    Returns the new pointer.  */
18262
18263 static gdb_byte *
18264 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
18265                  enum dwarf_form form,
18266                  unsigned int offset_size,
18267                  struct dwarf2_section_info *section)
18268 {
18269   unsigned int bytes_read;
18270
18271   switch (form)
18272     {
18273     case DW_FORM_data1:
18274     case DW_FORM_flag:
18275       ++bytes;
18276       break;
18277
18278     case DW_FORM_data2:
18279       bytes += 2;
18280       break;
18281
18282     case DW_FORM_data4:
18283       bytes += 4;
18284       break;
18285
18286     case DW_FORM_data8:
18287       bytes += 8;
18288       break;
18289
18290     case DW_FORM_string:
18291       read_direct_string (abfd, bytes, &bytes_read);
18292       bytes += bytes_read;
18293       break;
18294
18295     case DW_FORM_sec_offset:
18296     case DW_FORM_strp:
18297     case DW_FORM_GNU_strp_alt:
18298       bytes += offset_size;
18299       break;
18300
18301     case DW_FORM_block:
18302       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18303       bytes += bytes_read;
18304       break;
18305
18306     case DW_FORM_block1:
18307       bytes += 1 + read_1_byte (abfd, bytes);
18308       break;
18309     case DW_FORM_block2:
18310       bytes += 2 + read_2_bytes (abfd, bytes);
18311       break;
18312     case DW_FORM_block4:
18313       bytes += 4 + read_4_bytes (abfd, bytes);
18314       break;
18315
18316     case DW_FORM_sdata:
18317     case DW_FORM_udata:
18318     case DW_FORM_GNU_addr_index:
18319     case DW_FORM_GNU_str_index:
18320       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
18321       if (bytes == NULL)
18322         {
18323           dwarf2_section_buffer_overflow_complaint (section);
18324           return NULL;
18325         }
18326       break;
18327
18328     default:
18329       {
18330       complain:
18331         complaint (&symfile_complaints,
18332                    _("invalid form 0x%x in `%s'"),
18333                    form,
18334                    section->asection->name);
18335         return NULL;
18336       }
18337     }
18338
18339   return bytes;
18340 }
18341
18342 /* A helper for dwarf_decode_macros that handles skipping an unknown
18343    opcode.  Returns an updated pointer to the macro data buffer; or,
18344    on error, issues a complaint and returns NULL.  */
18345
18346 static gdb_byte *
18347 skip_unknown_opcode (unsigned int opcode,
18348                      gdb_byte **opcode_definitions,
18349                      gdb_byte *mac_ptr, gdb_byte *mac_end,
18350                      bfd *abfd,
18351                      unsigned int offset_size,
18352                      struct dwarf2_section_info *section)
18353 {
18354   unsigned int bytes_read, i;
18355   unsigned long arg;
18356   gdb_byte *defn;
18357
18358   if (opcode_definitions[opcode] == NULL)
18359     {
18360       complaint (&symfile_complaints,
18361                  _("unrecognized DW_MACFINO opcode 0x%x"),
18362                  opcode);
18363       return NULL;
18364     }
18365
18366   defn = opcode_definitions[opcode];
18367   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18368   defn += bytes_read;
18369
18370   for (i = 0; i < arg; ++i)
18371     {
18372       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18373                                  section);
18374       if (mac_ptr == NULL)
18375         {
18376           /* skip_form_bytes already issued the complaint.  */
18377           return NULL;
18378         }
18379     }
18380
18381   return mac_ptr;
18382 }
18383
18384 /* A helper function which parses the header of a macro section.
18385    If the macro section is the extended (for now called "GNU") type,
18386    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18387    the header, or issues a complaint and returns NULL on error.  */
18388
18389 static gdb_byte *
18390 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
18391                           bfd *abfd,
18392                           gdb_byte *mac_ptr,
18393                           unsigned int *offset_size,
18394                           int section_is_gnu)
18395 {
18396   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18397
18398   if (section_is_gnu)
18399     {
18400       unsigned int version, flags;
18401
18402       version = read_2_bytes (abfd, mac_ptr);
18403       if (version != 4)
18404         {
18405           complaint (&symfile_complaints,
18406                      _("unrecognized version `%d' in .debug_macro section"),
18407                      version);
18408           return NULL;
18409         }
18410       mac_ptr += 2;
18411
18412       flags = read_1_byte (abfd, mac_ptr);
18413       ++mac_ptr;
18414       *offset_size = (flags & 1) ? 8 : 4;
18415
18416       if ((flags & 2) != 0)
18417         /* We don't need the line table offset.  */
18418         mac_ptr += *offset_size;
18419
18420       /* Vendor opcode descriptions.  */
18421       if ((flags & 4) != 0)
18422         {
18423           unsigned int i, count;
18424
18425           count = read_1_byte (abfd, mac_ptr);
18426           ++mac_ptr;
18427           for (i = 0; i < count; ++i)
18428             {
18429               unsigned int opcode, bytes_read;
18430               unsigned long arg;
18431
18432               opcode = read_1_byte (abfd, mac_ptr);
18433               ++mac_ptr;
18434               opcode_definitions[opcode] = mac_ptr;
18435               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18436               mac_ptr += bytes_read;
18437               mac_ptr += arg;
18438             }
18439         }
18440     }
18441
18442   return mac_ptr;
18443 }
18444
18445 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18446    including DW_MACRO_GNU_transparent_include.  */
18447
18448 static void
18449 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
18450                           struct macro_source_file *current_file,
18451                           struct line_header *lh, const char *comp_dir,
18452                           struct dwarf2_section_info *section,
18453                           int section_is_gnu, int section_is_dwz,
18454                           unsigned int offset_size,
18455                           struct objfile *objfile,
18456                           htab_t include_hash)
18457 {
18458   enum dwarf_macro_record_type macinfo_type;
18459   int at_commandline;
18460   gdb_byte *opcode_definitions[256];
18461
18462   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18463                                       &offset_size, section_is_gnu);
18464   if (mac_ptr == NULL)
18465     {
18466       /* We already issued a complaint.  */
18467       return;
18468     }
18469
18470   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18471      GDB is still reading the definitions from command line.  First
18472      DW_MACINFO_start_file will need to be ignored as it was already executed
18473      to create CURRENT_FILE for the main source holding also the command line
18474      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18475      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18476
18477   at_commandline = 1;
18478
18479   do
18480     {
18481       /* Do we at least have room for a macinfo type byte?  */
18482       if (mac_ptr >= mac_end)
18483         {
18484           dwarf2_section_buffer_overflow_complaint (section);
18485           break;
18486         }
18487
18488       macinfo_type = read_1_byte (abfd, mac_ptr);
18489       mac_ptr++;
18490
18491       /* Note that we rely on the fact that the corresponding GNU and
18492          DWARF constants are the same.  */
18493       switch (macinfo_type)
18494         {
18495           /* A zero macinfo type indicates the end of the macro
18496              information.  */
18497         case 0:
18498           break;
18499
18500         case DW_MACRO_GNU_define:
18501         case DW_MACRO_GNU_undef:
18502         case DW_MACRO_GNU_define_indirect:
18503         case DW_MACRO_GNU_undef_indirect:
18504         case DW_MACRO_GNU_define_indirect_alt:
18505         case DW_MACRO_GNU_undef_indirect_alt:
18506           {
18507             unsigned int bytes_read;
18508             int line;
18509             char *body;
18510             int is_define;
18511
18512             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18513             mac_ptr += bytes_read;
18514
18515             if (macinfo_type == DW_MACRO_GNU_define
18516                 || macinfo_type == DW_MACRO_GNU_undef)
18517               {
18518                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18519                 mac_ptr += bytes_read;
18520               }
18521             else
18522               {
18523                 LONGEST str_offset;
18524
18525                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18526                 mac_ptr += offset_size;
18527
18528                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18529                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18530                     || section_is_dwz)
18531                   {
18532                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18533
18534                     body = read_indirect_string_from_dwz (dwz, str_offset);
18535                   }
18536                 else
18537                   body = read_indirect_string_at_offset (abfd, str_offset);
18538               }
18539
18540             is_define = (macinfo_type == DW_MACRO_GNU_define
18541                          || macinfo_type == DW_MACRO_GNU_define_indirect
18542                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18543             if (! current_file)
18544               {
18545                 /* DWARF violation as no main source is present.  */
18546                 complaint (&symfile_complaints,
18547                            _("debug info with no main source gives macro %s "
18548                              "on line %d: %s"),
18549                            is_define ? _("definition") : _("undefinition"),
18550                            line, body);
18551                 break;
18552               }
18553             if ((line == 0 && !at_commandline)
18554                 || (line != 0 && at_commandline))
18555               complaint (&symfile_complaints,
18556                          _("debug info gives %s macro %s with %s line %d: %s"),
18557                          at_commandline ? _("command-line") : _("in-file"),
18558                          is_define ? _("definition") : _("undefinition"),
18559                          line == 0 ? _("zero") : _("non-zero"), line, body);
18560
18561             if (is_define)
18562               parse_macro_definition (current_file, line, body);
18563             else
18564               {
18565                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18566                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18567                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18568                 macro_undef (current_file, line, body);
18569               }
18570           }
18571           break;
18572
18573         case DW_MACRO_GNU_start_file:
18574           {
18575             unsigned int bytes_read;
18576             int line, file;
18577
18578             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18579             mac_ptr += bytes_read;
18580             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18581             mac_ptr += bytes_read;
18582
18583             if ((line == 0 && !at_commandline)
18584                 || (line != 0 && at_commandline))
18585               complaint (&symfile_complaints,
18586                          _("debug info gives source %d included "
18587                            "from %s at %s line %d"),
18588                          file, at_commandline ? _("command-line") : _("file"),
18589                          line == 0 ? _("zero") : _("non-zero"), line);
18590
18591             if (at_commandline)
18592               {
18593                 /* This DW_MACRO_GNU_start_file was executed in the
18594                    pass one.  */
18595                 at_commandline = 0;
18596               }
18597             else
18598               current_file = macro_start_file (file, line,
18599                                                current_file, comp_dir,
18600                                                lh, objfile);
18601           }
18602           break;
18603
18604         case DW_MACRO_GNU_end_file:
18605           if (! current_file)
18606             complaint (&symfile_complaints,
18607                        _("macro debug info has an unmatched "
18608                          "`close_file' directive"));
18609           else
18610             {
18611               current_file = current_file->included_by;
18612               if (! current_file)
18613                 {
18614                   enum dwarf_macro_record_type next_type;
18615
18616                   /* GCC circa March 2002 doesn't produce the zero
18617                      type byte marking the end of the compilation
18618                      unit.  Complain if it's not there, but exit no
18619                      matter what.  */
18620
18621                   /* Do we at least have room for a macinfo type byte?  */
18622                   if (mac_ptr >= mac_end)
18623                     {
18624                       dwarf2_section_buffer_overflow_complaint (section);
18625                       return;
18626                     }
18627
18628                   /* We don't increment mac_ptr here, so this is just
18629                      a look-ahead.  */
18630                   next_type = read_1_byte (abfd, mac_ptr);
18631                   if (next_type != 0)
18632                     complaint (&symfile_complaints,
18633                                _("no terminating 0-type entry for "
18634                                  "macros in `.debug_macinfo' section"));
18635
18636                   return;
18637                 }
18638             }
18639           break;
18640
18641         case DW_MACRO_GNU_transparent_include:
18642         case DW_MACRO_GNU_transparent_include_alt:
18643           {
18644             LONGEST offset;
18645             void **slot;
18646             bfd *include_bfd = abfd;
18647             struct dwarf2_section_info *include_section = section;
18648             struct dwarf2_section_info alt_section;
18649             gdb_byte *include_mac_end = mac_end;
18650             int is_dwz = section_is_dwz;
18651             gdb_byte *new_mac_ptr;
18652
18653             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18654             mac_ptr += offset_size;
18655
18656             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18657               {
18658                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18659
18660                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18661                                      &dwz->macro);
18662
18663                 include_bfd = dwz->macro.asection->owner;
18664                 include_section = &dwz->macro;
18665                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18666                 is_dwz = 1;
18667               }
18668
18669             new_mac_ptr = include_section->buffer + offset;
18670             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18671
18672             if (*slot != NULL)
18673               {
18674                 /* This has actually happened; see
18675                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18676                 complaint (&symfile_complaints,
18677                            _("recursive DW_MACRO_GNU_transparent_include in "
18678                              ".debug_macro section"));
18679               }
18680             else
18681               {
18682                 *slot = new_mac_ptr;
18683
18684                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18685                                           include_mac_end, current_file,
18686                                           lh, comp_dir,
18687                                           section, section_is_gnu, is_dwz,
18688                                           offset_size, objfile, include_hash);
18689
18690                 htab_remove_elt (include_hash, new_mac_ptr);
18691               }
18692           }
18693           break;
18694
18695         case DW_MACINFO_vendor_ext:
18696           if (!section_is_gnu)
18697             {
18698               unsigned int bytes_read;
18699               int constant;
18700
18701               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18702               mac_ptr += bytes_read;
18703               read_direct_string (abfd, mac_ptr, &bytes_read);
18704               mac_ptr += bytes_read;
18705
18706               /* We don't recognize any vendor extensions.  */
18707               break;
18708             }
18709           /* FALLTHROUGH */
18710
18711         default:
18712           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18713                                          mac_ptr, mac_end, abfd, offset_size,
18714                                          section);
18715           if (mac_ptr == NULL)
18716             return;
18717           break;
18718         }
18719     } while (macinfo_type != 0);
18720 }
18721
18722 static void
18723 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18724                      const char *comp_dir, int section_is_gnu)
18725 {
18726   struct objfile *objfile = dwarf2_per_objfile->objfile;
18727   struct line_header *lh = cu->line_header;
18728   bfd *abfd;
18729   gdb_byte *mac_ptr, *mac_end;
18730   struct macro_source_file *current_file = 0;
18731   enum dwarf_macro_record_type macinfo_type;
18732   unsigned int offset_size = cu->header.offset_size;
18733   gdb_byte *opcode_definitions[256];
18734   struct cleanup *cleanup;
18735   htab_t include_hash;
18736   void **slot;
18737   struct dwarf2_section_info *section;
18738   const char *section_name;
18739
18740   if (cu->dwo_unit != NULL)
18741     {
18742       if (section_is_gnu)
18743         {
18744           section = &cu->dwo_unit->dwo_file->sections.macro;
18745           section_name = ".debug_macro.dwo";
18746         }
18747       else
18748         {
18749           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18750           section_name = ".debug_macinfo.dwo";
18751         }
18752     }
18753   else
18754     {
18755       if (section_is_gnu)
18756         {
18757           section = &dwarf2_per_objfile->macro;
18758           section_name = ".debug_macro";
18759         }
18760       else
18761         {
18762           section = &dwarf2_per_objfile->macinfo;
18763           section_name = ".debug_macinfo";
18764         }
18765     }
18766
18767   dwarf2_read_section (objfile, section);
18768   if (section->buffer == NULL)
18769     {
18770       complaint (&symfile_complaints, _("missing %s section"), section_name);
18771       return;
18772     }
18773   abfd = section->asection->owner;
18774
18775   /* First pass: Find the name of the base filename.
18776      This filename is needed in order to process all macros whose definition
18777      (or undefinition) comes from the command line.  These macros are defined
18778      before the first DW_MACINFO_start_file entry, and yet still need to be
18779      associated to the base file.
18780
18781      To determine the base file name, we scan the macro definitions until we
18782      reach the first DW_MACINFO_start_file entry.  We then initialize
18783      CURRENT_FILE accordingly so that any macro definition found before the
18784      first DW_MACINFO_start_file can still be associated to the base file.  */
18785
18786   mac_ptr = section->buffer + offset;
18787   mac_end = section->buffer + section->size;
18788
18789   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18790                                       &offset_size, section_is_gnu);
18791   if (mac_ptr == NULL)
18792     {
18793       /* We already issued a complaint.  */
18794       return;
18795     }
18796
18797   do
18798     {
18799       /* Do we at least have room for a macinfo type byte?  */
18800       if (mac_ptr >= mac_end)
18801         {
18802           /* Complaint is printed during the second pass as GDB will probably
18803              stop the first pass earlier upon finding
18804              DW_MACINFO_start_file.  */
18805           break;
18806         }
18807
18808       macinfo_type = read_1_byte (abfd, mac_ptr);
18809       mac_ptr++;
18810
18811       /* Note that we rely on the fact that the corresponding GNU and
18812          DWARF constants are the same.  */
18813       switch (macinfo_type)
18814         {
18815           /* A zero macinfo type indicates the end of the macro
18816              information.  */
18817         case 0:
18818           break;
18819
18820         case DW_MACRO_GNU_define:
18821         case DW_MACRO_GNU_undef:
18822           /* Only skip the data by MAC_PTR.  */
18823           {
18824             unsigned int bytes_read;
18825
18826             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18827             mac_ptr += bytes_read;
18828             read_direct_string (abfd, mac_ptr, &bytes_read);
18829             mac_ptr += bytes_read;
18830           }
18831           break;
18832
18833         case DW_MACRO_GNU_start_file:
18834           {
18835             unsigned int bytes_read;
18836             int line, file;
18837
18838             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18839             mac_ptr += bytes_read;
18840             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18841             mac_ptr += bytes_read;
18842
18843             current_file = macro_start_file (file, line, current_file,
18844                                              comp_dir, lh, objfile);
18845           }
18846           break;
18847
18848         case DW_MACRO_GNU_end_file:
18849           /* No data to skip by MAC_PTR.  */
18850           break;
18851
18852         case DW_MACRO_GNU_define_indirect:
18853         case DW_MACRO_GNU_undef_indirect:
18854         case DW_MACRO_GNU_define_indirect_alt:
18855         case DW_MACRO_GNU_undef_indirect_alt:
18856           {
18857             unsigned int bytes_read;
18858
18859             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18860             mac_ptr += bytes_read;
18861             mac_ptr += offset_size;
18862           }
18863           break;
18864
18865         case DW_MACRO_GNU_transparent_include:
18866         case DW_MACRO_GNU_transparent_include_alt:
18867           /* Note that, according to the spec, a transparent include
18868              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
18869              skip this opcode.  */
18870           mac_ptr += offset_size;
18871           break;
18872
18873         case DW_MACINFO_vendor_ext:
18874           /* Only skip the data by MAC_PTR.  */
18875           if (!section_is_gnu)
18876             {
18877               unsigned int bytes_read;
18878
18879               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18880               mac_ptr += bytes_read;
18881               read_direct_string (abfd, mac_ptr, &bytes_read);
18882               mac_ptr += bytes_read;
18883             }
18884           /* FALLTHROUGH */
18885
18886         default:
18887           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18888                                          mac_ptr, mac_end, abfd, offset_size,
18889                                          section);
18890           if (mac_ptr == NULL)
18891             return;
18892           break;
18893         }
18894     } while (macinfo_type != 0 && current_file == NULL);
18895
18896   /* Second pass: Process all entries.
18897
18898      Use the AT_COMMAND_LINE flag to determine whether we are still processing
18899      command-line macro definitions/undefinitions.  This flag is unset when we
18900      reach the first DW_MACINFO_start_file entry.  */
18901
18902   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
18903                                     NULL, xcalloc, xfree);
18904   cleanup = make_cleanup_htab_delete (include_hash);
18905   mac_ptr = section->buffer + offset;
18906   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
18907   *slot = mac_ptr;
18908   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
18909                             current_file, lh, comp_dir, section,
18910                             section_is_gnu, 0,
18911                             offset_size, objfile, include_hash);
18912   do_cleanups (cleanup);
18913 }
18914
18915 /* Check if the attribute's form is a DW_FORM_block*
18916    if so return true else false.  */
18917
18918 static int
18919 attr_form_is_block (struct attribute *attr)
18920 {
18921   return (attr == NULL ? 0 :
18922       attr->form == DW_FORM_block1
18923       || attr->form == DW_FORM_block2
18924       || attr->form == DW_FORM_block4
18925       || attr->form == DW_FORM_block
18926       || attr->form == DW_FORM_exprloc);
18927 }
18928
18929 /* Return non-zero if ATTR's value is a section offset --- classes
18930    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
18931    You may use DW_UNSND (attr) to retrieve such offsets.
18932
18933    Section 7.5.4, "Attribute Encodings", explains that no attribute
18934    may have a value that belongs to more than one of these classes; it
18935    would be ambiguous if we did, because we use the same forms for all
18936    of them.  */
18937
18938 static int
18939 attr_form_is_section_offset (struct attribute *attr)
18940 {
18941   return (attr->form == DW_FORM_data4
18942           || attr->form == DW_FORM_data8
18943           || attr->form == DW_FORM_sec_offset);
18944 }
18945
18946 /* Return non-zero if ATTR's value falls in the 'constant' class, or
18947    zero otherwise.  When this function returns true, you can apply
18948    dwarf2_get_attr_constant_value to it.
18949
18950    However, note that for some attributes you must check
18951    attr_form_is_section_offset before using this test.  DW_FORM_data4
18952    and DW_FORM_data8 are members of both the constant class, and of
18953    the classes that contain offsets into other debug sections
18954    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
18955    that, if an attribute's can be either a constant or one of the
18956    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
18957    taken as section offsets, not constants.  */
18958
18959 static int
18960 attr_form_is_constant (struct attribute *attr)
18961 {
18962   switch (attr->form)
18963     {
18964     case DW_FORM_sdata:
18965     case DW_FORM_udata:
18966     case DW_FORM_data1:
18967     case DW_FORM_data2:
18968     case DW_FORM_data4:
18969     case DW_FORM_data8:
18970       return 1;
18971     default:
18972       return 0;
18973     }
18974 }
18975
18976 /* Return the .debug_loc section to use for CU.
18977    For DWO files use .debug_loc.dwo.  */
18978
18979 static struct dwarf2_section_info *
18980 cu_debug_loc_section (struct dwarf2_cu *cu)
18981 {
18982   if (cu->dwo_unit)
18983     return &cu->dwo_unit->dwo_file->sections.loc;
18984   return &dwarf2_per_objfile->loc;
18985 }
18986
18987 /* A helper function that fills in a dwarf2_loclist_baton.  */
18988
18989 static void
18990 fill_in_loclist_baton (struct dwarf2_cu *cu,
18991                        struct dwarf2_loclist_baton *baton,
18992                        struct attribute *attr)
18993 {
18994   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
18995
18996   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18997
18998   baton->per_cu = cu->per_cu;
18999   gdb_assert (baton->per_cu);
19000   /* We don't know how long the location list is, but make sure we
19001      don't run off the edge of the section.  */
19002   baton->size = section->size - DW_UNSND (attr);
19003   baton->data = section->buffer + DW_UNSND (attr);
19004   baton->base_address = cu->base_address;
19005   baton->from_dwo = cu->dwo_unit != NULL;
19006 }
19007
19008 static void
19009 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19010                              struct dwarf2_cu *cu)
19011 {
19012   struct objfile *objfile = dwarf2_per_objfile->objfile;
19013   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19014
19015   if (attr_form_is_section_offset (attr)
19016       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19017          the section.  If so, fall through to the complaint in the
19018          other branch.  */
19019       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19020     {
19021       struct dwarf2_loclist_baton *baton;
19022
19023       baton = obstack_alloc (&objfile->objfile_obstack,
19024                              sizeof (struct dwarf2_loclist_baton));
19025
19026       fill_in_loclist_baton (cu, baton, attr);
19027
19028       if (cu->base_known == 0)
19029         complaint (&symfile_complaints,
19030                    _("Location list used without "
19031                      "specifying the CU base address."));
19032
19033       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_loclist_funcs;
19034       SYMBOL_LOCATION_BATON (sym) = baton;
19035     }
19036   else
19037     {
19038       struct dwarf2_locexpr_baton *baton;
19039
19040       baton = obstack_alloc (&objfile->objfile_obstack,
19041                              sizeof (struct dwarf2_locexpr_baton));
19042       baton->per_cu = cu->per_cu;
19043       gdb_assert (baton->per_cu);
19044
19045       if (attr_form_is_block (attr))
19046         {
19047           /* Note that we're just copying the block's data pointer
19048              here, not the actual data.  We're still pointing into the
19049              info_buffer for SYM's objfile; right now we never release
19050              that buffer, but when we do clean up properly this may
19051              need to change.  */
19052           baton->size = DW_BLOCK (attr)->size;
19053           baton->data = DW_BLOCK (attr)->data;
19054         }
19055       else
19056         {
19057           dwarf2_invalid_attrib_class_complaint ("location description",
19058                                                  SYMBOL_NATURAL_NAME (sym));
19059           baton->size = 0;
19060         }
19061
19062       SYMBOL_COMPUTED_OPS (sym) = &dwarf2_locexpr_funcs;
19063       SYMBOL_LOCATION_BATON (sym) = baton;
19064     }
19065 }
19066
19067 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19068    came from a separate debuginfo file, then the master objfile is
19069    returned.  */
19070
19071 struct objfile *
19072 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19073 {
19074   struct objfile *objfile = per_cu->objfile;
19075
19076   /* Return the master objfile, so that we can report and look up the
19077      correct file containing this variable.  */
19078   if (objfile->separate_debug_objfile_backlink)
19079     objfile = objfile->separate_debug_objfile_backlink;
19080
19081   return objfile;
19082 }
19083
19084 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19085    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19086    CU_HEADERP first.  */
19087
19088 static const struct comp_unit_head *
19089 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19090                        struct dwarf2_per_cu_data *per_cu)
19091 {
19092   gdb_byte *info_ptr;
19093
19094   if (per_cu->cu)
19095     return &per_cu->cu->header;
19096
19097   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
19098
19099   memset (cu_headerp, 0, sizeof (*cu_headerp));
19100   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19101
19102   return cu_headerp;
19103 }
19104
19105 /* Return the address size given in the compilation unit header for CU.  */
19106
19107 int
19108 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19109 {
19110   struct comp_unit_head cu_header_local;
19111   const struct comp_unit_head *cu_headerp;
19112
19113   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19114
19115   return cu_headerp->addr_size;
19116 }
19117
19118 /* Return the offset size given in the compilation unit header for CU.  */
19119
19120 int
19121 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19122 {
19123   struct comp_unit_head cu_header_local;
19124   const struct comp_unit_head *cu_headerp;
19125
19126   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19127
19128   return cu_headerp->offset_size;
19129 }
19130
19131 /* See its dwarf2loc.h declaration.  */
19132
19133 int
19134 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19135 {
19136   struct comp_unit_head cu_header_local;
19137   const struct comp_unit_head *cu_headerp;
19138
19139   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19140
19141   if (cu_headerp->version == 2)
19142     return cu_headerp->addr_size;
19143   else
19144     return cu_headerp->offset_size;
19145 }
19146
19147 /* Return the text offset of the CU.  The returned offset comes from
19148    this CU's objfile.  If this objfile came from a separate debuginfo
19149    file, then the offset may be different from the corresponding
19150    offset in the parent objfile.  */
19151
19152 CORE_ADDR
19153 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19154 {
19155   struct objfile *objfile = per_cu->objfile;
19156
19157   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19158 }
19159
19160 /* Locate the .debug_info compilation unit from CU's objfile which contains
19161    the DIE at OFFSET.  Raises an error on failure.  */
19162
19163 static struct dwarf2_per_cu_data *
19164 dwarf2_find_containing_comp_unit (sect_offset offset,
19165                                   unsigned int offset_in_dwz,
19166                                   struct objfile *objfile)
19167 {
19168   struct dwarf2_per_cu_data *this_cu;
19169   int low, high;
19170   const sect_offset *cu_off;
19171
19172   low = 0;
19173   high = dwarf2_per_objfile->n_comp_units - 1;
19174   while (high > low)
19175     {
19176       struct dwarf2_per_cu_data *mid_cu;
19177       int mid = low + (high - low) / 2;
19178
19179       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19180       cu_off = &mid_cu->offset;
19181       if (mid_cu->is_dwz > offset_in_dwz
19182           || (mid_cu->is_dwz == offset_in_dwz
19183               && cu_off->sect_off >= offset.sect_off))
19184         high = mid;
19185       else
19186         low = mid + 1;
19187     }
19188   gdb_assert (low == high);
19189   this_cu = dwarf2_per_objfile->all_comp_units[low];
19190   cu_off = &this_cu->offset;
19191   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19192     {
19193       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19194         error (_("Dwarf Error: could not find partial DIE containing "
19195                "offset 0x%lx [in module %s]"),
19196                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19197
19198       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19199                   <= offset.sect_off);
19200       return dwarf2_per_objfile->all_comp_units[low-1];
19201     }
19202   else
19203     {
19204       this_cu = dwarf2_per_objfile->all_comp_units[low];
19205       if (low == dwarf2_per_objfile->n_comp_units - 1
19206           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19207         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19208       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19209       return this_cu;
19210     }
19211 }
19212
19213 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19214
19215 static void
19216 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19217 {
19218   memset (cu, 0, sizeof (*cu));
19219   per_cu->cu = cu;
19220   cu->per_cu = per_cu;
19221   cu->objfile = per_cu->objfile;
19222   obstack_init (&cu->comp_unit_obstack);
19223 }
19224
19225 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19226
19227 static void
19228 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19229                        enum language pretend_language)
19230 {
19231   struct attribute *attr;
19232
19233   /* Set the language we're debugging.  */
19234   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19235   if (attr)
19236     set_cu_language (DW_UNSND (attr), cu);
19237   else
19238     {
19239       cu->language = pretend_language;
19240       cu->language_defn = language_def (cu->language);
19241     }
19242
19243   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19244   if (attr)
19245     cu->producer = DW_STRING (attr);
19246 }
19247
19248 /* Release one cached compilation unit, CU.  We unlink it from the tree
19249    of compilation units, but we don't remove it from the read_in_chain;
19250    the caller is responsible for that.
19251    NOTE: DATA is a void * because this function is also used as a
19252    cleanup routine.  */
19253
19254 static void
19255 free_heap_comp_unit (void *data)
19256 {
19257   struct dwarf2_cu *cu = data;
19258
19259   gdb_assert (cu->per_cu != NULL);
19260   cu->per_cu->cu = NULL;
19261   cu->per_cu = NULL;
19262
19263   obstack_free (&cu->comp_unit_obstack, NULL);
19264
19265   xfree (cu);
19266 }
19267
19268 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19269    when we're finished with it.  We can't free the pointer itself, but be
19270    sure to unlink it from the cache.  Also release any associated storage.  */
19271
19272 static void
19273 free_stack_comp_unit (void *data)
19274 {
19275   struct dwarf2_cu *cu = data;
19276
19277   gdb_assert (cu->per_cu != NULL);
19278   cu->per_cu->cu = NULL;
19279   cu->per_cu = NULL;
19280
19281   obstack_free (&cu->comp_unit_obstack, NULL);
19282   cu->partial_dies = NULL;
19283 }
19284
19285 /* Free all cached compilation units.  */
19286
19287 static void
19288 free_cached_comp_units (void *data)
19289 {
19290   struct dwarf2_per_cu_data *per_cu, **last_chain;
19291
19292   per_cu = dwarf2_per_objfile->read_in_chain;
19293   last_chain = &dwarf2_per_objfile->read_in_chain;
19294   while (per_cu != NULL)
19295     {
19296       struct dwarf2_per_cu_data *next_cu;
19297
19298       next_cu = per_cu->cu->read_in_chain;
19299
19300       free_heap_comp_unit (per_cu->cu);
19301       *last_chain = next_cu;
19302
19303       per_cu = next_cu;
19304     }
19305 }
19306
19307 /* Increase the age counter on each cached compilation unit, and free
19308    any that are too old.  */
19309
19310 static void
19311 age_cached_comp_units (void)
19312 {
19313   struct dwarf2_per_cu_data *per_cu, **last_chain;
19314
19315   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19316   per_cu = dwarf2_per_objfile->read_in_chain;
19317   while (per_cu != NULL)
19318     {
19319       per_cu->cu->last_used ++;
19320       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19321         dwarf2_mark (per_cu->cu);
19322       per_cu = per_cu->cu->read_in_chain;
19323     }
19324
19325   per_cu = dwarf2_per_objfile->read_in_chain;
19326   last_chain = &dwarf2_per_objfile->read_in_chain;
19327   while (per_cu != NULL)
19328     {
19329       struct dwarf2_per_cu_data *next_cu;
19330
19331       next_cu = per_cu->cu->read_in_chain;
19332
19333       if (!per_cu->cu->mark)
19334         {
19335           free_heap_comp_unit (per_cu->cu);
19336           *last_chain = next_cu;
19337         }
19338       else
19339         last_chain = &per_cu->cu->read_in_chain;
19340
19341       per_cu = next_cu;
19342     }
19343 }
19344
19345 /* Remove a single compilation unit from the cache.  */
19346
19347 static void
19348 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19349 {
19350   struct dwarf2_per_cu_data *per_cu, **last_chain;
19351
19352   per_cu = dwarf2_per_objfile->read_in_chain;
19353   last_chain = &dwarf2_per_objfile->read_in_chain;
19354   while (per_cu != NULL)
19355     {
19356       struct dwarf2_per_cu_data *next_cu;
19357
19358       next_cu = per_cu->cu->read_in_chain;
19359
19360       if (per_cu == target_per_cu)
19361         {
19362           free_heap_comp_unit (per_cu->cu);
19363           per_cu->cu = NULL;
19364           *last_chain = next_cu;
19365           break;
19366         }
19367       else
19368         last_chain = &per_cu->cu->read_in_chain;
19369
19370       per_cu = next_cu;
19371     }
19372 }
19373
19374 /* Release all extra memory associated with OBJFILE.  */
19375
19376 void
19377 dwarf2_free_objfile (struct objfile *objfile)
19378 {
19379   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19380
19381   if (dwarf2_per_objfile == NULL)
19382     return;
19383
19384   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19385   free_cached_comp_units (NULL);
19386
19387   if (dwarf2_per_objfile->quick_file_names_table)
19388     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19389
19390   /* Everything else should be on the objfile obstack.  */
19391 }
19392
19393 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19394    We store these in a hash table separate from the DIEs, and preserve them
19395    when the DIEs are flushed out of cache.
19396
19397    The CU "per_cu" pointer is needed because offset alone is not enough to
19398    uniquely identify the type.  A file may have multiple .debug_types sections,
19399    or the type may come from a DWO file.  We have to use something in
19400    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
19401    routine, get_die_type_at_offset, from outside this file, and thus won't
19402    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
19403    of the objfile.  */
19404
19405 struct dwarf2_per_cu_offset_and_type
19406 {
19407   const struct dwarf2_per_cu_data *per_cu;
19408   sect_offset offset;
19409   struct type *type;
19410 };
19411
19412 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19413
19414 static hashval_t
19415 per_cu_offset_and_type_hash (const void *item)
19416 {
19417   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19418
19419   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19420 }
19421
19422 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19423
19424 static int
19425 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19426 {
19427   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19428   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19429
19430   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19431           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19432 }
19433
19434 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19435    table if necessary.  For convenience, return TYPE.
19436
19437    The DIEs reading must have careful ordering to:
19438     * Not cause infite loops trying to read in DIEs as a prerequisite for
19439       reading current DIE.
19440     * Not trying to dereference contents of still incompletely read in types
19441       while reading in other DIEs.
19442     * Enable referencing still incompletely read in types just by a pointer to
19443       the type without accessing its fields.
19444
19445    Therefore caller should follow these rules:
19446      * Try to fetch any prerequisite types we may need to build this DIE type
19447        before building the type and calling set_die_type.
19448      * After building type call set_die_type for current DIE as soon as
19449        possible before fetching more types to complete the current type.
19450      * Make the type as complete as possible before fetching more types.  */
19451
19452 static struct type *
19453 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19454 {
19455   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19456   struct objfile *objfile = cu->objfile;
19457
19458   /* For Ada types, make sure that the gnat-specific data is always
19459      initialized (if not already set).  There are a few types where
19460      we should not be doing so, because the type-specific area is
19461      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19462      where the type-specific area is used to store the floatformat).
19463      But this is not a problem, because the gnat-specific information
19464      is actually not needed for these types.  */
19465   if (need_gnat_info (cu)
19466       && TYPE_CODE (type) != TYPE_CODE_FUNC
19467       && TYPE_CODE (type) != TYPE_CODE_FLT
19468       && !HAVE_GNAT_AUX_INFO (type))
19469     INIT_GNAT_SPECIFIC (type);
19470
19471   if (dwarf2_per_objfile->die_type_hash == NULL)
19472     {
19473       dwarf2_per_objfile->die_type_hash =
19474         htab_create_alloc_ex (127,
19475                               per_cu_offset_and_type_hash,
19476                               per_cu_offset_and_type_eq,
19477                               NULL,
19478                               &objfile->objfile_obstack,
19479                               hashtab_obstack_allocate,
19480                               dummy_obstack_deallocate);
19481     }
19482
19483   ofs.per_cu = cu->per_cu;
19484   ofs.offset = die->offset;
19485   ofs.type = type;
19486   slot = (struct dwarf2_per_cu_offset_and_type **)
19487     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19488   if (*slot)
19489     complaint (&symfile_complaints,
19490                _("A problem internal to GDB: DIE 0x%x has type already set"),
19491                die->offset.sect_off);
19492   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19493   **slot = ofs;
19494   return type;
19495 }
19496
19497 /* Look up the type for the die at OFFSET in the appropriate type_hash
19498    table, or return NULL if the die does not have a saved type.  */
19499
19500 static struct type *
19501 get_die_type_at_offset (sect_offset offset,
19502                         struct dwarf2_per_cu_data *per_cu)
19503 {
19504   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19505
19506   if (dwarf2_per_objfile->die_type_hash == NULL)
19507     return NULL;
19508
19509   ofs.per_cu = per_cu;
19510   ofs.offset = offset;
19511   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19512   if (slot)
19513     return slot->type;
19514   else
19515     return NULL;
19516 }
19517
19518 /* Look up the type for DIE in the appropriate type_hash table,
19519    or return NULL if DIE does not have a saved type.  */
19520
19521 static struct type *
19522 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19523 {
19524   return get_die_type_at_offset (die->offset, cu->per_cu);
19525 }
19526
19527 /* Add a dependence relationship from CU to REF_PER_CU.  */
19528
19529 static void
19530 dwarf2_add_dependence (struct dwarf2_cu *cu,
19531                        struct dwarf2_per_cu_data *ref_per_cu)
19532 {
19533   void **slot;
19534
19535   if (cu->dependencies == NULL)
19536     cu->dependencies
19537       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19538                               NULL, &cu->comp_unit_obstack,
19539                               hashtab_obstack_allocate,
19540                               dummy_obstack_deallocate);
19541
19542   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19543   if (*slot == NULL)
19544     *slot = ref_per_cu;
19545 }
19546
19547 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19548    Set the mark field in every compilation unit in the
19549    cache that we must keep because we are keeping CU.  */
19550
19551 static int
19552 dwarf2_mark_helper (void **slot, void *data)
19553 {
19554   struct dwarf2_per_cu_data *per_cu;
19555
19556   per_cu = (struct dwarf2_per_cu_data *) *slot;
19557
19558   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19559      reading of the chain.  As such dependencies remain valid it is not much
19560      useful to track and undo them during QUIT cleanups.  */
19561   if (per_cu->cu == NULL)
19562     return 1;
19563
19564   if (per_cu->cu->mark)
19565     return 1;
19566   per_cu->cu->mark = 1;
19567
19568   if (per_cu->cu->dependencies != NULL)
19569     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19570
19571   return 1;
19572 }
19573
19574 /* Set the mark field in CU and in every other compilation unit in the
19575    cache that we must keep because we are keeping CU.  */
19576
19577 static void
19578 dwarf2_mark (struct dwarf2_cu *cu)
19579 {
19580   if (cu->mark)
19581     return;
19582   cu->mark = 1;
19583   if (cu->dependencies != NULL)
19584     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19585 }
19586
19587 static void
19588 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19589 {
19590   while (per_cu)
19591     {
19592       per_cu->cu->mark = 0;
19593       per_cu = per_cu->cu->read_in_chain;
19594     }
19595 }
19596
19597 /* Trivial hash function for partial_die_info: the hash value of a DIE
19598    is its offset in .debug_info for this objfile.  */
19599
19600 static hashval_t
19601 partial_die_hash (const void *item)
19602 {
19603   const struct partial_die_info *part_die = item;
19604
19605   return part_die->offset.sect_off;
19606 }
19607
19608 /* Trivial comparison function for partial_die_info structures: two DIEs
19609    are equal if they have the same offset.  */
19610
19611 static int
19612 partial_die_eq (const void *item_lhs, const void *item_rhs)
19613 {
19614   const struct partial_die_info *part_die_lhs = item_lhs;
19615   const struct partial_die_info *part_die_rhs = item_rhs;
19616
19617   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19618 }
19619
19620 static struct cmd_list_element *set_dwarf2_cmdlist;
19621 static struct cmd_list_element *show_dwarf2_cmdlist;
19622
19623 static void
19624 set_dwarf2_cmd (char *args, int from_tty)
19625 {
19626   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19627 }
19628
19629 static void
19630 show_dwarf2_cmd (char *args, int from_tty)
19631 {
19632   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19633 }
19634
19635 /* Free data associated with OBJFILE, if necessary.  */
19636
19637 static void
19638 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19639 {
19640   struct dwarf2_per_objfile *data = d;
19641   int ix;
19642
19643   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19644     VEC_free (dwarf2_per_cu_ptr,
19645               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19646
19647   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19648     VEC_free (dwarf2_per_cu_ptr,
19649               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19650
19651   VEC_free (dwarf2_section_info_def, data->types);
19652
19653   if (data->dwo_files)
19654     free_dwo_files (data->dwo_files, objfile);
19655
19656   if (data->dwz_file && data->dwz_file->dwz_bfd)
19657     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19658 }
19659
19660 \f
19661 /* The "save gdb-index" command.  */
19662
19663 /* The contents of the hash table we create when building the string
19664    table.  */
19665 struct strtab_entry
19666 {
19667   offset_type offset;
19668   const char *str;
19669 };
19670
19671 /* Hash function for a strtab_entry.
19672
19673    Function is used only during write_hash_table so no index format backward
19674    compatibility is needed.  */
19675
19676 static hashval_t
19677 hash_strtab_entry (const void *e)
19678 {
19679   const struct strtab_entry *entry = e;
19680   return mapped_index_string_hash (INT_MAX, entry->str);
19681 }
19682
19683 /* Equality function for a strtab_entry.  */
19684
19685 static int
19686 eq_strtab_entry (const void *a, const void *b)
19687 {
19688   const struct strtab_entry *ea = a;
19689   const struct strtab_entry *eb = b;
19690   return !strcmp (ea->str, eb->str);
19691 }
19692
19693 /* Create a strtab_entry hash table.  */
19694
19695 static htab_t
19696 create_strtab (void)
19697 {
19698   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19699                             xfree, xcalloc, xfree);
19700 }
19701
19702 /* Add a string to the constant pool.  Return the string's offset in
19703    host order.  */
19704
19705 static offset_type
19706 add_string (htab_t table, struct obstack *cpool, const char *str)
19707 {
19708   void **slot;
19709   struct strtab_entry entry;
19710   struct strtab_entry *result;
19711
19712   entry.str = str;
19713   slot = htab_find_slot (table, &entry, INSERT);
19714   if (*slot)
19715     result = *slot;
19716   else
19717     {
19718       result = XNEW (struct strtab_entry);
19719       result->offset = obstack_object_size (cpool);
19720       result->str = str;
19721       obstack_grow_str0 (cpool, str);
19722       *slot = result;
19723     }
19724   return result->offset;
19725 }
19726
19727 /* An entry in the symbol table.  */
19728 struct symtab_index_entry
19729 {
19730   /* The name of the symbol.  */
19731   const char *name;
19732   /* The offset of the name in the constant pool.  */
19733   offset_type index_offset;
19734   /* A sorted vector of the indices of all the CUs that hold an object
19735      of this name.  */
19736   VEC (offset_type) *cu_indices;
19737 };
19738
19739 /* The symbol table.  This is a power-of-2-sized hash table.  */
19740 struct mapped_symtab
19741 {
19742   offset_type n_elements;
19743   offset_type size;
19744   struct symtab_index_entry **data;
19745 };
19746
19747 /* Hash function for a symtab_index_entry.  */
19748
19749 static hashval_t
19750 hash_symtab_entry (const void *e)
19751 {
19752   const struct symtab_index_entry *entry = e;
19753   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19754                          sizeof (offset_type) * VEC_length (offset_type,
19755                                                             entry->cu_indices),
19756                          0);
19757 }
19758
19759 /* Equality function for a symtab_index_entry.  */
19760
19761 static int
19762 eq_symtab_entry (const void *a, const void *b)
19763 {
19764   const struct symtab_index_entry *ea = a;
19765   const struct symtab_index_entry *eb = b;
19766   int len = VEC_length (offset_type, ea->cu_indices);
19767   if (len != VEC_length (offset_type, eb->cu_indices))
19768     return 0;
19769   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19770                   VEC_address (offset_type, eb->cu_indices),
19771                   sizeof (offset_type) * len);
19772 }
19773
19774 /* Destroy a symtab_index_entry.  */
19775
19776 static void
19777 delete_symtab_entry (void *p)
19778 {
19779   struct symtab_index_entry *entry = p;
19780   VEC_free (offset_type, entry->cu_indices);
19781   xfree (entry);
19782 }
19783
19784 /* Create a hash table holding symtab_index_entry objects.  */
19785
19786 static htab_t
19787 create_symbol_hash_table (void)
19788 {
19789   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19790                             delete_symtab_entry, xcalloc, xfree);
19791 }
19792
19793 /* Create a new mapped symtab object.  */
19794
19795 static struct mapped_symtab *
19796 create_mapped_symtab (void)
19797 {
19798   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
19799   symtab->n_elements = 0;
19800   symtab->size = 1024;
19801   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19802   return symtab;
19803 }
19804
19805 /* Destroy a mapped_symtab.  */
19806
19807 static void
19808 cleanup_mapped_symtab (void *p)
19809 {
19810   struct mapped_symtab *symtab = p;
19811   /* The contents of the array are freed when the other hash table is
19812      destroyed.  */
19813   xfree (symtab->data);
19814   xfree (symtab);
19815 }
19816
19817 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
19818    the slot.
19819    
19820    Function is used only during write_hash_table so no index format backward
19821    compatibility is needed.  */
19822
19823 static struct symtab_index_entry **
19824 find_slot (struct mapped_symtab *symtab, const char *name)
19825 {
19826   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
19827
19828   index = hash & (symtab->size - 1);
19829   step = ((hash * 17) & (symtab->size - 1)) | 1;
19830
19831   for (;;)
19832     {
19833       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
19834         return &symtab->data[index];
19835       index = (index + step) & (symtab->size - 1);
19836     }
19837 }
19838
19839 /* Expand SYMTAB's hash table.  */
19840
19841 static void
19842 hash_expand (struct mapped_symtab *symtab)
19843 {
19844   offset_type old_size = symtab->size;
19845   offset_type i;
19846   struct symtab_index_entry **old_entries = symtab->data;
19847
19848   symtab->size *= 2;
19849   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19850
19851   for (i = 0; i < old_size; ++i)
19852     {
19853       if (old_entries[i])
19854         {
19855           struct symtab_index_entry **slot = find_slot (symtab,
19856                                                         old_entries[i]->name);
19857           *slot = old_entries[i];
19858         }
19859     }
19860
19861   xfree (old_entries);
19862 }
19863
19864 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
19865    CU_INDEX is the index of the CU in which the symbol appears.
19866    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
19867
19868 static void
19869 add_index_entry (struct mapped_symtab *symtab, const char *name,
19870                  int is_static, gdb_index_symbol_kind kind,
19871                  offset_type cu_index)
19872 {
19873   struct symtab_index_entry **slot;
19874   offset_type cu_index_and_attrs;
19875
19876   ++symtab->n_elements;
19877   if (4 * symtab->n_elements / 3 >= symtab->size)
19878     hash_expand (symtab);
19879
19880   slot = find_slot (symtab, name);
19881   if (!*slot)
19882     {
19883       *slot = XNEW (struct symtab_index_entry);
19884       (*slot)->name = name;
19885       /* index_offset is set later.  */
19886       (*slot)->cu_indices = NULL;
19887     }
19888
19889   cu_index_and_attrs = 0;
19890   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
19891   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
19892   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
19893
19894   /* We don't want to record an index value twice as we want to avoid the
19895      duplication.
19896      We process all global symbols and then all static symbols
19897      (which would allow us to avoid the duplication by only having to check
19898      the last entry pushed), but a symbol could have multiple kinds in one CU.
19899      To keep things simple we don't worry about the duplication here and
19900      sort and uniqufy the list after we've processed all symbols.  */
19901   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
19902 }
19903
19904 /* qsort helper routine for uniquify_cu_indices.  */
19905
19906 static int
19907 offset_type_compare (const void *ap, const void *bp)
19908 {
19909   offset_type a = *(offset_type *) ap;
19910   offset_type b = *(offset_type *) bp;
19911
19912   return (a > b) - (b > a);
19913 }
19914
19915 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
19916
19917 static void
19918 uniquify_cu_indices (struct mapped_symtab *symtab)
19919 {
19920   int i;
19921
19922   for (i = 0; i < symtab->size; ++i)
19923     {
19924       struct symtab_index_entry *entry = symtab->data[i];
19925
19926       if (entry
19927           && entry->cu_indices != NULL)
19928         {
19929           unsigned int next_to_insert, next_to_check;
19930           offset_type last_value;
19931
19932           qsort (VEC_address (offset_type, entry->cu_indices),
19933                  VEC_length (offset_type, entry->cu_indices),
19934                  sizeof (offset_type), offset_type_compare);
19935
19936           last_value = VEC_index (offset_type, entry->cu_indices, 0);
19937           next_to_insert = 1;
19938           for (next_to_check = 1;
19939                next_to_check < VEC_length (offset_type, entry->cu_indices);
19940                ++next_to_check)
19941             {
19942               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
19943                   != last_value)
19944                 {
19945                   last_value = VEC_index (offset_type, entry->cu_indices,
19946                                           next_to_check);
19947                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
19948                                last_value);
19949                   ++next_to_insert;
19950                 }
19951             }
19952           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
19953         }
19954     }
19955 }
19956
19957 /* Add a vector of indices to the constant pool.  */
19958
19959 static offset_type
19960 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
19961                       struct symtab_index_entry *entry)
19962 {
19963   void **slot;
19964
19965   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
19966   if (!*slot)
19967     {
19968       offset_type len = VEC_length (offset_type, entry->cu_indices);
19969       offset_type val = MAYBE_SWAP (len);
19970       offset_type iter;
19971       int i;
19972
19973       *slot = entry;
19974       entry->index_offset = obstack_object_size (cpool);
19975
19976       obstack_grow (cpool, &val, sizeof (val));
19977       for (i = 0;
19978            VEC_iterate (offset_type, entry->cu_indices, i, iter);
19979            ++i)
19980         {
19981           val = MAYBE_SWAP (iter);
19982           obstack_grow (cpool, &val, sizeof (val));
19983         }
19984     }
19985   else
19986     {
19987       struct symtab_index_entry *old_entry = *slot;
19988       entry->index_offset = old_entry->index_offset;
19989       entry = old_entry;
19990     }
19991   return entry->index_offset;
19992 }
19993
19994 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
19995    constant pool entries going into the obstack CPOOL.  */
19996
19997 static void
19998 write_hash_table (struct mapped_symtab *symtab,
19999                   struct obstack *output, struct obstack *cpool)
20000 {
20001   offset_type i;
20002   htab_t symbol_hash_table;
20003   htab_t str_table;
20004
20005   symbol_hash_table = create_symbol_hash_table ();
20006   str_table = create_strtab ();
20007
20008   /* We add all the index vectors to the constant pool first, to
20009      ensure alignment is ok.  */
20010   for (i = 0; i < symtab->size; ++i)
20011     {
20012       if (symtab->data[i])
20013         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20014     }
20015
20016   /* Now write out the hash table.  */
20017   for (i = 0; i < symtab->size; ++i)
20018     {
20019       offset_type str_off, vec_off;
20020
20021       if (symtab->data[i])
20022         {
20023           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20024           vec_off = symtab->data[i]->index_offset;
20025         }
20026       else
20027         {
20028           /* While 0 is a valid constant pool index, it is not valid
20029              to have 0 for both offsets.  */
20030           str_off = 0;
20031           vec_off = 0;
20032         }
20033
20034       str_off = MAYBE_SWAP (str_off);
20035       vec_off = MAYBE_SWAP (vec_off);
20036
20037       obstack_grow (output, &str_off, sizeof (str_off));
20038       obstack_grow (output, &vec_off, sizeof (vec_off));
20039     }
20040
20041   htab_delete (str_table);
20042   htab_delete (symbol_hash_table);
20043 }
20044
20045 /* Struct to map psymtab to CU index in the index file.  */
20046 struct psymtab_cu_index_map
20047 {
20048   struct partial_symtab *psymtab;
20049   unsigned int cu_index;
20050 };
20051
20052 static hashval_t
20053 hash_psymtab_cu_index (const void *item)
20054 {
20055   const struct psymtab_cu_index_map *map = item;
20056
20057   return htab_hash_pointer (map->psymtab);
20058 }
20059
20060 static int
20061 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20062 {
20063   const struct psymtab_cu_index_map *lhs = item_lhs;
20064   const struct psymtab_cu_index_map *rhs = item_rhs;
20065
20066   return lhs->psymtab == rhs->psymtab;
20067 }
20068
20069 /* Helper struct for building the address table.  */
20070 struct addrmap_index_data
20071 {
20072   struct objfile *objfile;
20073   struct obstack *addr_obstack;
20074   htab_t cu_index_htab;
20075
20076   /* Non-zero if the previous_* fields are valid.
20077      We can't write an entry until we see the next entry (since it is only then
20078      that we know the end of the entry).  */
20079   int previous_valid;
20080   /* Index of the CU in the table of all CUs in the index file.  */
20081   unsigned int previous_cu_index;
20082   /* Start address of the CU.  */
20083   CORE_ADDR previous_cu_start;
20084 };
20085
20086 /* Write an address entry to OBSTACK.  */
20087
20088 static void
20089 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20090                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20091 {
20092   offset_type cu_index_to_write;
20093   char addr[8];
20094   CORE_ADDR baseaddr;
20095
20096   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20097
20098   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20099   obstack_grow (obstack, addr, 8);
20100   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20101   obstack_grow (obstack, addr, 8);
20102   cu_index_to_write = MAYBE_SWAP (cu_index);
20103   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20104 }
20105
20106 /* Worker function for traversing an addrmap to build the address table.  */
20107
20108 static int
20109 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20110 {
20111   struct addrmap_index_data *data = datap;
20112   struct partial_symtab *pst = obj;
20113
20114   if (data->previous_valid)
20115     add_address_entry (data->objfile, data->addr_obstack,
20116                        data->previous_cu_start, start_addr,
20117                        data->previous_cu_index);
20118
20119   data->previous_cu_start = start_addr;
20120   if (pst != NULL)
20121     {
20122       struct psymtab_cu_index_map find_map, *map;
20123       find_map.psymtab = pst;
20124       map = htab_find (data->cu_index_htab, &find_map);
20125       gdb_assert (map != NULL);
20126       data->previous_cu_index = map->cu_index;
20127       data->previous_valid = 1;
20128     }
20129   else
20130       data->previous_valid = 0;
20131
20132   return 0;
20133 }
20134
20135 /* Write OBJFILE's address map to OBSTACK.
20136    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20137    in the index file.  */
20138
20139 static void
20140 write_address_map (struct objfile *objfile, struct obstack *obstack,
20141                    htab_t cu_index_htab)
20142 {
20143   struct addrmap_index_data addrmap_index_data;
20144
20145   /* When writing the address table, we have to cope with the fact that
20146      the addrmap iterator only provides the start of a region; we have to
20147      wait until the next invocation to get the start of the next region.  */
20148
20149   addrmap_index_data.objfile = objfile;
20150   addrmap_index_data.addr_obstack = obstack;
20151   addrmap_index_data.cu_index_htab = cu_index_htab;
20152   addrmap_index_data.previous_valid = 0;
20153
20154   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20155                    &addrmap_index_data);
20156
20157   /* It's highly unlikely the last entry (end address = 0xff...ff)
20158      is valid, but we should still handle it.
20159      The end address is recorded as the start of the next region, but that
20160      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20161      anyway.  */
20162   if (addrmap_index_data.previous_valid)
20163     add_address_entry (objfile, obstack,
20164                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20165                        addrmap_index_data.previous_cu_index);
20166 }
20167
20168 /* Return the symbol kind of PSYM.  */
20169
20170 static gdb_index_symbol_kind
20171 symbol_kind (struct partial_symbol *psym)
20172 {
20173   domain_enum domain = PSYMBOL_DOMAIN (psym);
20174   enum address_class aclass = PSYMBOL_CLASS (psym);
20175
20176   switch (domain)
20177     {
20178     case VAR_DOMAIN:
20179       switch (aclass)
20180         {
20181         case LOC_BLOCK:
20182           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20183         case LOC_TYPEDEF:
20184           return GDB_INDEX_SYMBOL_KIND_TYPE;
20185         case LOC_COMPUTED:
20186         case LOC_CONST_BYTES:
20187         case LOC_OPTIMIZED_OUT:
20188         case LOC_STATIC:
20189           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20190         case LOC_CONST:
20191           /* Note: It's currently impossible to recognize psyms as enum values
20192              short of reading the type info.  For now punt.  */
20193           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20194         default:
20195           /* There are other LOC_FOO values that one might want to classify
20196              as variables, but dwarf2read.c doesn't currently use them.  */
20197           return GDB_INDEX_SYMBOL_KIND_OTHER;
20198         }
20199     case STRUCT_DOMAIN:
20200       return GDB_INDEX_SYMBOL_KIND_TYPE;
20201     default:
20202       return GDB_INDEX_SYMBOL_KIND_OTHER;
20203     }
20204 }
20205
20206 /* Add a list of partial symbols to SYMTAB.  */
20207
20208 static void
20209 write_psymbols (struct mapped_symtab *symtab,
20210                 htab_t psyms_seen,
20211                 struct partial_symbol **psymp,
20212                 int count,
20213                 offset_type cu_index,
20214                 int is_static)
20215 {
20216   for (; count-- > 0; ++psymp)
20217     {
20218       struct partial_symbol *psym = *psymp;
20219       void **slot;
20220
20221       if (SYMBOL_LANGUAGE (psym) == language_ada)
20222         error (_("Ada is not currently supported by the index"));
20223
20224       /* Only add a given psymbol once.  */
20225       slot = htab_find_slot (psyms_seen, psym, INSERT);
20226       if (!*slot)
20227         {
20228           gdb_index_symbol_kind kind = symbol_kind (psym);
20229
20230           *slot = psym;
20231           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20232                            is_static, kind, cu_index);
20233         }
20234     }
20235 }
20236
20237 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20238    exception if there is an error.  */
20239
20240 static void
20241 write_obstack (FILE *file, struct obstack *obstack)
20242 {
20243   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20244               file)
20245       != obstack_object_size (obstack))
20246     error (_("couldn't data write to file"));
20247 }
20248
20249 /* Unlink a file if the argument is not NULL.  */
20250
20251 static void
20252 unlink_if_set (void *p)
20253 {
20254   char **filename = p;
20255   if (*filename)
20256     unlink (*filename);
20257 }
20258
20259 /* A helper struct used when iterating over debug_types.  */
20260 struct signatured_type_index_data
20261 {
20262   struct objfile *objfile;
20263   struct mapped_symtab *symtab;
20264   struct obstack *types_list;
20265   htab_t psyms_seen;
20266   int cu_index;
20267 };
20268
20269 /* A helper function that writes a single signatured_type to an
20270    obstack.  */
20271
20272 static int
20273 write_one_signatured_type (void **slot, void *d)
20274 {
20275   struct signatured_type_index_data *info = d;
20276   struct signatured_type *entry = (struct signatured_type *) *slot;
20277   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
20278   struct partial_symtab *psymtab = per_cu->v.psymtab;
20279   gdb_byte val[8];
20280
20281   write_psymbols (info->symtab,
20282                   info->psyms_seen,
20283                   info->objfile->global_psymbols.list
20284                   + psymtab->globals_offset,
20285                   psymtab->n_global_syms, info->cu_index,
20286                   0);
20287   write_psymbols (info->symtab,
20288                   info->psyms_seen,
20289                   info->objfile->static_psymbols.list
20290                   + psymtab->statics_offset,
20291                   psymtab->n_static_syms, info->cu_index,
20292                   1);
20293
20294   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20295                           entry->per_cu.offset.sect_off);
20296   obstack_grow (info->types_list, val, 8);
20297   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20298                           entry->type_offset_in_tu.cu_off);
20299   obstack_grow (info->types_list, val, 8);
20300   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20301   obstack_grow (info->types_list, val, 8);
20302
20303   ++info->cu_index;
20304
20305   return 1;
20306 }
20307
20308 /* Recurse into all "included" dependencies and write their symbols as
20309    if they appeared in this psymtab.  */
20310
20311 static void
20312 recursively_write_psymbols (struct objfile *objfile,
20313                             struct partial_symtab *psymtab,
20314                             struct mapped_symtab *symtab,
20315                             htab_t psyms_seen,
20316                             offset_type cu_index)
20317 {
20318   int i;
20319
20320   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20321     if (psymtab->dependencies[i]->user != NULL)
20322       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20323                                   symtab, psyms_seen, cu_index);
20324
20325   write_psymbols (symtab,
20326                   psyms_seen,
20327                   objfile->global_psymbols.list + psymtab->globals_offset,
20328                   psymtab->n_global_syms, cu_index,
20329                   0);
20330   write_psymbols (symtab,
20331                   psyms_seen,
20332                   objfile->static_psymbols.list + psymtab->statics_offset,
20333                   psymtab->n_static_syms, cu_index,
20334                   1);
20335 }
20336
20337 /* Create an index file for OBJFILE in the directory DIR.  */
20338
20339 static void
20340 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20341 {
20342   struct cleanup *cleanup;
20343   char *filename, *cleanup_filename;
20344   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20345   struct obstack cu_list, types_cu_list;
20346   int i;
20347   FILE *out_file;
20348   struct mapped_symtab *symtab;
20349   offset_type val, size_of_contents, total_len;
20350   struct stat st;
20351   htab_t psyms_seen;
20352   htab_t cu_index_htab;
20353   struct psymtab_cu_index_map *psymtab_cu_index_map;
20354
20355   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20356     return;
20357
20358   if (dwarf2_per_objfile->using_index)
20359     error (_("Cannot use an index to create the index"));
20360
20361   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20362     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20363
20364   if (stat (objfile->name, &st) < 0)
20365     perror_with_name (objfile->name);
20366
20367   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20368                      INDEX_SUFFIX, (char *) NULL);
20369   cleanup = make_cleanup (xfree, filename);
20370
20371   out_file = fopen (filename, "wb");
20372   if (!out_file)
20373     error (_("Can't open `%s' for writing"), filename);
20374
20375   cleanup_filename = filename;
20376   make_cleanup (unlink_if_set, &cleanup_filename);
20377
20378   symtab = create_mapped_symtab ();
20379   make_cleanup (cleanup_mapped_symtab, symtab);
20380
20381   obstack_init (&addr_obstack);
20382   make_cleanup_obstack_free (&addr_obstack);
20383
20384   obstack_init (&cu_list);
20385   make_cleanup_obstack_free (&cu_list);
20386
20387   obstack_init (&types_cu_list);
20388   make_cleanup_obstack_free (&types_cu_list);
20389
20390   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20391                                   NULL, xcalloc, xfree);
20392   make_cleanup_htab_delete (psyms_seen);
20393
20394   /* While we're scanning CU's create a table that maps a psymtab pointer
20395      (which is what addrmap records) to its index (which is what is recorded
20396      in the index file).  This will later be needed to write the address
20397      table.  */
20398   cu_index_htab = htab_create_alloc (100,
20399                                      hash_psymtab_cu_index,
20400                                      eq_psymtab_cu_index,
20401                                      NULL, xcalloc, xfree);
20402   make_cleanup_htab_delete (cu_index_htab);
20403   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20404     xmalloc (sizeof (struct psymtab_cu_index_map)
20405              * dwarf2_per_objfile->n_comp_units);
20406   make_cleanup (xfree, psymtab_cu_index_map);
20407
20408   /* The CU list is already sorted, so we don't need to do additional
20409      work here.  Also, the debug_types entries do not appear in
20410      all_comp_units, but only in their own hash table.  */
20411   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20412     {
20413       struct dwarf2_per_cu_data *per_cu
20414         = dwarf2_per_objfile->all_comp_units[i];
20415       struct partial_symtab *psymtab = per_cu->v.psymtab;
20416       gdb_byte val[8];
20417       struct psymtab_cu_index_map *map;
20418       void **slot;
20419
20420       if (psymtab->user == NULL)
20421         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20422
20423       map = &psymtab_cu_index_map[i];
20424       map->psymtab = psymtab;
20425       map->cu_index = i;
20426       slot = htab_find_slot (cu_index_htab, map, INSERT);
20427       gdb_assert (slot != NULL);
20428       gdb_assert (*slot == NULL);
20429       *slot = map;
20430
20431       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20432                               per_cu->offset.sect_off);
20433       obstack_grow (&cu_list, val, 8);
20434       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20435       obstack_grow (&cu_list, val, 8);
20436     }
20437
20438   /* Dump the address map.  */
20439   write_address_map (objfile, &addr_obstack, cu_index_htab);
20440
20441   /* Write out the .debug_type entries, if any.  */
20442   if (dwarf2_per_objfile->signatured_types)
20443     {
20444       struct signatured_type_index_data sig_data;
20445
20446       sig_data.objfile = objfile;
20447       sig_data.symtab = symtab;
20448       sig_data.types_list = &types_cu_list;
20449       sig_data.psyms_seen = psyms_seen;
20450       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20451       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20452                               write_one_signatured_type, &sig_data);
20453     }
20454
20455   /* Now that we've processed all symbols we can shrink their cu_indices
20456      lists.  */
20457   uniquify_cu_indices (symtab);
20458
20459   obstack_init (&constant_pool);
20460   make_cleanup_obstack_free (&constant_pool);
20461   obstack_init (&symtab_obstack);
20462   make_cleanup_obstack_free (&symtab_obstack);
20463   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20464
20465   obstack_init (&contents);
20466   make_cleanup_obstack_free (&contents);
20467   size_of_contents = 6 * sizeof (offset_type);
20468   total_len = size_of_contents;
20469
20470   /* The version number.  */
20471   val = MAYBE_SWAP (8);
20472   obstack_grow (&contents, &val, sizeof (val));
20473
20474   /* The offset of the CU list from the start of the file.  */
20475   val = MAYBE_SWAP (total_len);
20476   obstack_grow (&contents, &val, sizeof (val));
20477   total_len += obstack_object_size (&cu_list);
20478
20479   /* The offset of the types CU list from the start of the file.  */
20480   val = MAYBE_SWAP (total_len);
20481   obstack_grow (&contents, &val, sizeof (val));
20482   total_len += obstack_object_size (&types_cu_list);
20483
20484   /* The offset of the address table from the start of the file.  */
20485   val = MAYBE_SWAP (total_len);
20486   obstack_grow (&contents, &val, sizeof (val));
20487   total_len += obstack_object_size (&addr_obstack);
20488
20489   /* The offset of the symbol table from the start of the file.  */
20490   val = MAYBE_SWAP (total_len);
20491   obstack_grow (&contents, &val, sizeof (val));
20492   total_len += obstack_object_size (&symtab_obstack);
20493
20494   /* The offset of the constant pool from the start of the file.  */
20495   val = MAYBE_SWAP (total_len);
20496   obstack_grow (&contents, &val, sizeof (val));
20497   total_len += obstack_object_size (&constant_pool);
20498
20499   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20500
20501   write_obstack (out_file, &contents);
20502   write_obstack (out_file, &cu_list);
20503   write_obstack (out_file, &types_cu_list);
20504   write_obstack (out_file, &addr_obstack);
20505   write_obstack (out_file, &symtab_obstack);
20506   write_obstack (out_file, &constant_pool);
20507
20508   fclose (out_file);
20509
20510   /* We want to keep the file, so we set cleanup_filename to NULL
20511      here.  See unlink_if_set.  */
20512   cleanup_filename = NULL;
20513
20514   do_cleanups (cleanup);
20515 }
20516
20517 /* Implementation of the `save gdb-index' command.
20518    
20519    Note that the file format used by this command is documented in the
20520    GDB manual.  Any changes here must be documented there.  */
20521
20522 static void
20523 save_gdb_index_command (char *arg, int from_tty)
20524 {
20525   struct objfile *objfile;
20526
20527   if (!arg || !*arg)
20528     error (_("usage: save gdb-index DIRECTORY"));
20529
20530   ALL_OBJFILES (objfile)
20531   {
20532     struct stat st;
20533
20534     /* If the objfile does not correspond to an actual file, skip it.  */
20535     if (stat (objfile->name, &st) < 0)
20536       continue;
20537
20538     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20539     if (dwarf2_per_objfile)
20540       {
20541         volatile struct gdb_exception except;
20542
20543         TRY_CATCH (except, RETURN_MASK_ERROR)
20544           {
20545             write_psymtabs_to_index (objfile, arg);
20546           }
20547         if (except.reason < 0)
20548           exception_fprintf (gdb_stderr, except,
20549                              _("Error while writing index for `%s': "),
20550                              objfile->name);
20551       }
20552   }
20553 }
20554
20555 \f
20556
20557 int dwarf2_always_disassemble;
20558
20559 static void
20560 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20561                                 struct cmd_list_element *c, const char *value)
20562 {
20563   fprintf_filtered (file,
20564                     _("Whether to always disassemble "
20565                       "DWARF expressions is %s.\n"),
20566                     value);
20567 }
20568
20569 static void
20570 show_check_physname (struct ui_file *file, int from_tty,
20571                      struct cmd_list_element *c, const char *value)
20572 {
20573   fprintf_filtered (file,
20574                     _("Whether to check \"physname\" is %s.\n"),
20575                     value);
20576 }
20577
20578 void _initialize_dwarf2_read (void);
20579
20580 void
20581 _initialize_dwarf2_read (void)
20582 {
20583   struct cmd_list_element *c;
20584
20585   dwarf2_objfile_data_key
20586     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20587
20588   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20589 Set DWARF 2 specific variables.\n\
20590 Configure DWARF 2 variables such as the cache size"),
20591                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20592                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20593
20594   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20595 Show DWARF 2 specific variables\n\
20596 Show DWARF 2 variables such as the cache size"),
20597                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20598                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20599
20600   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20601                             &dwarf2_max_cache_age, _("\
20602 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20603 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20604 A higher limit means that cached compilation units will be stored\n\
20605 in memory longer, and more total memory will be used.  Zero disables\n\
20606 caching, which can slow down startup."),
20607                             NULL,
20608                             show_dwarf2_max_cache_age,
20609                             &set_dwarf2_cmdlist,
20610                             &show_dwarf2_cmdlist);
20611
20612   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20613                            &dwarf2_always_disassemble, _("\
20614 Set whether `info address' always disassembles DWARF expressions."), _("\
20615 Show whether `info address' always disassembles DWARF expressions."), _("\
20616 When enabled, DWARF expressions are always printed in an assembly-like\n\
20617 syntax.  When disabled, expressions will be printed in a more\n\
20618 conversational style, when possible."),
20619                            NULL,
20620                            show_dwarf2_always_disassemble,
20621                            &set_dwarf2_cmdlist,
20622                            &show_dwarf2_cmdlist);
20623
20624   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20625 Set debugging of the dwarf2 reader."), _("\
20626 Show debugging of the dwarf2 reader."), _("\
20627 When enabled, debugging messages are printed during dwarf2 reading\n\
20628 and symtab expansion."),
20629                             NULL,
20630                             NULL,
20631                             &setdebuglist, &showdebuglist);
20632
20633   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20634 Set debugging of the dwarf2 DIE reader."), _("\
20635 Show debugging of the dwarf2 DIE reader."), _("\
20636 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20637 The value is the maximum depth to print."),
20638                              NULL,
20639                              NULL,
20640                              &setdebuglist, &showdebuglist);
20641
20642   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20643 Set cross-checking of \"physname\" code against demangler."), _("\
20644 Show cross-checking of \"physname\" code against demangler."), _("\
20645 When enabled, GDB's internal \"physname\" code is checked against\n\
20646 the demangler."),
20647                            NULL, show_check_physname,
20648                            &setdebuglist, &showdebuglist);
20649
20650   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20651                            no_class, &use_deprecated_index_sections, _("\
20652 Set whether to use deprecated gdb_index sections."), _("\
20653 Show whether to use deprecated gdb_index sections."), _("\
20654 When enabled, deprecated .gdb_index sections are used anyway.\n\
20655 Normally they are ignored either because of a missing feature or\n\
20656 performance issue.\n\
20657 Warning: This option must be enabled before gdb reads the file."),
20658                            NULL,
20659                            NULL,
20660                            &setlist, &showlist);
20661
20662   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20663                _("\
20664 Save a gdb-index file.\n\
20665 Usage: save gdb-index DIRECTORY"),
20666                &save_cmdlist);
20667   set_cmd_completer (c, filename_completer);
20668 }