ef21092aabb10834882a743f1443ca256dc07995
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 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 "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76
77 #include <fcntl.h>
78 #include <sys/types.h>
79 #include <algorithm>
80 #include <unordered_set>
81 #include <unordered_map>
82
83 typedef struct symbol *symbolp;
84 DEF_VEC_P (symbolp);
85
86 /* When == 1, print basic high level tracing messages.
87    When > 1, be more verbose.
88    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
89 static unsigned int dwarf_read_debug = 0;
90
91 /* When non-zero, dump DIEs after they are read in.  */
92 static unsigned int dwarf_die_debug = 0;
93
94 /* When non-zero, dump line number entries as they are read in.  */
95 static unsigned int dwarf_line_debug = 0;
96
97 /* When non-zero, cross-check physname against demangler.  */
98 static int check_physname = 0;
99
100 /* When non-zero, do not reject deprecated .gdb_index sections.  */
101 static int use_deprecated_index_sections = 0;
102
103 static const struct objfile_data *dwarf2_objfile_data_key;
104
105 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
106
107 static int dwarf2_locexpr_index;
108 static int dwarf2_loclist_index;
109 static int dwarf2_locexpr_block_index;
110 static int dwarf2_loclist_block_index;
111
112 /* A descriptor for dwarf sections.
113
114    S.ASECTION, SIZE are typically initialized when the objfile is first
115    scanned.  BUFFER, READIN are filled in later when the section is read.
116    If the section contained compressed data then SIZE is updated to record
117    the uncompressed size of the section.
118
119    DWP file format V2 introduces a wrinkle that is easiest to handle by
120    creating the concept of virtual sections contained within a real section.
121    In DWP V2 the sections of the input DWO files are concatenated together
122    into one section, but section offsets are kept relative to the original
123    input section.
124    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
125    the real section this "virtual" section is contained in, and BUFFER,SIZE
126    describe the virtual section.  */
127
128 struct dwarf2_section_info
129 {
130   union
131   {
132     /* If this is a real section, the bfd section.  */
133     asection *section;
134     /* If this is a virtual section, pointer to the containing ("real")
135        section.  */
136     struct dwarf2_section_info *containing_section;
137   } s;
138   /* Pointer to section data, only valid if readin.  */
139   const gdb_byte *buffer;
140   /* The size of the section, real or virtual.  */
141   bfd_size_type size;
142   /* If this is a virtual section, the offset in the real section.
143      Only valid if is_virtual.  */
144   bfd_size_type virtual_offset;
145   /* True if we have tried to read this section.  */
146   char readin;
147   /* True if this is a virtual section, False otherwise.
148      This specifies which of s.section and s.containing_section to use.  */
149   char is_virtual;
150 };
151
152 typedef struct dwarf2_section_info dwarf2_section_info_def;
153 DEF_VEC_O (dwarf2_section_info_def);
154
155 /* All offsets in the index are of this type.  It must be
156    architecture-independent.  */
157 typedef uint32_t offset_type;
158
159 DEF_VEC_I (offset_type);
160
161 /* Ensure only legit values are used.  */
162 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
163   do { \
164     gdb_assert ((unsigned int) (value) <= 1); \
165     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
166   } while (0)
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
172                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
173     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
174   } while (0)
175
176 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
177 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
178   do { \
179     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
180     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 /* A description of the mapped index.  The file format is described in
184    a comment by the code that writes the index.  */
185 struct mapped_index
186 {
187   /* Index data format version.  */
188   int version;
189
190   /* The total length of the buffer.  */
191   off_t total_size;
192
193   /* A pointer to the address table data.  */
194   const gdb_byte *address_table;
195
196   /* Size of the address table data in bytes.  */
197   offset_type address_table_size;
198
199   /* The symbol table, implemented as a hash table.  */
200   const offset_type *symbol_table;
201
202   /* Size in slots, each slot is 2 offset_types.  */
203   offset_type symbol_table_slots;
204
205   /* A pointer to the constant pool.  */
206   const char *constant_pool;
207 };
208
209 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
210 DEF_VEC_P (dwarf2_per_cu_ptr);
211
212 struct tu_stats
213 {
214   int nr_uniq_abbrev_tables;
215   int nr_symtabs;
216   int nr_symtab_sharers;
217   int nr_stmt_less_type_units;
218   int nr_all_type_units_reallocs;
219 };
220
221 /* Collection of data recorded per objfile.
222    This hangs off of dwarf2_objfile_data_key.  */
223
224 struct dwarf2_per_objfile
225 {
226   struct dwarf2_section_info info;
227   struct dwarf2_section_info abbrev;
228   struct dwarf2_section_info line;
229   struct dwarf2_section_info loc;
230   struct dwarf2_section_info loclists;
231   struct dwarf2_section_info macinfo;
232   struct dwarf2_section_info macro;
233   struct dwarf2_section_info str;
234   struct dwarf2_section_info line_str;
235   struct dwarf2_section_info ranges;
236   struct dwarf2_section_info rnglists;
237   struct dwarf2_section_info addr;
238   struct dwarf2_section_info frame;
239   struct dwarf2_section_info eh_frame;
240   struct dwarf2_section_info gdb_index;
241
242   VEC (dwarf2_section_info_def) *types;
243
244   /* Back link.  */
245   struct objfile *objfile;
246
247   /* Table of all the compilation units.  This is used to locate
248      the target compilation unit of a particular reference.  */
249   struct dwarf2_per_cu_data **all_comp_units;
250
251   /* The number of compilation units in ALL_COMP_UNITS.  */
252   int n_comp_units;
253
254   /* The number of .debug_types-related CUs.  */
255   int n_type_units;
256
257   /* The number of elements allocated in all_type_units.
258      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
259   int n_allocated_type_units;
260
261   /* The .debug_types-related CUs (TUs).
262      This is stored in malloc space because we may realloc it.  */
263   struct signatured_type **all_type_units;
264
265   /* Table of struct type_unit_group objects.
266      The hash key is the DW_AT_stmt_list value.  */
267   htab_t type_unit_groups;
268
269   /* A table mapping .debug_types signatures to its signatured_type entry.
270      This is NULL if the .debug_types section hasn't been read in yet.  */
271   htab_t signatured_types;
272
273   /* Type unit statistics, to see how well the scaling improvements
274      are doing.  */
275   struct tu_stats tu_stats;
276
277   /* A chain of compilation units that are currently read in, so that
278      they can be freed later.  */
279   struct dwarf2_per_cu_data *read_in_chain;
280
281   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
282      This is NULL if the table hasn't been allocated yet.  */
283   htab_t dwo_files;
284
285   /* Non-zero if we've check for whether there is a DWP file.  */
286   int dwp_checked;
287
288   /* The DWP file if there is one, or NULL.  */
289   struct dwp_file *dwp_file;
290
291   /* The shared '.dwz' file, if one exists.  This is used when the
292      original data was compressed using 'dwz -m'.  */
293   struct dwz_file *dwz_file;
294
295   /* A flag indicating wether this objfile has a section loaded at a
296      VMA of 0.  */
297   int has_section_at_zero;
298
299   /* True if we are using the mapped index,
300      or we are faking it for OBJF_READNOW's sake.  */
301   unsigned char using_index;
302
303   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
304   struct mapped_index *index_table;
305
306   /* When using index_table, this keeps track of all quick_file_names entries.
307      TUs typically share line table entries with a CU, so we maintain a
308      separate table of all line table entries to support the sharing.
309      Note that while there can be way more TUs than CUs, we've already
310      sorted all the TUs into "type unit groups", grouped by their
311      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
312      CU and its associated TU group if there is one.  */
313   htab_t quick_file_names_table;
314
315   /* Set during partial symbol reading, to prevent queueing of full
316      symbols.  */
317   int reading_partial_symbols;
318
319   /* Table mapping type DIEs to their struct type *.
320      This is NULL if not allocated yet.
321      The mapping is done via (CU/TU + DIE offset) -> type.  */
322   htab_t die_type_hash;
323
324   /* The CUs we recently read.  */
325   VEC (dwarf2_per_cu_ptr) *just_read_cus;
326
327   /* Table containing line_header indexed by offset and offset_in_dwz.  */
328   htab_t line_header_hash;
329 };
330
331 static struct dwarf2_per_objfile *dwarf2_per_objfile;
332
333 /* Default names of the debugging sections.  */
334
335 /* Note that if the debugging section has been compressed, it might
336    have a name like .zdebug_info.  */
337
338 static const struct dwarf2_debug_sections dwarf2_elf_names =
339 {
340   { ".debug_info", ".zdebug_info" },
341   { ".debug_abbrev", ".zdebug_abbrev" },
342   { ".debug_line", ".zdebug_line" },
343   { ".debug_loc", ".zdebug_loc" },
344   { ".debug_loclists", ".zdebug_loclists" },
345   { ".debug_macinfo", ".zdebug_macinfo" },
346   { ".debug_macro", ".zdebug_macro" },
347   { ".debug_str", ".zdebug_str" },
348   { ".debug_line_str", ".zdebug_line_str" },
349   { ".debug_ranges", ".zdebug_ranges" },
350   { ".debug_rnglists", ".zdebug_rnglists" },
351   { ".debug_types", ".zdebug_types" },
352   { ".debug_addr", ".zdebug_addr" },
353   { ".debug_frame", ".zdebug_frame" },
354   { ".eh_frame", NULL },
355   { ".gdb_index", ".zgdb_index" },
356   23
357 };
358
359 /* List of DWO/DWP sections.  */
360
361 static const struct dwop_section_names
362 {
363   struct dwarf2_section_names abbrev_dwo;
364   struct dwarf2_section_names info_dwo;
365   struct dwarf2_section_names line_dwo;
366   struct dwarf2_section_names loc_dwo;
367   struct dwarf2_section_names loclists_dwo;
368   struct dwarf2_section_names macinfo_dwo;
369   struct dwarf2_section_names macro_dwo;
370   struct dwarf2_section_names str_dwo;
371   struct dwarf2_section_names str_offsets_dwo;
372   struct dwarf2_section_names types_dwo;
373   struct dwarf2_section_names cu_index;
374   struct dwarf2_section_names tu_index;
375 }
376 dwop_section_names =
377 {
378   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
379   { ".debug_info.dwo", ".zdebug_info.dwo" },
380   { ".debug_line.dwo", ".zdebug_line.dwo" },
381   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
382   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
383   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
384   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
385   { ".debug_str.dwo", ".zdebug_str.dwo" },
386   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
387   { ".debug_types.dwo", ".zdebug_types.dwo" },
388   { ".debug_cu_index", ".zdebug_cu_index" },
389   { ".debug_tu_index", ".zdebug_tu_index" },
390 };
391
392 /* local data types */
393
394 /* The data in a compilation unit header, after target2host
395    translation, looks like this.  */
396 struct comp_unit_head
397 {
398   unsigned int length;
399   short version;
400   unsigned char addr_size;
401   unsigned char signed_addr_p;
402   sect_offset abbrev_sect_off;
403
404   /* Size of file offsets; either 4 or 8.  */
405   unsigned int offset_size;
406
407   /* Size of the length field; either 4 or 12.  */
408   unsigned int initial_length_size;
409
410   enum dwarf_unit_type unit_type;
411
412   /* Offset to the first byte of this compilation unit header in the
413      .debug_info section, for resolving relative reference dies.  */
414   sect_offset sect_off;
415
416   /* Offset to first die in this cu from the start of the cu.
417      This will be the first byte following the compilation unit header.  */
418   cu_offset first_die_cu_offset;
419
420   /* 64-bit signature of this type unit - it is valid only for
421      UNIT_TYPE DW_UT_type.  */
422   ULONGEST signature;
423
424   /* For types, offset in the type's DIE of the type defined by this TU.  */
425   cu_offset type_cu_offset_in_tu;
426 };
427
428 /* Type used for delaying computation of method physnames.
429    See comments for compute_delayed_physnames.  */
430 struct delayed_method_info
431 {
432   /* The type to which the method is attached, i.e., its parent class.  */
433   struct type *type;
434
435   /* The index of the method in the type's function fieldlists.  */
436   int fnfield_index;
437
438   /* The index of the method in the fieldlist.  */
439   int index;
440
441   /* The name of the DIE.  */
442   const char *name;
443
444   /*  The DIE associated with this method.  */
445   struct die_info *die;
446 };
447
448 typedef struct delayed_method_info delayed_method_info;
449 DEF_VEC_O (delayed_method_info);
450
451 /* Internal state when decoding a particular compilation unit.  */
452 struct dwarf2_cu
453 {
454   /* The objfile containing this compilation unit.  */
455   struct objfile *objfile;
456
457   /* The header of the compilation unit.  */
458   struct comp_unit_head header;
459
460   /* Base address of this compilation unit.  */
461   CORE_ADDR base_address;
462
463   /* Non-zero if base_address has been set.  */
464   int base_known;
465
466   /* The language we are debugging.  */
467   enum language language;
468   const struct language_defn *language_defn;
469
470   const char *producer;
471
472   /* The generic symbol table building routines have separate lists for
473      file scope symbols and all all other scopes (local scopes).  So
474      we need to select the right one to pass to add_symbol_to_list().
475      We do it by keeping a pointer to the correct list in list_in_scope.
476
477      FIXME: The original dwarf code just treated the file scope as the
478      first local scope, and all other local scopes as nested local
479      scopes, and worked fine.  Check to see if we really need to
480      distinguish these in buildsym.c.  */
481   struct pending **list_in_scope;
482
483   /* The abbrev table for this CU.
484      Normally this points to the abbrev table in the objfile.
485      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
486   struct abbrev_table *abbrev_table;
487
488   /* Hash table holding all the loaded partial DIEs
489      with partial_die->offset.SECT_OFF as hash.  */
490   htab_t partial_dies;
491
492   /* Storage for things with the same lifetime as this read-in compilation
493      unit, including partial DIEs.  */
494   struct obstack comp_unit_obstack;
495
496   /* When multiple dwarf2_cu structures are living in memory, this field
497      chains them all together, so that they can be released efficiently.
498      We will probably also want a generation counter so that most-recently-used
499      compilation units are cached...  */
500   struct dwarf2_per_cu_data *read_in_chain;
501
502   /* Backlink to our per_cu entry.  */
503   struct dwarf2_per_cu_data *per_cu;
504
505   /* How many compilation units ago was this CU last referenced?  */
506   int last_used;
507
508   /* A hash table of DIE cu_offset for following references with
509      die_info->offset.sect_off as hash.  */
510   htab_t die_hash;
511
512   /* Full DIEs if read in.  */
513   struct die_info *dies;
514
515   /* A set of pointers to dwarf2_per_cu_data objects for compilation
516      units referenced by this one.  Only set during full symbol processing;
517      partial symbol tables do not have dependencies.  */
518   htab_t dependencies;
519
520   /* Header data from the line table, during full symbol processing.  */
521   struct line_header *line_header;
522
523   /* A list of methods which need to have physnames computed
524      after all type information has been read.  */
525   VEC (delayed_method_info) *method_list;
526
527   /* To be copied to symtab->call_site_htab.  */
528   htab_t call_site_htab;
529
530   /* Non-NULL if this CU came from a DWO file.
531      There is an invariant here that is important to remember:
532      Except for attributes copied from the top level DIE in the "main"
533      (or "stub") file in preparation for reading the DWO file
534      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
535      Either there isn't a DWO file (in which case this is NULL and the point
536      is moot), or there is and either we're not going to read it (in which
537      case this is NULL) or there is and we are reading it (in which case this
538      is non-NULL).  */
539   struct dwo_unit *dwo_unit;
540
541   /* The DW_AT_addr_base attribute if present, zero otherwise
542      (zero is a valid value though).
543      Note this value comes from the Fission stub CU/TU's DIE.  */
544   ULONGEST addr_base;
545
546   /* The DW_AT_ranges_base attribute if present, zero otherwise
547      (zero is a valid value though).
548      Note this value comes from the Fission stub CU/TU's DIE.
549      Also note that the value is zero in the non-DWO case so this value can
550      be used without needing to know whether DWO files are in use or not.
551      N.B. This does not apply to DW_AT_ranges appearing in
552      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
553      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
554      DW_AT_ranges_base *would* have to be applied, and we'd have to care
555      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
556   ULONGEST ranges_base;
557
558   /* Mark used when releasing cached dies.  */
559   unsigned int mark : 1;
560
561   /* This CU references .debug_loc.  See the symtab->locations_valid field.
562      This test is imperfect as there may exist optimized debug code not using
563      any location list and still facing inlining issues if handled as
564      unoptimized code.  For a future better test see GCC PR other/32998.  */
565   unsigned int has_loclist : 1;
566
567   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
568      if all the producer_is_* fields are valid.  This information is cached
569      because profiling CU expansion showed excessive time spent in
570      producer_is_gxx_lt_4_6.  */
571   unsigned int checked_producer : 1;
572   unsigned int producer_is_gxx_lt_4_6 : 1;
573   unsigned int producer_is_gcc_lt_4_3 : 1;
574   unsigned int producer_is_icc : 1;
575
576   /* When set, the file that we're processing is known to have
577      debugging info for C++ namespaces.  GCC 3.3.x did not produce
578      this information, but later versions do.  */
579
580   unsigned int processing_has_namespace_info : 1;
581 };
582
583 /* Persistent data held for a compilation unit, even when not
584    processing it.  We put a pointer to this structure in the
585    read_symtab_private field of the psymtab.  */
586
587 struct dwarf2_per_cu_data
588 {
589   /* The start offset and length of this compilation unit.
590      NOTE: Unlike comp_unit_head.length, this length includes
591      initial_length_size.
592      If the DIE refers to a DWO file, this is always of the original die,
593      not the DWO file.  */
594   sect_offset sect_off;
595   unsigned int length;
596
597   /* DWARF standard version this data has been read from (such as 4 or 5).  */
598   short dwarf_version;
599
600   /* Flag indicating this compilation unit will be read in before
601      any of the current compilation units are processed.  */
602   unsigned int queued : 1;
603
604   /* This flag will be set when reading partial DIEs if we need to load
605      absolutely all DIEs for this compilation unit, instead of just the ones
606      we think are interesting.  It gets set if we look for a DIE in the
607      hash table and don't find it.  */
608   unsigned int load_all_dies : 1;
609
610   /* Non-zero if this CU is from .debug_types.
611      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
612      this is non-zero.  */
613   unsigned int is_debug_types : 1;
614
615   /* Non-zero if this CU is from the .dwz file.  */
616   unsigned int is_dwz : 1;
617
618   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
619      This flag is only valid if is_debug_types is true.
620      We can't read a CU directly from a DWO file: There are required
621      attributes in the stub.  */
622   unsigned int reading_dwo_directly : 1;
623
624   /* Non-zero if the TU has been read.
625      This is used to assist the "Stay in DWO Optimization" for Fission:
626      When reading a DWO, it's faster to read TUs from the DWO instead of
627      fetching them from random other DWOs (due to comdat folding).
628      If the TU has already been read, the optimization is unnecessary
629      (and unwise - we don't want to change where gdb thinks the TU lives
630      "midflight").
631      This flag is only valid if is_debug_types is true.  */
632   unsigned int tu_read : 1;
633
634   /* The section this CU/TU lives in.
635      If the DIE refers to a DWO file, this is always the original die,
636      not the DWO file.  */
637   struct dwarf2_section_info *section;
638
639   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
640      of the CU cache it gets reset to NULL again.  This is left as NULL for
641      dummy CUs (a CU header, but nothing else).  */
642   struct dwarf2_cu *cu;
643
644   /* The corresponding objfile.
645      Normally we can get the objfile from dwarf2_per_objfile.
646      However we can enter this file with just a "per_cu" handle.  */
647   struct objfile *objfile;
648
649   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
650      is active.  Otherwise, the 'psymtab' field is active.  */
651   union
652   {
653     /* The partial symbol table associated with this compilation unit,
654        or NULL for unread partial units.  */
655     struct partial_symtab *psymtab;
656
657     /* Data needed by the "quick" functions.  */
658     struct dwarf2_per_cu_quick_data *quick;
659   } v;
660
661   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
662      while reading psymtabs, used to compute the psymtab dependencies,
663      and then cleared.  Then it is filled in again while reading full
664      symbols, and only deleted when the objfile is destroyed.
665
666      This is also used to work around a difference between the way gold
667      generates .gdb_index version <=7 and the way gdb does.  Arguably this
668      is a gold bug.  For symbols coming from TUs, gold records in the index
669      the CU that includes the TU instead of the TU itself.  This breaks
670      dw2_lookup_symbol: It assumes that if the index says symbol X lives
671      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
672      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
673      we need to look in TU Z to find X.  Fortunately, this is akin to
674      DW_TAG_imported_unit, so we just use the same mechanism: For
675      .gdb_index version <=7 this also records the TUs that the CU referred
676      to.  Concurrently with this change gdb was modified to emit version 8
677      indices so we only pay a price for gold generated indices.
678      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
679   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
680 };
681
682 /* Entry in the signatured_types hash table.  */
683
684 struct signatured_type
685 {
686   /* The "per_cu" object of this type.
687      This struct is used iff per_cu.is_debug_types.
688      N.B.: This is the first member so that it's easy to convert pointers
689      between them.  */
690   struct dwarf2_per_cu_data per_cu;
691
692   /* The type's signature.  */
693   ULONGEST signature;
694
695   /* Offset in the TU of the type's DIE, as read from the TU header.
696      If this TU is a DWO stub and the definition lives in a DWO file
697      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
698   cu_offset type_offset_in_tu;
699
700   /* Offset in the section of the type's DIE.
701      If the definition lives in a DWO file, this is the offset in the
702      .debug_types.dwo section.
703      The value is zero until the actual value is known.
704      Zero is otherwise not a valid section offset.  */
705   sect_offset type_offset_in_section;
706
707   /* Type units are grouped by their DW_AT_stmt_list entry so that they
708      can share them.  This points to the containing symtab.  */
709   struct type_unit_group *type_unit_group;
710
711   /* The type.
712      The first time we encounter this type we fully read it in and install it
713      in the symbol tables.  Subsequent times we only need the type.  */
714   struct type *type;
715
716   /* Containing DWO unit.
717      This field is valid iff per_cu.reading_dwo_directly.  */
718   struct dwo_unit *dwo_unit;
719 };
720
721 typedef struct signatured_type *sig_type_ptr;
722 DEF_VEC_P (sig_type_ptr);
723
724 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
725    This includes type_unit_group and quick_file_names.  */
726
727 struct stmt_list_hash
728 {
729   /* The DWO unit this table is from or NULL if there is none.  */
730   struct dwo_unit *dwo_unit;
731
732   /* Offset in .debug_line or .debug_line.dwo.  */
733   sect_offset line_sect_off;
734 };
735
736 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
737    an object of this type.  */
738
739 struct type_unit_group
740 {
741   /* dwarf2read.c's main "handle" on a TU symtab.
742      To simplify things we create an artificial CU that "includes" all the
743      type units using this stmt_list so that the rest of the code still has
744      a "per_cu" handle on the symtab.
745      This PER_CU is recognized by having no section.  */
746 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
747   struct dwarf2_per_cu_data per_cu;
748
749   /* The TUs that share this DW_AT_stmt_list entry.
750      This is added to while parsing type units to build partial symtabs,
751      and is deleted afterwards and not used again.  */
752   VEC (sig_type_ptr) *tus;
753
754   /* The compunit symtab.
755      Type units in a group needn't all be defined in the same source file,
756      so we create an essentially anonymous symtab as the compunit symtab.  */
757   struct compunit_symtab *compunit_symtab;
758
759   /* The data used to construct the hash key.  */
760   struct stmt_list_hash hash;
761
762   /* The number of symtabs from the line header.
763      The value here must match line_header.num_file_names.  */
764   unsigned int num_symtabs;
765
766   /* The symbol tables for this TU (obtained from the files listed in
767      DW_AT_stmt_list).
768      WARNING: The order of entries here must match the order of entries
769      in the line header.  After the first TU using this type_unit_group, the
770      line header for the subsequent TUs is recreated from this.  This is done
771      because we need to use the same symtabs for each TU using the same
772      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
773      there's no guarantee the line header doesn't have duplicate entries.  */
774   struct symtab **symtabs;
775 };
776
777 /* These sections are what may appear in a (real or virtual) DWO file.  */
778
779 struct dwo_sections
780 {
781   struct dwarf2_section_info abbrev;
782   struct dwarf2_section_info line;
783   struct dwarf2_section_info loc;
784   struct dwarf2_section_info loclists;
785   struct dwarf2_section_info macinfo;
786   struct dwarf2_section_info macro;
787   struct dwarf2_section_info str;
788   struct dwarf2_section_info str_offsets;
789   /* In the case of a virtual DWO file, these two are unused.  */
790   struct dwarf2_section_info info;
791   VEC (dwarf2_section_info_def) *types;
792 };
793
794 /* CUs/TUs in DWP/DWO files.  */
795
796 struct dwo_unit
797 {
798   /* Backlink to the containing struct dwo_file.  */
799   struct dwo_file *dwo_file;
800
801   /* The "id" that distinguishes this CU/TU.
802      .debug_info calls this "dwo_id", .debug_types calls this "signature".
803      Since signatures came first, we stick with it for consistency.  */
804   ULONGEST signature;
805
806   /* The section this CU/TU lives in, in the DWO file.  */
807   struct dwarf2_section_info *section;
808
809   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
810   sect_offset sect_off;
811   unsigned int length;
812
813   /* For types, offset in the type's DIE of the type defined by this TU.  */
814   cu_offset type_offset_in_tu;
815 };
816
817 /* include/dwarf2.h defines the DWP section codes.
818    It defines a max value but it doesn't define a min value, which we
819    use for error checking, so provide one.  */
820
821 enum dwp_v2_section_ids
822 {
823   DW_SECT_MIN = 1
824 };
825
826 /* Data for one DWO file.
827
828    This includes virtual DWO files (a virtual DWO file is a DWO file as it
829    appears in a DWP file).  DWP files don't really have DWO files per se -
830    comdat folding of types "loses" the DWO file they came from, and from
831    a high level view DWP files appear to contain a mass of random types.
832    However, to maintain consistency with the non-DWP case we pretend DWP
833    files contain virtual DWO files, and we assign each TU with one virtual
834    DWO file (generally based on the line and abbrev section offsets -
835    a heuristic that seems to work in practice).  */
836
837 struct dwo_file
838 {
839   /* The DW_AT_GNU_dwo_name attribute.
840      For virtual DWO files the name is constructed from the section offsets
841      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
842      from related CU+TUs.  */
843   const char *dwo_name;
844
845   /* The DW_AT_comp_dir attribute.  */
846   const char *comp_dir;
847
848   /* The bfd, when the file is open.  Otherwise this is NULL.
849      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
850   bfd *dbfd;
851
852   /* The sections that make up this DWO file.
853      Remember that for virtual DWO files in DWP V2, these are virtual
854      sections (for lack of a better name).  */
855   struct dwo_sections sections;
856
857   /* The CU in the file.
858      We only support one because having more than one requires hacking the
859      dwo_name of each to match, which is highly unlikely to happen.
860      Doing this means all TUs can share comp_dir: We also assume that
861      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
862   struct dwo_unit *cu;
863
864   /* Table of TUs in the file.
865      Each element is a struct dwo_unit.  */
866   htab_t tus;
867 };
868
869 /* These sections are what may appear in a DWP file.  */
870
871 struct dwp_sections
872 {
873   /* These are used by both DWP version 1 and 2.  */
874   struct dwarf2_section_info str;
875   struct dwarf2_section_info cu_index;
876   struct dwarf2_section_info tu_index;
877
878   /* These are only used by DWP version 2 files.
879      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
880      sections are referenced by section number, and are not recorded here.
881      In DWP version 2 there is at most one copy of all these sections, each
882      section being (effectively) comprised of the concatenation of all of the
883      individual sections that exist in the version 1 format.
884      To keep the code simple we treat each of these concatenated pieces as a
885      section itself (a virtual section?).  */
886   struct dwarf2_section_info abbrev;
887   struct dwarf2_section_info info;
888   struct dwarf2_section_info line;
889   struct dwarf2_section_info loc;
890   struct dwarf2_section_info macinfo;
891   struct dwarf2_section_info macro;
892   struct dwarf2_section_info str_offsets;
893   struct dwarf2_section_info types;
894 };
895
896 /* These sections are what may appear in a virtual DWO file in DWP version 1.
897    A virtual DWO file is a DWO file as it appears in a DWP file.  */
898
899 struct virtual_v1_dwo_sections
900 {
901   struct dwarf2_section_info abbrev;
902   struct dwarf2_section_info line;
903   struct dwarf2_section_info loc;
904   struct dwarf2_section_info macinfo;
905   struct dwarf2_section_info macro;
906   struct dwarf2_section_info str_offsets;
907   /* Each DWP hash table entry records one CU or one TU.
908      That is recorded here, and copied to dwo_unit.section.  */
909   struct dwarf2_section_info info_or_types;
910 };
911
912 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
913    In version 2, the sections of the DWO files are concatenated together
914    and stored in one section of that name.  Thus each ELF section contains
915    several "virtual" sections.  */
916
917 struct virtual_v2_dwo_sections
918 {
919   bfd_size_type abbrev_offset;
920   bfd_size_type abbrev_size;
921
922   bfd_size_type line_offset;
923   bfd_size_type line_size;
924
925   bfd_size_type loc_offset;
926   bfd_size_type loc_size;
927
928   bfd_size_type macinfo_offset;
929   bfd_size_type macinfo_size;
930
931   bfd_size_type macro_offset;
932   bfd_size_type macro_size;
933
934   bfd_size_type str_offsets_offset;
935   bfd_size_type str_offsets_size;
936
937   /* Each DWP hash table entry records one CU or one TU.
938      That is recorded here, and copied to dwo_unit.section.  */
939   bfd_size_type info_or_types_offset;
940   bfd_size_type info_or_types_size;
941 };
942
943 /* Contents of DWP hash tables.  */
944
945 struct dwp_hash_table
946 {
947   uint32_t version, nr_columns;
948   uint32_t nr_units, nr_slots;
949   const gdb_byte *hash_table, *unit_table;
950   union
951   {
952     struct
953     {
954       const gdb_byte *indices;
955     } v1;
956     struct
957     {
958       /* This is indexed by column number and gives the id of the section
959          in that column.  */
960 #define MAX_NR_V2_DWO_SECTIONS \
961   (1 /* .debug_info or .debug_types */ \
962    + 1 /* .debug_abbrev */ \
963    + 1 /* .debug_line */ \
964    + 1 /* .debug_loc */ \
965    + 1 /* .debug_str_offsets */ \
966    + 1 /* .debug_macro or .debug_macinfo */)
967       int section_ids[MAX_NR_V2_DWO_SECTIONS];
968       const gdb_byte *offsets;
969       const gdb_byte *sizes;
970     } v2;
971   } section_pool;
972 };
973
974 /* Data for one DWP file.  */
975
976 struct dwp_file
977 {
978   /* Name of the file.  */
979   const char *name;
980
981   /* File format version.  */
982   int version;
983
984   /* The bfd.  */
985   bfd *dbfd;
986
987   /* Section info for this file.  */
988   struct dwp_sections sections;
989
990   /* Table of CUs in the file.  */
991   const struct dwp_hash_table *cus;
992
993   /* Table of TUs in the file.  */
994   const struct dwp_hash_table *tus;
995
996   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
997   htab_t loaded_cus;
998   htab_t loaded_tus;
999
1000   /* Table to map ELF section numbers to their sections.
1001      This is only needed for the DWP V1 file format.  */
1002   unsigned int num_sections;
1003   asection **elf_sections;
1004 };
1005
1006 /* This represents a '.dwz' file.  */
1007
1008 struct dwz_file
1009 {
1010   /* A dwz file can only contain a few sections.  */
1011   struct dwarf2_section_info abbrev;
1012   struct dwarf2_section_info info;
1013   struct dwarf2_section_info str;
1014   struct dwarf2_section_info line;
1015   struct dwarf2_section_info macro;
1016   struct dwarf2_section_info gdb_index;
1017
1018   /* The dwz's BFD.  */
1019   bfd *dwz_bfd;
1020 };
1021
1022 /* Struct used to pass misc. parameters to read_die_and_children, et
1023    al.  which are used for both .debug_info and .debug_types dies.
1024    All parameters here are unchanging for the life of the call.  This
1025    struct exists to abstract away the constant parameters of die reading.  */
1026
1027 struct die_reader_specs
1028 {
1029   /* The bfd of die_section.  */
1030   bfd* abfd;
1031
1032   /* The CU of the DIE we are parsing.  */
1033   struct dwarf2_cu *cu;
1034
1035   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1036   struct dwo_file *dwo_file;
1037
1038   /* The section the die comes from.
1039      This is either .debug_info or .debug_types, or the .dwo variants.  */
1040   struct dwarf2_section_info *die_section;
1041
1042   /* die_section->buffer.  */
1043   const gdb_byte *buffer;
1044
1045   /* The end of the buffer.  */
1046   const gdb_byte *buffer_end;
1047
1048   /* The value of the DW_AT_comp_dir attribute.  */
1049   const char *comp_dir;
1050 };
1051
1052 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1053 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1054                                       const gdb_byte *info_ptr,
1055                                       struct die_info *comp_unit_die,
1056                                       int has_children,
1057                                       void *data);
1058
1059 /* A 1-based directory index.  This is a strong typedef to prevent
1060    accidentally using a directory index as a 0-based index into an
1061    array/vector.  */
1062 enum class dir_index : unsigned int {};
1063
1064 /* Likewise, a 1-based file name index.  */
1065 enum class file_name_index : unsigned int {};
1066
1067 struct file_entry
1068 {
1069   file_entry () = default;
1070
1071   file_entry (const char *name_, dir_index d_index_,
1072               unsigned int mod_time_, unsigned int length_)
1073     : name (name_),
1074       d_index (d_index_),
1075       mod_time (mod_time_),
1076       length (length_)
1077   {}
1078
1079   /* Return the include directory at D_INDEX stored in LH.  Returns
1080      NULL if D_INDEX is out of bounds.  */
1081   const char *include_dir (const line_header *lh) const;
1082
1083   /* The file name.  Note this is an observing pointer.  The memory is
1084      owned by debug_line_buffer.  */
1085   const char *name {};
1086
1087   /* The directory index (1-based).  */
1088   dir_index d_index {};
1089
1090   unsigned int mod_time {};
1091
1092   unsigned int length {};
1093
1094   /* True if referenced by the Line Number Program.  */
1095   bool included_p {};
1096
1097   /* The associated symbol table, if any.  */
1098   struct symtab *symtab {};
1099 };
1100
1101 /* The line number information for a compilation unit (found in the
1102    .debug_line section) begins with a "statement program header",
1103    which contains the following information.  */
1104 struct line_header
1105 {
1106   line_header ()
1107     : offset_in_dwz {}
1108   {}
1109
1110   /* Add an entry to the include directory table.  */
1111   void add_include_dir (const char *include_dir);
1112
1113   /* Add an entry to the file name table.  */
1114   void add_file_name (const char *name, dir_index d_index,
1115                       unsigned int mod_time, unsigned int length);
1116
1117   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1118      is out of bounds.  */
1119   const char *include_dir_at (dir_index index) const
1120   {
1121     /* Convert directory index number (1-based) to vector index
1122        (0-based).  */
1123     size_t vec_index = to_underlying (index) - 1;
1124
1125     if (vec_index >= include_dirs.size ())
1126       return NULL;
1127     return include_dirs[vec_index];
1128   }
1129
1130   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1131      is out of bounds.  */
1132   file_entry *file_name_at (file_name_index index)
1133   {
1134     /* Convert file name index number (1-based) to vector index
1135        (0-based).  */
1136     size_t vec_index = to_underlying (index) - 1;
1137
1138     if (vec_index >= file_names.size ())
1139       return NULL;
1140     return &file_names[vec_index];
1141   }
1142
1143   /* Const version of the above.  */
1144   const file_entry *file_name_at (unsigned int index) const
1145   {
1146     if (index >= file_names.size ())
1147       return NULL;
1148     return &file_names[index];
1149   }
1150
1151   /* Offset of line number information in .debug_line section.  */
1152   sect_offset sect_off {};
1153
1154   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1155   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1156
1157   unsigned int total_length {};
1158   unsigned short version {};
1159   unsigned int header_length {};
1160   unsigned char minimum_instruction_length {};
1161   unsigned char maximum_ops_per_instruction {};
1162   unsigned char default_is_stmt {};
1163   int line_base {};
1164   unsigned char line_range {};
1165   unsigned char opcode_base {};
1166
1167   /* standard_opcode_lengths[i] is the number of operands for the
1168      standard opcode whose value is i.  This means that
1169      standard_opcode_lengths[0] is unused, and the last meaningful
1170      element is standard_opcode_lengths[opcode_base - 1].  */
1171   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1172
1173   /* The include_directories table.  Note these are observing
1174      pointers.  The memory is owned by debug_line_buffer.  */
1175   std::vector<const char *> include_dirs;
1176
1177   /* The file_names table.  */
1178   std::vector<file_entry> file_names;
1179
1180   /* The start and end of the statement program following this
1181      header.  These point into dwarf2_per_objfile->line_buffer.  */
1182   const gdb_byte *statement_program_start {}, *statement_program_end {};
1183 };
1184
1185 typedef std::unique_ptr<line_header> line_header_up;
1186
1187 const char *
1188 file_entry::include_dir (const line_header *lh) const
1189 {
1190   return lh->include_dir_at (d_index);
1191 }
1192
1193 /* When we construct a partial symbol table entry we only
1194    need this much information.  */
1195 struct partial_die_info
1196   {
1197     /* Offset of this DIE.  */
1198     sect_offset sect_off;
1199
1200     /* DWARF-2 tag for this DIE.  */
1201     ENUM_BITFIELD(dwarf_tag) tag : 16;
1202
1203     /* Assorted flags describing the data found in this DIE.  */
1204     unsigned int has_children : 1;
1205     unsigned int is_external : 1;
1206     unsigned int is_declaration : 1;
1207     unsigned int has_type : 1;
1208     unsigned int has_specification : 1;
1209     unsigned int has_pc_info : 1;
1210     unsigned int may_be_inlined : 1;
1211
1212     /* This DIE has been marked DW_AT_main_subprogram.  */
1213     unsigned int main_subprogram : 1;
1214
1215     /* Flag set if the SCOPE field of this structure has been
1216        computed.  */
1217     unsigned int scope_set : 1;
1218
1219     /* Flag set if the DIE has a byte_size attribute.  */
1220     unsigned int has_byte_size : 1;
1221
1222     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1223     unsigned int has_const_value : 1;
1224
1225     /* Flag set if any of the DIE's children are template arguments.  */
1226     unsigned int has_template_arguments : 1;
1227
1228     /* Flag set if fixup_partial_die has been called on this die.  */
1229     unsigned int fixup_called : 1;
1230
1231     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1232     unsigned int is_dwz : 1;
1233
1234     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1235     unsigned int spec_is_dwz : 1;
1236
1237     /* The name of this DIE.  Normally the value of DW_AT_name, but
1238        sometimes a default name for unnamed DIEs.  */
1239     const char *name;
1240
1241     /* The linkage name, if present.  */
1242     const char *linkage_name;
1243
1244     /* The scope to prepend to our children.  This is generally
1245        allocated on the comp_unit_obstack, so will disappear
1246        when this compilation unit leaves the cache.  */
1247     const char *scope;
1248
1249     /* Some data associated with the partial DIE.  The tag determines
1250        which field is live.  */
1251     union
1252     {
1253       /* The location description associated with this DIE, if any.  */
1254       struct dwarf_block *locdesc;
1255       /* The offset of an import, for DW_TAG_imported_unit.  */
1256       sect_offset sect_off;
1257     } d;
1258
1259     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1260     CORE_ADDR lowpc;
1261     CORE_ADDR highpc;
1262
1263     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1264        DW_AT_sibling, if any.  */
1265     /* NOTE: This member isn't strictly necessary, read_partial_die could
1266        return DW_AT_sibling values to its caller load_partial_dies.  */
1267     const gdb_byte *sibling;
1268
1269     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1270        DW_AT_specification (or DW_AT_abstract_origin or
1271        DW_AT_extension).  */
1272     sect_offset spec_offset;
1273
1274     /* Pointers to this DIE's parent, first child, and next sibling,
1275        if any.  */
1276     struct partial_die_info *die_parent, *die_child, *die_sibling;
1277   };
1278
1279 /* This data structure holds the information of an abbrev.  */
1280 struct abbrev_info
1281   {
1282     unsigned int number;        /* number identifying abbrev */
1283     enum dwarf_tag tag;         /* dwarf tag */
1284     unsigned short has_children;                /* boolean */
1285     unsigned short num_attrs;   /* number of attributes */
1286     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1287     struct abbrev_info *next;   /* next in chain */
1288   };
1289
1290 struct attr_abbrev
1291   {
1292     ENUM_BITFIELD(dwarf_attribute) name : 16;
1293     ENUM_BITFIELD(dwarf_form) form : 16;
1294
1295     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1296     LONGEST implicit_const;
1297   };
1298
1299 /* Size of abbrev_table.abbrev_hash_table.  */
1300 #define ABBREV_HASH_SIZE 121
1301
1302 /* Top level data structure to contain an abbreviation table.  */
1303
1304 struct abbrev_table
1305 {
1306   /* Where the abbrev table came from.
1307      This is used as a sanity check when the table is used.  */
1308   sect_offset sect_off;
1309
1310   /* Storage for the abbrev table.  */
1311   struct obstack abbrev_obstack;
1312
1313   /* Hash table of abbrevs.
1314      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1315      It could be statically allocated, but the previous code didn't so we
1316      don't either.  */
1317   struct abbrev_info **abbrevs;
1318 };
1319
1320 /* Attributes have a name and a value.  */
1321 struct attribute
1322   {
1323     ENUM_BITFIELD(dwarf_attribute) name : 16;
1324     ENUM_BITFIELD(dwarf_form) form : 15;
1325
1326     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1327        field should be in u.str (existing only for DW_STRING) but it is kept
1328        here for better struct attribute alignment.  */
1329     unsigned int string_is_canonical : 1;
1330
1331     union
1332       {
1333         const char *str;
1334         struct dwarf_block *blk;
1335         ULONGEST unsnd;
1336         LONGEST snd;
1337         CORE_ADDR addr;
1338         ULONGEST signature;
1339       }
1340     u;
1341   };
1342
1343 /* This data structure holds a complete die structure.  */
1344 struct die_info
1345   {
1346     /* DWARF-2 tag for this DIE.  */
1347     ENUM_BITFIELD(dwarf_tag) tag : 16;
1348
1349     /* Number of attributes */
1350     unsigned char num_attrs;
1351
1352     /* True if we're presently building the full type name for the
1353        type derived from this DIE.  */
1354     unsigned char building_fullname : 1;
1355
1356     /* True if this die is in process.  PR 16581.  */
1357     unsigned char in_process : 1;
1358
1359     /* Abbrev number */
1360     unsigned int abbrev;
1361
1362     /* Offset in .debug_info or .debug_types section.  */
1363     sect_offset sect_off;
1364
1365     /* The dies in a compilation unit form an n-ary tree.  PARENT
1366        points to this die's parent; CHILD points to the first child of
1367        this node; and all the children of a given node are chained
1368        together via their SIBLING fields.  */
1369     struct die_info *child;     /* Its first child, if any.  */
1370     struct die_info *sibling;   /* Its next sibling, if any.  */
1371     struct die_info *parent;    /* Its parent, if any.  */
1372
1373     /* An array of attributes, with NUM_ATTRS elements.  There may be
1374        zero, but it's not common and zero-sized arrays are not
1375        sufficiently portable C.  */
1376     struct attribute attrs[1];
1377   };
1378
1379 /* Get at parts of an attribute structure.  */
1380
1381 #define DW_STRING(attr)    ((attr)->u.str)
1382 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1383 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1384 #define DW_BLOCK(attr)     ((attr)->u.blk)
1385 #define DW_SND(attr)       ((attr)->u.snd)
1386 #define DW_ADDR(attr)      ((attr)->u.addr)
1387 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1388
1389 /* Blocks are a bunch of untyped bytes.  */
1390 struct dwarf_block
1391   {
1392     size_t size;
1393
1394     /* Valid only if SIZE is not zero.  */
1395     const gdb_byte *data;
1396   };
1397
1398 #ifndef ATTR_ALLOC_CHUNK
1399 #define ATTR_ALLOC_CHUNK 4
1400 #endif
1401
1402 /* Allocate fields for structs, unions and enums in this size.  */
1403 #ifndef DW_FIELD_ALLOC_CHUNK
1404 #define DW_FIELD_ALLOC_CHUNK 4
1405 #endif
1406
1407 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1408    but this would require a corresponding change in unpack_field_as_long
1409    and friends.  */
1410 static int bits_per_byte = 8;
1411
1412 struct nextfield
1413 {
1414   struct nextfield *next;
1415   int accessibility;
1416   int virtuality;
1417   struct field field;
1418 };
1419
1420 struct nextfnfield
1421 {
1422   struct nextfnfield *next;
1423   struct fn_field fnfield;
1424 };
1425
1426 struct fnfieldlist
1427 {
1428   const char *name;
1429   int length;
1430   struct nextfnfield *head;
1431 };
1432
1433 struct typedef_field_list
1434 {
1435   struct typedef_field field;
1436   struct typedef_field_list *next;
1437 };
1438
1439 /* The routines that read and process dies for a C struct or C++ class
1440    pass lists of data member fields and lists of member function fields
1441    in an instance of a field_info structure, as defined below.  */
1442 struct field_info
1443   {
1444     /* List of data member and baseclasses fields.  */
1445     struct nextfield *fields, *baseclasses;
1446
1447     /* Number of fields (including baseclasses).  */
1448     int nfields;
1449
1450     /* Number of baseclasses.  */
1451     int nbaseclasses;
1452
1453     /* Set if the accesibility of one of the fields is not public.  */
1454     int non_public_fields;
1455
1456     /* Member function fields array, entries are allocated in the order they
1457        are encountered in the object file.  */
1458     struct nextfnfield *fnfields;
1459
1460     /* Member function fieldlist array, contains name of possibly overloaded
1461        member function, number of overloaded member functions and a pointer
1462        to the head of the member function field chain.  */
1463     struct fnfieldlist *fnfieldlists;
1464
1465     /* Number of entries in the fnfieldlists array.  */
1466     int nfnfields;
1467
1468     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1469        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1470     struct typedef_field_list *typedef_field_list;
1471     unsigned typedef_field_list_count;
1472   };
1473
1474 /* One item on the queue of compilation units to read in full symbols
1475    for.  */
1476 struct dwarf2_queue_item
1477 {
1478   struct dwarf2_per_cu_data *per_cu;
1479   enum language pretend_language;
1480   struct dwarf2_queue_item *next;
1481 };
1482
1483 /* The current queue.  */
1484 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1485
1486 /* Loaded secondary compilation units are kept in memory until they
1487    have not been referenced for the processing of this many
1488    compilation units.  Set this to zero to disable caching.  Cache
1489    sizes of up to at least twenty will improve startup time for
1490    typical inter-CU-reference binaries, at an obvious memory cost.  */
1491 static int dwarf_max_cache_age = 5;
1492 static void
1493 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1494                           struct cmd_list_element *c, const char *value)
1495 {
1496   fprintf_filtered (file, _("The upper bound on the age of cached "
1497                             "DWARF compilation units is %s.\n"),
1498                     value);
1499 }
1500 \f
1501 /* local function prototypes */
1502
1503 static const char *get_section_name (const struct dwarf2_section_info *);
1504
1505 static const char *get_section_file_name (const struct dwarf2_section_info *);
1506
1507 static void dwarf2_locate_sections (bfd *, asection *, void *);
1508
1509 static void dwarf2_find_base_address (struct die_info *die,
1510                                       struct dwarf2_cu *cu);
1511
1512 static struct partial_symtab *create_partial_symtab
1513   (struct dwarf2_per_cu_data *per_cu, const char *name);
1514
1515 static void dwarf2_build_psymtabs_hard (struct objfile *);
1516
1517 static void scan_partial_symbols (struct partial_die_info *,
1518                                   CORE_ADDR *, CORE_ADDR *,
1519                                   int, struct dwarf2_cu *);
1520
1521 static void add_partial_symbol (struct partial_die_info *,
1522                                 struct dwarf2_cu *);
1523
1524 static void add_partial_namespace (struct partial_die_info *pdi,
1525                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1526                                    int set_addrmap, struct dwarf2_cu *cu);
1527
1528 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1529                                 CORE_ADDR *highpc, int set_addrmap,
1530                                 struct dwarf2_cu *cu);
1531
1532 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1533                                      struct dwarf2_cu *cu);
1534
1535 static void add_partial_subprogram (struct partial_die_info *pdi,
1536                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1537                                     int need_pc, struct dwarf2_cu *cu);
1538
1539 static void dwarf2_read_symtab (struct partial_symtab *,
1540                                 struct objfile *);
1541
1542 static void psymtab_to_symtab_1 (struct partial_symtab *);
1543
1544 static struct abbrev_info *abbrev_table_lookup_abbrev
1545   (const struct abbrev_table *, unsigned int);
1546
1547 static struct abbrev_table *abbrev_table_read_table
1548   (struct dwarf2_section_info *, sect_offset);
1549
1550 static void abbrev_table_free (struct abbrev_table *);
1551
1552 static void abbrev_table_free_cleanup (void *);
1553
1554 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1555                                  struct dwarf2_section_info *);
1556
1557 static void dwarf2_free_abbrev_table (void *);
1558
1559 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1560
1561 static struct partial_die_info *load_partial_dies
1562   (const struct die_reader_specs *, const gdb_byte *, int);
1563
1564 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1565                                          struct partial_die_info *,
1566                                          struct abbrev_info *,
1567                                          unsigned int,
1568                                          const gdb_byte *);
1569
1570 static struct partial_die_info *find_partial_die (sect_offset, int,
1571                                                   struct dwarf2_cu *);
1572
1573 static void fixup_partial_die (struct partial_die_info *,
1574                                struct dwarf2_cu *);
1575
1576 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1577                                        struct attribute *, struct attr_abbrev *,
1578                                        const gdb_byte *);
1579
1580 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1581
1582 static int read_1_signed_byte (bfd *, const gdb_byte *);
1583
1584 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1585
1586 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1587
1588 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1589
1590 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1591                                unsigned int *);
1592
1593 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1594
1595 static LONGEST read_checked_initial_length_and_offset
1596   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1597    unsigned int *, unsigned int *);
1598
1599 static LONGEST read_offset (bfd *, const gdb_byte *,
1600                             const struct comp_unit_head *,
1601                             unsigned int *);
1602
1603 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1604
1605 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1606                                        sect_offset);
1607
1608 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1609
1610 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1611
1612 static const char *read_indirect_string (bfd *, const gdb_byte *,
1613                                          const struct comp_unit_head *,
1614                                          unsigned int *);
1615
1616 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1617                                               const struct comp_unit_head *,
1618                                               unsigned int *);
1619
1620 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1621
1622 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1623
1624 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1625                                               const gdb_byte *,
1626                                               unsigned int *);
1627
1628 static const char *read_str_index (const struct die_reader_specs *reader,
1629                                    ULONGEST str_index);
1630
1631 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1632
1633 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1634                                       struct dwarf2_cu *);
1635
1636 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1637                                                 unsigned int);
1638
1639 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1640                                        struct dwarf2_cu *cu);
1641
1642 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1643                                struct dwarf2_cu *cu);
1644
1645 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1646
1647 static struct die_info *die_specification (struct die_info *die,
1648                                            struct dwarf2_cu **);
1649
1650 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1651                                                 struct dwarf2_cu *cu);
1652
1653 static void dwarf_decode_lines (struct line_header *, const char *,
1654                                 struct dwarf2_cu *, struct partial_symtab *,
1655                                 CORE_ADDR, int decode_mapping);
1656
1657 static void dwarf2_start_subfile (const char *, const char *);
1658
1659 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1660                                                     const char *, const char *,
1661                                                     CORE_ADDR);
1662
1663 static struct symbol *new_symbol (struct die_info *, struct type *,
1664                                   struct dwarf2_cu *);
1665
1666 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1667                                        struct dwarf2_cu *, struct symbol *);
1668
1669 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1670                                 struct dwarf2_cu *);
1671
1672 static void dwarf2_const_value_attr (const struct attribute *attr,
1673                                      struct type *type,
1674                                      const char *name,
1675                                      struct obstack *obstack,
1676                                      struct dwarf2_cu *cu, LONGEST *value,
1677                                      const gdb_byte **bytes,
1678                                      struct dwarf2_locexpr_baton **baton);
1679
1680 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1681
1682 static int need_gnat_info (struct dwarf2_cu *);
1683
1684 static struct type *die_descriptive_type (struct die_info *,
1685                                           struct dwarf2_cu *);
1686
1687 static void set_descriptive_type (struct type *, struct die_info *,
1688                                   struct dwarf2_cu *);
1689
1690 static struct type *die_containing_type (struct die_info *,
1691                                          struct dwarf2_cu *);
1692
1693 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1694                                      struct dwarf2_cu *);
1695
1696 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1697
1698 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1699
1700 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1701
1702 static char *typename_concat (struct obstack *obs, const char *prefix,
1703                               const char *suffix, int physname,
1704                               struct dwarf2_cu *cu);
1705
1706 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1707
1708 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1709
1710 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1711
1712 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1713
1714 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1715
1716 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1717                                struct dwarf2_cu *, struct partial_symtab *);
1718
1719 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1720    values.  Keep the items ordered with increasing constraints compliance.  */
1721 enum pc_bounds_kind
1722 {
1723   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1724   PC_BOUNDS_NOT_PRESENT,
1725
1726   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1727      were present but they do not form a valid range of PC addresses.  */
1728   PC_BOUNDS_INVALID,
1729
1730   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1731   PC_BOUNDS_RANGES,
1732
1733   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1734   PC_BOUNDS_HIGH_LOW,
1735 };
1736
1737 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1738                                                  CORE_ADDR *, CORE_ADDR *,
1739                                                  struct dwarf2_cu *,
1740                                                  struct partial_symtab *);
1741
1742 static void get_scope_pc_bounds (struct die_info *,
1743                                  CORE_ADDR *, CORE_ADDR *,
1744                                  struct dwarf2_cu *);
1745
1746 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1747                                         CORE_ADDR, struct dwarf2_cu *);
1748
1749 static void dwarf2_add_field (struct field_info *, struct die_info *,
1750                               struct dwarf2_cu *);
1751
1752 static void dwarf2_attach_fields_to_type (struct field_info *,
1753                                           struct type *, struct dwarf2_cu *);
1754
1755 static void dwarf2_add_member_fn (struct field_info *,
1756                                   struct die_info *, struct type *,
1757                                   struct dwarf2_cu *);
1758
1759 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1760                                              struct type *,
1761                                              struct dwarf2_cu *);
1762
1763 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1764
1765 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1766
1767 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1768
1769 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1770
1771 static struct using_direct **using_directives (enum language);
1772
1773 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1774
1775 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1776
1777 static struct type *read_module_type (struct die_info *die,
1778                                       struct dwarf2_cu *cu);
1779
1780 static const char *namespace_name (struct die_info *die,
1781                                    int *is_anonymous, struct dwarf2_cu *);
1782
1783 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1784
1785 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1786
1787 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1788                                                        struct dwarf2_cu *);
1789
1790 static struct die_info *read_die_and_siblings_1
1791   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1792    struct die_info *);
1793
1794 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1795                                                const gdb_byte *info_ptr,
1796                                                const gdb_byte **new_info_ptr,
1797                                                struct die_info *parent);
1798
1799 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1800                                         struct die_info **, const gdb_byte *,
1801                                         int *, int);
1802
1803 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1804                                       struct die_info **, const gdb_byte *,
1805                                       int *);
1806
1807 static void process_die (struct die_info *, struct dwarf2_cu *);
1808
1809 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1810                                              struct obstack *);
1811
1812 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1813
1814 static const char *dwarf2_full_name (const char *name,
1815                                      struct die_info *die,
1816                                      struct dwarf2_cu *cu);
1817
1818 static const char *dwarf2_physname (const char *name, struct die_info *die,
1819                                     struct dwarf2_cu *cu);
1820
1821 static struct die_info *dwarf2_extension (struct die_info *die,
1822                                           struct dwarf2_cu **);
1823
1824 static const char *dwarf_tag_name (unsigned int);
1825
1826 static const char *dwarf_attr_name (unsigned int);
1827
1828 static const char *dwarf_form_name (unsigned int);
1829
1830 static const char *dwarf_bool_name (unsigned int);
1831
1832 static const char *dwarf_type_encoding_name (unsigned int);
1833
1834 static struct die_info *sibling_die (struct die_info *);
1835
1836 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1837
1838 static void dump_die_for_error (struct die_info *);
1839
1840 static void dump_die_1 (struct ui_file *, int level, int max_level,
1841                         struct die_info *);
1842
1843 /*static*/ void dump_die (struct die_info *, int max_level);
1844
1845 static void store_in_ref_table (struct die_info *,
1846                                 struct dwarf2_cu *);
1847
1848 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1849
1850 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1851
1852 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1853                                                const struct attribute *,
1854                                                struct dwarf2_cu **);
1855
1856 static struct die_info *follow_die_ref (struct die_info *,
1857                                         const struct attribute *,
1858                                         struct dwarf2_cu **);
1859
1860 static struct die_info *follow_die_sig (struct die_info *,
1861                                         const struct attribute *,
1862                                         struct dwarf2_cu **);
1863
1864 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1865                                          struct dwarf2_cu *);
1866
1867 static struct type *get_DW_AT_signature_type (struct die_info *,
1868                                               const struct attribute *,
1869                                               struct dwarf2_cu *);
1870
1871 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1872
1873 static void read_signatured_type (struct signatured_type *);
1874
1875 static int attr_to_dynamic_prop (const struct attribute *attr,
1876                                  struct die_info *die, struct dwarf2_cu *cu,
1877                                  struct dynamic_prop *prop);
1878
1879 /* memory allocation interface */
1880
1881 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1882
1883 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1884
1885 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1886
1887 static int attr_form_is_block (const struct attribute *);
1888
1889 static int attr_form_is_section_offset (const struct attribute *);
1890
1891 static int attr_form_is_constant (const struct attribute *);
1892
1893 static int attr_form_is_ref (const struct attribute *);
1894
1895 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1896                                    struct dwarf2_loclist_baton *baton,
1897                                    const struct attribute *attr);
1898
1899 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1900                                          struct symbol *sym,
1901                                          struct dwarf2_cu *cu,
1902                                          int is_block);
1903
1904 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1905                                      const gdb_byte *info_ptr,
1906                                      struct abbrev_info *abbrev);
1907
1908 static void free_stack_comp_unit (void *);
1909
1910 static hashval_t partial_die_hash (const void *item);
1911
1912 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1913
1914 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1915   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1916
1917 static void init_one_comp_unit (struct dwarf2_cu *cu,
1918                                 struct dwarf2_per_cu_data *per_cu);
1919
1920 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1921                                    struct die_info *comp_unit_die,
1922                                    enum language pretend_language);
1923
1924 static void free_heap_comp_unit (void *);
1925
1926 static void free_cached_comp_units (void *);
1927
1928 static void age_cached_comp_units (void);
1929
1930 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1931
1932 static struct type *set_die_type (struct die_info *, struct type *,
1933                                   struct dwarf2_cu *);
1934
1935 static void create_all_comp_units (struct objfile *);
1936
1937 static int create_all_type_units (struct objfile *);
1938
1939 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1940                                  enum language);
1941
1942 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1943                                     enum language);
1944
1945 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1946                                     enum language);
1947
1948 static void dwarf2_add_dependence (struct dwarf2_cu *,
1949                                    struct dwarf2_per_cu_data *);
1950
1951 static void dwarf2_mark (struct dwarf2_cu *);
1952
1953 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1954
1955 static struct type *get_die_type_at_offset (sect_offset,
1956                                             struct dwarf2_per_cu_data *);
1957
1958 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1959
1960 static void dwarf2_release_queue (void *dummy);
1961
1962 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1963                              enum language pretend_language);
1964
1965 static void process_queue (void);
1966
1967 /* The return type of find_file_and_directory.  Note, the enclosed
1968    string pointers are only valid while this object is valid.  */
1969
1970 struct file_and_directory
1971 {
1972   /* The filename.  This is never NULL.  */
1973   const char *name;
1974
1975   /* The compilation directory.  NULL if not known.  If we needed to
1976      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1977      points directly to the DW_AT_comp_dir string attribute owned by
1978      the obstack that owns the DIE.  */
1979   const char *comp_dir;
1980
1981   /* If we needed to build a new string for comp_dir, this is what
1982      owns the storage.  */
1983   std::string comp_dir_storage;
1984 };
1985
1986 static file_and_directory find_file_and_directory (struct die_info *die,
1987                                                    struct dwarf2_cu *cu);
1988
1989 static char *file_full_name (int file, struct line_header *lh,
1990                              const char *comp_dir);
1991
1992 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1993 enum class rcuh_kind { COMPILE, TYPE };
1994
1995 static const gdb_byte *read_and_check_comp_unit_head
1996   (struct comp_unit_head *header,
1997    struct dwarf2_section_info *section,
1998    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1999    rcuh_kind section_kind);
2000
2001 static void init_cutu_and_read_dies
2002   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2003    int use_existing_cu, int keep,
2004    die_reader_func_ftype *die_reader_func, void *data);
2005
2006 static void init_cutu_and_read_dies_simple
2007   (struct dwarf2_per_cu_data *this_cu,
2008    die_reader_func_ftype *die_reader_func, void *data);
2009
2010 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2011
2012 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2013
2014 static struct dwo_unit *lookup_dwo_unit_in_dwp
2015   (struct dwp_file *dwp_file, const char *comp_dir,
2016    ULONGEST signature, int is_debug_types);
2017
2018 static struct dwp_file *get_dwp_file (void);
2019
2020 static struct dwo_unit *lookup_dwo_comp_unit
2021   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2022
2023 static struct dwo_unit *lookup_dwo_type_unit
2024   (struct signatured_type *, const char *, const char *);
2025
2026 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2027
2028 static void free_dwo_file_cleanup (void *);
2029
2030 static void process_cu_includes (void);
2031
2032 static void check_producer (struct dwarf2_cu *cu);
2033
2034 static void free_line_header_voidp (void *arg);
2035 \f
2036 /* Various complaints about symbol reading that don't abort the process.  */
2037
2038 static void
2039 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2040 {
2041   complaint (&symfile_complaints,
2042              _("statement list doesn't fit in .debug_line section"));
2043 }
2044
2045 static void
2046 dwarf2_debug_line_missing_file_complaint (void)
2047 {
2048   complaint (&symfile_complaints,
2049              _(".debug_line section has line data without a file"));
2050 }
2051
2052 static void
2053 dwarf2_debug_line_missing_end_sequence_complaint (void)
2054 {
2055   complaint (&symfile_complaints,
2056              _(".debug_line section has line "
2057                "program sequence without an end"));
2058 }
2059
2060 static void
2061 dwarf2_complex_location_expr_complaint (void)
2062 {
2063   complaint (&symfile_complaints, _("location expression too complex"));
2064 }
2065
2066 static void
2067 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2068                                               int arg3)
2069 {
2070   complaint (&symfile_complaints,
2071              _("const value length mismatch for '%s', got %d, expected %d"),
2072              arg1, arg2, arg3);
2073 }
2074
2075 static void
2076 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2077 {
2078   complaint (&symfile_complaints,
2079              _("debug info runs off end of %s section"
2080                " [in module %s]"),
2081              get_section_name (section),
2082              get_section_file_name (section));
2083 }
2084
2085 static void
2086 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2087 {
2088   complaint (&symfile_complaints,
2089              _("macro debug info contains a "
2090                "malformed macro definition:\n`%s'"),
2091              arg1);
2092 }
2093
2094 static void
2095 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2096 {
2097   complaint (&symfile_complaints,
2098              _("invalid attribute class or form for '%s' in '%s'"),
2099              arg1, arg2);
2100 }
2101
2102 /* Hash function for line_header_hash.  */
2103
2104 static hashval_t
2105 line_header_hash (const struct line_header *ofs)
2106 {
2107   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2108 }
2109
2110 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2111
2112 static hashval_t
2113 line_header_hash_voidp (const void *item)
2114 {
2115   const struct line_header *ofs = (const struct line_header *) item;
2116
2117   return line_header_hash (ofs);
2118 }
2119
2120 /* Equality function for line_header_hash.  */
2121
2122 static int
2123 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2124 {
2125   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2126   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2127
2128   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2129           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2130 }
2131
2132 \f
2133 #if WORDS_BIGENDIAN
2134
2135 /* Convert VALUE between big- and little-endian.  */
2136 static offset_type
2137 byte_swap (offset_type value)
2138 {
2139   offset_type result;
2140
2141   result = (value & 0xff) << 24;
2142   result |= (value & 0xff00) << 8;
2143   result |= (value & 0xff0000) >> 8;
2144   result |= (value & 0xff000000) >> 24;
2145   return result;
2146 }
2147
2148 #define MAYBE_SWAP(V)  byte_swap (V)
2149
2150 #else
2151 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2152 #endif /* WORDS_BIGENDIAN */
2153
2154 /* Read the given attribute value as an address, taking the attribute's
2155    form into account.  */
2156
2157 static CORE_ADDR
2158 attr_value_as_address (struct attribute *attr)
2159 {
2160   CORE_ADDR addr;
2161
2162   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2163     {
2164       /* Aside from a few clearly defined exceptions, attributes that
2165          contain an address must always be in DW_FORM_addr form.
2166          Unfortunately, some compilers happen to be violating this
2167          requirement by encoding addresses using other forms, such
2168          as DW_FORM_data4 for example.  For those broken compilers,
2169          we try to do our best, without any guarantee of success,
2170          to interpret the address correctly.  It would also be nice
2171          to generate a complaint, but that would require us to maintain
2172          a list of legitimate cases where a non-address form is allowed,
2173          as well as update callers to pass in at least the CU's DWARF
2174          version.  This is more overhead than what we're willing to
2175          expand for a pretty rare case.  */
2176       addr = DW_UNSND (attr);
2177     }
2178   else
2179     addr = DW_ADDR (attr);
2180
2181   return addr;
2182 }
2183
2184 /* The suffix for an index file.  */
2185 #define INDEX_SUFFIX ".gdb-index"
2186
2187 /* Try to locate the sections we need for DWARF 2 debugging
2188    information and return true if we have enough to do something.
2189    NAMES points to the dwarf2 section names, or is NULL if the standard
2190    ELF names are used.  */
2191
2192 int
2193 dwarf2_has_info (struct objfile *objfile,
2194                  const struct dwarf2_debug_sections *names)
2195 {
2196   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2197                         objfile_data (objfile, dwarf2_objfile_data_key));
2198   if (!dwarf2_per_objfile)
2199     {
2200       /* Initialize per-objfile state.  */
2201       struct dwarf2_per_objfile *data
2202         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2203
2204       memset (data, 0, sizeof (*data));
2205       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
2206       dwarf2_per_objfile = data;
2207
2208       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
2209                              (void *) names);
2210       dwarf2_per_objfile->objfile = objfile;
2211     }
2212   return (!dwarf2_per_objfile->info.is_virtual
2213           && dwarf2_per_objfile->info.s.section != NULL
2214           && !dwarf2_per_objfile->abbrev.is_virtual
2215           && dwarf2_per_objfile->abbrev.s.section != NULL);
2216 }
2217
2218 /* Return the containing section of virtual section SECTION.  */
2219
2220 static struct dwarf2_section_info *
2221 get_containing_section (const struct dwarf2_section_info *section)
2222 {
2223   gdb_assert (section->is_virtual);
2224   return section->s.containing_section;
2225 }
2226
2227 /* Return the bfd owner of SECTION.  */
2228
2229 static struct bfd *
2230 get_section_bfd_owner (const struct dwarf2_section_info *section)
2231 {
2232   if (section->is_virtual)
2233     {
2234       section = get_containing_section (section);
2235       gdb_assert (!section->is_virtual);
2236     }
2237   return section->s.section->owner;
2238 }
2239
2240 /* Return the bfd section of SECTION.
2241    Returns NULL if the section is not present.  */
2242
2243 static asection *
2244 get_section_bfd_section (const struct dwarf2_section_info *section)
2245 {
2246   if (section->is_virtual)
2247     {
2248       section = get_containing_section (section);
2249       gdb_assert (!section->is_virtual);
2250     }
2251   return section->s.section;
2252 }
2253
2254 /* Return the name of SECTION.  */
2255
2256 static const char *
2257 get_section_name (const struct dwarf2_section_info *section)
2258 {
2259   asection *sectp = get_section_bfd_section (section);
2260
2261   gdb_assert (sectp != NULL);
2262   return bfd_section_name (get_section_bfd_owner (section), sectp);
2263 }
2264
2265 /* Return the name of the file SECTION is in.  */
2266
2267 static const char *
2268 get_section_file_name (const struct dwarf2_section_info *section)
2269 {
2270   bfd *abfd = get_section_bfd_owner (section);
2271
2272   return bfd_get_filename (abfd);
2273 }
2274
2275 /* Return the id of SECTION.
2276    Returns 0 if SECTION doesn't exist.  */
2277
2278 static int
2279 get_section_id (const struct dwarf2_section_info *section)
2280 {
2281   asection *sectp = get_section_bfd_section (section);
2282
2283   if (sectp == NULL)
2284     return 0;
2285   return sectp->id;
2286 }
2287
2288 /* Return the flags of SECTION.
2289    SECTION (or containing section if this is a virtual section) must exist.  */
2290
2291 static int
2292 get_section_flags (const struct dwarf2_section_info *section)
2293 {
2294   asection *sectp = get_section_bfd_section (section);
2295
2296   gdb_assert (sectp != NULL);
2297   return bfd_get_section_flags (sectp->owner, sectp);
2298 }
2299
2300 /* When loading sections, we look either for uncompressed section or for
2301    compressed section names.  */
2302
2303 static int
2304 section_is_p (const char *section_name,
2305               const struct dwarf2_section_names *names)
2306 {
2307   if (names->normal != NULL
2308       && strcmp (section_name, names->normal) == 0)
2309     return 1;
2310   if (names->compressed != NULL
2311       && strcmp (section_name, names->compressed) == 0)
2312     return 1;
2313   return 0;
2314 }
2315
2316 /* This function is mapped across the sections and remembers the
2317    offset and size of each of the debugging sections we are interested
2318    in.  */
2319
2320 static void
2321 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
2322 {
2323   const struct dwarf2_debug_sections *names;
2324   flagword aflag = bfd_get_section_flags (abfd, sectp);
2325
2326   if (vnames == NULL)
2327     names = &dwarf2_elf_names;
2328   else
2329     names = (const struct dwarf2_debug_sections *) vnames;
2330
2331   if ((aflag & SEC_HAS_CONTENTS) == 0)
2332     {
2333     }
2334   else if (section_is_p (sectp->name, &names->info))
2335     {
2336       dwarf2_per_objfile->info.s.section = sectp;
2337       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
2338     }
2339   else if (section_is_p (sectp->name, &names->abbrev))
2340     {
2341       dwarf2_per_objfile->abbrev.s.section = sectp;
2342       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
2343     }
2344   else if (section_is_p (sectp->name, &names->line))
2345     {
2346       dwarf2_per_objfile->line.s.section = sectp;
2347       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
2348     }
2349   else if (section_is_p (sectp->name, &names->loc))
2350     {
2351       dwarf2_per_objfile->loc.s.section = sectp;
2352       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
2353     }
2354   else if (section_is_p (sectp->name, &names->loclists))
2355     {
2356       dwarf2_per_objfile->loclists.s.section = sectp;
2357       dwarf2_per_objfile->loclists.size = bfd_get_section_size (sectp);
2358     }
2359   else if (section_is_p (sectp->name, &names->macinfo))
2360     {
2361       dwarf2_per_objfile->macinfo.s.section = sectp;
2362       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
2363     }
2364   else if (section_is_p (sectp->name, &names->macro))
2365     {
2366       dwarf2_per_objfile->macro.s.section = sectp;
2367       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
2368     }
2369   else if (section_is_p (sectp->name, &names->str))
2370     {
2371       dwarf2_per_objfile->str.s.section = sectp;
2372       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
2373     }
2374   else if (section_is_p (sectp->name, &names->line_str))
2375     {
2376       dwarf2_per_objfile->line_str.s.section = sectp;
2377       dwarf2_per_objfile->line_str.size = bfd_get_section_size (sectp);
2378     }
2379   else if (section_is_p (sectp->name, &names->addr))
2380     {
2381       dwarf2_per_objfile->addr.s.section = sectp;
2382       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
2383     }
2384   else if (section_is_p (sectp->name, &names->frame))
2385     {
2386       dwarf2_per_objfile->frame.s.section = sectp;
2387       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
2388     }
2389   else if (section_is_p (sectp->name, &names->eh_frame))
2390     {
2391       dwarf2_per_objfile->eh_frame.s.section = sectp;
2392       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
2393     }
2394   else if (section_is_p (sectp->name, &names->ranges))
2395     {
2396       dwarf2_per_objfile->ranges.s.section = sectp;
2397       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2398     }
2399   else if (section_is_p (sectp->name, &names->rnglists))
2400     {
2401       dwarf2_per_objfile->rnglists.s.section = sectp;
2402       dwarf2_per_objfile->rnglists.size = bfd_get_section_size (sectp);
2403     }
2404   else if (section_is_p (sectp->name, &names->types))
2405     {
2406       struct dwarf2_section_info type_section;
2407
2408       memset (&type_section, 0, sizeof (type_section));
2409       type_section.s.section = sectp;
2410       type_section.size = bfd_get_section_size (sectp);
2411
2412       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2413                      &type_section);
2414     }
2415   else if (section_is_p (sectp->name, &names->gdb_index))
2416     {
2417       dwarf2_per_objfile->gdb_index.s.section = sectp;
2418       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2419     }
2420
2421   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2422       && bfd_section_vma (abfd, sectp) == 0)
2423     dwarf2_per_objfile->has_section_at_zero = 1;
2424 }
2425
2426 /* A helper function that decides whether a section is empty,
2427    or not present.  */
2428
2429 static int
2430 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2431 {
2432   if (section->is_virtual)
2433     return section->size == 0;
2434   return section->s.section == NULL || section->size == 0;
2435 }
2436
2437 /* Read the contents of the section INFO.
2438    OBJFILE is the main object file, but not necessarily the file where
2439    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2440    of the DWO file.
2441    If the section is compressed, uncompress it before returning.  */
2442
2443 static void
2444 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2445 {
2446   asection *sectp;
2447   bfd *abfd;
2448   gdb_byte *buf, *retbuf;
2449
2450   if (info->readin)
2451     return;
2452   info->buffer = NULL;
2453   info->readin = 1;
2454
2455   if (dwarf2_section_empty_p (info))
2456     return;
2457
2458   sectp = get_section_bfd_section (info);
2459
2460   /* If this is a virtual section we need to read in the real one first.  */
2461   if (info->is_virtual)
2462     {
2463       struct dwarf2_section_info *containing_section =
2464         get_containing_section (info);
2465
2466       gdb_assert (sectp != NULL);
2467       if ((sectp->flags & SEC_RELOC) != 0)
2468         {
2469           error (_("Dwarf Error: DWP format V2 with relocations is not"
2470                    " supported in section %s [in module %s]"),
2471                  get_section_name (info), get_section_file_name (info));
2472         }
2473       dwarf2_read_section (objfile, containing_section);
2474       /* Other code should have already caught virtual sections that don't
2475          fit.  */
2476       gdb_assert (info->virtual_offset + info->size
2477                   <= containing_section->size);
2478       /* If the real section is empty or there was a problem reading the
2479          section we shouldn't get here.  */
2480       gdb_assert (containing_section->buffer != NULL);
2481       info->buffer = containing_section->buffer + info->virtual_offset;
2482       return;
2483     }
2484
2485   /* If the section has relocations, we must read it ourselves.
2486      Otherwise we attach it to the BFD.  */
2487   if ((sectp->flags & SEC_RELOC) == 0)
2488     {
2489       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2490       return;
2491     }
2492
2493   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2494   info->buffer = buf;
2495
2496   /* When debugging .o files, we may need to apply relocations; see
2497      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2498      We never compress sections in .o files, so we only need to
2499      try this when the section is not compressed.  */
2500   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2501   if (retbuf != NULL)
2502     {
2503       info->buffer = retbuf;
2504       return;
2505     }
2506
2507   abfd = get_section_bfd_owner (info);
2508   gdb_assert (abfd != NULL);
2509
2510   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2511       || bfd_bread (buf, info->size, abfd) != info->size)
2512     {
2513       error (_("Dwarf Error: Can't read DWARF data"
2514                " in section %s [in module %s]"),
2515              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2516     }
2517 }
2518
2519 /* A helper function that returns the size of a section in a safe way.
2520    If you are positive that the section has been read before using the
2521    size, then it is safe to refer to the dwarf2_section_info object's
2522    "size" field directly.  In other cases, you must call this
2523    function, because for compressed sections the size field is not set
2524    correctly until the section has been read.  */
2525
2526 static bfd_size_type
2527 dwarf2_section_size (struct objfile *objfile,
2528                      struct dwarf2_section_info *info)
2529 {
2530   if (!info->readin)
2531     dwarf2_read_section (objfile, info);
2532   return info->size;
2533 }
2534
2535 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2536    SECTION_NAME.  */
2537
2538 void
2539 dwarf2_get_section_info (struct objfile *objfile,
2540                          enum dwarf2_section_enum sect,
2541                          asection **sectp, const gdb_byte **bufp,
2542                          bfd_size_type *sizep)
2543 {
2544   struct dwarf2_per_objfile *data
2545     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2546                                                   dwarf2_objfile_data_key);
2547   struct dwarf2_section_info *info;
2548
2549   /* We may see an objfile without any DWARF, in which case we just
2550      return nothing.  */
2551   if (data == NULL)
2552     {
2553       *sectp = NULL;
2554       *bufp = NULL;
2555       *sizep = 0;
2556       return;
2557     }
2558   switch (sect)
2559     {
2560     case DWARF2_DEBUG_FRAME:
2561       info = &data->frame;
2562       break;
2563     case DWARF2_EH_FRAME:
2564       info = &data->eh_frame;
2565       break;
2566     default:
2567       gdb_assert_not_reached ("unexpected section");
2568     }
2569
2570   dwarf2_read_section (objfile, info);
2571
2572   *sectp = get_section_bfd_section (info);
2573   *bufp = info->buffer;
2574   *sizep = info->size;
2575 }
2576
2577 /* A helper function to find the sections for a .dwz file.  */
2578
2579 static void
2580 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2581 {
2582   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2583
2584   /* Note that we only support the standard ELF names, because .dwz
2585      is ELF-only (at the time of writing).  */
2586   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2587     {
2588       dwz_file->abbrev.s.section = sectp;
2589       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2590     }
2591   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2592     {
2593       dwz_file->info.s.section = sectp;
2594       dwz_file->info.size = bfd_get_section_size (sectp);
2595     }
2596   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2597     {
2598       dwz_file->str.s.section = sectp;
2599       dwz_file->str.size = bfd_get_section_size (sectp);
2600     }
2601   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2602     {
2603       dwz_file->line.s.section = sectp;
2604       dwz_file->line.size = bfd_get_section_size (sectp);
2605     }
2606   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2607     {
2608       dwz_file->macro.s.section = sectp;
2609       dwz_file->macro.size = bfd_get_section_size (sectp);
2610     }
2611   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2612     {
2613       dwz_file->gdb_index.s.section = sectp;
2614       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2615     }
2616 }
2617
2618 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2619    there is no .gnu_debugaltlink section in the file.  Error if there
2620    is such a section but the file cannot be found.  */
2621
2622 static struct dwz_file *
2623 dwarf2_get_dwz_file (void)
2624 {
2625   char *data;
2626   struct cleanup *cleanup;
2627   const char *filename;
2628   struct dwz_file *result;
2629   bfd_size_type buildid_len_arg;
2630   size_t buildid_len;
2631   bfd_byte *buildid;
2632
2633   if (dwarf2_per_objfile->dwz_file != NULL)
2634     return dwarf2_per_objfile->dwz_file;
2635
2636   bfd_set_error (bfd_error_no_error);
2637   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2638                                       &buildid_len_arg, &buildid);
2639   if (data == NULL)
2640     {
2641       if (bfd_get_error () == bfd_error_no_error)
2642         return NULL;
2643       error (_("could not read '.gnu_debugaltlink' section: %s"),
2644              bfd_errmsg (bfd_get_error ()));
2645     }
2646   cleanup = make_cleanup (xfree, data);
2647   make_cleanup (xfree, buildid);
2648
2649   buildid_len = (size_t) buildid_len_arg;
2650
2651   filename = (const char *) data;
2652
2653   std::string abs_storage;
2654   if (!IS_ABSOLUTE_PATH (filename))
2655     {
2656       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2657
2658       make_cleanup (xfree, abs);
2659       abs_storage = ldirname (abs) + SLASH_STRING + filename;
2660       filename = abs_storage.c_str ();
2661     }
2662
2663   /* First try the file name given in the section.  If that doesn't
2664      work, try to use the build-id instead.  */
2665   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2666   if (dwz_bfd != NULL)
2667     {
2668       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2669         dwz_bfd.release ();
2670     }
2671
2672   if (dwz_bfd == NULL)
2673     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2674
2675   if (dwz_bfd == NULL)
2676     error (_("could not find '.gnu_debugaltlink' file for %s"),
2677            objfile_name (dwarf2_per_objfile->objfile));
2678
2679   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2680                            struct dwz_file);
2681   result->dwz_bfd = dwz_bfd.release ();
2682
2683   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2684
2685   do_cleanups (cleanup);
2686
2687   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2688   dwarf2_per_objfile->dwz_file = result;
2689   return result;
2690 }
2691 \f
2692 /* DWARF quick_symbols_functions support.  */
2693
2694 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2695    unique line tables, so we maintain a separate table of all .debug_line
2696    derived entries to support the sharing.
2697    All the quick functions need is the list of file names.  We discard the
2698    line_header when we're done and don't need to record it here.  */
2699 struct quick_file_names
2700 {
2701   /* The data used to construct the hash key.  */
2702   struct stmt_list_hash hash;
2703
2704   /* The number of entries in file_names, real_names.  */
2705   unsigned int num_file_names;
2706
2707   /* The file names from the line table, after being run through
2708      file_full_name.  */
2709   const char **file_names;
2710
2711   /* The file names from the line table after being run through
2712      gdb_realpath.  These are computed lazily.  */
2713   const char **real_names;
2714 };
2715
2716 /* When using the index (and thus not using psymtabs), each CU has an
2717    object of this type.  This is used to hold information needed by
2718    the various "quick" methods.  */
2719 struct dwarf2_per_cu_quick_data
2720 {
2721   /* The file table.  This can be NULL if there was no file table
2722      or it's currently not read in.
2723      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2724   struct quick_file_names *file_names;
2725
2726   /* The corresponding symbol table.  This is NULL if symbols for this
2727      CU have not yet been read.  */
2728   struct compunit_symtab *compunit_symtab;
2729
2730   /* A temporary mark bit used when iterating over all CUs in
2731      expand_symtabs_matching.  */
2732   unsigned int mark : 1;
2733
2734   /* True if we've tried to read the file table and found there isn't one.
2735      There will be no point in trying to read it again next time.  */
2736   unsigned int no_file_data : 1;
2737 };
2738
2739 /* Utility hash function for a stmt_list_hash.  */
2740
2741 static hashval_t
2742 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2743 {
2744   hashval_t v = 0;
2745
2746   if (stmt_list_hash->dwo_unit != NULL)
2747     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2748   v += to_underlying (stmt_list_hash->line_sect_off);
2749   return v;
2750 }
2751
2752 /* Utility equality function for a stmt_list_hash.  */
2753
2754 static int
2755 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2756                     const struct stmt_list_hash *rhs)
2757 {
2758   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2759     return 0;
2760   if (lhs->dwo_unit != NULL
2761       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2762     return 0;
2763
2764   return lhs->line_sect_off == rhs->line_sect_off;
2765 }
2766
2767 /* Hash function for a quick_file_names.  */
2768
2769 static hashval_t
2770 hash_file_name_entry (const void *e)
2771 {
2772   const struct quick_file_names *file_data
2773     = (const struct quick_file_names *) e;
2774
2775   return hash_stmt_list_entry (&file_data->hash);
2776 }
2777
2778 /* Equality function for a quick_file_names.  */
2779
2780 static int
2781 eq_file_name_entry (const void *a, const void *b)
2782 {
2783   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2784   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2785
2786   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2787 }
2788
2789 /* Delete function for a quick_file_names.  */
2790
2791 static void
2792 delete_file_name_entry (void *e)
2793 {
2794   struct quick_file_names *file_data = (struct quick_file_names *) e;
2795   int i;
2796
2797   for (i = 0; i < file_data->num_file_names; ++i)
2798     {
2799       xfree ((void*) file_data->file_names[i]);
2800       if (file_data->real_names)
2801         xfree ((void*) file_data->real_names[i]);
2802     }
2803
2804   /* The space for the struct itself lives on objfile_obstack,
2805      so we don't free it here.  */
2806 }
2807
2808 /* Create a quick_file_names hash table.  */
2809
2810 static htab_t
2811 create_quick_file_names_table (unsigned int nr_initial_entries)
2812 {
2813   return htab_create_alloc (nr_initial_entries,
2814                             hash_file_name_entry, eq_file_name_entry,
2815                             delete_file_name_entry, xcalloc, xfree);
2816 }
2817
2818 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2819    have to be created afterwards.  You should call age_cached_comp_units after
2820    processing PER_CU->CU.  dw2_setup must have been already called.  */
2821
2822 static void
2823 load_cu (struct dwarf2_per_cu_data *per_cu)
2824 {
2825   if (per_cu->is_debug_types)
2826     load_full_type_unit (per_cu);
2827   else
2828     load_full_comp_unit (per_cu, language_minimal);
2829
2830   if (per_cu->cu == NULL)
2831     return;  /* Dummy CU.  */
2832
2833   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2834 }
2835
2836 /* Read in the symbols for PER_CU.  */
2837
2838 static void
2839 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2840 {
2841   struct cleanup *back_to;
2842
2843   /* Skip type_unit_groups, reading the type units they contain
2844      is handled elsewhere.  */
2845   if (IS_TYPE_UNIT_GROUP (per_cu))
2846     return;
2847
2848   back_to = make_cleanup (dwarf2_release_queue, NULL);
2849
2850   if (dwarf2_per_objfile->using_index
2851       ? per_cu->v.quick->compunit_symtab == NULL
2852       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2853     {
2854       queue_comp_unit (per_cu, language_minimal);
2855       load_cu (per_cu);
2856
2857       /* If we just loaded a CU from a DWO, and we're working with an index
2858          that may badly handle TUs, load all the TUs in that DWO as well.
2859          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2860       if (!per_cu->is_debug_types
2861           && per_cu->cu != NULL
2862           && per_cu->cu->dwo_unit != NULL
2863           && dwarf2_per_objfile->index_table != NULL
2864           && dwarf2_per_objfile->index_table->version <= 7
2865           /* DWP files aren't supported yet.  */
2866           && get_dwp_file () == NULL)
2867         queue_and_load_all_dwo_tus (per_cu);
2868     }
2869
2870   process_queue ();
2871
2872   /* Age the cache, releasing compilation units that have not
2873      been used recently.  */
2874   age_cached_comp_units ();
2875
2876   do_cleanups (back_to);
2877 }
2878
2879 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2880    the objfile from which this CU came.  Returns the resulting symbol
2881    table.  */
2882
2883 static struct compunit_symtab *
2884 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2885 {
2886   gdb_assert (dwarf2_per_objfile->using_index);
2887   if (!per_cu->v.quick->compunit_symtab)
2888     {
2889       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2890       scoped_restore decrementer = increment_reading_symtab ();
2891       dw2_do_instantiate_symtab (per_cu);
2892       process_cu_includes ();
2893       do_cleanups (back_to);
2894     }
2895
2896   return per_cu->v.quick->compunit_symtab;
2897 }
2898
2899 /* Return the CU/TU given its index.
2900
2901    This is intended for loops like:
2902
2903    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2904                     + dwarf2_per_objfile->n_type_units); ++i)
2905      {
2906        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2907
2908        ...;
2909      }
2910 */
2911
2912 static struct dwarf2_per_cu_data *
2913 dw2_get_cutu (int index)
2914 {
2915   if (index >= dwarf2_per_objfile->n_comp_units)
2916     {
2917       index -= dwarf2_per_objfile->n_comp_units;
2918       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2919       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2920     }
2921
2922   return dwarf2_per_objfile->all_comp_units[index];
2923 }
2924
2925 /* Return the CU given its index.
2926    This differs from dw2_get_cutu in that it's for when you know INDEX
2927    refers to a CU.  */
2928
2929 static struct dwarf2_per_cu_data *
2930 dw2_get_cu (int index)
2931 {
2932   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2933
2934   return dwarf2_per_objfile->all_comp_units[index];
2935 }
2936
2937 /* A helper for create_cus_from_index that handles a given list of
2938    CUs.  */
2939
2940 static void
2941 create_cus_from_index_list (struct objfile *objfile,
2942                             const gdb_byte *cu_list, offset_type n_elements,
2943                             struct dwarf2_section_info *section,
2944                             int is_dwz,
2945                             int base_offset)
2946 {
2947   offset_type i;
2948
2949   for (i = 0; i < n_elements; i += 2)
2950     {
2951       gdb_static_assert (sizeof (ULONGEST) >= 8);
2952
2953       sect_offset sect_off
2954         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2955       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2956       cu_list += 2 * 8;
2957
2958       dwarf2_per_cu_data *the_cu
2959         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2960                           struct dwarf2_per_cu_data);
2961       the_cu->sect_off = sect_off;
2962       the_cu->length = length;
2963       the_cu->objfile = objfile;
2964       the_cu->section = section;
2965       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2966                                         struct dwarf2_per_cu_quick_data);
2967       the_cu->is_dwz = is_dwz;
2968       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2969     }
2970 }
2971
2972 /* Read the CU list from the mapped index, and use it to create all
2973    the CU objects for this objfile.  */
2974
2975 static void
2976 create_cus_from_index (struct objfile *objfile,
2977                        const gdb_byte *cu_list, offset_type cu_list_elements,
2978                        const gdb_byte *dwz_list, offset_type dwz_elements)
2979 {
2980   struct dwz_file *dwz;
2981
2982   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2983   dwarf2_per_objfile->all_comp_units =
2984     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
2985                dwarf2_per_objfile->n_comp_units);
2986
2987   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2988                               &dwarf2_per_objfile->info, 0, 0);
2989
2990   if (dwz_elements == 0)
2991     return;
2992
2993   dwz = dwarf2_get_dwz_file ();
2994   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2995                               cu_list_elements / 2);
2996 }
2997
2998 /* Create the signatured type hash table from the index.  */
2999
3000 static void
3001 create_signatured_type_table_from_index (struct objfile *objfile,
3002                                          struct dwarf2_section_info *section,
3003                                          const gdb_byte *bytes,
3004                                          offset_type elements)
3005 {
3006   offset_type i;
3007   htab_t sig_types_hash;
3008
3009   dwarf2_per_objfile->n_type_units
3010     = dwarf2_per_objfile->n_allocated_type_units
3011     = elements / 3;
3012   dwarf2_per_objfile->all_type_units =
3013     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3014
3015   sig_types_hash = allocate_signatured_type_table (objfile);
3016
3017   for (i = 0; i < elements; i += 3)
3018     {
3019       struct signatured_type *sig_type;
3020       ULONGEST signature;
3021       void **slot;
3022       cu_offset type_offset_in_tu;
3023
3024       gdb_static_assert (sizeof (ULONGEST) >= 8);
3025       sect_offset sect_off
3026         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3027       type_offset_in_tu
3028         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3029                                                 BFD_ENDIAN_LITTLE);
3030       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3031       bytes += 3 * 8;
3032
3033       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3034                                  struct signatured_type);
3035       sig_type->signature = signature;
3036       sig_type->type_offset_in_tu = type_offset_in_tu;
3037       sig_type->per_cu.is_debug_types = 1;
3038       sig_type->per_cu.section = section;
3039       sig_type->per_cu.sect_off = sect_off;
3040       sig_type->per_cu.objfile = objfile;
3041       sig_type->per_cu.v.quick
3042         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3043                           struct dwarf2_per_cu_quick_data);
3044
3045       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3046       *slot = sig_type;
3047
3048       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3049     }
3050
3051   dwarf2_per_objfile->signatured_types = sig_types_hash;
3052 }
3053
3054 /* Read the address map data from the mapped index, and use it to
3055    populate the objfile's psymtabs_addrmap.  */
3056
3057 static void
3058 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3059 {
3060   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3061   const gdb_byte *iter, *end;
3062   struct obstack temp_obstack;
3063   struct addrmap *mutable_map;
3064   struct cleanup *cleanup;
3065   CORE_ADDR baseaddr;
3066
3067   obstack_init (&temp_obstack);
3068   cleanup = make_cleanup_obstack_free (&temp_obstack);
3069   mutable_map = addrmap_create_mutable (&temp_obstack);
3070
3071   iter = index->address_table;
3072   end = iter + index->address_table_size;
3073
3074   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3075
3076   while (iter < end)
3077     {
3078       ULONGEST hi, lo, cu_index;
3079       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3080       iter += 8;
3081       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3082       iter += 8;
3083       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3084       iter += 4;
3085
3086       if (lo > hi)
3087         {
3088           complaint (&symfile_complaints,
3089                      _(".gdb_index address table has invalid range (%s - %s)"),
3090                      hex_string (lo), hex_string (hi));
3091           continue;
3092         }
3093
3094       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3095         {
3096           complaint (&symfile_complaints,
3097                      _(".gdb_index address table has invalid CU number %u"),
3098                      (unsigned) cu_index);
3099           continue;
3100         }
3101
3102       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3103       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3104       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3105     }
3106
3107   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3108                                                     &objfile->objfile_obstack);
3109   do_cleanups (cleanup);
3110 }
3111
3112 /* The hash function for strings in the mapped index.  This is the same as
3113    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3114    implementation.  This is necessary because the hash function is tied to the
3115    format of the mapped index file.  The hash values do not have to match with
3116    SYMBOL_HASH_NEXT.
3117    
3118    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3119
3120 static hashval_t
3121 mapped_index_string_hash (int index_version, const void *p)
3122 {
3123   const unsigned char *str = (const unsigned char *) p;
3124   hashval_t r = 0;
3125   unsigned char c;
3126
3127   while ((c = *str++) != 0)
3128     {
3129       if (index_version >= 5)
3130         c = tolower (c);
3131       r = r * 67 + c - 113;
3132     }
3133
3134   return r;
3135 }
3136
3137 /* Find a slot in the mapped index INDEX for the object named NAME.
3138    If NAME is found, set *VEC_OUT to point to the CU vector in the
3139    constant pool and return 1.  If NAME cannot be found, return 0.  */
3140
3141 static int
3142 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3143                           offset_type **vec_out)
3144 {
3145   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3146   offset_type hash;
3147   offset_type slot, step;
3148   int (*cmp) (const char *, const char *);
3149
3150   if (current_language->la_language == language_cplus
3151       || current_language->la_language == language_fortran
3152       || current_language->la_language == language_d)
3153     {
3154       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3155          not contain any.  */
3156
3157       if (strchr (name, '(') != NULL)
3158         {
3159           char *without_params = cp_remove_params (name);
3160
3161           if (without_params != NULL)
3162             {
3163               make_cleanup (xfree, without_params);
3164               name = without_params;
3165             }
3166         }
3167     }
3168
3169   /* Index version 4 did not support case insensitive searches.  But the
3170      indices for case insensitive languages are built in lowercase, therefore
3171      simulate our NAME being searched is also lowercased.  */
3172   hash = mapped_index_string_hash ((index->version == 4
3173                                     && case_sensitivity == case_sensitive_off
3174                                     ? 5 : index->version),
3175                                    name);
3176
3177   slot = hash & (index->symbol_table_slots - 1);
3178   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3179   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3180
3181   for (;;)
3182     {
3183       /* Convert a slot number to an offset into the table.  */
3184       offset_type i = 2 * slot;
3185       const char *str;
3186       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3187         {
3188           do_cleanups (back_to);
3189           return 0;
3190         }
3191
3192       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3193       if (!cmp (name, str))
3194         {
3195           *vec_out = (offset_type *) (index->constant_pool
3196                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3197           do_cleanups (back_to);
3198           return 1;
3199         }
3200
3201       slot = (slot + step) & (index->symbol_table_slots - 1);
3202     }
3203 }
3204
3205 /* A helper function that reads the .gdb_index from SECTION and fills
3206    in MAP.  FILENAME is the name of the file containing the section;
3207    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3208    ok to use deprecated sections.
3209
3210    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3211    out parameters that are filled in with information about the CU and
3212    TU lists in the section.
3213
3214    Returns 1 if all went well, 0 otherwise.  */
3215
3216 static int
3217 read_index_from_section (struct objfile *objfile,
3218                          const char *filename,
3219                          int deprecated_ok,
3220                          struct dwarf2_section_info *section,
3221                          struct mapped_index *map,
3222                          const gdb_byte **cu_list,
3223                          offset_type *cu_list_elements,
3224                          const gdb_byte **types_list,
3225                          offset_type *types_list_elements)
3226 {
3227   const gdb_byte *addr;
3228   offset_type version;
3229   offset_type *metadata;
3230   int i;
3231
3232   if (dwarf2_section_empty_p (section))
3233     return 0;
3234
3235   /* Older elfutils strip versions could keep the section in the main
3236      executable while splitting it for the separate debug info file.  */
3237   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3238     return 0;
3239
3240   dwarf2_read_section (objfile, section);
3241
3242   addr = section->buffer;
3243   /* Version check.  */
3244   version = MAYBE_SWAP (*(offset_type *) addr);
3245   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3246      causes the index to behave very poorly for certain requests.  Version 3
3247      contained incomplete addrmap.  So, it seems better to just ignore such
3248      indices.  */
3249   if (version < 4)
3250     {
3251       static int warning_printed = 0;
3252       if (!warning_printed)
3253         {
3254           warning (_("Skipping obsolete .gdb_index section in %s."),
3255                    filename);
3256           warning_printed = 1;
3257         }
3258       return 0;
3259     }
3260   /* Index version 4 uses a different hash function than index version
3261      5 and later.
3262
3263      Versions earlier than 6 did not emit psymbols for inlined
3264      functions.  Using these files will cause GDB not to be able to
3265      set breakpoints on inlined functions by name, so we ignore these
3266      indices unless the user has done
3267      "set use-deprecated-index-sections on".  */
3268   if (version < 6 && !deprecated_ok)
3269     {
3270       static int warning_printed = 0;
3271       if (!warning_printed)
3272         {
3273           warning (_("\
3274 Skipping deprecated .gdb_index section in %s.\n\
3275 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3276 to use the section anyway."),
3277                    filename);
3278           warning_printed = 1;
3279         }
3280       return 0;
3281     }
3282   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3283      of the TU (for symbols coming from TUs),
3284      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3285      Plus gold-generated indices can have duplicate entries for global symbols,
3286      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3287      These are just performance bugs, and we can't distinguish gdb-generated
3288      indices from gold-generated ones, so issue no warning here.  */
3289
3290   /* Indexes with higher version than the one supported by GDB may be no
3291      longer backward compatible.  */
3292   if (version > 8)
3293     return 0;
3294
3295   map->version = version;
3296   map->total_size = section->size;
3297
3298   metadata = (offset_type *) (addr + sizeof (offset_type));
3299
3300   i = 0;
3301   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3302   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3303                        / 8);
3304   ++i;
3305
3306   *types_list = addr + MAYBE_SWAP (metadata[i]);
3307   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3308                            - MAYBE_SWAP (metadata[i]))
3309                           / 8);
3310   ++i;
3311
3312   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3313   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3314                              - MAYBE_SWAP (metadata[i]));
3315   ++i;
3316
3317   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3318   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3319                               - MAYBE_SWAP (metadata[i]))
3320                              / (2 * sizeof (offset_type)));
3321   ++i;
3322
3323   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3324
3325   return 1;
3326 }
3327
3328
3329 /* Read the index file.  If everything went ok, initialize the "quick"
3330    elements of all the CUs and return 1.  Otherwise, return 0.  */
3331
3332 static int
3333 dwarf2_read_index (struct objfile *objfile)
3334 {
3335   struct mapped_index local_map, *map;
3336   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3337   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3338   struct dwz_file *dwz;
3339
3340   if (!read_index_from_section (objfile, objfile_name (objfile),
3341                                 use_deprecated_index_sections,
3342                                 &dwarf2_per_objfile->gdb_index, &local_map,
3343                                 &cu_list, &cu_list_elements,
3344                                 &types_list, &types_list_elements))
3345     return 0;
3346
3347   /* Don't use the index if it's empty.  */
3348   if (local_map.symbol_table_slots == 0)
3349     return 0;
3350
3351   /* If there is a .dwz file, read it so we can get its CU list as
3352      well.  */
3353   dwz = dwarf2_get_dwz_file ();
3354   if (dwz != NULL)
3355     {
3356       struct mapped_index dwz_map;
3357       const gdb_byte *dwz_types_ignore;
3358       offset_type dwz_types_elements_ignore;
3359
3360       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3361                                     1,
3362                                     &dwz->gdb_index, &dwz_map,
3363                                     &dwz_list, &dwz_list_elements,
3364                                     &dwz_types_ignore,
3365                                     &dwz_types_elements_ignore))
3366         {
3367           warning (_("could not read '.gdb_index' section from %s; skipping"),
3368                    bfd_get_filename (dwz->dwz_bfd));
3369           return 0;
3370         }
3371     }
3372
3373   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3374                          dwz_list_elements);
3375
3376   if (types_list_elements)
3377     {
3378       struct dwarf2_section_info *section;
3379
3380       /* We can only handle a single .debug_types when we have an
3381          index.  */
3382       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3383         return 0;
3384
3385       section = VEC_index (dwarf2_section_info_def,
3386                            dwarf2_per_objfile->types, 0);
3387
3388       create_signatured_type_table_from_index (objfile, section, types_list,
3389                                                types_list_elements);
3390     }
3391
3392   create_addrmap_from_index (objfile, &local_map);
3393
3394   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3395   *map = local_map;
3396
3397   dwarf2_per_objfile->index_table = map;
3398   dwarf2_per_objfile->using_index = 1;
3399   dwarf2_per_objfile->quick_file_names_table =
3400     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3401
3402   return 1;
3403 }
3404
3405 /* A helper for the "quick" functions which sets the global
3406    dwarf2_per_objfile according to OBJFILE.  */
3407
3408 static void
3409 dw2_setup (struct objfile *objfile)
3410 {
3411   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3412                         objfile_data (objfile, dwarf2_objfile_data_key));
3413   gdb_assert (dwarf2_per_objfile);
3414 }
3415
3416 /* die_reader_func for dw2_get_file_names.  */
3417
3418 static void
3419 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3420                            const gdb_byte *info_ptr,
3421                            struct die_info *comp_unit_die,
3422                            int has_children,
3423                            void *data)
3424 {
3425   struct dwarf2_cu *cu = reader->cu;
3426   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3427   struct objfile *objfile = dwarf2_per_objfile->objfile;
3428   struct dwarf2_per_cu_data *lh_cu;
3429   struct attribute *attr;
3430   int i;
3431   void **slot;
3432   struct quick_file_names *qfn;
3433
3434   gdb_assert (! this_cu->is_debug_types);
3435
3436   /* Our callers never want to match partial units -- instead they
3437      will match the enclosing full CU.  */
3438   if (comp_unit_die->tag == DW_TAG_partial_unit)
3439     {
3440       this_cu->v.quick->no_file_data = 1;
3441       return;
3442     }
3443
3444   lh_cu = this_cu;
3445   slot = NULL;
3446
3447   line_header_up lh;
3448   sect_offset line_offset {};
3449
3450   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3451   if (attr)
3452     {
3453       struct quick_file_names find_entry;
3454
3455       line_offset = (sect_offset) DW_UNSND (attr);
3456
3457       /* We may have already read in this line header (TU line header sharing).
3458          If we have we're done.  */
3459       find_entry.hash.dwo_unit = cu->dwo_unit;
3460       find_entry.hash.line_sect_off = line_offset;
3461       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3462                              &find_entry, INSERT);
3463       if (*slot != NULL)
3464         {
3465           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3466           return;
3467         }
3468
3469       lh = dwarf_decode_line_header (line_offset, cu);
3470     }
3471   if (lh == NULL)
3472     {
3473       lh_cu->v.quick->no_file_data = 1;
3474       return;
3475     }
3476
3477   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3478   qfn->hash.dwo_unit = cu->dwo_unit;
3479   qfn->hash.line_sect_off = line_offset;
3480   gdb_assert (slot != NULL);
3481   *slot = qfn;
3482
3483   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3484
3485   qfn->num_file_names = lh->file_names.size ();
3486   qfn->file_names =
3487     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3488   for (i = 0; i < lh->file_names.size (); ++i)
3489     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3490   qfn->real_names = NULL;
3491
3492   lh_cu->v.quick->file_names = qfn;
3493 }
3494
3495 /* A helper for the "quick" functions which attempts to read the line
3496    table for THIS_CU.  */
3497
3498 static struct quick_file_names *
3499 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3500 {
3501   /* This should never be called for TUs.  */
3502   gdb_assert (! this_cu->is_debug_types);
3503   /* Nor type unit groups.  */
3504   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3505
3506   if (this_cu->v.quick->file_names != NULL)
3507     return this_cu->v.quick->file_names;
3508   /* If we know there is no line data, no point in looking again.  */
3509   if (this_cu->v.quick->no_file_data)
3510     return NULL;
3511
3512   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3513
3514   if (this_cu->v.quick->no_file_data)
3515     return NULL;
3516   return this_cu->v.quick->file_names;
3517 }
3518
3519 /* A helper for the "quick" functions which computes and caches the
3520    real path for a given file name from the line table.  */
3521
3522 static const char *
3523 dw2_get_real_path (struct objfile *objfile,
3524                    struct quick_file_names *qfn, int index)
3525 {
3526   if (qfn->real_names == NULL)
3527     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3528                                       qfn->num_file_names, const char *);
3529
3530   if (qfn->real_names[index] == NULL)
3531     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3532
3533   return qfn->real_names[index];
3534 }
3535
3536 static struct symtab *
3537 dw2_find_last_source_symtab (struct objfile *objfile)
3538 {
3539   struct compunit_symtab *cust;
3540   int index;
3541
3542   dw2_setup (objfile);
3543   index = dwarf2_per_objfile->n_comp_units - 1;
3544   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3545   if (cust == NULL)
3546     return NULL;
3547   return compunit_primary_filetab (cust);
3548 }
3549
3550 /* Traversal function for dw2_forget_cached_source_info.  */
3551
3552 static int
3553 dw2_free_cached_file_names (void **slot, void *info)
3554 {
3555   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3556
3557   if (file_data->real_names)
3558     {
3559       int i;
3560
3561       for (i = 0; i < file_data->num_file_names; ++i)
3562         {
3563           xfree ((void*) file_data->real_names[i]);
3564           file_data->real_names[i] = NULL;
3565         }
3566     }
3567
3568   return 1;
3569 }
3570
3571 static void
3572 dw2_forget_cached_source_info (struct objfile *objfile)
3573 {
3574   dw2_setup (objfile);
3575
3576   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3577                           dw2_free_cached_file_names, NULL);
3578 }
3579
3580 /* Helper function for dw2_map_symtabs_matching_filename that expands
3581    the symtabs and calls the iterator.  */
3582
3583 static int
3584 dw2_map_expand_apply (struct objfile *objfile,
3585                       struct dwarf2_per_cu_data *per_cu,
3586                       const char *name, const char *real_path,
3587                       gdb::function_view<bool (symtab *)> callback)
3588 {
3589   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3590
3591   /* Don't visit already-expanded CUs.  */
3592   if (per_cu->v.quick->compunit_symtab)
3593     return 0;
3594
3595   /* This may expand more than one symtab, and we want to iterate over
3596      all of them.  */
3597   dw2_instantiate_symtab (per_cu);
3598
3599   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3600                                     last_made, callback);
3601 }
3602
3603 /* Implementation of the map_symtabs_matching_filename method.  */
3604
3605 static bool
3606 dw2_map_symtabs_matching_filename
3607   (struct objfile *objfile, const char *name, const char *real_path,
3608    gdb::function_view<bool (symtab *)> callback)
3609 {
3610   int i;
3611   const char *name_basename = lbasename (name);
3612
3613   dw2_setup (objfile);
3614
3615   /* The rule is CUs specify all the files, including those used by
3616      any TU, so there's no need to scan TUs here.  */
3617
3618   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3619     {
3620       int j;
3621       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3622       struct quick_file_names *file_data;
3623
3624       /* We only need to look at symtabs not already expanded.  */
3625       if (per_cu->v.quick->compunit_symtab)
3626         continue;
3627
3628       file_data = dw2_get_file_names (per_cu);
3629       if (file_data == NULL)
3630         continue;
3631
3632       for (j = 0; j < file_data->num_file_names; ++j)
3633         {
3634           const char *this_name = file_data->file_names[j];
3635           const char *this_real_name;
3636
3637           if (compare_filenames_for_search (this_name, name))
3638             {
3639               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3640                                         callback))
3641                 return true;
3642               continue;
3643             }
3644
3645           /* Before we invoke realpath, which can get expensive when many
3646              files are involved, do a quick comparison of the basenames.  */
3647           if (! basenames_may_differ
3648               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3649             continue;
3650
3651           this_real_name = dw2_get_real_path (objfile, file_data, j);
3652           if (compare_filenames_for_search (this_real_name, name))
3653             {
3654               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3655                                         callback))
3656                 return true;
3657               continue;
3658             }
3659
3660           if (real_path != NULL)
3661             {
3662               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3663               gdb_assert (IS_ABSOLUTE_PATH (name));
3664               if (this_real_name != NULL
3665                   && FILENAME_CMP (real_path, this_real_name) == 0)
3666                 {
3667                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3668                                             callback))
3669                     return true;
3670                   continue;
3671                 }
3672             }
3673         }
3674     }
3675
3676   return false;
3677 }
3678
3679 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3680
3681 struct dw2_symtab_iterator
3682 {
3683   /* The internalized form of .gdb_index.  */
3684   struct mapped_index *index;
3685   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3686   int want_specific_block;
3687   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3688      Unused if !WANT_SPECIFIC_BLOCK.  */
3689   int block_index;
3690   /* The kind of symbol we're looking for.  */
3691   domain_enum domain;
3692   /* The list of CUs from the index entry of the symbol,
3693      or NULL if not found.  */
3694   offset_type *vec;
3695   /* The next element in VEC to look at.  */
3696   int next;
3697   /* The number of elements in VEC, or zero if there is no match.  */
3698   int length;
3699   /* Have we seen a global version of the symbol?
3700      If so we can ignore all further global instances.
3701      This is to work around gold/15646, inefficient gold-generated
3702      indices.  */
3703   int global_seen;
3704 };
3705
3706 /* Initialize the index symtab iterator ITER.
3707    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3708    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3709
3710 static void
3711 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3712                       struct mapped_index *index,
3713                       int want_specific_block,
3714                       int block_index,
3715                       domain_enum domain,
3716                       const char *name)
3717 {
3718   iter->index = index;
3719   iter->want_specific_block = want_specific_block;
3720   iter->block_index = block_index;
3721   iter->domain = domain;
3722   iter->next = 0;
3723   iter->global_seen = 0;
3724
3725   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3726     iter->length = MAYBE_SWAP (*iter->vec);
3727   else
3728     {
3729       iter->vec = NULL;
3730       iter->length = 0;
3731     }
3732 }
3733
3734 /* Return the next matching CU or NULL if there are no more.  */
3735
3736 static struct dwarf2_per_cu_data *
3737 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3738 {
3739   for ( ; iter->next < iter->length; ++iter->next)
3740     {
3741       offset_type cu_index_and_attrs =
3742         MAYBE_SWAP (iter->vec[iter->next + 1]);
3743       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3744       struct dwarf2_per_cu_data *per_cu;
3745       int want_static = iter->block_index != GLOBAL_BLOCK;
3746       /* This value is only valid for index versions >= 7.  */
3747       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3748       gdb_index_symbol_kind symbol_kind =
3749         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3750       /* Only check the symbol attributes if they're present.
3751          Indices prior to version 7 don't record them,
3752          and indices >= 7 may elide them for certain symbols
3753          (gold does this).  */
3754       int attrs_valid =
3755         (iter->index->version >= 7
3756          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3757
3758       /* Don't crash on bad data.  */
3759       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3760                        + dwarf2_per_objfile->n_type_units))
3761         {
3762           complaint (&symfile_complaints,
3763                      _(".gdb_index entry has bad CU index"
3764                        " [in module %s]"),
3765                      objfile_name (dwarf2_per_objfile->objfile));
3766           continue;
3767         }
3768
3769       per_cu = dw2_get_cutu (cu_index);
3770
3771       /* Skip if already read in.  */
3772       if (per_cu->v.quick->compunit_symtab)
3773         continue;
3774
3775       /* Check static vs global.  */
3776       if (attrs_valid)
3777         {
3778           if (iter->want_specific_block
3779               && want_static != is_static)
3780             continue;
3781           /* Work around gold/15646.  */
3782           if (!is_static && iter->global_seen)
3783             continue;
3784           if (!is_static)
3785             iter->global_seen = 1;
3786         }
3787
3788       /* Only check the symbol's kind if it has one.  */
3789       if (attrs_valid)
3790         {
3791           switch (iter->domain)
3792             {
3793             case VAR_DOMAIN:
3794               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3795                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3796                   /* Some types are also in VAR_DOMAIN.  */
3797                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3798                 continue;
3799               break;
3800             case STRUCT_DOMAIN:
3801               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3802                 continue;
3803               break;
3804             case LABEL_DOMAIN:
3805               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3806                 continue;
3807               break;
3808             default:
3809               break;
3810             }
3811         }
3812
3813       ++iter->next;
3814       return per_cu;
3815     }
3816
3817   return NULL;
3818 }
3819
3820 static struct compunit_symtab *
3821 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3822                    const char *name, domain_enum domain)
3823 {
3824   struct compunit_symtab *stab_best = NULL;
3825   struct mapped_index *index;
3826
3827   dw2_setup (objfile);
3828
3829   index = dwarf2_per_objfile->index_table;
3830
3831   /* index is NULL if OBJF_READNOW.  */
3832   if (index)
3833     {
3834       struct dw2_symtab_iterator iter;
3835       struct dwarf2_per_cu_data *per_cu;
3836
3837       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3838
3839       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3840         {
3841           struct symbol *sym, *with_opaque = NULL;
3842           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3843           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3844           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3845
3846           sym = block_find_symbol (block, name, domain,
3847                                    block_find_non_opaque_type_preferred,
3848                                    &with_opaque);
3849
3850           /* Some caution must be observed with overloaded functions
3851              and methods, since the index will not contain any overload
3852              information (but NAME might contain it).  */
3853
3854           if (sym != NULL
3855               && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3856             return stab;
3857           if (with_opaque != NULL
3858               && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
3859             stab_best = stab;
3860
3861           /* Keep looking through other CUs.  */
3862         }
3863     }
3864
3865   return stab_best;
3866 }
3867
3868 static void
3869 dw2_print_stats (struct objfile *objfile)
3870 {
3871   int i, total, count;
3872
3873   dw2_setup (objfile);
3874   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3875   count = 0;
3876   for (i = 0; i < total; ++i)
3877     {
3878       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3879
3880       if (!per_cu->v.quick->compunit_symtab)
3881         ++count;
3882     }
3883   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3884   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3885 }
3886
3887 /* This dumps minimal information about the index.
3888    It is called via "mt print objfiles".
3889    One use is to verify .gdb_index has been loaded by the
3890    gdb.dwarf2/gdb-index.exp testcase.  */
3891
3892 static void
3893 dw2_dump (struct objfile *objfile)
3894 {
3895   dw2_setup (objfile);
3896   gdb_assert (dwarf2_per_objfile->using_index);
3897   printf_filtered (".gdb_index:");
3898   if (dwarf2_per_objfile->index_table != NULL)
3899     {
3900       printf_filtered (" version %d\n",
3901                        dwarf2_per_objfile->index_table->version);
3902     }
3903   else
3904     printf_filtered (" faked for \"readnow\"\n");
3905   printf_filtered ("\n");
3906 }
3907
3908 static void
3909 dw2_relocate (struct objfile *objfile,
3910               const struct section_offsets *new_offsets,
3911               const struct section_offsets *delta)
3912 {
3913   /* There's nothing to relocate here.  */
3914 }
3915
3916 static void
3917 dw2_expand_symtabs_for_function (struct objfile *objfile,
3918                                  const char *func_name)
3919 {
3920   struct mapped_index *index;
3921
3922   dw2_setup (objfile);
3923
3924   index = dwarf2_per_objfile->index_table;
3925
3926   /* index is NULL if OBJF_READNOW.  */
3927   if (index)
3928     {
3929       struct dw2_symtab_iterator iter;
3930       struct dwarf2_per_cu_data *per_cu;
3931
3932       /* Note: It doesn't matter what we pass for block_index here.  */
3933       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3934                             func_name);
3935
3936       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3937         dw2_instantiate_symtab (per_cu);
3938     }
3939 }
3940
3941 static void
3942 dw2_expand_all_symtabs (struct objfile *objfile)
3943 {
3944   int i;
3945
3946   dw2_setup (objfile);
3947
3948   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3949                    + dwarf2_per_objfile->n_type_units); ++i)
3950     {
3951       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3952
3953       dw2_instantiate_symtab (per_cu);
3954     }
3955 }
3956
3957 static void
3958 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3959                                   const char *fullname)
3960 {
3961   int i;
3962
3963   dw2_setup (objfile);
3964
3965   /* We don't need to consider type units here.
3966      This is only called for examining code, e.g. expand_line_sal.
3967      There can be an order of magnitude (or more) more type units
3968      than comp units, and we avoid them if we can.  */
3969
3970   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3971     {
3972       int j;
3973       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3974       struct quick_file_names *file_data;
3975
3976       /* We only need to look at symtabs not already expanded.  */
3977       if (per_cu->v.quick->compunit_symtab)
3978         continue;
3979
3980       file_data = dw2_get_file_names (per_cu);
3981       if (file_data == NULL)
3982         continue;
3983
3984       for (j = 0; j < file_data->num_file_names; ++j)
3985         {
3986           const char *this_fullname = file_data->file_names[j];
3987
3988           if (filename_cmp (this_fullname, fullname) == 0)
3989             {
3990               dw2_instantiate_symtab (per_cu);
3991               break;
3992             }
3993         }
3994     }
3995 }
3996
3997 static void
3998 dw2_map_matching_symbols (struct objfile *objfile,
3999                           const char * name, domain_enum domain,
4000                           int global,
4001                           int (*callback) (struct block *,
4002                                            struct symbol *, void *),
4003                           void *data, symbol_compare_ftype *match,
4004                           symbol_compare_ftype *ordered_compare)
4005 {
4006   /* Currently unimplemented; used for Ada.  The function can be called if the
4007      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4008      does not look for non-Ada symbols this function should just return.  */
4009 }
4010
4011 static void
4012 dw2_expand_symtabs_matching
4013   (struct objfile *objfile,
4014    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4015    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4016    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4017    enum search_domain kind)
4018 {
4019   int i;
4020   offset_type iter;
4021   struct mapped_index *index;
4022
4023   dw2_setup (objfile);
4024
4025   /* index_table is NULL if OBJF_READNOW.  */
4026   if (!dwarf2_per_objfile->index_table)
4027     return;
4028   index = dwarf2_per_objfile->index_table;
4029
4030   if (file_matcher != NULL)
4031     {
4032       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4033                                                 htab_eq_pointer,
4034                                                 NULL, xcalloc, xfree));
4035       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4036                                                     htab_eq_pointer,
4037                                                     NULL, xcalloc, xfree));
4038
4039       /* The rule is CUs specify all the files, including those used by
4040          any TU, so there's no need to scan TUs here.  */
4041
4042       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4043         {
4044           int j;
4045           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4046           struct quick_file_names *file_data;
4047           void **slot;
4048
4049           QUIT;
4050
4051           per_cu->v.quick->mark = 0;
4052
4053           /* We only need to look at symtabs not already expanded.  */
4054           if (per_cu->v.quick->compunit_symtab)
4055             continue;
4056
4057           file_data = dw2_get_file_names (per_cu);
4058           if (file_data == NULL)
4059             continue;
4060
4061           if (htab_find (visited_not_found.get (), file_data) != NULL)
4062             continue;
4063           else if (htab_find (visited_found.get (), file_data) != NULL)
4064             {
4065               per_cu->v.quick->mark = 1;
4066               continue;
4067             }
4068
4069           for (j = 0; j < file_data->num_file_names; ++j)
4070             {
4071               const char *this_real_name;
4072
4073               if (file_matcher (file_data->file_names[j], false))
4074                 {
4075                   per_cu->v.quick->mark = 1;
4076                   break;
4077                 }
4078
4079               /* Before we invoke realpath, which can get expensive when many
4080                  files are involved, do a quick comparison of the basenames.  */
4081               if (!basenames_may_differ
4082                   && !file_matcher (lbasename (file_data->file_names[j]),
4083                                     true))
4084                 continue;
4085
4086               this_real_name = dw2_get_real_path (objfile, file_data, j);
4087               if (file_matcher (this_real_name, false))
4088                 {
4089                   per_cu->v.quick->mark = 1;
4090                   break;
4091                 }
4092             }
4093
4094           slot = htab_find_slot (per_cu->v.quick->mark
4095                                  ? visited_found.get ()
4096                                  : visited_not_found.get (),
4097                                  file_data, INSERT);
4098           *slot = file_data;
4099         }
4100     }
4101
4102   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4103     {
4104       offset_type idx = 2 * iter;
4105       const char *name;
4106       offset_type *vec, vec_len, vec_idx;
4107       int global_seen = 0;
4108
4109       QUIT;
4110
4111       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4112         continue;
4113
4114       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4115
4116       if (!symbol_matcher (name))
4117         continue;
4118
4119       /* The name was matched, now expand corresponding CUs that were
4120          marked.  */
4121       vec = (offset_type *) (index->constant_pool
4122                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4123       vec_len = MAYBE_SWAP (vec[0]);
4124       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4125         {
4126           struct dwarf2_per_cu_data *per_cu;
4127           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4128           /* This value is only valid for index versions >= 7.  */
4129           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4130           gdb_index_symbol_kind symbol_kind =
4131             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4132           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4133           /* Only check the symbol attributes if they're present.
4134              Indices prior to version 7 don't record them,
4135              and indices >= 7 may elide them for certain symbols
4136              (gold does this).  */
4137           int attrs_valid =
4138             (index->version >= 7
4139              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4140
4141           /* Work around gold/15646.  */
4142           if (attrs_valid)
4143             {
4144               if (!is_static && global_seen)
4145                 continue;
4146               if (!is_static)
4147                 global_seen = 1;
4148             }
4149
4150           /* Only check the symbol's kind if it has one.  */
4151           if (attrs_valid)
4152             {
4153               switch (kind)
4154                 {
4155                 case VARIABLES_DOMAIN:
4156                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4157                     continue;
4158                   break;
4159                 case FUNCTIONS_DOMAIN:
4160                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4161                     continue;
4162                   break;
4163                 case TYPES_DOMAIN:
4164                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4165                     continue;
4166                   break;
4167                 default:
4168                   break;
4169                 }
4170             }
4171
4172           /* Don't crash on bad data.  */
4173           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4174                            + dwarf2_per_objfile->n_type_units))
4175             {
4176               complaint (&symfile_complaints,
4177                          _(".gdb_index entry has bad CU index"
4178                            " [in module %s]"), objfile_name (objfile));
4179               continue;
4180             }
4181
4182           per_cu = dw2_get_cutu (cu_index);
4183           if (file_matcher == NULL || per_cu->v.quick->mark)
4184             {
4185               int symtab_was_null =
4186                 (per_cu->v.quick->compunit_symtab == NULL);
4187
4188               dw2_instantiate_symtab (per_cu);
4189
4190               if (expansion_notify != NULL
4191                   && symtab_was_null
4192                   && per_cu->v.quick->compunit_symtab != NULL)
4193                 {
4194                   expansion_notify (per_cu->v.quick->compunit_symtab);
4195                 }
4196             }
4197         }
4198     }
4199 }
4200
4201 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4202    symtab.  */
4203
4204 static struct compunit_symtab *
4205 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4206                                           CORE_ADDR pc)
4207 {
4208   int i;
4209
4210   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4211       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4212     return cust;
4213
4214   if (cust->includes == NULL)
4215     return NULL;
4216
4217   for (i = 0; cust->includes[i]; ++i)
4218     {
4219       struct compunit_symtab *s = cust->includes[i];
4220
4221       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4222       if (s != NULL)
4223         return s;
4224     }
4225
4226   return NULL;
4227 }
4228
4229 static struct compunit_symtab *
4230 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4231                                   struct bound_minimal_symbol msymbol,
4232                                   CORE_ADDR pc,
4233                                   struct obj_section *section,
4234                                   int warn_if_readin)
4235 {
4236   struct dwarf2_per_cu_data *data;
4237   struct compunit_symtab *result;
4238
4239   dw2_setup (objfile);
4240
4241   if (!objfile->psymtabs_addrmap)
4242     return NULL;
4243
4244   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4245                                                      pc);
4246   if (!data)
4247     return NULL;
4248
4249   if (warn_if_readin && data->v.quick->compunit_symtab)
4250     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4251              paddress (get_objfile_arch (objfile), pc));
4252
4253   result
4254     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4255                                                 pc);
4256   gdb_assert (result != NULL);
4257   return result;
4258 }
4259
4260 static void
4261 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4262                           void *data, int need_fullname)
4263 {
4264   int i;
4265   htab_up visited (htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
4266                                       NULL, xcalloc, xfree));
4267
4268   dw2_setup (objfile);
4269
4270   /* The rule is CUs specify all the files, including those used by
4271      any TU, so there's no need to scan TUs here.
4272      We can ignore file names coming from already-expanded CUs.  */
4273
4274   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4275     {
4276       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4277
4278       if (per_cu->v.quick->compunit_symtab)
4279         {
4280           void **slot = htab_find_slot (visited.get (),
4281                                         per_cu->v.quick->file_names,
4282                                         INSERT);
4283
4284           *slot = per_cu->v.quick->file_names;
4285         }
4286     }
4287
4288   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4289     {
4290       int j;
4291       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4292       struct quick_file_names *file_data;
4293       void **slot;
4294
4295       /* We only need to look at symtabs not already expanded.  */
4296       if (per_cu->v.quick->compunit_symtab)
4297         continue;
4298
4299       file_data = dw2_get_file_names (per_cu);
4300       if (file_data == NULL)
4301         continue;
4302
4303       slot = htab_find_slot (visited.get (), file_data, INSERT);
4304       if (*slot)
4305         {
4306           /* Already visited.  */
4307           continue;
4308         }
4309       *slot = file_data;
4310
4311       for (j = 0; j < file_data->num_file_names; ++j)
4312         {
4313           const char *this_real_name;
4314
4315           if (need_fullname)
4316             this_real_name = dw2_get_real_path (objfile, file_data, j);
4317           else
4318             this_real_name = NULL;
4319           (*fun) (file_data->file_names[j], this_real_name, data);
4320         }
4321     }
4322 }
4323
4324 static int
4325 dw2_has_symbols (struct objfile *objfile)
4326 {
4327   return 1;
4328 }
4329
4330 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4331 {
4332   dw2_has_symbols,
4333   dw2_find_last_source_symtab,
4334   dw2_forget_cached_source_info,
4335   dw2_map_symtabs_matching_filename,
4336   dw2_lookup_symbol,
4337   dw2_print_stats,
4338   dw2_dump,
4339   dw2_relocate,
4340   dw2_expand_symtabs_for_function,
4341   dw2_expand_all_symtabs,
4342   dw2_expand_symtabs_with_fullname,
4343   dw2_map_matching_symbols,
4344   dw2_expand_symtabs_matching,
4345   dw2_find_pc_sect_compunit_symtab,
4346   dw2_map_symbol_filenames
4347 };
4348
4349 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4350    file will use psymtabs, or 1 if using the GNU index.  */
4351
4352 int
4353 dwarf2_initialize_objfile (struct objfile *objfile)
4354 {
4355   /* If we're about to read full symbols, don't bother with the
4356      indices.  In this case we also don't care if some other debug
4357      format is making psymtabs, because they are all about to be
4358      expanded anyway.  */
4359   if ((objfile->flags & OBJF_READNOW))
4360     {
4361       int i;
4362
4363       dwarf2_per_objfile->using_index = 1;
4364       create_all_comp_units (objfile);
4365       create_all_type_units (objfile);
4366       dwarf2_per_objfile->quick_file_names_table =
4367         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4368
4369       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4370                        + dwarf2_per_objfile->n_type_units); ++i)
4371         {
4372           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4373
4374           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4375                                             struct dwarf2_per_cu_quick_data);
4376         }
4377
4378       /* Return 1 so that gdb sees the "quick" functions.  However,
4379          these functions will be no-ops because we will have expanded
4380          all symtabs.  */
4381       return 1;
4382     }
4383
4384   if (dwarf2_read_index (objfile))
4385     return 1;
4386
4387   return 0;
4388 }
4389
4390 \f
4391
4392 /* Build a partial symbol table.  */
4393
4394 void
4395 dwarf2_build_psymtabs (struct objfile *objfile)
4396 {
4397
4398   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4399     {
4400       init_psymbol_list (objfile, 1024);
4401     }
4402
4403   TRY
4404     {
4405       /* This isn't really ideal: all the data we allocate on the
4406          objfile's obstack is still uselessly kept around.  However,
4407          freeing it seems unsafe.  */
4408       psymtab_discarder psymtabs (objfile);
4409       dwarf2_build_psymtabs_hard (objfile);
4410       psymtabs.keep ();
4411     }
4412   CATCH (except, RETURN_MASK_ERROR)
4413     {
4414       exception_print (gdb_stderr, except);
4415     }
4416   END_CATCH
4417 }
4418
4419 /* Return the total length of the CU described by HEADER.  */
4420
4421 static unsigned int
4422 get_cu_length (const struct comp_unit_head *header)
4423 {
4424   return header->initial_length_size + header->length;
4425 }
4426
4427 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4428
4429 static inline bool
4430 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4431 {
4432   sect_offset bottom = cu_header->sect_off;
4433   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4434
4435   return sect_off >= bottom && sect_off < top;
4436 }
4437
4438 /* Find the base address of the compilation unit for range lists and
4439    location lists.  It will normally be specified by DW_AT_low_pc.
4440    In DWARF-3 draft 4, the base address could be overridden by
4441    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4442    compilation units with discontinuous ranges.  */
4443
4444 static void
4445 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4446 {
4447   struct attribute *attr;
4448
4449   cu->base_known = 0;
4450   cu->base_address = 0;
4451
4452   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4453   if (attr)
4454     {
4455       cu->base_address = attr_value_as_address (attr);
4456       cu->base_known = 1;
4457     }
4458   else
4459     {
4460       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4461       if (attr)
4462         {
4463           cu->base_address = attr_value_as_address (attr);
4464           cu->base_known = 1;
4465         }
4466     }
4467 }
4468
4469 /* Read in the comp unit header information from the debug_info at info_ptr.
4470    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4471    NOTE: This leaves members offset, first_die_offset to be filled in
4472    by the caller.  */
4473
4474 static const gdb_byte *
4475 read_comp_unit_head (struct comp_unit_head *cu_header,
4476                      const gdb_byte *info_ptr,
4477                      struct dwarf2_section_info *section,
4478                      rcuh_kind section_kind)
4479 {
4480   int signed_addr;
4481   unsigned int bytes_read;
4482   const char *filename = get_section_file_name (section);
4483   bfd *abfd = get_section_bfd_owner (section);
4484
4485   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4486   cu_header->initial_length_size = bytes_read;
4487   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4488   info_ptr += bytes_read;
4489   cu_header->version = read_2_bytes (abfd, info_ptr);
4490   info_ptr += 2;
4491   if (cu_header->version < 5)
4492     switch (section_kind)
4493       {
4494       case rcuh_kind::COMPILE:
4495         cu_header->unit_type = DW_UT_compile;
4496         break;
4497       case rcuh_kind::TYPE:
4498         cu_header->unit_type = DW_UT_type;
4499         break;
4500       default:
4501         internal_error (__FILE__, __LINE__,
4502                         _("read_comp_unit_head: invalid section_kind"));
4503       }
4504   else
4505     {
4506       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4507                                                  (read_1_byte (abfd, info_ptr));
4508       info_ptr += 1;
4509       switch (cu_header->unit_type)
4510         {
4511         case DW_UT_compile:
4512           if (section_kind != rcuh_kind::COMPILE)
4513             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4514                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4515                    filename);
4516           break;
4517         case DW_UT_type:
4518           section_kind = rcuh_kind::TYPE;
4519           break;
4520         default:
4521           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4522                  "(is %d, should be %d or %d) [in module %s]"),
4523                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4524         }
4525
4526       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4527       info_ptr += 1;
4528     }
4529   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4530                                                           cu_header,
4531                                                           &bytes_read);
4532   info_ptr += bytes_read;
4533   if (cu_header->version < 5)
4534     {
4535       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4536       info_ptr += 1;
4537     }
4538   signed_addr = bfd_get_sign_extend_vma (abfd);
4539   if (signed_addr < 0)
4540     internal_error (__FILE__, __LINE__,
4541                     _("read_comp_unit_head: dwarf from non elf file"));
4542   cu_header->signed_addr_p = signed_addr;
4543
4544   if (section_kind == rcuh_kind::TYPE)
4545     {
4546       LONGEST type_offset;
4547
4548       cu_header->signature = read_8_bytes (abfd, info_ptr);
4549       info_ptr += 8;
4550
4551       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4552       info_ptr += bytes_read;
4553       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4554       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4555         error (_("Dwarf Error: Too big type_offset in compilation unit "
4556                "header (is %s) [in module %s]"), plongest (type_offset),
4557                filename);
4558     }
4559
4560   return info_ptr;
4561 }
4562
4563 /* Helper function that returns the proper abbrev section for
4564    THIS_CU.  */
4565
4566 static struct dwarf2_section_info *
4567 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4568 {
4569   struct dwarf2_section_info *abbrev;
4570
4571   if (this_cu->is_dwz)
4572     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4573   else
4574     abbrev = &dwarf2_per_objfile->abbrev;
4575
4576   return abbrev;
4577 }
4578
4579 /* Subroutine of read_and_check_comp_unit_head and
4580    read_and_check_type_unit_head to simplify them.
4581    Perform various error checking on the header.  */
4582
4583 static void
4584 error_check_comp_unit_head (struct comp_unit_head *header,
4585                             struct dwarf2_section_info *section,
4586                             struct dwarf2_section_info *abbrev_section)
4587 {
4588   const char *filename = get_section_file_name (section);
4589
4590   if (header->version < 2 || header->version > 5)
4591     error (_("Dwarf Error: wrong version in compilation unit header "
4592            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4593            filename);
4594
4595   if (to_underlying (header->abbrev_sect_off)
4596       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4597     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4598            "(offset 0x%x + 6) [in module %s]"),
4599            to_underlying (header->abbrev_sect_off),
4600            to_underlying (header->sect_off),
4601            filename);
4602
4603   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4604      avoid potential 32-bit overflow.  */
4605   if (((ULONGEST) header->sect_off + get_cu_length (header))
4606       > section->size)
4607     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4608            "(offset 0x%x + 0) [in module %s]"),
4609            header->length, to_underlying (header->sect_off),
4610            filename);
4611 }
4612
4613 /* Read in a CU/TU header and perform some basic error checking.
4614    The contents of the header are stored in HEADER.
4615    The result is a pointer to the start of the first DIE.  */
4616
4617 static const gdb_byte *
4618 read_and_check_comp_unit_head (struct comp_unit_head *header,
4619                                struct dwarf2_section_info *section,
4620                                struct dwarf2_section_info *abbrev_section,
4621                                const gdb_byte *info_ptr,
4622                                rcuh_kind section_kind)
4623 {
4624   const gdb_byte *beg_of_comp_unit = info_ptr;
4625   bfd *abfd = get_section_bfd_owner (section);
4626
4627   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4628
4629   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4630
4631   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4632
4633   error_check_comp_unit_head (header, section, abbrev_section);
4634
4635   return info_ptr;
4636 }
4637
4638 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4639
4640 static sect_offset
4641 read_abbrev_offset (struct dwarf2_section_info *section,
4642                     sect_offset sect_off)
4643 {
4644   bfd *abfd = get_section_bfd_owner (section);
4645   const gdb_byte *info_ptr;
4646   unsigned int initial_length_size, offset_size;
4647   uint16_t version;
4648
4649   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4650   info_ptr = section->buffer + to_underlying (sect_off);
4651   read_initial_length (abfd, info_ptr, &initial_length_size);
4652   offset_size = initial_length_size == 4 ? 4 : 8;
4653   info_ptr += initial_length_size;
4654
4655   version = read_2_bytes (abfd, info_ptr);
4656   info_ptr += 2;
4657   if (version >= 5)
4658     {
4659       /* Skip unit type and address size.  */
4660       info_ptr += 2;
4661     }
4662
4663   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4664 }
4665
4666 /* Allocate a new partial symtab for file named NAME and mark this new
4667    partial symtab as being an include of PST.  */
4668
4669 static void
4670 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4671                                struct objfile *objfile)
4672 {
4673   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4674
4675   if (!IS_ABSOLUTE_PATH (subpst->filename))
4676     {
4677       /* It shares objfile->objfile_obstack.  */
4678       subpst->dirname = pst->dirname;
4679     }
4680
4681   subpst->textlow = 0;
4682   subpst->texthigh = 0;
4683
4684   subpst->dependencies
4685     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4686   subpst->dependencies[0] = pst;
4687   subpst->number_of_dependencies = 1;
4688
4689   subpst->globals_offset = 0;
4690   subpst->n_global_syms = 0;
4691   subpst->statics_offset = 0;
4692   subpst->n_static_syms = 0;
4693   subpst->compunit_symtab = NULL;
4694   subpst->read_symtab = pst->read_symtab;
4695   subpst->readin = 0;
4696
4697   /* No private part is necessary for include psymtabs.  This property
4698      can be used to differentiate between such include psymtabs and
4699      the regular ones.  */
4700   subpst->read_symtab_private = NULL;
4701 }
4702
4703 /* Read the Line Number Program data and extract the list of files
4704    included by the source file represented by PST.  Build an include
4705    partial symtab for each of these included files.  */
4706
4707 static void
4708 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4709                                struct die_info *die,
4710                                struct partial_symtab *pst)
4711 {
4712   line_header_up lh;
4713   struct attribute *attr;
4714
4715   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4716   if (attr)
4717     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4718   if (lh == NULL)
4719     return;  /* No linetable, so no includes.  */
4720
4721   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4722   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4723 }
4724
4725 static hashval_t
4726 hash_signatured_type (const void *item)
4727 {
4728   const struct signatured_type *sig_type
4729     = (const struct signatured_type *) item;
4730
4731   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4732   return sig_type->signature;
4733 }
4734
4735 static int
4736 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4737 {
4738   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4739   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4740
4741   return lhs->signature == rhs->signature;
4742 }
4743
4744 /* Allocate a hash table for signatured types.  */
4745
4746 static htab_t
4747 allocate_signatured_type_table (struct objfile *objfile)
4748 {
4749   return htab_create_alloc_ex (41,
4750                                hash_signatured_type,
4751                                eq_signatured_type,
4752                                NULL,
4753                                &objfile->objfile_obstack,
4754                                hashtab_obstack_allocate,
4755                                dummy_obstack_deallocate);
4756 }
4757
4758 /* A helper function to add a signatured type CU to a table.  */
4759
4760 static int
4761 add_signatured_type_cu_to_table (void **slot, void *datum)
4762 {
4763   struct signatured_type *sigt = (struct signatured_type *) *slot;
4764   struct signatured_type ***datap = (struct signatured_type ***) datum;
4765
4766   **datap = sigt;
4767   ++*datap;
4768
4769   return 1;
4770 }
4771
4772 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4773    and fill them into TYPES_HTAB.  It will process only type units,
4774    therefore DW_UT_type.  */
4775
4776 static void
4777 create_debug_type_hash_table (struct dwo_file *dwo_file,
4778                               dwarf2_section_info *section, htab_t &types_htab,
4779                               rcuh_kind section_kind)
4780 {
4781   struct objfile *objfile = dwarf2_per_objfile->objfile;
4782   struct dwarf2_section_info *abbrev_section;
4783   bfd *abfd;
4784   const gdb_byte *info_ptr, *end_ptr;
4785
4786   abbrev_section = (dwo_file != NULL
4787                     ? &dwo_file->sections.abbrev
4788                     : &dwarf2_per_objfile->abbrev);
4789
4790   if (dwarf_read_debug)
4791     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4792                         get_section_name (section),
4793                         get_section_file_name (abbrev_section));
4794
4795   dwarf2_read_section (objfile, section);
4796   info_ptr = section->buffer;
4797
4798   if (info_ptr == NULL)
4799     return;
4800
4801   /* We can't set abfd until now because the section may be empty or
4802      not present, in which case the bfd is unknown.  */
4803   abfd = get_section_bfd_owner (section);
4804
4805   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4806      because we don't need to read any dies: the signature is in the
4807      header.  */
4808
4809   end_ptr = info_ptr + section->size;
4810   while (info_ptr < end_ptr)
4811     {
4812       struct signatured_type *sig_type;
4813       struct dwo_unit *dwo_tu;
4814       void **slot;
4815       const gdb_byte *ptr = info_ptr;
4816       struct comp_unit_head header;
4817       unsigned int length;
4818
4819       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4820
4821       /* Initialize it due to a false compiler warning.  */
4822       header.signature = -1;
4823       header.type_cu_offset_in_tu = (cu_offset) -1;
4824
4825       /* We need to read the type's signature in order to build the hash
4826          table, but we don't need anything else just yet.  */
4827
4828       ptr = read_and_check_comp_unit_head (&header, section,
4829                                            abbrev_section, ptr, section_kind);
4830
4831       length = get_cu_length (&header);
4832
4833       /* Skip dummy type units.  */
4834       if (ptr >= info_ptr + length
4835           || peek_abbrev_code (abfd, ptr) == 0
4836           || header.unit_type != DW_UT_type)
4837         {
4838           info_ptr += length;
4839           continue;
4840         }
4841
4842       if (types_htab == NULL)
4843         {
4844           if (dwo_file)
4845             types_htab = allocate_dwo_unit_table (objfile);
4846           else
4847             types_htab = allocate_signatured_type_table (objfile);
4848         }
4849
4850       if (dwo_file)
4851         {
4852           sig_type = NULL;
4853           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4854                                    struct dwo_unit);
4855           dwo_tu->dwo_file = dwo_file;
4856           dwo_tu->signature = header.signature;
4857           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4858           dwo_tu->section = section;
4859           dwo_tu->sect_off = sect_off;
4860           dwo_tu->length = length;
4861         }
4862       else
4863         {
4864           /* N.B.: type_offset is not usable if this type uses a DWO file.
4865              The real type_offset is in the DWO file.  */
4866           dwo_tu = NULL;
4867           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4868                                      struct signatured_type);
4869           sig_type->signature = header.signature;
4870           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4871           sig_type->per_cu.objfile = objfile;
4872           sig_type->per_cu.is_debug_types = 1;
4873           sig_type->per_cu.section = section;
4874           sig_type->per_cu.sect_off = sect_off;
4875           sig_type->per_cu.length = length;
4876         }
4877
4878       slot = htab_find_slot (types_htab,
4879                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4880                              INSERT);
4881       gdb_assert (slot != NULL);
4882       if (*slot != NULL)
4883         {
4884           sect_offset dup_sect_off;
4885
4886           if (dwo_file)
4887             {
4888               const struct dwo_unit *dup_tu
4889                 = (const struct dwo_unit *) *slot;
4890
4891               dup_sect_off = dup_tu->sect_off;
4892             }
4893           else
4894             {
4895               const struct signatured_type *dup_tu
4896                 = (const struct signatured_type *) *slot;
4897
4898               dup_sect_off = dup_tu->per_cu.sect_off;
4899             }
4900
4901           complaint (&symfile_complaints,
4902                      _("debug type entry at offset 0x%x is duplicate to"
4903                        " the entry at offset 0x%x, signature %s"),
4904                      to_underlying (sect_off), to_underlying (dup_sect_off),
4905                      hex_string (header.signature));
4906         }
4907       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4908
4909       if (dwarf_read_debug > 1)
4910         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4911                             to_underlying (sect_off),
4912                             hex_string (header.signature));
4913
4914       info_ptr += length;
4915     }
4916 }
4917
4918 /* Create the hash table of all entries in the .debug_types
4919    (or .debug_types.dwo) section(s).
4920    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4921    otherwise it is NULL.
4922
4923    The result is a pointer to the hash table or NULL if there are no types.
4924
4925    Note: This function processes DWO files only, not DWP files.  */
4926
4927 static void
4928 create_debug_types_hash_table (struct dwo_file *dwo_file,
4929                                VEC (dwarf2_section_info_def) *types,
4930                                htab_t &types_htab)
4931 {
4932   int ix;
4933   struct dwarf2_section_info *section;
4934
4935   if (VEC_empty (dwarf2_section_info_def, types))
4936     return;
4937
4938   for (ix = 0;
4939        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4940        ++ix)
4941     create_debug_type_hash_table (dwo_file, section, types_htab,
4942                                   rcuh_kind::TYPE);
4943 }
4944
4945 /* Create the hash table of all entries in the .debug_types section,
4946    and initialize all_type_units.
4947    The result is zero if there is an error (e.g. missing .debug_types section),
4948    otherwise non-zero.  */
4949
4950 static int
4951 create_all_type_units (struct objfile *objfile)
4952 {
4953   htab_t types_htab = NULL;
4954   struct signatured_type **iter;
4955
4956   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
4957                                 rcuh_kind::COMPILE);
4958   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
4959   if (types_htab == NULL)
4960     {
4961       dwarf2_per_objfile->signatured_types = NULL;
4962       return 0;
4963     }
4964
4965   dwarf2_per_objfile->signatured_types = types_htab;
4966
4967   dwarf2_per_objfile->n_type_units
4968     = dwarf2_per_objfile->n_allocated_type_units
4969     = htab_elements (types_htab);
4970   dwarf2_per_objfile->all_type_units =
4971     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
4972   iter = &dwarf2_per_objfile->all_type_units[0];
4973   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4974   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4975               == dwarf2_per_objfile->n_type_units);
4976
4977   return 1;
4978 }
4979
4980 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
4981    If SLOT is non-NULL, it is the entry to use in the hash table.
4982    Otherwise we find one.  */
4983
4984 static struct signatured_type *
4985 add_type_unit (ULONGEST sig, void **slot)
4986 {
4987   struct objfile *objfile = dwarf2_per_objfile->objfile;
4988   int n_type_units = dwarf2_per_objfile->n_type_units;
4989   struct signatured_type *sig_type;
4990
4991   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
4992   ++n_type_units;
4993   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
4994     {
4995       if (dwarf2_per_objfile->n_allocated_type_units == 0)
4996         dwarf2_per_objfile->n_allocated_type_units = 1;
4997       dwarf2_per_objfile->n_allocated_type_units *= 2;
4998       dwarf2_per_objfile->all_type_units
4999         = XRESIZEVEC (struct signatured_type *,
5000                       dwarf2_per_objfile->all_type_units,
5001                       dwarf2_per_objfile->n_allocated_type_units);
5002       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5003     }
5004   dwarf2_per_objfile->n_type_units = n_type_units;
5005
5006   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5007                              struct signatured_type);
5008   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5009   sig_type->signature = sig;
5010   sig_type->per_cu.is_debug_types = 1;
5011   if (dwarf2_per_objfile->using_index)
5012     {
5013       sig_type->per_cu.v.quick =
5014         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5015                         struct dwarf2_per_cu_quick_data);
5016     }
5017
5018   if (slot == NULL)
5019     {
5020       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5021                              sig_type, INSERT);
5022     }
5023   gdb_assert (*slot == NULL);
5024   *slot = sig_type;
5025   /* The rest of sig_type must be filled in by the caller.  */
5026   return sig_type;
5027 }
5028
5029 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5030    Fill in SIG_ENTRY with DWO_ENTRY.  */
5031
5032 static void
5033 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5034                                   struct signatured_type *sig_entry,
5035                                   struct dwo_unit *dwo_entry)
5036 {
5037   /* Make sure we're not clobbering something we don't expect to.  */
5038   gdb_assert (! sig_entry->per_cu.queued);
5039   gdb_assert (sig_entry->per_cu.cu == NULL);
5040   if (dwarf2_per_objfile->using_index)
5041     {
5042       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5043       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5044     }
5045   else
5046       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5047   gdb_assert (sig_entry->signature == dwo_entry->signature);
5048   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5049   gdb_assert (sig_entry->type_unit_group == NULL);
5050   gdb_assert (sig_entry->dwo_unit == NULL);
5051
5052   sig_entry->per_cu.section = dwo_entry->section;
5053   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5054   sig_entry->per_cu.length = dwo_entry->length;
5055   sig_entry->per_cu.reading_dwo_directly = 1;
5056   sig_entry->per_cu.objfile = objfile;
5057   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5058   sig_entry->dwo_unit = dwo_entry;
5059 }
5060
5061 /* Subroutine of lookup_signatured_type.
5062    If we haven't read the TU yet, create the signatured_type data structure
5063    for a TU to be read in directly from a DWO file, bypassing the stub.
5064    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5065    using .gdb_index, then when reading a CU we want to stay in the DWO file
5066    containing that CU.  Otherwise we could end up reading several other DWO
5067    files (due to comdat folding) to process the transitive closure of all the
5068    mentioned TUs, and that can be slow.  The current DWO file will have every
5069    type signature that it needs.
5070    We only do this for .gdb_index because in the psymtab case we already have
5071    to read all the DWOs to build the type unit groups.  */
5072
5073 static struct signatured_type *
5074 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5075 {
5076   struct objfile *objfile = dwarf2_per_objfile->objfile;
5077   struct dwo_file *dwo_file;
5078   struct dwo_unit find_dwo_entry, *dwo_entry;
5079   struct signatured_type find_sig_entry, *sig_entry;
5080   void **slot;
5081
5082   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5083
5084   /* If TU skeletons have been removed then we may not have read in any
5085      TUs yet.  */
5086   if (dwarf2_per_objfile->signatured_types == NULL)
5087     {
5088       dwarf2_per_objfile->signatured_types
5089         = allocate_signatured_type_table (objfile);
5090     }
5091
5092   /* We only ever need to read in one copy of a signatured type.
5093      Use the global signatured_types array to do our own comdat-folding
5094      of types.  If this is the first time we're reading this TU, and
5095      the TU has an entry in .gdb_index, replace the recorded data from
5096      .gdb_index with this TU.  */
5097
5098   find_sig_entry.signature = sig;
5099   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5100                          &find_sig_entry, INSERT);
5101   sig_entry = (struct signatured_type *) *slot;
5102
5103   /* We can get here with the TU already read, *or* in the process of being
5104      read.  Don't reassign the global entry to point to this DWO if that's
5105      the case.  Also note that if the TU is already being read, it may not
5106      have come from a DWO, the program may be a mix of Fission-compiled
5107      code and non-Fission-compiled code.  */
5108
5109   /* Have we already tried to read this TU?
5110      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5111      needn't exist in the global table yet).  */
5112   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5113     return sig_entry;
5114
5115   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5116      dwo_unit of the TU itself.  */
5117   dwo_file = cu->dwo_unit->dwo_file;
5118
5119   /* Ok, this is the first time we're reading this TU.  */
5120   if (dwo_file->tus == NULL)
5121     return NULL;
5122   find_dwo_entry.signature = sig;
5123   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5124   if (dwo_entry == NULL)
5125     return NULL;
5126
5127   /* If the global table doesn't have an entry for this TU, add one.  */
5128   if (sig_entry == NULL)
5129     sig_entry = add_type_unit (sig, slot);
5130
5131   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5132   sig_entry->per_cu.tu_read = 1;
5133   return sig_entry;
5134 }
5135
5136 /* Subroutine of lookup_signatured_type.
5137    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5138    then try the DWP file.  If the TU stub (skeleton) has been removed then
5139    it won't be in .gdb_index.  */
5140
5141 static struct signatured_type *
5142 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5143 {
5144   struct objfile *objfile = dwarf2_per_objfile->objfile;
5145   struct dwp_file *dwp_file = get_dwp_file ();
5146   struct dwo_unit *dwo_entry;
5147   struct signatured_type find_sig_entry, *sig_entry;
5148   void **slot;
5149
5150   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5151   gdb_assert (dwp_file != NULL);
5152
5153   /* If TU skeletons have been removed then we may not have read in any
5154      TUs yet.  */
5155   if (dwarf2_per_objfile->signatured_types == NULL)
5156     {
5157       dwarf2_per_objfile->signatured_types
5158         = allocate_signatured_type_table (objfile);
5159     }
5160
5161   find_sig_entry.signature = sig;
5162   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5163                          &find_sig_entry, INSERT);
5164   sig_entry = (struct signatured_type *) *slot;
5165
5166   /* Have we already tried to read this TU?
5167      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5168      needn't exist in the global table yet).  */
5169   if (sig_entry != NULL)
5170     return sig_entry;
5171
5172   if (dwp_file->tus == NULL)
5173     return NULL;
5174   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5175                                       sig, 1 /* is_debug_types */);
5176   if (dwo_entry == NULL)
5177     return NULL;
5178
5179   sig_entry = add_type_unit (sig, slot);
5180   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5181
5182   return sig_entry;
5183 }
5184
5185 /* Lookup a signature based type for DW_FORM_ref_sig8.
5186    Returns NULL if signature SIG is not present in the table.
5187    It is up to the caller to complain about this.  */
5188
5189 static struct signatured_type *
5190 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5191 {
5192   if (cu->dwo_unit
5193       && dwarf2_per_objfile->using_index)
5194     {
5195       /* We're in a DWO/DWP file, and we're using .gdb_index.
5196          These cases require special processing.  */
5197       if (get_dwp_file () == NULL)
5198         return lookup_dwo_signatured_type (cu, sig);
5199       else
5200         return lookup_dwp_signatured_type (cu, sig);
5201     }
5202   else
5203     {
5204       struct signatured_type find_entry, *entry;
5205
5206       if (dwarf2_per_objfile->signatured_types == NULL)
5207         return NULL;
5208       find_entry.signature = sig;
5209       entry = ((struct signatured_type *)
5210                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5211       return entry;
5212     }
5213 }
5214 \f
5215 /* Low level DIE reading support.  */
5216
5217 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5218
5219 static void
5220 init_cu_die_reader (struct die_reader_specs *reader,
5221                     struct dwarf2_cu *cu,
5222                     struct dwarf2_section_info *section,
5223                     struct dwo_file *dwo_file)
5224 {
5225   gdb_assert (section->readin && section->buffer != NULL);
5226   reader->abfd = get_section_bfd_owner (section);
5227   reader->cu = cu;
5228   reader->dwo_file = dwo_file;
5229   reader->die_section = section;
5230   reader->buffer = section->buffer;
5231   reader->buffer_end = section->buffer + section->size;
5232   reader->comp_dir = NULL;
5233 }
5234
5235 /* Subroutine of init_cutu_and_read_dies to simplify it.
5236    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5237    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5238    already.
5239
5240    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5241    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5242    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5243    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5244    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5245    STUB_COMP_DIR may be non-NULL.
5246    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5247    are filled in with the info of the DIE from the DWO file.
5248    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5249    provided an abbrev table to use.
5250    The result is non-zero if a valid (non-dummy) DIE was found.  */
5251
5252 static int
5253 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5254                         struct dwo_unit *dwo_unit,
5255                         int abbrev_table_provided,
5256                         struct die_info *stub_comp_unit_die,
5257                         const char *stub_comp_dir,
5258                         struct die_reader_specs *result_reader,
5259                         const gdb_byte **result_info_ptr,
5260                         struct die_info **result_comp_unit_die,
5261                         int *result_has_children)
5262 {
5263   struct objfile *objfile = dwarf2_per_objfile->objfile;
5264   struct dwarf2_cu *cu = this_cu->cu;
5265   struct dwarf2_section_info *section;
5266   bfd *abfd;
5267   const gdb_byte *begin_info_ptr, *info_ptr;
5268   ULONGEST signature; /* Or dwo_id.  */
5269   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5270   int i,num_extra_attrs;
5271   struct dwarf2_section_info *dwo_abbrev_section;
5272   struct attribute *attr;
5273   struct die_info *comp_unit_die;
5274
5275   /* At most one of these may be provided.  */
5276   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5277
5278   /* These attributes aren't processed until later:
5279      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5280      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5281      referenced later.  However, these attributes are found in the stub
5282      which we won't have later.  In order to not impose this complication
5283      on the rest of the code, we read them here and copy them to the
5284      DWO CU/TU die.  */
5285
5286   stmt_list = NULL;
5287   low_pc = NULL;
5288   high_pc = NULL;
5289   ranges = NULL;
5290   comp_dir = NULL;
5291
5292   if (stub_comp_unit_die != NULL)
5293     {
5294       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5295          DWO file.  */
5296       if (! this_cu->is_debug_types)
5297         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5298       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5299       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5300       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5301       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5302
5303       /* There should be a DW_AT_addr_base attribute here (if needed).
5304          We need the value before we can process DW_FORM_GNU_addr_index.  */
5305       cu->addr_base = 0;
5306       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5307       if (attr)
5308         cu->addr_base = DW_UNSND (attr);
5309
5310       /* There should be a DW_AT_ranges_base attribute here (if needed).
5311          We need the value before we can process DW_AT_ranges.  */
5312       cu->ranges_base = 0;
5313       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5314       if (attr)
5315         cu->ranges_base = DW_UNSND (attr);
5316     }
5317   else if (stub_comp_dir != NULL)
5318     {
5319       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5320       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5321       comp_dir->name = DW_AT_comp_dir;
5322       comp_dir->form = DW_FORM_string;
5323       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5324       DW_STRING (comp_dir) = stub_comp_dir;
5325     }
5326
5327   /* Set up for reading the DWO CU/TU.  */
5328   cu->dwo_unit = dwo_unit;
5329   section = dwo_unit->section;
5330   dwarf2_read_section (objfile, section);
5331   abfd = get_section_bfd_owner (section);
5332   begin_info_ptr = info_ptr = (section->buffer
5333                                + to_underlying (dwo_unit->sect_off));
5334   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5335   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5336
5337   if (this_cu->is_debug_types)
5338     {
5339       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5340
5341       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5342                                                 dwo_abbrev_section,
5343                                                 info_ptr, rcuh_kind::TYPE);
5344       /* This is not an assert because it can be caused by bad debug info.  */
5345       if (sig_type->signature != cu->header.signature)
5346         {
5347           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5348                    " TU at offset 0x%x [in module %s]"),
5349                  hex_string (sig_type->signature),
5350                  hex_string (cu->header.signature),
5351                  to_underlying (dwo_unit->sect_off),
5352                  bfd_get_filename (abfd));
5353         }
5354       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5355       /* For DWOs coming from DWP files, we don't know the CU length
5356          nor the type's offset in the TU until now.  */
5357       dwo_unit->length = get_cu_length (&cu->header);
5358       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5359
5360       /* Establish the type offset that can be used to lookup the type.
5361          For DWO files, we don't know it until now.  */
5362       sig_type->type_offset_in_section
5363         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5364     }
5365   else
5366     {
5367       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5368                                                 dwo_abbrev_section,
5369                                                 info_ptr, rcuh_kind::COMPILE);
5370       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5371       /* For DWOs coming from DWP files, we don't know the CU length
5372          until now.  */
5373       dwo_unit->length = get_cu_length (&cu->header);
5374     }
5375
5376   /* Replace the CU's original abbrev table with the DWO's.
5377      Reminder: We can't read the abbrev table until we've read the header.  */
5378   if (abbrev_table_provided)
5379     {
5380       /* Don't free the provided abbrev table, the caller of
5381          init_cutu_and_read_dies owns it.  */
5382       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5383       /* Ensure the DWO abbrev table gets freed.  */
5384       make_cleanup (dwarf2_free_abbrev_table, cu);
5385     }
5386   else
5387     {
5388       dwarf2_free_abbrev_table (cu);
5389       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5390       /* Leave any existing abbrev table cleanup as is.  */
5391     }
5392
5393   /* Read in the die, but leave space to copy over the attributes
5394      from the stub.  This has the benefit of simplifying the rest of
5395      the code - all the work to maintain the illusion of a single
5396      DW_TAG_{compile,type}_unit DIE is done here.  */
5397   num_extra_attrs = ((stmt_list != NULL)
5398                      + (low_pc != NULL)
5399                      + (high_pc != NULL)
5400                      + (ranges != NULL)
5401                      + (comp_dir != NULL));
5402   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5403                               result_has_children, num_extra_attrs);
5404
5405   /* Copy over the attributes from the stub to the DIE we just read in.  */
5406   comp_unit_die = *result_comp_unit_die;
5407   i = comp_unit_die->num_attrs;
5408   if (stmt_list != NULL)
5409     comp_unit_die->attrs[i++] = *stmt_list;
5410   if (low_pc != NULL)
5411     comp_unit_die->attrs[i++] = *low_pc;
5412   if (high_pc != NULL)
5413     comp_unit_die->attrs[i++] = *high_pc;
5414   if (ranges != NULL)
5415     comp_unit_die->attrs[i++] = *ranges;
5416   if (comp_dir != NULL)
5417     comp_unit_die->attrs[i++] = *comp_dir;
5418   comp_unit_die->num_attrs += num_extra_attrs;
5419
5420   if (dwarf_die_debug)
5421     {
5422       fprintf_unfiltered (gdb_stdlog,
5423                           "Read die from %s@0x%x of %s:\n",
5424                           get_section_name (section),
5425                           (unsigned) (begin_info_ptr - section->buffer),
5426                           bfd_get_filename (abfd));
5427       dump_die (comp_unit_die, dwarf_die_debug);
5428     }
5429
5430   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5431      TUs by skipping the stub and going directly to the entry in the DWO file.
5432      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5433      to get it via circuitous means.  Blech.  */
5434   if (comp_dir != NULL)
5435     result_reader->comp_dir = DW_STRING (comp_dir);
5436
5437   /* Skip dummy compilation units.  */
5438   if (info_ptr >= begin_info_ptr + dwo_unit->length
5439       || peek_abbrev_code (abfd, info_ptr) == 0)
5440     return 0;
5441
5442   *result_info_ptr = info_ptr;
5443   return 1;
5444 }
5445
5446 /* Subroutine of init_cutu_and_read_dies to simplify it.
5447    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5448    Returns NULL if the specified DWO unit cannot be found.  */
5449
5450 static struct dwo_unit *
5451 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5452                  struct die_info *comp_unit_die)
5453 {
5454   struct dwarf2_cu *cu = this_cu->cu;
5455   struct attribute *attr;
5456   ULONGEST signature;
5457   struct dwo_unit *dwo_unit;
5458   const char *comp_dir, *dwo_name;
5459
5460   gdb_assert (cu != NULL);
5461
5462   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5463   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5464   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5465
5466   if (this_cu->is_debug_types)
5467     {
5468       struct signatured_type *sig_type;
5469
5470       /* Since this_cu is the first member of struct signatured_type,
5471          we can go from a pointer to one to a pointer to the other.  */
5472       sig_type = (struct signatured_type *) this_cu;
5473       signature = sig_type->signature;
5474       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5475     }
5476   else
5477     {
5478       struct attribute *attr;
5479
5480       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5481       if (! attr)
5482         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5483                  " [in module %s]"),
5484                dwo_name, objfile_name (this_cu->objfile));
5485       signature = DW_UNSND (attr);
5486       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5487                                        signature);
5488     }
5489
5490   return dwo_unit;
5491 }
5492
5493 /* Subroutine of init_cutu_and_read_dies to simplify it.
5494    See it for a description of the parameters.
5495    Read a TU directly from a DWO file, bypassing the stub.
5496
5497    Note: This function could be a little bit simpler if we shared cleanups
5498    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5499    to do, so we keep this function self-contained.  Or we could move this
5500    into our caller, but it's complex enough already.  */
5501
5502 static void
5503 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5504                            int use_existing_cu, int keep,
5505                            die_reader_func_ftype *die_reader_func,
5506                            void *data)
5507 {
5508   struct dwarf2_cu *cu;
5509   struct signatured_type *sig_type;
5510   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5511   struct die_reader_specs reader;
5512   const gdb_byte *info_ptr;
5513   struct die_info *comp_unit_die;
5514   int has_children;
5515
5516   /* Verify we can do the following downcast, and that we have the
5517      data we need.  */
5518   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5519   sig_type = (struct signatured_type *) this_cu;
5520   gdb_assert (sig_type->dwo_unit != NULL);
5521
5522   cleanups = make_cleanup (null_cleanup, NULL);
5523
5524   if (use_existing_cu && this_cu->cu != NULL)
5525     {
5526       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5527       cu = this_cu->cu;
5528       /* There's no need to do the rereading_dwo_cu handling that
5529          init_cutu_and_read_dies does since we don't read the stub.  */
5530     }
5531   else
5532     {
5533       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5534       gdb_assert (this_cu->cu == NULL);
5535       cu = XNEW (struct dwarf2_cu);
5536       init_one_comp_unit (cu, this_cu);
5537       /* If an error occurs while loading, release our storage.  */
5538       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5539     }
5540
5541   /* A future optimization, if needed, would be to use an existing
5542      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5543      could share abbrev tables.  */
5544
5545   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5546                               0 /* abbrev_table_provided */,
5547                               NULL /* stub_comp_unit_die */,
5548                               sig_type->dwo_unit->dwo_file->comp_dir,
5549                               &reader, &info_ptr,
5550                               &comp_unit_die, &has_children) == 0)
5551     {
5552       /* Dummy die.  */
5553       do_cleanups (cleanups);
5554       return;
5555     }
5556
5557   /* All the "real" work is done here.  */
5558   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5559
5560   /* This duplicates the code in init_cutu_and_read_dies,
5561      but the alternative is making the latter more complex.
5562      This function is only for the special case of using DWO files directly:
5563      no point in overly complicating the general case just to handle this.  */
5564   if (free_cu_cleanup != NULL)
5565     {
5566       if (keep)
5567         {
5568           /* We've successfully allocated this compilation unit.  Let our
5569              caller clean it up when finished with it.  */
5570           discard_cleanups (free_cu_cleanup);
5571
5572           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5573              So we have to manually free the abbrev table.  */
5574           dwarf2_free_abbrev_table (cu);
5575
5576           /* Link this CU into read_in_chain.  */
5577           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5578           dwarf2_per_objfile->read_in_chain = this_cu;
5579         }
5580       else
5581         do_cleanups (free_cu_cleanup);
5582     }
5583
5584   do_cleanups (cleanups);
5585 }
5586
5587 /* Initialize a CU (or TU) and read its DIEs.
5588    If the CU defers to a DWO file, read the DWO file as well.
5589
5590    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5591    Otherwise the table specified in the comp unit header is read in and used.
5592    This is an optimization for when we already have the abbrev table.
5593
5594    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5595    Otherwise, a new CU is allocated with xmalloc.
5596
5597    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5598    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5599
5600    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5601    linker) then DIE_READER_FUNC will not get called.  */
5602
5603 static void
5604 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5605                          struct abbrev_table *abbrev_table,
5606                          int use_existing_cu, int keep,
5607                          die_reader_func_ftype *die_reader_func,
5608                          void *data)
5609 {
5610   struct objfile *objfile = dwarf2_per_objfile->objfile;
5611   struct dwarf2_section_info *section = this_cu->section;
5612   bfd *abfd = get_section_bfd_owner (section);
5613   struct dwarf2_cu *cu;
5614   const gdb_byte *begin_info_ptr, *info_ptr;
5615   struct die_reader_specs reader;
5616   struct die_info *comp_unit_die;
5617   int has_children;
5618   struct attribute *attr;
5619   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5620   struct signatured_type *sig_type = NULL;
5621   struct dwarf2_section_info *abbrev_section;
5622   /* Non-zero if CU currently points to a DWO file and we need to
5623      reread it.  When this happens we need to reread the skeleton die
5624      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5625   int rereading_dwo_cu = 0;
5626
5627   if (dwarf_die_debug)
5628     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5629                         this_cu->is_debug_types ? "type" : "comp",
5630                         to_underlying (this_cu->sect_off));
5631
5632   if (use_existing_cu)
5633     gdb_assert (keep);
5634
5635   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5636      file (instead of going through the stub), short-circuit all of this.  */
5637   if (this_cu->reading_dwo_directly)
5638     {
5639       /* Narrow down the scope of possibilities to have to understand.  */
5640       gdb_assert (this_cu->is_debug_types);
5641       gdb_assert (abbrev_table == NULL);
5642       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5643                                  die_reader_func, data);
5644       return;
5645     }
5646
5647   cleanups = make_cleanup (null_cleanup, NULL);
5648
5649   /* This is cheap if the section is already read in.  */
5650   dwarf2_read_section (objfile, section);
5651
5652   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5653
5654   abbrev_section = get_abbrev_section_for_cu (this_cu);
5655
5656   if (use_existing_cu && this_cu->cu != NULL)
5657     {
5658       cu = this_cu->cu;
5659       /* If this CU is from a DWO file we need to start over, we need to
5660          refetch the attributes from the skeleton CU.
5661          This could be optimized by retrieving those attributes from when we
5662          were here the first time: the previous comp_unit_die was stored in
5663          comp_unit_obstack.  But there's no data yet that we need this
5664          optimization.  */
5665       if (cu->dwo_unit != NULL)
5666         rereading_dwo_cu = 1;
5667     }
5668   else
5669     {
5670       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5671       gdb_assert (this_cu->cu == NULL);
5672       cu = XNEW (struct dwarf2_cu);
5673       init_one_comp_unit (cu, this_cu);
5674       /* If an error occurs while loading, release our storage.  */
5675       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5676     }
5677
5678   /* Get the header.  */
5679   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5680     {
5681       /* We already have the header, there's no need to read it in again.  */
5682       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5683     }
5684   else
5685     {
5686       if (this_cu->is_debug_types)
5687         {
5688           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5689                                                     abbrev_section, info_ptr,
5690                                                     rcuh_kind::TYPE);
5691
5692           /* Since per_cu is the first member of struct signatured_type,
5693              we can go from a pointer to one to a pointer to the other.  */
5694           sig_type = (struct signatured_type *) this_cu;
5695           gdb_assert (sig_type->signature == cu->header.signature);
5696           gdb_assert (sig_type->type_offset_in_tu
5697                       == cu->header.type_cu_offset_in_tu);
5698           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5699
5700           /* LENGTH has not been set yet for type units if we're
5701              using .gdb_index.  */
5702           this_cu->length = get_cu_length (&cu->header);
5703
5704           /* Establish the type offset that can be used to lookup the type.  */
5705           sig_type->type_offset_in_section =
5706             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5707
5708           this_cu->dwarf_version = cu->header.version;
5709         }
5710       else
5711         {
5712           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5713                                                     abbrev_section,
5714                                                     info_ptr,
5715                                                     rcuh_kind::COMPILE);
5716
5717           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5718           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5719           this_cu->dwarf_version = cu->header.version;
5720         }
5721     }
5722
5723   /* Skip dummy compilation units.  */
5724   if (info_ptr >= begin_info_ptr + this_cu->length
5725       || peek_abbrev_code (abfd, info_ptr) == 0)
5726     {
5727       do_cleanups (cleanups);
5728       return;
5729     }
5730
5731   /* If we don't have them yet, read the abbrevs for this compilation unit.
5732      And if we need to read them now, make sure they're freed when we're
5733      done.  Note that it's important that if the CU had an abbrev table
5734      on entry we don't free it when we're done: Somewhere up the call stack
5735      it may be in use.  */
5736   if (abbrev_table != NULL)
5737     {
5738       gdb_assert (cu->abbrev_table == NULL);
5739       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5740       cu->abbrev_table = abbrev_table;
5741     }
5742   else if (cu->abbrev_table == NULL)
5743     {
5744       dwarf2_read_abbrevs (cu, abbrev_section);
5745       make_cleanup (dwarf2_free_abbrev_table, cu);
5746     }
5747   else if (rereading_dwo_cu)
5748     {
5749       dwarf2_free_abbrev_table (cu);
5750       dwarf2_read_abbrevs (cu, abbrev_section);
5751     }
5752
5753   /* Read the top level CU/TU die.  */
5754   init_cu_die_reader (&reader, cu, section, NULL);
5755   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5756
5757   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5758      from the DWO file.
5759      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5760      DWO CU, that this test will fail (the attribute will not be present).  */
5761   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5762   if (attr)
5763     {
5764       struct dwo_unit *dwo_unit;
5765       struct die_info *dwo_comp_unit_die;
5766
5767       if (has_children)
5768         {
5769           complaint (&symfile_complaints,
5770                      _("compilation unit with DW_AT_GNU_dwo_name"
5771                        " has children (offset 0x%x) [in module %s]"),
5772                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5773         }
5774       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5775       if (dwo_unit != NULL)
5776         {
5777           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5778                                       abbrev_table != NULL,
5779                                       comp_unit_die, NULL,
5780                                       &reader, &info_ptr,
5781                                       &dwo_comp_unit_die, &has_children) == 0)
5782             {
5783               /* Dummy die.  */
5784               do_cleanups (cleanups);
5785               return;
5786             }
5787           comp_unit_die = dwo_comp_unit_die;
5788         }
5789       else
5790         {
5791           /* Yikes, we couldn't find the rest of the DIE, we only have
5792              the stub.  A complaint has already been logged.  There's
5793              not much more we can do except pass on the stub DIE to
5794              die_reader_func.  We don't want to throw an error on bad
5795              debug info.  */
5796         }
5797     }
5798
5799   /* All of the above is setup for this call.  Yikes.  */
5800   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5801
5802   /* Done, clean up.  */
5803   if (free_cu_cleanup != NULL)
5804     {
5805       if (keep)
5806         {
5807           /* We've successfully allocated this compilation unit.  Let our
5808              caller clean it up when finished with it.  */
5809           discard_cleanups (free_cu_cleanup);
5810
5811           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5812              So we have to manually free the abbrev table.  */
5813           dwarf2_free_abbrev_table (cu);
5814
5815           /* Link this CU into read_in_chain.  */
5816           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5817           dwarf2_per_objfile->read_in_chain = this_cu;
5818         }
5819       else
5820         do_cleanups (free_cu_cleanup);
5821     }
5822
5823   do_cleanups (cleanups);
5824 }
5825
5826 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5827    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5828    to have already done the lookup to find the DWO file).
5829
5830    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5831    THIS_CU->is_debug_types, but nothing else.
5832
5833    We fill in THIS_CU->length.
5834
5835    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5836    linker) then DIE_READER_FUNC will not get called.
5837
5838    THIS_CU->cu is always freed when done.
5839    This is done in order to not leave THIS_CU->cu in a state where we have
5840    to care whether it refers to the "main" CU or the DWO CU.  */
5841
5842 static void
5843 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5844                                    struct dwo_file *dwo_file,
5845                                    die_reader_func_ftype *die_reader_func,
5846                                    void *data)
5847 {
5848   struct objfile *objfile = dwarf2_per_objfile->objfile;
5849   struct dwarf2_section_info *section = this_cu->section;
5850   bfd *abfd = get_section_bfd_owner (section);
5851   struct dwarf2_section_info *abbrev_section;
5852   struct dwarf2_cu cu;
5853   const gdb_byte *begin_info_ptr, *info_ptr;
5854   struct die_reader_specs reader;
5855   struct cleanup *cleanups;
5856   struct die_info *comp_unit_die;
5857   int has_children;
5858
5859   if (dwarf_die_debug)
5860     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5861                         this_cu->is_debug_types ? "type" : "comp",
5862                         to_underlying (this_cu->sect_off));
5863
5864   gdb_assert (this_cu->cu == NULL);
5865
5866   abbrev_section = (dwo_file != NULL
5867                     ? &dwo_file->sections.abbrev
5868                     : get_abbrev_section_for_cu (this_cu));
5869
5870   /* This is cheap if the section is already read in.  */
5871   dwarf2_read_section (objfile, section);
5872
5873   init_one_comp_unit (&cu, this_cu);
5874
5875   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5876
5877   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5878   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5879                                             abbrev_section, info_ptr,
5880                                             (this_cu->is_debug_types
5881                                              ? rcuh_kind::TYPE
5882                                              : rcuh_kind::COMPILE));
5883
5884   this_cu->length = get_cu_length (&cu.header);
5885
5886   /* Skip dummy compilation units.  */
5887   if (info_ptr >= begin_info_ptr + this_cu->length
5888       || peek_abbrev_code (abfd, info_ptr) == 0)
5889     {
5890       do_cleanups (cleanups);
5891       return;
5892     }
5893
5894   dwarf2_read_abbrevs (&cu, abbrev_section);
5895   make_cleanup (dwarf2_free_abbrev_table, &cu);
5896
5897   init_cu_die_reader (&reader, &cu, section, dwo_file);
5898   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5899
5900   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5901
5902   do_cleanups (cleanups);
5903 }
5904
5905 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5906    does not lookup the specified DWO file.
5907    This cannot be used to read DWO files.
5908
5909    THIS_CU->cu is always freed when done.
5910    This is done in order to not leave THIS_CU->cu in a state where we have
5911    to care whether it refers to the "main" CU or the DWO CU.
5912    We can revisit this if the data shows there's a performance issue.  */
5913
5914 static void
5915 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5916                                 die_reader_func_ftype *die_reader_func,
5917                                 void *data)
5918 {
5919   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5920 }
5921 \f
5922 /* Type Unit Groups.
5923
5924    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5925    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5926    so that all types coming from the same compilation (.o file) are grouped
5927    together.  A future step could be to put the types in the same symtab as
5928    the CU the types ultimately came from.  */
5929
5930 static hashval_t
5931 hash_type_unit_group (const void *item)
5932 {
5933   const struct type_unit_group *tu_group
5934     = (const struct type_unit_group *) item;
5935
5936   return hash_stmt_list_entry (&tu_group->hash);
5937 }
5938
5939 static int
5940 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5941 {
5942   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
5943   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
5944
5945   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5946 }
5947
5948 /* Allocate a hash table for type unit groups.  */
5949
5950 static htab_t
5951 allocate_type_unit_groups_table (void)
5952 {
5953   return htab_create_alloc_ex (3,
5954                                hash_type_unit_group,
5955                                eq_type_unit_group,
5956                                NULL,
5957                                &dwarf2_per_objfile->objfile->objfile_obstack,
5958                                hashtab_obstack_allocate,
5959                                dummy_obstack_deallocate);
5960 }
5961
5962 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5963    partial symtabs.  We combine several TUs per psymtab to not let the size
5964    of any one psymtab grow too big.  */
5965 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5966 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5967
5968 /* Helper routine for get_type_unit_group.
5969    Create the type_unit_group object used to hold one or more TUs.  */
5970
5971 static struct type_unit_group *
5972 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5973 {
5974   struct objfile *objfile = dwarf2_per_objfile->objfile;
5975   struct dwarf2_per_cu_data *per_cu;
5976   struct type_unit_group *tu_group;
5977
5978   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5979                              struct type_unit_group);
5980   per_cu = &tu_group->per_cu;
5981   per_cu->objfile = objfile;
5982
5983   if (dwarf2_per_objfile->using_index)
5984     {
5985       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5986                                         struct dwarf2_per_cu_quick_data);
5987     }
5988   else
5989     {
5990       unsigned int line_offset = to_underlying (line_offset_struct);
5991       struct partial_symtab *pst;
5992       char *name;
5993
5994       /* Give the symtab a useful name for debug purposes.  */
5995       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5996         name = xstrprintf ("<type_units_%d>",
5997                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5998       else
5999         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6000
6001       pst = create_partial_symtab (per_cu, name);
6002       pst->anonymous = 1;
6003
6004       xfree (name);
6005     }
6006
6007   tu_group->hash.dwo_unit = cu->dwo_unit;
6008   tu_group->hash.line_sect_off = line_offset_struct;
6009
6010   return tu_group;
6011 }
6012
6013 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6014    STMT_LIST is a DW_AT_stmt_list attribute.  */
6015
6016 static struct type_unit_group *
6017 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6018 {
6019   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6020   struct type_unit_group *tu_group;
6021   void **slot;
6022   unsigned int line_offset;
6023   struct type_unit_group type_unit_group_for_lookup;
6024
6025   if (dwarf2_per_objfile->type_unit_groups == NULL)
6026     {
6027       dwarf2_per_objfile->type_unit_groups =
6028         allocate_type_unit_groups_table ();
6029     }
6030
6031   /* Do we need to create a new group, or can we use an existing one?  */
6032
6033   if (stmt_list)
6034     {
6035       line_offset = DW_UNSND (stmt_list);
6036       ++tu_stats->nr_symtab_sharers;
6037     }
6038   else
6039     {
6040       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6041          We can do various things here like create one group per TU or
6042          spread them over multiple groups to split up the expansion work.
6043          To avoid worst case scenarios (too many groups or too large groups)
6044          we, umm, group them in bunches.  */
6045       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6046                      | (tu_stats->nr_stmt_less_type_units
6047                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6048       ++tu_stats->nr_stmt_less_type_units;
6049     }
6050
6051   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6052   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6053   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6054                          &type_unit_group_for_lookup, INSERT);
6055   if (*slot != NULL)
6056     {
6057       tu_group = (struct type_unit_group *) *slot;
6058       gdb_assert (tu_group != NULL);
6059     }
6060   else
6061     {
6062       sect_offset line_offset_struct = (sect_offset) line_offset;
6063       tu_group = create_type_unit_group (cu, line_offset_struct);
6064       *slot = tu_group;
6065       ++tu_stats->nr_symtabs;
6066     }
6067
6068   return tu_group;
6069 }
6070 \f
6071 /* Partial symbol tables.  */
6072
6073 /* Create a psymtab named NAME and assign it to PER_CU.
6074
6075    The caller must fill in the following details:
6076    dirname, textlow, texthigh.  */
6077
6078 static struct partial_symtab *
6079 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6080 {
6081   struct objfile *objfile = per_cu->objfile;
6082   struct partial_symtab *pst;
6083
6084   pst = start_psymtab_common (objfile, name, 0,
6085                               objfile->global_psymbols.next,
6086                               objfile->static_psymbols.next);
6087
6088   pst->psymtabs_addrmap_supported = 1;
6089
6090   /* This is the glue that links PST into GDB's symbol API.  */
6091   pst->read_symtab_private = per_cu;
6092   pst->read_symtab = dwarf2_read_symtab;
6093   per_cu->v.psymtab = pst;
6094
6095   return pst;
6096 }
6097
6098 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6099    type.  */
6100
6101 struct process_psymtab_comp_unit_data
6102 {
6103   /* True if we are reading a DW_TAG_partial_unit.  */
6104
6105   int want_partial_unit;
6106
6107   /* The "pretend" language that is used if the CU doesn't declare a
6108      language.  */
6109
6110   enum language pretend_language;
6111 };
6112
6113 /* die_reader_func for process_psymtab_comp_unit.  */
6114
6115 static void
6116 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6117                                   const gdb_byte *info_ptr,
6118                                   struct die_info *comp_unit_die,
6119                                   int has_children,
6120                                   void *data)
6121 {
6122   struct dwarf2_cu *cu = reader->cu;
6123   struct objfile *objfile = cu->objfile;
6124   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6125   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6126   CORE_ADDR baseaddr;
6127   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6128   struct partial_symtab *pst;
6129   enum pc_bounds_kind cu_bounds_kind;
6130   const char *filename;
6131   struct process_psymtab_comp_unit_data *info
6132     = (struct process_psymtab_comp_unit_data *) data;
6133
6134   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6135     return;
6136
6137   gdb_assert (! per_cu->is_debug_types);
6138
6139   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6140
6141   cu->list_in_scope = &file_symbols;
6142
6143   /* Allocate a new partial symbol table structure.  */
6144   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6145   if (filename == NULL)
6146     filename = "";
6147
6148   pst = create_partial_symtab (per_cu, filename);
6149
6150   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6151   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6152
6153   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6154
6155   dwarf2_find_base_address (comp_unit_die, cu);
6156
6157   /* Possibly set the default values of LOWPC and HIGHPC from
6158      `DW_AT_ranges'.  */
6159   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6160                                          &best_highpc, cu, pst);
6161   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6162     /* Store the contiguous range if it is not empty; it can be empty for
6163        CUs with no code.  */
6164     addrmap_set_empty (objfile->psymtabs_addrmap,
6165                        gdbarch_adjust_dwarf2_addr (gdbarch,
6166                                                    best_lowpc + baseaddr),
6167                        gdbarch_adjust_dwarf2_addr (gdbarch,
6168                                                    best_highpc + baseaddr) - 1,
6169                        pst);
6170
6171   /* Check if comp unit has_children.
6172      If so, read the rest of the partial symbols from this comp unit.
6173      If not, there's no more debug_info for this comp unit.  */
6174   if (has_children)
6175     {
6176       struct partial_die_info *first_die;
6177       CORE_ADDR lowpc, highpc;
6178
6179       lowpc = ((CORE_ADDR) -1);
6180       highpc = ((CORE_ADDR) 0);
6181
6182       first_die = load_partial_dies (reader, info_ptr, 1);
6183
6184       scan_partial_symbols (first_die, &lowpc, &highpc,
6185                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6186
6187       /* If we didn't find a lowpc, set it to highpc to avoid
6188          complaints from `maint check'.  */
6189       if (lowpc == ((CORE_ADDR) -1))
6190         lowpc = highpc;
6191
6192       /* If the compilation unit didn't have an explicit address range,
6193          then use the information extracted from its child dies.  */
6194       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6195         {
6196           best_lowpc = lowpc;
6197           best_highpc = highpc;
6198         }
6199     }
6200   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6201   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6202
6203   end_psymtab_common (objfile, pst);
6204
6205   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6206     {
6207       int i;
6208       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6209       struct dwarf2_per_cu_data *iter;
6210
6211       /* Fill in 'dependencies' here; we fill in 'users' in a
6212          post-pass.  */
6213       pst->number_of_dependencies = len;
6214       pst->dependencies =
6215         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6216       for (i = 0;
6217            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6218                         i, iter);
6219            ++i)
6220         pst->dependencies[i] = iter->v.psymtab;
6221
6222       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6223     }
6224
6225   /* Get the list of files included in the current compilation unit,
6226      and build a psymtab for each of them.  */
6227   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6228
6229   if (dwarf_read_debug)
6230     {
6231       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6232
6233       fprintf_unfiltered (gdb_stdlog,
6234                           "Psymtab for %s unit @0x%x: %s - %s"
6235                           ", %d global, %d static syms\n",
6236                           per_cu->is_debug_types ? "type" : "comp",
6237                           to_underlying (per_cu->sect_off),
6238                           paddress (gdbarch, pst->textlow),
6239                           paddress (gdbarch, pst->texthigh),
6240                           pst->n_global_syms, pst->n_static_syms);
6241     }
6242 }
6243
6244 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6245    Process compilation unit THIS_CU for a psymtab.  */
6246
6247 static void
6248 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6249                            int want_partial_unit,
6250                            enum language pretend_language)
6251 {
6252   struct process_psymtab_comp_unit_data info;
6253
6254   /* If this compilation unit was already read in, free the
6255      cached copy in order to read it in again.  This is
6256      necessary because we skipped some symbols when we first
6257      read in the compilation unit (see load_partial_dies).
6258      This problem could be avoided, but the benefit is unclear.  */
6259   if (this_cu->cu != NULL)
6260     free_one_cached_comp_unit (this_cu);
6261
6262   gdb_assert (! this_cu->is_debug_types);
6263   info.want_partial_unit = want_partial_unit;
6264   info.pretend_language = pretend_language;
6265   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6266                            process_psymtab_comp_unit_reader,
6267                            &info);
6268
6269   /* Age out any secondary CUs.  */
6270   age_cached_comp_units ();
6271 }
6272
6273 /* Reader function for build_type_psymtabs.  */
6274
6275 static void
6276 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6277                             const gdb_byte *info_ptr,
6278                             struct die_info *type_unit_die,
6279                             int has_children,
6280                             void *data)
6281 {
6282   struct objfile *objfile = dwarf2_per_objfile->objfile;
6283   struct dwarf2_cu *cu = reader->cu;
6284   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6285   struct signatured_type *sig_type;
6286   struct type_unit_group *tu_group;
6287   struct attribute *attr;
6288   struct partial_die_info *first_die;
6289   CORE_ADDR lowpc, highpc;
6290   struct partial_symtab *pst;
6291
6292   gdb_assert (data == NULL);
6293   gdb_assert (per_cu->is_debug_types);
6294   sig_type = (struct signatured_type *) per_cu;
6295
6296   if (! has_children)
6297     return;
6298
6299   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6300   tu_group = get_type_unit_group (cu, attr);
6301
6302   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6303
6304   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6305   cu->list_in_scope = &file_symbols;
6306   pst = create_partial_symtab (per_cu, "");
6307   pst->anonymous = 1;
6308
6309   first_die = load_partial_dies (reader, info_ptr, 1);
6310
6311   lowpc = (CORE_ADDR) -1;
6312   highpc = (CORE_ADDR) 0;
6313   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6314
6315   end_psymtab_common (objfile, pst);
6316 }
6317
6318 /* Struct used to sort TUs by their abbreviation table offset.  */
6319
6320 struct tu_abbrev_offset
6321 {
6322   struct signatured_type *sig_type;
6323   sect_offset abbrev_offset;
6324 };
6325
6326 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6327
6328 static int
6329 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6330 {
6331   const struct tu_abbrev_offset * const *a
6332     = (const struct tu_abbrev_offset * const*) ap;
6333   const struct tu_abbrev_offset * const *b
6334     = (const struct tu_abbrev_offset * const*) bp;
6335   sect_offset aoff = (*a)->abbrev_offset;
6336   sect_offset boff = (*b)->abbrev_offset;
6337
6338   return (aoff > boff) - (aoff < boff);
6339 }
6340
6341 /* Efficiently read all the type units.
6342    This does the bulk of the work for build_type_psymtabs.
6343
6344    The efficiency is because we sort TUs by the abbrev table they use and
6345    only read each abbrev table once.  In one program there are 200K TUs
6346    sharing 8K abbrev tables.
6347
6348    The main purpose of this function is to support building the
6349    dwarf2_per_objfile->type_unit_groups table.
6350    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6351    can collapse the search space by grouping them by stmt_list.
6352    The savings can be significant, in the same program from above the 200K TUs
6353    share 8K stmt_list tables.
6354
6355    FUNC is expected to call get_type_unit_group, which will create the
6356    struct type_unit_group if necessary and add it to
6357    dwarf2_per_objfile->type_unit_groups.  */
6358
6359 static void
6360 build_type_psymtabs_1 (void)
6361 {
6362   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6363   struct cleanup *cleanups;
6364   struct abbrev_table *abbrev_table;
6365   sect_offset abbrev_offset;
6366   struct tu_abbrev_offset *sorted_by_abbrev;
6367   int i;
6368
6369   /* It's up to the caller to not call us multiple times.  */
6370   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6371
6372   if (dwarf2_per_objfile->n_type_units == 0)
6373     return;
6374
6375   /* TUs typically share abbrev tables, and there can be way more TUs than
6376      abbrev tables.  Sort by abbrev table to reduce the number of times we
6377      read each abbrev table in.
6378      Alternatives are to punt or to maintain a cache of abbrev tables.
6379      This is simpler and efficient enough for now.
6380
6381      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6382      symtab to use).  Typically TUs with the same abbrev offset have the same
6383      stmt_list value too so in practice this should work well.
6384
6385      The basic algorithm here is:
6386
6387       sort TUs by abbrev table
6388       for each TU with same abbrev table:
6389         read abbrev table if first user
6390         read TU top level DIE
6391           [IWBN if DWO skeletons had DW_AT_stmt_list]
6392         call FUNC  */
6393
6394   if (dwarf_read_debug)
6395     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6396
6397   /* Sort in a separate table to maintain the order of all_type_units
6398      for .gdb_index: TU indices directly index all_type_units.  */
6399   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6400                               dwarf2_per_objfile->n_type_units);
6401   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6402     {
6403       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6404
6405       sorted_by_abbrev[i].sig_type = sig_type;
6406       sorted_by_abbrev[i].abbrev_offset =
6407         read_abbrev_offset (sig_type->per_cu.section,
6408                             sig_type->per_cu.sect_off);
6409     }
6410   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6411   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6412          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6413
6414   abbrev_offset = (sect_offset) ~(unsigned) 0;
6415   abbrev_table = NULL;
6416   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6417
6418   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6419     {
6420       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6421
6422       /* Switch to the next abbrev table if necessary.  */
6423       if (abbrev_table == NULL
6424           || tu->abbrev_offset != abbrev_offset)
6425         {
6426           if (abbrev_table != NULL)
6427             {
6428               abbrev_table_free (abbrev_table);
6429               /* Reset to NULL in case abbrev_table_read_table throws
6430                  an error: abbrev_table_free_cleanup will get called.  */
6431               abbrev_table = NULL;
6432             }
6433           abbrev_offset = tu->abbrev_offset;
6434           abbrev_table =
6435             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6436                                      abbrev_offset);
6437           ++tu_stats->nr_uniq_abbrev_tables;
6438         }
6439
6440       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6441                                build_type_psymtabs_reader, NULL);
6442     }
6443
6444   do_cleanups (cleanups);
6445 }
6446
6447 /* Print collected type unit statistics.  */
6448
6449 static void
6450 print_tu_stats (void)
6451 {
6452   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6453
6454   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6455   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6456                       dwarf2_per_objfile->n_type_units);
6457   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6458                       tu_stats->nr_uniq_abbrev_tables);
6459   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6460                       tu_stats->nr_symtabs);
6461   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6462                       tu_stats->nr_symtab_sharers);
6463   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6464                       tu_stats->nr_stmt_less_type_units);
6465   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6466                       tu_stats->nr_all_type_units_reallocs);
6467 }
6468
6469 /* Traversal function for build_type_psymtabs.  */
6470
6471 static int
6472 build_type_psymtab_dependencies (void **slot, void *info)
6473 {
6474   struct objfile *objfile = dwarf2_per_objfile->objfile;
6475   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6476   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6477   struct partial_symtab *pst = per_cu->v.psymtab;
6478   int len = VEC_length (sig_type_ptr, tu_group->tus);
6479   struct signatured_type *iter;
6480   int i;
6481
6482   gdb_assert (len > 0);
6483   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6484
6485   pst->number_of_dependencies = len;
6486   pst->dependencies =
6487     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6488   for (i = 0;
6489        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6490        ++i)
6491     {
6492       gdb_assert (iter->per_cu.is_debug_types);
6493       pst->dependencies[i] = iter->per_cu.v.psymtab;
6494       iter->type_unit_group = tu_group;
6495     }
6496
6497   VEC_free (sig_type_ptr, tu_group->tus);
6498
6499   return 1;
6500 }
6501
6502 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6503    Build partial symbol tables for the .debug_types comp-units.  */
6504
6505 static void
6506 build_type_psymtabs (struct objfile *objfile)
6507 {
6508   if (! create_all_type_units (objfile))
6509     return;
6510
6511   build_type_psymtabs_1 ();
6512 }
6513
6514 /* Traversal function for process_skeletonless_type_unit.
6515    Read a TU in a DWO file and build partial symbols for it.  */
6516
6517 static int
6518 process_skeletonless_type_unit (void **slot, void *info)
6519 {
6520   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6521   struct objfile *objfile = (struct objfile *) info;
6522   struct signatured_type find_entry, *entry;
6523
6524   /* If this TU doesn't exist in the global table, add it and read it in.  */
6525
6526   if (dwarf2_per_objfile->signatured_types == NULL)
6527     {
6528       dwarf2_per_objfile->signatured_types
6529         = allocate_signatured_type_table (objfile);
6530     }
6531
6532   find_entry.signature = dwo_unit->signature;
6533   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6534                          INSERT);
6535   /* If we've already seen this type there's nothing to do.  What's happening
6536      is we're doing our own version of comdat-folding here.  */
6537   if (*slot != NULL)
6538     return 1;
6539
6540   /* This does the job that create_all_type_units would have done for
6541      this TU.  */
6542   entry = add_type_unit (dwo_unit->signature, slot);
6543   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6544   *slot = entry;
6545
6546   /* This does the job that build_type_psymtabs_1 would have done.  */
6547   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6548                            build_type_psymtabs_reader, NULL);
6549
6550   return 1;
6551 }
6552
6553 /* Traversal function for process_skeletonless_type_units.  */
6554
6555 static int
6556 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6557 {
6558   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6559
6560   if (dwo_file->tus != NULL)
6561     {
6562       htab_traverse_noresize (dwo_file->tus,
6563                               process_skeletonless_type_unit, info);
6564     }
6565
6566   return 1;
6567 }
6568
6569 /* Scan all TUs of DWO files, verifying we've processed them.
6570    This is needed in case a TU was emitted without its skeleton.
6571    Note: This can't be done until we know what all the DWO files are.  */
6572
6573 static void
6574 process_skeletonless_type_units (struct objfile *objfile)
6575 {
6576   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6577   if (get_dwp_file () == NULL
6578       && dwarf2_per_objfile->dwo_files != NULL)
6579     {
6580       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6581                               process_dwo_file_for_skeletonless_type_units,
6582                               objfile);
6583     }
6584 }
6585
6586 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6587
6588 static void
6589 psymtabs_addrmap_cleanup (void *o)
6590 {
6591   struct objfile *objfile = (struct objfile *) o;
6592
6593   objfile->psymtabs_addrmap = NULL;
6594 }
6595
6596 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6597
6598 static void
6599 set_partial_user (struct objfile *objfile)
6600 {
6601   int i;
6602
6603   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6604     {
6605       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6606       struct partial_symtab *pst = per_cu->v.psymtab;
6607       int j;
6608
6609       if (pst == NULL)
6610         continue;
6611
6612       for (j = 0; j < pst->number_of_dependencies; ++j)
6613         {
6614           /* Set the 'user' field only if it is not already set.  */
6615           if (pst->dependencies[j]->user == NULL)
6616             pst->dependencies[j]->user = pst;
6617         }
6618     }
6619 }
6620
6621 /* Build the partial symbol table by doing a quick pass through the
6622    .debug_info and .debug_abbrev sections.  */
6623
6624 static void
6625 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6626 {
6627   struct cleanup *back_to, *addrmap_cleanup;
6628   struct obstack temp_obstack;
6629   int i;
6630
6631   if (dwarf_read_debug)
6632     {
6633       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6634                           objfile_name (objfile));
6635     }
6636
6637   dwarf2_per_objfile->reading_partial_symbols = 1;
6638
6639   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6640
6641   /* Any cached compilation units will be linked by the per-objfile
6642      read_in_chain.  Make sure to free them when we're done.  */
6643   back_to = make_cleanup (free_cached_comp_units, NULL);
6644
6645   build_type_psymtabs (objfile);
6646
6647   create_all_comp_units (objfile);
6648
6649   /* Create a temporary address map on a temporary obstack.  We later
6650      copy this to the final obstack.  */
6651   obstack_init (&temp_obstack);
6652   make_cleanup_obstack_free (&temp_obstack);
6653   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6654   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6655
6656   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6657     {
6658       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6659
6660       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6661     }
6662
6663   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6664   process_skeletonless_type_units (objfile);
6665
6666   /* Now that all TUs have been processed we can fill in the dependencies.  */
6667   if (dwarf2_per_objfile->type_unit_groups != NULL)
6668     {
6669       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6670                               build_type_psymtab_dependencies, NULL);
6671     }
6672
6673   if (dwarf_read_debug)
6674     print_tu_stats ();
6675
6676   set_partial_user (objfile);
6677
6678   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6679                                                     &objfile->objfile_obstack);
6680   discard_cleanups (addrmap_cleanup);
6681
6682   do_cleanups (back_to);
6683
6684   if (dwarf_read_debug)
6685     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6686                         objfile_name (objfile));
6687 }
6688
6689 /* die_reader_func for load_partial_comp_unit.  */
6690
6691 static void
6692 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6693                                const gdb_byte *info_ptr,
6694                                struct die_info *comp_unit_die,
6695                                int has_children,
6696                                void *data)
6697 {
6698   struct dwarf2_cu *cu = reader->cu;
6699
6700   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6701
6702   /* Check if comp unit has_children.
6703      If so, read the rest of the partial symbols from this comp unit.
6704      If not, there's no more debug_info for this comp unit.  */
6705   if (has_children)
6706     load_partial_dies (reader, info_ptr, 0);
6707 }
6708
6709 /* Load the partial DIEs for a secondary CU into memory.
6710    This is also used when rereading a primary CU with load_all_dies.  */
6711
6712 static void
6713 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6714 {
6715   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6716                            load_partial_comp_unit_reader, NULL);
6717 }
6718
6719 static void
6720 read_comp_units_from_section (struct objfile *objfile,
6721                               struct dwarf2_section_info *section,
6722                               unsigned int is_dwz,
6723                               int *n_allocated,
6724                               int *n_comp_units,
6725                               struct dwarf2_per_cu_data ***all_comp_units)
6726 {
6727   const gdb_byte *info_ptr;
6728   bfd *abfd = get_section_bfd_owner (section);
6729
6730   if (dwarf_read_debug)
6731     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6732                         get_section_name (section),
6733                         get_section_file_name (section));
6734
6735   dwarf2_read_section (objfile, section);
6736
6737   info_ptr = section->buffer;
6738
6739   while (info_ptr < section->buffer + section->size)
6740     {
6741       unsigned int length, initial_length_size;
6742       struct dwarf2_per_cu_data *this_cu;
6743
6744       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6745
6746       /* Read just enough information to find out where the next
6747          compilation unit is.  */
6748       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6749
6750       /* Save the compilation unit for later lookup.  */
6751       this_cu = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_cu_data);
6752       memset (this_cu, 0, sizeof (*this_cu));
6753       this_cu->sect_off = sect_off;
6754       this_cu->length = length + initial_length_size;
6755       this_cu->is_dwz = is_dwz;
6756       this_cu->objfile = objfile;
6757       this_cu->section = section;
6758
6759       if (*n_comp_units == *n_allocated)
6760         {
6761           *n_allocated *= 2;
6762           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6763                                         *all_comp_units, *n_allocated);
6764         }
6765       (*all_comp_units)[*n_comp_units] = this_cu;
6766       ++*n_comp_units;
6767
6768       info_ptr = info_ptr + this_cu->length;
6769     }
6770 }
6771
6772 /* Create a list of all compilation units in OBJFILE.
6773    This is only done for -readnow and building partial symtabs.  */
6774
6775 static void
6776 create_all_comp_units (struct objfile *objfile)
6777 {
6778   int n_allocated;
6779   int n_comp_units;
6780   struct dwarf2_per_cu_data **all_comp_units;
6781   struct dwz_file *dwz;
6782
6783   n_comp_units = 0;
6784   n_allocated = 10;
6785   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6786
6787   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6788                                 &n_allocated, &n_comp_units, &all_comp_units);
6789
6790   dwz = dwarf2_get_dwz_file ();
6791   if (dwz != NULL)
6792     read_comp_units_from_section (objfile, &dwz->info, 1,
6793                                   &n_allocated, &n_comp_units,
6794                                   &all_comp_units);
6795
6796   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6797                                                   struct dwarf2_per_cu_data *,
6798                                                   n_comp_units);
6799   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6800           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6801   xfree (all_comp_units);
6802   dwarf2_per_objfile->n_comp_units = n_comp_units;
6803 }
6804
6805 /* Process all loaded DIEs for compilation unit CU, starting at
6806    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6807    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6808    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6809    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6810
6811 static void
6812 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6813                       CORE_ADDR *highpc, int set_addrmap,
6814                       struct dwarf2_cu *cu)
6815 {
6816   struct partial_die_info *pdi;
6817
6818   /* Now, march along the PDI's, descending into ones which have
6819      interesting children but skipping the children of the other ones,
6820      until we reach the end of the compilation unit.  */
6821
6822   pdi = first_die;
6823
6824   while (pdi != NULL)
6825     {
6826       fixup_partial_die (pdi, cu);
6827
6828       /* Anonymous namespaces or modules have no name but have interesting
6829          children, so we need to look at them.  Ditto for anonymous
6830          enums.  */
6831
6832       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6833           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6834           || pdi->tag == DW_TAG_imported_unit)
6835         {
6836           switch (pdi->tag)
6837             {
6838             case DW_TAG_subprogram:
6839               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6840               break;
6841             case DW_TAG_constant:
6842             case DW_TAG_variable:
6843             case DW_TAG_typedef:
6844             case DW_TAG_union_type:
6845               if (!pdi->is_declaration)
6846                 {
6847                   add_partial_symbol (pdi, cu);
6848                 }
6849               break;
6850             case DW_TAG_class_type:
6851             case DW_TAG_interface_type:
6852             case DW_TAG_structure_type:
6853               if (!pdi->is_declaration)
6854                 {
6855                   add_partial_symbol (pdi, cu);
6856                 }
6857               if (cu->language == language_rust && pdi->has_children)
6858                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6859                                       set_addrmap, cu);
6860               break;
6861             case DW_TAG_enumeration_type:
6862               if (!pdi->is_declaration)
6863                 add_partial_enumeration (pdi, cu);
6864               break;
6865             case DW_TAG_base_type:
6866             case DW_TAG_subrange_type:
6867               /* File scope base type definitions are added to the partial
6868                  symbol table.  */
6869               add_partial_symbol (pdi, cu);
6870               break;
6871             case DW_TAG_namespace:
6872               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6873               break;
6874             case DW_TAG_module:
6875               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6876               break;
6877             case DW_TAG_imported_unit:
6878               {
6879                 struct dwarf2_per_cu_data *per_cu;
6880
6881                 /* For now we don't handle imported units in type units.  */
6882                 if (cu->per_cu->is_debug_types)
6883                   {
6884                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6885                              " supported in type units [in module %s]"),
6886                            objfile_name (cu->objfile));
6887                   }
6888
6889                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6890                                                            pdi->is_dwz,
6891                                                            cu->objfile);
6892
6893                 /* Go read the partial unit, if needed.  */
6894                 if (per_cu->v.psymtab == NULL)
6895                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6896
6897                 VEC_safe_push (dwarf2_per_cu_ptr,
6898                                cu->per_cu->imported_symtabs, per_cu);
6899               }
6900               break;
6901             case DW_TAG_imported_declaration:
6902               add_partial_symbol (pdi, cu);
6903               break;
6904             default:
6905               break;
6906             }
6907         }
6908
6909       /* If the die has a sibling, skip to the sibling.  */
6910
6911       pdi = pdi->die_sibling;
6912     }
6913 }
6914
6915 /* Functions used to compute the fully scoped name of a partial DIE.
6916
6917    Normally, this is simple.  For C++, the parent DIE's fully scoped
6918    name is concatenated with "::" and the partial DIE's name.
6919    Enumerators are an exception; they use the scope of their parent
6920    enumeration type, i.e. the name of the enumeration type is not
6921    prepended to the enumerator.
6922
6923    There are two complexities.  One is DW_AT_specification; in this
6924    case "parent" means the parent of the target of the specification,
6925    instead of the direct parent of the DIE.  The other is compilers
6926    which do not emit DW_TAG_namespace; in this case we try to guess
6927    the fully qualified name of structure types from their members'
6928    linkage names.  This must be done using the DIE's children rather
6929    than the children of any DW_AT_specification target.  We only need
6930    to do this for structures at the top level, i.e. if the target of
6931    any DW_AT_specification (if any; otherwise the DIE itself) does not
6932    have a parent.  */
6933
6934 /* Compute the scope prefix associated with PDI's parent, in
6935    compilation unit CU.  The result will be allocated on CU's
6936    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6937    field.  NULL is returned if no prefix is necessary.  */
6938 static const char *
6939 partial_die_parent_scope (struct partial_die_info *pdi,
6940                           struct dwarf2_cu *cu)
6941 {
6942   const char *grandparent_scope;
6943   struct partial_die_info *parent, *real_pdi;
6944
6945   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6946      then this means the parent of the specification DIE.  */
6947
6948   real_pdi = pdi;
6949   while (real_pdi->has_specification)
6950     real_pdi = find_partial_die (real_pdi->spec_offset,
6951                                  real_pdi->spec_is_dwz, cu);
6952
6953   parent = real_pdi->die_parent;
6954   if (parent == NULL)
6955     return NULL;
6956
6957   if (parent->scope_set)
6958     return parent->scope;
6959
6960   fixup_partial_die (parent, cu);
6961
6962   grandparent_scope = partial_die_parent_scope (parent, cu);
6963
6964   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6965      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6966      Work around this problem here.  */
6967   if (cu->language == language_cplus
6968       && parent->tag == DW_TAG_namespace
6969       && strcmp (parent->name, "::") == 0
6970       && grandparent_scope == NULL)
6971     {
6972       parent->scope = NULL;
6973       parent->scope_set = 1;
6974       return NULL;
6975     }
6976
6977   if (pdi->tag == DW_TAG_enumerator)
6978     /* Enumerators should not get the name of the enumeration as a prefix.  */
6979     parent->scope = grandparent_scope;
6980   else if (parent->tag == DW_TAG_namespace
6981       || parent->tag == DW_TAG_module
6982       || parent->tag == DW_TAG_structure_type
6983       || parent->tag == DW_TAG_class_type
6984       || parent->tag == DW_TAG_interface_type
6985       || parent->tag == DW_TAG_union_type
6986       || parent->tag == DW_TAG_enumeration_type)
6987     {
6988       if (grandparent_scope == NULL)
6989         parent->scope = parent->name;
6990       else
6991         parent->scope = typename_concat (&cu->comp_unit_obstack,
6992                                          grandparent_scope,
6993                                          parent->name, 0, cu);
6994     }
6995   else
6996     {
6997       /* FIXME drow/2004-04-01: What should we be doing with
6998          function-local names?  For partial symbols, we should probably be
6999          ignoring them.  */
7000       complaint (&symfile_complaints,
7001                  _("unhandled containing DIE tag %d for DIE at %d"),
7002                  parent->tag, to_underlying (pdi->sect_off));
7003       parent->scope = grandparent_scope;
7004     }
7005
7006   parent->scope_set = 1;
7007   return parent->scope;
7008 }
7009
7010 /* Return the fully scoped name associated with PDI, from compilation unit
7011    CU.  The result will be allocated with malloc.  */
7012
7013 static char *
7014 partial_die_full_name (struct partial_die_info *pdi,
7015                        struct dwarf2_cu *cu)
7016 {
7017   const char *parent_scope;
7018
7019   /* If this is a template instantiation, we can not work out the
7020      template arguments from partial DIEs.  So, unfortunately, we have
7021      to go through the full DIEs.  At least any work we do building
7022      types here will be reused if full symbols are loaded later.  */
7023   if (pdi->has_template_arguments)
7024     {
7025       fixup_partial_die (pdi, cu);
7026
7027       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7028         {
7029           struct die_info *die;
7030           struct attribute attr;
7031           struct dwarf2_cu *ref_cu = cu;
7032
7033           /* DW_FORM_ref_addr is using section offset.  */
7034           attr.name = (enum dwarf_attribute) 0;
7035           attr.form = DW_FORM_ref_addr;
7036           attr.u.unsnd = to_underlying (pdi->sect_off);
7037           die = follow_die_ref (NULL, &attr, &ref_cu);
7038
7039           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7040         }
7041     }
7042
7043   parent_scope = partial_die_parent_scope (pdi, cu);
7044   if (parent_scope == NULL)
7045     return NULL;
7046   else
7047     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7048 }
7049
7050 static void
7051 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7052 {
7053   struct objfile *objfile = cu->objfile;
7054   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7055   CORE_ADDR addr = 0;
7056   const char *actual_name = NULL;
7057   CORE_ADDR baseaddr;
7058   char *built_actual_name;
7059
7060   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7061
7062   built_actual_name = partial_die_full_name (pdi, cu);
7063   if (built_actual_name != NULL)
7064     actual_name = built_actual_name;
7065
7066   if (actual_name == NULL)
7067     actual_name = pdi->name;
7068
7069   switch (pdi->tag)
7070     {
7071     case DW_TAG_subprogram:
7072       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7073       if (pdi->is_external || cu->language == language_ada)
7074         {
7075           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7076              of the global scope.  But in Ada, we want to be able to access
7077              nested procedures globally.  So all Ada subprograms are stored
7078              in the global scope.  */
7079           add_psymbol_to_list (actual_name, strlen (actual_name),
7080                                built_actual_name != NULL,
7081                                VAR_DOMAIN, LOC_BLOCK,
7082                                &objfile->global_psymbols,
7083                                addr, cu->language, objfile);
7084         }
7085       else
7086         {
7087           add_psymbol_to_list (actual_name, strlen (actual_name),
7088                                built_actual_name != NULL,
7089                                VAR_DOMAIN, LOC_BLOCK,
7090                                &objfile->static_psymbols,
7091                                addr, cu->language, objfile);
7092         }
7093
7094       if (pdi->main_subprogram && actual_name != NULL)
7095         set_objfile_main_name (objfile, actual_name, cu->language);
7096       break;
7097     case DW_TAG_constant:
7098       {
7099         struct psymbol_allocation_list *list;
7100
7101         if (pdi->is_external)
7102           list = &objfile->global_psymbols;
7103         else
7104           list = &objfile->static_psymbols;
7105         add_psymbol_to_list (actual_name, strlen (actual_name),
7106                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7107                              list, 0, cu->language, objfile);
7108       }
7109       break;
7110     case DW_TAG_variable:
7111       if (pdi->d.locdesc)
7112         addr = decode_locdesc (pdi->d.locdesc, cu);
7113
7114       if (pdi->d.locdesc
7115           && addr == 0
7116           && !dwarf2_per_objfile->has_section_at_zero)
7117         {
7118           /* A global or static variable may also have been stripped
7119              out by the linker if unused, in which case its address
7120              will be nullified; do not add such variables into partial
7121              symbol table then.  */
7122         }
7123       else if (pdi->is_external)
7124         {
7125           /* Global Variable.
7126              Don't enter into the minimal symbol tables as there is
7127              a minimal symbol table entry from the ELF symbols already.
7128              Enter into partial symbol table if it has a location
7129              descriptor or a type.
7130              If the location descriptor is missing, new_symbol will create
7131              a LOC_UNRESOLVED symbol, the address of the variable will then
7132              be determined from the minimal symbol table whenever the variable
7133              is referenced.
7134              The address for the partial symbol table entry is not
7135              used by GDB, but it comes in handy for debugging partial symbol
7136              table building.  */
7137
7138           if (pdi->d.locdesc || pdi->has_type)
7139             add_psymbol_to_list (actual_name, strlen (actual_name),
7140                                  built_actual_name != NULL,
7141                                  VAR_DOMAIN, LOC_STATIC,
7142                                  &objfile->global_psymbols,
7143                                  addr + baseaddr,
7144                                  cu->language, objfile);
7145         }
7146       else
7147         {
7148           int has_loc = pdi->d.locdesc != NULL;
7149
7150           /* Static Variable.  Skip symbols whose value we cannot know (those
7151              without location descriptors or constant values).  */
7152           if (!has_loc && !pdi->has_const_value)
7153             {
7154               xfree (built_actual_name);
7155               return;
7156             }
7157
7158           add_psymbol_to_list (actual_name, strlen (actual_name),
7159                                built_actual_name != NULL,
7160                                VAR_DOMAIN, LOC_STATIC,
7161                                &objfile->static_psymbols,
7162                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7163                                cu->language, objfile);
7164         }
7165       break;
7166     case DW_TAG_typedef:
7167     case DW_TAG_base_type:
7168     case DW_TAG_subrange_type:
7169       add_psymbol_to_list (actual_name, strlen (actual_name),
7170                            built_actual_name != NULL,
7171                            VAR_DOMAIN, LOC_TYPEDEF,
7172                            &objfile->static_psymbols,
7173                            0, cu->language, objfile);
7174       break;
7175     case DW_TAG_imported_declaration:
7176     case DW_TAG_namespace:
7177       add_psymbol_to_list (actual_name, strlen (actual_name),
7178                            built_actual_name != NULL,
7179                            VAR_DOMAIN, LOC_TYPEDEF,
7180                            &objfile->global_psymbols,
7181                            0, cu->language, objfile);
7182       break;
7183     case DW_TAG_module:
7184       add_psymbol_to_list (actual_name, strlen (actual_name),
7185                            built_actual_name != NULL,
7186                            MODULE_DOMAIN, LOC_TYPEDEF,
7187                            &objfile->global_psymbols,
7188                            0, cu->language, objfile);
7189       break;
7190     case DW_TAG_class_type:
7191     case DW_TAG_interface_type:
7192     case DW_TAG_structure_type:
7193     case DW_TAG_union_type:
7194     case DW_TAG_enumeration_type:
7195       /* Skip external references.  The DWARF standard says in the section
7196          about "Structure, Union, and Class Type Entries": "An incomplete
7197          structure, union or class type is represented by a structure,
7198          union or class entry that does not have a byte size attribute
7199          and that has a DW_AT_declaration attribute."  */
7200       if (!pdi->has_byte_size && pdi->is_declaration)
7201         {
7202           xfree (built_actual_name);
7203           return;
7204         }
7205
7206       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7207          static vs. global.  */
7208       add_psymbol_to_list (actual_name, strlen (actual_name),
7209                            built_actual_name != NULL,
7210                            STRUCT_DOMAIN, LOC_TYPEDEF,
7211                            cu->language == language_cplus
7212                            ? &objfile->global_psymbols
7213                            : &objfile->static_psymbols,
7214                            0, cu->language, objfile);
7215
7216       break;
7217     case DW_TAG_enumerator:
7218       add_psymbol_to_list (actual_name, strlen (actual_name),
7219                            built_actual_name != NULL,
7220                            VAR_DOMAIN, LOC_CONST,
7221                            cu->language == language_cplus
7222                            ? &objfile->global_psymbols
7223                            : &objfile->static_psymbols,
7224                            0, cu->language, objfile);
7225       break;
7226     default:
7227       break;
7228     }
7229
7230   xfree (built_actual_name);
7231 }
7232
7233 /* Read a partial die corresponding to a namespace; also, add a symbol
7234    corresponding to that namespace to the symbol table.  NAMESPACE is
7235    the name of the enclosing namespace.  */
7236
7237 static void
7238 add_partial_namespace (struct partial_die_info *pdi,
7239                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7240                        int set_addrmap, struct dwarf2_cu *cu)
7241 {
7242   /* Add a symbol for the namespace.  */
7243
7244   add_partial_symbol (pdi, cu);
7245
7246   /* Now scan partial symbols in that namespace.  */
7247
7248   if (pdi->has_children)
7249     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7250 }
7251
7252 /* Read a partial die corresponding to a Fortran module.  */
7253
7254 static void
7255 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7256                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7257 {
7258   /* Add a symbol for the namespace.  */
7259
7260   add_partial_symbol (pdi, cu);
7261
7262   /* Now scan partial symbols in that module.  */
7263
7264   if (pdi->has_children)
7265     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7266 }
7267
7268 /* Read a partial die corresponding to a subprogram and create a partial
7269    symbol for that subprogram.  When the CU language allows it, this
7270    routine also defines a partial symbol for each nested subprogram
7271    that this subprogram contains.  If SET_ADDRMAP is true, record the
7272    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7273    and highest PC values found in PDI.
7274
7275    PDI may also be a lexical block, in which case we simply search
7276    recursively for subprograms defined inside that lexical block.
7277    Again, this is only performed when the CU language allows this
7278    type of definitions.  */
7279
7280 static void
7281 add_partial_subprogram (struct partial_die_info *pdi,
7282                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7283                         int set_addrmap, struct dwarf2_cu *cu)
7284 {
7285   if (pdi->tag == DW_TAG_subprogram)
7286     {
7287       if (pdi->has_pc_info)
7288         {
7289           if (pdi->lowpc < *lowpc)
7290             *lowpc = pdi->lowpc;
7291           if (pdi->highpc > *highpc)
7292             *highpc = pdi->highpc;
7293           if (set_addrmap)
7294             {
7295               struct objfile *objfile = cu->objfile;
7296               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7297               CORE_ADDR baseaddr;
7298               CORE_ADDR highpc;
7299               CORE_ADDR lowpc;
7300
7301               baseaddr = ANOFFSET (objfile->section_offsets,
7302                                    SECT_OFF_TEXT (objfile));
7303               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7304                                                   pdi->lowpc + baseaddr);
7305               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7306                                                    pdi->highpc + baseaddr);
7307               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7308                                  cu->per_cu->v.psymtab);
7309             }
7310         }
7311
7312       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7313         {
7314           if (!pdi->is_declaration)
7315             /* Ignore subprogram DIEs that do not have a name, they are
7316                illegal.  Do not emit a complaint at this point, we will
7317                do so when we convert this psymtab into a symtab.  */
7318             if (pdi->name)
7319               add_partial_symbol (pdi, cu);
7320         }
7321     }
7322
7323   if (! pdi->has_children)
7324     return;
7325
7326   if (cu->language == language_ada)
7327     {
7328       pdi = pdi->die_child;
7329       while (pdi != NULL)
7330         {
7331           fixup_partial_die (pdi, cu);
7332           if (pdi->tag == DW_TAG_subprogram
7333               || pdi->tag == DW_TAG_lexical_block)
7334             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7335           pdi = pdi->die_sibling;
7336         }
7337     }
7338 }
7339
7340 /* Read a partial die corresponding to an enumeration type.  */
7341
7342 static void
7343 add_partial_enumeration (struct partial_die_info *enum_pdi,
7344                          struct dwarf2_cu *cu)
7345 {
7346   struct partial_die_info *pdi;
7347
7348   if (enum_pdi->name != NULL)
7349     add_partial_symbol (enum_pdi, cu);
7350
7351   pdi = enum_pdi->die_child;
7352   while (pdi)
7353     {
7354       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7355         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7356       else
7357         add_partial_symbol (pdi, cu);
7358       pdi = pdi->die_sibling;
7359     }
7360 }
7361
7362 /* Return the initial uleb128 in the die at INFO_PTR.  */
7363
7364 static unsigned int
7365 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7366 {
7367   unsigned int bytes_read;
7368
7369   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7370 }
7371
7372 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7373    Return the corresponding abbrev, or NULL if the number is zero (indicating
7374    an empty DIE).  In either case *BYTES_READ will be set to the length of
7375    the initial number.  */
7376
7377 static struct abbrev_info *
7378 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7379                  struct dwarf2_cu *cu)
7380 {
7381   bfd *abfd = cu->objfile->obfd;
7382   unsigned int abbrev_number;
7383   struct abbrev_info *abbrev;
7384
7385   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7386
7387   if (abbrev_number == 0)
7388     return NULL;
7389
7390   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7391   if (!abbrev)
7392     {
7393       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7394                " at offset 0x%x [in module %s]"),
7395              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7396              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7397     }
7398
7399   return abbrev;
7400 }
7401
7402 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7403    Returns a pointer to the end of a series of DIEs, terminated by an empty
7404    DIE.  Any children of the skipped DIEs will also be skipped.  */
7405
7406 static const gdb_byte *
7407 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7408 {
7409   struct dwarf2_cu *cu = reader->cu;
7410   struct abbrev_info *abbrev;
7411   unsigned int bytes_read;
7412
7413   while (1)
7414     {
7415       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7416       if (abbrev == NULL)
7417         return info_ptr + bytes_read;
7418       else
7419         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7420     }
7421 }
7422
7423 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7424    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7425    abbrev corresponding to that skipped uleb128 should be passed in
7426    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7427    children.  */
7428
7429 static const gdb_byte *
7430 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7431               struct abbrev_info *abbrev)
7432 {
7433   unsigned int bytes_read;
7434   struct attribute attr;
7435   bfd *abfd = reader->abfd;
7436   struct dwarf2_cu *cu = reader->cu;
7437   const gdb_byte *buffer = reader->buffer;
7438   const gdb_byte *buffer_end = reader->buffer_end;
7439   unsigned int form, i;
7440
7441   for (i = 0; i < abbrev->num_attrs; i++)
7442     {
7443       /* The only abbrev we care about is DW_AT_sibling.  */
7444       if (abbrev->attrs[i].name == DW_AT_sibling)
7445         {
7446           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7447           if (attr.form == DW_FORM_ref_addr)
7448             complaint (&symfile_complaints,
7449                        _("ignoring absolute DW_AT_sibling"));
7450           else
7451             {
7452               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7453               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7454
7455               if (sibling_ptr < info_ptr)
7456                 complaint (&symfile_complaints,
7457                            _("DW_AT_sibling points backwards"));
7458               else if (sibling_ptr > reader->buffer_end)
7459                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7460               else
7461                 return sibling_ptr;
7462             }
7463         }
7464
7465       /* If it isn't DW_AT_sibling, skip this attribute.  */
7466       form = abbrev->attrs[i].form;
7467     skip_attribute:
7468       switch (form)
7469         {
7470         case DW_FORM_ref_addr:
7471           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7472              and later it is offset sized.  */
7473           if (cu->header.version == 2)
7474             info_ptr += cu->header.addr_size;
7475           else
7476             info_ptr += cu->header.offset_size;
7477           break;
7478         case DW_FORM_GNU_ref_alt:
7479           info_ptr += cu->header.offset_size;
7480           break;
7481         case DW_FORM_addr:
7482           info_ptr += cu->header.addr_size;
7483           break;
7484         case DW_FORM_data1:
7485         case DW_FORM_ref1:
7486         case DW_FORM_flag:
7487           info_ptr += 1;
7488           break;
7489         case DW_FORM_flag_present:
7490         case DW_FORM_implicit_const:
7491           break;
7492         case DW_FORM_data2:
7493         case DW_FORM_ref2:
7494           info_ptr += 2;
7495           break;
7496         case DW_FORM_data4:
7497         case DW_FORM_ref4:
7498           info_ptr += 4;
7499           break;
7500         case DW_FORM_data8:
7501         case DW_FORM_ref8:
7502         case DW_FORM_ref_sig8:
7503           info_ptr += 8;
7504           break;
7505         case DW_FORM_data16:
7506           info_ptr += 16;
7507           break;
7508         case DW_FORM_string:
7509           read_direct_string (abfd, info_ptr, &bytes_read);
7510           info_ptr += bytes_read;
7511           break;
7512         case DW_FORM_sec_offset:
7513         case DW_FORM_strp:
7514         case DW_FORM_GNU_strp_alt:
7515           info_ptr += cu->header.offset_size;
7516           break;
7517         case DW_FORM_exprloc:
7518         case DW_FORM_block:
7519           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7520           info_ptr += bytes_read;
7521           break;
7522         case DW_FORM_block1:
7523           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7524           break;
7525         case DW_FORM_block2:
7526           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7527           break;
7528         case DW_FORM_block4:
7529           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7530           break;
7531         case DW_FORM_sdata:
7532         case DW_FORM_udata:
7533         case DW_FORM_ref_udata:
7534         case DW_FORM_GNU_addr_index:
7535         case DW_FORM_GNU_str_index:
7536           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7537           break;
7538         case DW_FORM_indirect:
7539           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7540           info_ptr += bytes_read;
7541           /* We need to continue parsing from here, so just go back to
7542              the top.  */
7543           goto skip_attribute;
7544
7545         default:
7546           error (_("Dwarf Error: Cannot handle %s "
7547                    "in DWARF reader [in module %s]"),
7548                  dwarf_form_name (form),
7549                  bfd_get_filename (abfd));
7550         }
7551     }
7552
7553   if (abbrev->has_children)
7554     return skip_children (reader, info_ptr);
7555   else
7556     return info_ptr;
7557 }
7558
7559 /* Locate ORIG_PDI's sibling.
7560    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7561
7562 static const gdb_byte *
7563 locate_pdi_sibling (const struct die_reader_specs *reader,
7564                     struct partial_die_info *orig_pdi,
7565                     const gdb_byte *info_ptr)
7566 {
7567   /* Do we know the sibling already?  */
7568
7569   if (orig_pdi->sibling)
7570     return orig_pdi->sibling;
7571
7572   /* Are there any children to deal with?  */
7573
7574   if (!orig_pdi->has_children)
7575     return info_ptr;
7576
7577   /* Skip the children the long way.  */
7578
7579   return skip_children (reader, info_ptr);
7580 }
7581
7582 /* Expand this partial symbol table into a full symbol table.  SELF is
7583    not NULL.  */
7584
7585 static void
7586 dwarf2_read_symtab (struct partial_symtab *self,
7587                     struct objfile *objfile)
7588 {
7589   if (self->readin)
7590     {
7591       warning (_("bug: psymtab for %s is already read in."),
7592                self->filename);
7593     }
7594   else
7595     {
7596       if (info_verbose)
7597         {
7598           printf_filtered (_("Reading in symbols for %s..."),
7599                            self->filename);
7600           gdb_flush (gdb_stdout);
7601         }
7602
7603       /* Restore our global data.  */
7604       dwarf2_per_objfile
7605         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7606                                                       dwarf2_objfile_data_key);
7607
7608       /* If this psymtab is constructed from a debug-only objfile, the
7609          has_section_at_zero flag will not necessarily be correct.  We
7610          can get the correct value for this flag by looking at the data
7611          associated with the (presumably stripped) associated objfile.  */
7612       if (objfile->separate_debug_objfile_backlink)
7613         {
7614           struct dwarf2_per_objfile *dpo_backlink
7615             = ((struct dwarf2_per_objfile *)
7616                objfile_data (objfile->separate_debug_objfile_backlink,
7617                              dwarf2_objfile_data_key));
7618
7619           dwarf2_per_objfile->has_section_at_zero
7620             = dpo_backlink->has_section_at_zero;
7621         }
7622
7623       dwarf2_per_objfile->reading_partial_symbols = 0;
7624
7625       psymtab_to_symtab_1 (self);
7626
7627       /* Finish up the debug error message.  */
7628       if (info_verbose)
7629         printf_filtered (_("done.\n"));
7630     }
7631
7632   process_cu_includes ();
7633 }
7634 \f
7635 /* Reading in full CUs.  */
7636
7637 /* Add PER_CU to the queue.  */
7638
7639 static void
7640 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7641                  enum language pretend_language)
7642 {
7643   struct dwarf2_queue_item *item;
7644
7645   per_cu->queued = 1;
7646   item = XNEW (struct dwarf2_queue_item);
7647   item->per_cu = per_cu;
7648   item->pretend_language = pretend_language;
7649   item->next = NULL;
7650
7651   if (dwarf2_queue == NULL)
7652     dwarf2_queue = item;
7653   else
7654     dwarf2_queue_tail->next = item;
7655
7656   dwarf2_queue_tail = item;
7657 }
7658
7659 /* If PER_CU is not yet queued, add it to the queue.
7660    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7661    dependency.
7662    The result is non-zero if PER_CU was queued, otherwise the result is zero
7663    meaning either PER_CU is already queued or it is already loaded.
7664
7665    N.B. There is an invariant here that if a CU is queued then it is loaded.
7666    The caller is required to load PER_CU if we return non-zero.  */
7667
7668 static int
7669 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7670                        struct dwarf2_per_cu_data *per_cu,
7671                        enum language pretend_language)
7672 {
7673   /* We may arrive here during partial symbol reading, if we need full
7674      DIEs to process an unusual case (e.g. template arguments).  Do
7675      not queue PER_CU, just tell our caller to load its DIEs.  */
7676   if (dwarf2_per_objfile->reading_partial_symbols)
7677     {
7678       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7679         return 1;
7680       return 0;
7681     }
7682
7683   /* Mark the dependence relation so that we don't flush PER_CU
7684      too early.  */
7685   if (dependent_cu != NULL)
7686     dwarf2_add_dependence (dependent_cu, per_cu);
7687
7688   /* If it's already on the queue, we have nothing to do.  */
7689   if (per_cu->queued)
7690     return 0;
7691
7692   /* If the compilation unit is already loaded, just mark it as
7693      used.  */
7694   if (per_cu->cu != NULL)
7695     {
7696       per_cu->cu->last_used = 0;
7697       return 0;
7698     }
7699
7700   /* Add it to the queue.  */
7701   queue_comp_unit (per_cu, pretend_language);
7702
7703   return 1;
7704 }
7705
7706 /* Process the queue.  */
7707
7708 static void
7709 process_queue (void)
7710 {
7711   struct dwarf2_queue_item *item, *next_item;
7712
7713   if (dwarf_read_debug)
7714     {
7715       fprintf_unfiltered (gdb_stdlog,
7716                           "Expanding one or more symtabs of objfile %s ...\n",
7717                           objfile_name (dwarf2_per_objfile->objfile));
7718     }
7719
7720   /* The queue starts out with one item, but following a DIE reference
7721      may load a new CU, adding it to the end of the queue.  */
7722   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7723     {
7724       if ((dwarf2_per_objfile->using_index
7725            ? !item->per_cu->v.quick->compunit_symtab
7726            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7727           /* Skip dummy CUs.  */
7728           && item->per_cu->cu != NULL)
7729         {
7730           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7731           unsigned int debug_print_threshold;
7732           char buf[100];
7733
7734           if (per_cu->is_debug_types)
7735             {
7736               struct signatured_type *sig_type =
7737                 (struct signatured_type *) per_cu;
7738
7739               sprintf (buf, "TU %s at offset 0x%x",
7740                        hex_string (sig_type->signature),
7741                        to_underlying (per_cu->sect_off));
7742               /* There can be 100s of TUs.
7743                  Only print them in verbose mode.  */
7744               debug_print_threshold = 2;
7745             }
7746           else
7747             {
7748               sprintf (buf, "CU at offset 0x%x",
7749                        to_underlying (per_cu->sect_off));
7750               debug_print_threshold = 1;
7751             }
7752
7753           if (dwarf_read_debug >= debug_print_threshold)
7754             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7755
7756           if (per_cu->is_debug_types)
7757             process_full_type_unit (per_cu, item->pretend_language);
7758           else
7759             process_full_comp_unit (per_cu, item->pretend_language);
7760
7761           if (dwarf_read_debug >= debug_print_threshold)
7762             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7763         }
7764
7765       item->per_cu->queued = 0;
7766       next_item = item->next;
7767       xfree (item);
7768     }
7769
7770   dwarf2_queue_tail = NULL;
7771
7772   if (dwarf_read_debug)
7773     {
7774       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7775                           objfile_name (dwarf2_per_objfile->objfile));
7776     }
7777 }
7778
7779 /* Free all allocated queue entries.  This function only releases anything if
7780    an error was thrown; if the queue was processed then it would have been
7781    freed as we went along.  */
7782
7783 static void
7784 dwarf2_release_queue (void *dummy)
7785 {
7786   struct dwarf2_queue_item *item, *last;
7787
7788   item = dwarf2_queue;
7789   while (item)
7790     {
7791       /* Anything still marked queued is likely to be in an
7792          inconsistent state, so discard it.  */
7793       if (item->per_cu->queued)
7794         {
7795           if (item->per_cu->cu != NULL)
7796             free_one_cached_comp_unit (item->per_cu);
7797           item->per_cu->queued = 0;
7798         }
7799
7800       last = item;
7801       item = item->next;
7802       xfree (last);
7803     }
7804
7805   dwarf2_queue = dwarf2_queue_tail = NULL;
7806 }
7807
7808 /* Read in full symbols for PST, and anything it depends on.  */
7809
7810 static void
7811 psymtab_to_symtab_1 (struct partial_symtab *pst)
7812 {
7813   struct dwarf2_per_cu_data *per_cu;
7814   int i;
7815
7816   if (pst->readin)
7817     return;
7818
7819   for (i = 0; i < pst->number_of_dependencies; i++)
7820     if (!pst->dependencies[i]->readin
7821         && pst->dependencies[i]->user == NULL)
7822       {
7823         /* Inform about additional files that need to be read in.  */
7824         if (info_verbose)
7825           {
7826             /* FIXME: i18n: Need to make this a single string.  */
7827             fputs_filtered (" ", gdb_stdout);
7828             wrap_here ("");
7829             fputs_filtered ("and ", gdb_stdout);
7830             wrap_here ("");
7831             printf_filtered ("%s...", pst->dependencies[i]->filename);
7832             wrap_here ("");     /* Flush output.  */
7833             gdb_flush (gdb_stdout);
7834           }
7835         psymtab_to_symtab_1 (pst->dependencies[i]);
7836       }
7837
7838   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7839
7840   if (per_cu == NULL)
7841     {
7842       /* It's an include file, no symbols to read for it.
7843          Everything is in the parent symtab.  */
7844       pst->readin = 1;
7845       return;
7846     }
7847
7848   dw2_do_instantiate_symtab (per_cu);
7849 }
7850
7851 /* Trivial hash function for die_info: the hash value of a DIE
7852    is its offset in .debug_info for this objfile.  */
7853
7854 static hashval_t
7855 die_hash (const void *item)
7856 {
7857   const struct die_info *die = (const struct die_info *) item;
7858
7859   return to_underlying (die->sect_off);
7860 }
7861
7862 /* Trivial comparison function for die_info structures: two DIEs
7863    are equal if they have the same offset.  */
7864
7865 static int
7866 die_eq (const void *item_lhs, const void *item_rhs)
7867 {
7868   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7869   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7870
7871   return die_lhs->sect_off == die_rhs->sect_off;
7872 }
7873
7874 /* die_reader_func for load_full_comp_unit.
7875    This is identical to read_signatured_type_reader,
7876    but is kept separate for now.  */
7877
7878 static void
7879 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7880                             const gdb_byte *info_ptr,
7881                             struct die_info *comp_unit_die,
7882                             int has_children,
7883                             void *data)
7884 {
7885   struct dwarf2_cu *cu = reader->cu;
7886   enum language *language_ptr = (enum language *) data;
7887
7888   gdb_assert (cu->die_hash == NULL);
7889   cu->die_hash =
7890     htab_create_alloc_ex (cu->header.length / 12,
7891                           die_hash,
7892                           die_eq,
7893                           NULL,
7894                           &cu->comp_unit_obstack,
7895                           hashtab_obstack_allocate,
7896                           dummy_obstack_deallocate);
7897
7898   if (has_children)
7899     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7900                                                   &info_ptr, comp_unit_die);
7901   cu->dies = comp_unit_die;
7902   /* comp_unit_die is not stored in die_hash, no need.  */
7903
7904   /* We try not to read any attributes in this function, because not
7905      all CUs needed for references have been loaded yet, and symbol
7906      table processing isn't initialized.  But we have to set the CU language,
7907      or we won't be able to build types correctly.
7908      Similarly, if we do not read the producer, we can not apply
7909      producer-specific interpretation.  */
7910   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7911 }
7912
7913 /* Load the DIEs associated with PER_CU into memory.  */
7914
7915 static void
7916 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7917                      enum language pretend_language)
7918 {
7919   gdb_assert (! this_cu->is_debug_types);
7920
7921   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7922                            load_full_comp_unit_reader, &pretend_language);
7923 }
7924
7925 /* Add a DIE to the delayed physname list.  */
7926
7927 static void
7928 add_to_method_list (struct type *type, int fnfield_index, int index,
7929                     const char *name, struct die_info *die,
7930                     struct dwarf2_cu *cu)
7931 {
7932   struct delayed_method_info mi;
7933   mi.type = type;
7934   mi.fnfield_index = fnfield_index;
7935   mi.index = index;
7936   mi.name = name;
7937   mi.die = die;
7938   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7939 }
7940
7941 /* A cleanup for freeing the delayed method list.  */
7942
7943 static void
7944 free_delayed_list (void *ptr)
7945 {
7946   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7947   if (cu->method_list != NULL)
7948     {
7949       VEC_free (delayed_method_info, cu->method_list);
7950       cu->method_list = NULL;
7951     }
7952 }
7953
7954 /* Compute the physnames of any methods on the CU's method list.
7955
7956    The computation of method physnames is delayed in order to avoid the
7957    (bad) condition that one of the method's formal parameters is of an as yet
7958    incomplete type.  */
7959
7960 static void
7961 compute_delayed_physnames (struct dwarf2_cu *cu)
7962 {
7963   int i;
7964   struct delayed_method_info *mi;
7965   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7966     {
7967       const char *physname;
7968       struct fn_fieldlist *fn_flp
7969         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7970       physname = dwarf2_physname (mi->name, mi->die, cu);
7971       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
7972         = physname ? physname : "";
7973     }
7974 }
7975
7976 /* Go objects should be embedded in a DW_TAG_module DIE,
7977    and it's not clear if/how imported objects will appear.
7978    To keep Go support simple until that's worked out,
7979    go back through what we've read and create something usable.
7980    We could do this while processing each DIE, and feels kinda cleaner,
7981    but that way is more invasive.
7982    This is to, for example, allow the user to type "p var" or "b main"
7983    without having to specify the package name, and allow lookups
7984    of module.object to work in contexts that use the expression
7985    parser.  */
7986
7987 static void
7988 fixup_go_packaging (struct dwarf2_cu *cu)
7989 {
7990   char *package_name = NULL;
7991   struct pending *list;
7992   int i;
7993
7994   for (list = global_symbols; list != NULL; list = list->next)
7995     {
7996       for (i = 0; i < list->nsyms; ++i)
7997         {
7998           struct symbol *sym = list->symbol[i];
7999
8000           if (SYMBOL_LANGUAGE (sym) == language_go
8001               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8002             {
8003               char *this_package_name = go_symbol_package_name (sym);
8004
8005               if (this_package_name == NULL)
8006                 continue;
8007               if (package_name == NULL)
8008                 package_name = this_package_name;
8009               else
8010                 {
8011                   if (strcmp (package_name, this_package_name) != 0)
8012                     complaint (&symfile_complaints,
8013                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8014                                (symbol_symtab (sym) != NULL
8015                                 ? symtab_to_filename_for_display
8016                                     (symbol_symtab (sym))
8017                                 : objfile_name (cu->objfile)),
8018                                this_package_name, package_name);
8019                   xfree (this_package_name);
8020                 }
8021             }
8022         }
8023     }
8024
8025   if (package_name != NULL)
8026     {
8027       struct objfile *objfile = cu->objfile;
8028       const char *saved_package_name
8029         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8030                                         package_name,
8031                                         strlen (package_name));
8032       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8033                                      saved_package_name);
8034       struct symbol *sym;
8035
8036       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8037
8038       sym = allocate_symbol (objfile);
8039       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8040       SYMBOL_SET_NAMES (sym, saved_package_name,
8041                         strlen (saved_package_name), 0, objfile);
8042       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8043          e.g., "main" finds the "main" module and not C's main().  */
8044       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8045       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8046       SYMBOL_TYPE (sym) = type;
8047
8048       add_symbol_to_list (sym, &global_symbols);
8049
8050       xfree (package_name);
8051     }
8052 }
8053
8054 /* Return the symtab for PER_CU.  This works properly regardless of
8055    whether we're using the index or psymtabs.  */
8056
8057 static struct compunit_symtab *
8058 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8059 {
8060   return (dwarf2_per_objfile->using_index
8061           ? per_cu->v.quick->compunit_symtab
8062           : per_cu->v.psymtab->compunit_symtab);
8063 }
8064
8065 /* A helper function for computing the list of all symbol tables
8066    included by PER_CU.  */
8067
8068 static void
8069 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8070                                 htab_t all_children, htab_t all_type_symtabs,
8071                                 struct dwarf2_per_cu_data *per_cu,
8072                                 struct compunit_symtab *immediate_parent)
8073 {
8074   void **slot;
8075   int ix;
8076   struct compunit_symtab *cust;
8077   struct dwarf2_per_cu_data *iter;
8078
8079   slot = htab_find_slot (all_children, per_cu, INSERT);
8080   if (*slot != NULL)
8081     {
8082       /* This inclusion and its children have been processed.  */
8083       return;
8084     }
8085
8086   *slot = per_cu;
8087   /* Only add a CU if it has a symbol table.  */
8088   cust = get_compunit_symtab (per_cu);
8089   if (cust != NULL)
8090     {
8091       /* If this is a type unit only add its symbol table if we haven't
8092          seen it yet (type unit per_cu's can share symtabs).  */
8093       if (per_cu->is_debug_types)
8094         {
8095           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8096           if (*slot == NULL)
8097             {
8098               *slot = cust;
8099               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8100               if (cust->user == NULL)
8101                 cust->user = immediate_parent;
8102             }
8103         }
8104       else
8105         {
8106           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8107           if (cust->user == NULL)
8108             cust->user = immediate_parent;
8109         }
8110     }
8111
8112   for (ix = 0;
8113        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8114        ++ix)
8115     {
8116       recursively_compute_inclusions (result, all_children,
8117                                       all_type_symtabs, iter, cust);
8118     }
8119 }
8120
8121 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8122    PER_CU.  */
8123
8124 static void
8125 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8126 {
8127   gdb_assert (! per_cu->is_debug_types);
8128
8129   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8130     {
8131       int ix, len;
8132       struct dwarf2_per_cu_data *per_cu_iter;
8133       struct compunit_symtab *compunit_symtab_iter;
8134       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8135       htab_t all_children, all_type_symtabs;
8136       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8137
8138       /* If we don't have a symtab, we can just skip this case.  */
8139       if (cust == NULL)
8140         return;
8141
8142       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8143                                         NULL, xcalloc, xfree);
8144       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8145                                             NULL, xcalloc, xfree);
8146
8147       for (ix = 0;
8148            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8149                         ix, per_cu_iter);
8150            ++ix)
8151         {
8152           recursively_compute_inclusions (&result_symtabs, all_children,
8153                                           all_type_symtabs, per_cu_iter,
8154                                           cust);
8155         }
8156
8157       /* Now we have a transitive closure of all the included symtabs.  */
8158       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8159       cust->includes
8160         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8161                      struct compunit_symtab *, len + 1);
8162       for (ix = 0;
8163            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8164                         compunit_symtab_iter);
8165            ++ix)
8166         cust->includes[ix] = compunit_symtab_iter;
8167       cust->includes[len] = NULL;
8168
8169       VEC_free (compunit_symtab_ptr, result_symtabs);
8170       htab_delete (all_children);
8171       htab_delete (all_type_symtabs);
8172     }
8173 }
8174
8175 /* Compute the 'includes' field for the symtabs of all the CUs we just
8176    read.  */
8177
8178 static void
8179 process_cu_includes (void)
8180 {
8181   int ix;
8182   struct dwarf2_per_cu_data *iter;
8183
8184   for (ix = 0;
8185        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8186                     ix, iter);
8187        ++ix)
8188     {
8189       if (! iter->is_debug_types)
8190         compute_compunit_symtab_includes (iter);
8191     }
8192
8193   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8194 }
8195
8196 /* Generate full symbol information for PER_CU, whose DIEs have
8197    already been loaded into memory.  */
8198
8199 static void
8200 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8201                         enum language pretend_language)
8202 {
8203   struct dwarf2_cu *cu = per_cu->cu;
8204   struct objfile *objfile = per_cu->objfile;
8205   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8206   CORE_ADDR lowpc, highpc;
8207   struct compunit_symtab *cust;
8208   struct cleanup *back_to, *delayed_list_cleanup;
8209   CORE_ADDR baseaddr;
8210   struct block *static_block;
8211   CORE_ADDR addr;
8212
8213   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8214
8215   buildsym_init ();
8216   back_to = make_cleanup (really_free_pendings, NULL);
8217   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8218
8219   cu->list_in_scope = &file_symbols;
8220
8221   cu->language = pretend_language;
8222   cu->language_defn = language_def (cu->language);
8223
8224   /* Do line number decoding in read_file_scope () */
8225   process_die (cu->dies, cu);
8226
8227   /* For now fudge the Go package.  */
8228   if (cu->language == language_go)
8229     fixup_go_packaging (cu);
8230
8231   /* Now that we have processed all the DIEs in the CU, all the types 
8232      should be complete, and it should now be safe to compute all of the
8233      physnames.  */
8234   compute_delayed_physnames (cu);
8235   do_cleanups (delayed_list_cleanup);
8236
8237   /* Some compilers don't define a DW_AT_high_pc attribute for the
8238      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8239      it, by scanning the DIE's below the compilation unit.  */
8240   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8241
8242   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8243   static_block = end_symtab_get_static_block (addr, 0, 1);
8244
8245   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8246      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8247      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8248      addrmap to help ensure it has an accurate map of pc values belonging to
8249      this comp unit.  */
8250   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8251
8252   cust = end_symtab_from_static_block (static_block,
8253                                        SECT_OFF_TEXT (objfile), 0);
8254
8255   if (cust != NULL)
8256     {
8257       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8258
8259       /* Set symtab language to language from DW_AT_language.  If the
8260          compilation is from a C file generated by language preprocessors, do
8261          not set the language if it was already deduced by start_subfile.  */
8262       if (!(cu->language == language_c
8263             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8264         COMPUNIT_FILETABS (cust)->language = cu->language;
8265
8266       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8267          produce DW_AT_location with location lists but it can be possibly
8268          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8269          there were bugs in prologue debug info, fixed later in GCC-4.5
8270          by "unwind info for epilogues" patch (which is not directly related).
8271
8272          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8273          needed, it would be wrong due to missing DW_AT_producer there.
8274
8275          Still one can confuse GDB by using non-standard GCC compilation
8276          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8277          */ 
8278       if (cu->has_loclist && gcc_4_minor >= 5)
8279         cust->locations_valid = 1;
8280
8281       if (gcc_4_minor >= 5)
8282         cust->epilogue_unwind_valid = 1;
8283
8284       cust->call_site_htab = cu->call_site_htab;
8285     }
8286
8287   if (dwarf2_per_objfile->using_index)
8288     per_cu->v.quick->compunit_symtab = cust;
8289   else
8290     {
8291       struct partial_symtab *pst = per_cu->v.psymtab;
8292       pst->compunit_symtab = cust;
8293       pst->readin = 1;
8294     }
8295
8296   /* Push it for inclusion processing later.  */
8297   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8298
8299   do_cleanups (back_to);
8300 }
8301
8302 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8303    already been loaded into memory.  */
8304
8305 static void
8306 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8307                         enum language pretend_language)
8308 {
8309   struct dwarf2_cu *cu = per_cu->cu;
8310   struct objfile *objfile = per_cu->objfile;
8311   struct compunit_symtab *cust;
8312   struct cleanup *back_to, *delayed_list_cleanup;
8313   struct signatured_type *sig_type;
8314
8315   gdb_assert (per_cu->is_debug_types);
8316   sig_type = (struct signatured_type *) per_cu;
8317
8318   buildsym_init ();
8319   back_to = make_cleanup (really_free_pendings, NULL);
8320   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8321
8322   cu->list_in_scope = &file_symbols;
8323
8324   cu->language = pretend_language;
8325   cu->language_defn = language_def (cu->language);
8326
8327   /* The symbol tables are set up in read_type_unit_scope.  */
8328   process_die (cu->dies, cu);
8329
8330   /* For now fudge the Go package.  */
8331   if (cu->language == language_go)
8332     fixup_go_packaging (cu);
8333
8334   /* Now that we have processed all the DIEs in the CU, all the types 
8335      should be complete, and it should now be safe to compute all of the
8336      physnames.  */
8337   compute_delayed_physnames (cu);
8338   do_cleanups (delayed_list_cleanup);
8339
8340   /* TUs share symbol tables.
8341      If this is the first TU to use this symtab, complete the construction
8342      of it with end_expandable_symtab.  Otherwise, complete the addition of
8343      this TU's symbols to the existing symtab.  */
8344   if (sig_type->type_unit_group->compunit_symtab == NULL)
8345     {
8346       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8347       sig_type->type_unit_group->compunit_symtab = cust;
8348
8349       if (cust != NULL)
8350         {
8351           /* Set symtab language to language from DW_AT_language.  If the
8352              compilation is from a C file generated by language preprocessors,
8353              do not set the language if it was already deduced by
8354              start_subfile.  */
8355           if (!(cu->language == language_c
8356                 && COMPUNIT_FILETABS (cust)->language != language_c))
8357             COMPUNIT_FILETABS (cust)->language = cu->language;
8358         }
8359     }
8360   else
8361     {
8362       augment_type_symtab ();
8363       cust = sig_type->type_unit_group->compunit_symtab;
8364     }
8365
8366   if (dwarf2_per_objfile->using_index)
8367     per_cu->v.quick->compunit_symtab = cust;
8368   else
8369     {
8370       struct partial_symtab *pst = per_cu->v.psymtab;
8371       pst->compunit_symtab = cust;
8372       pst->readin = 1;
8373     }
8374
8375   do_cleanups (back_to);
8376 }
8377
8378 /* Process an imported unit DIE.  */
8379
8380 static void
8381 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8382 {
8383   struct attribute *attr;
8384
8385   /* For now we don't handle imported units in type units.  */
8386   if (cu->per_cu->is_debug_types)
8387     {
8388       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8389                " supported in type units [in module %s]"),
8390              objfile_name (cu->objfile));
8391     }
8392
8393   attr = dwarf2_attr (die, DW_AT_import, cu);
8394   if (attr != NULL)
8395     {
8396       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8397       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8398       dwarf2_per_cu_data *per_cu
8399         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8400
8401       /* If necessary, add it to the queue and load its DIEs.  */
8402       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8403         load_full_comp_unit (per_cu, cu->language);
8404
8405       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8406                      per_cu);
8407     }
8408 }
8409
8410 /* Reset the in_process bit of a die.  */
8411
8412 static void
8413 reset_die_in_process (void *arg)
8414 {
8415   struct die_info *die = (struct die_info *) arg;
8416
8417   die->in_process = 0;
8418 }
8419
8420 /* Process a die and its children.  */
8421
8422 static void
8423 process_die (struct die_info *die, struct dwarf2_cu *cu)
8424 {
8425   struct cleanup *in_process;
8426
8427   /* We should only be processing those not already in process.  */
8428   gdb_assert (!die->in_process);
8429
8430   die->in_process = 1;
8431   in_process = make_cleanup (reset_die_in_process,die);
8432
8433   switch (die->tag)
8434     {
8435     case DW_TAG_padding:
8436       break;
8437     case DW_TAG_compile_unit:
8438     case DW_TAG_partial_unit:
8439       read_file_scope (die, cu);
8440       break;
8441     case DW_TAG_type_unit:
8442       read_type_unit_scope (die, cu);
8443       break;
8444     case DW_TAG_subprogram:
8445     case DW_TAG_inlined_subroutine:
8446       read_func_scope (die, cu);
8447       break;
8448     case DW_TAG_lexical_block:
8449     case DW_TAG_try_block:
8450     case DW_TAG_catch_block:
8451       read_lexical_block_scope (die, cu);
8452       break;
8453     case DW_TAG_call_site:
8454     case DW_TAG_GNU_call_site:
8455       read_call_site_scope (die, cu);
8456       break;
8457     case DW_TAG_class_type:
8458     case DW_TAG_interface_type:
8459     case DW_TAG_structure_type:
8460     case DW_TAG_union_type:
8461       process_structure_scope (die, cu);
8462       break;
8463     case DW_TAG_enumeration_type:
8464       process_enumeration_scope (die, cu);
8465       break;
8466
8467     /* These dies have a type, but processing them does not create
8468        a symbol or recurse to process the children.  Therefore we can
8469        read them on-demand through read_type_die.  */
8470     case DW_TAG_subroutine_type:
8471     case DW_TAG_set_type:
8472     case DW_TAG_array_type:
8473     case DW_TAG_pointer_type:
8474     case DW_TAG_ptr_to_member_type:
8475     case DW_TAG_reference_type:
8476     case DW_TAG_rvalue_reference_type:
8477     case DW_TAG_string_type:
8478       break;
8479
8480     case DW_TAG_base_type:
8481     case DW_TAG_subrange_type:
8482     case DW_TAG_typedef:
8483       /* Add a typedef symbol for the type definition, if it has a
8484          DW_AT_name.  */
8485       new_symbol (die, read_type_die (die, cu), cu);
8486       break;
8487     case DW_TAG_common_block:
8488       read_common_block (die, cu);
8489       break;
8490     case DW_TAG_common_inclusion:
8491       break;
8492     case DW_TAG_namespace:
8493       cu->processing_has_namespace_info = 1;
8494       read_namespace (die, cu);
8495       break;
8496     case DW_TAG_module:
8497       cu->processing_has_namespace_info = 1;
8498       read_module (die, cu);
8499       break;
8500     case DW_TAG_imported_declaration:
8501       cu->processing_has_namespace_info = 1;
8502       if (read_namespace_alias (die, cu))
8503         break;
8504       /* The declaration is not a global namespace alias: fall through.  */
8505     case DW_TAG_imported_module:
8506       cu->processing_has_namespace_info = 1;
8507       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8508                                  || cu->language != language_fortran))
8509         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8510                    dwarf_tag_name (die->tag));
8511       read_import_statement (die, cu);
8512       break;
8513
8514     case DW_TAG_imported_unit:
8515       process_imported_unit_die (die, cu);
8516       break;
8517
8518     default:
8519       new_symbol (die, NULL, cu);
8520       break;
8521     }
8522
8523   do_cleanups (in_process);
8524 }
8525 \f
8526 /* DWARF name computation.  */
8527
8528 /* A helper function for dwarf2_compute_name which determines whether DIE
8529    needs to have the name of the scope prepended to the name listed in the
8530    die.  */
8531
8532 static int
8533 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8534 {
8535   struct attribute *attr;
8536
8537   switch (die->tag)
8538     {
8539     case DW_TAG_namespace:
8540     case DW_TAG_typedef:
8541     case DW_TAG_class_type:
8542     case DW_TAG_interface_type:
8543     case DW_TAG_structure_type:
8544     case DW_TAG_union_type:
8545     case DW_TAG_enumeration_type:
8546     case DW_TAG_enumerator:
8547     case DW_TAG_subprogram:
8548     case DW_TAG_inlined_subroutine:
8549     case DW_TAG_member:
8550     case DW_TAG_imported_declaration:
8551       return 1;
8552
8553     case DW_TAG_variable:
8554     case DW_TAG_constant:
8555       /* We only need to prefix "globally" visible variables.  These include
8556          any variable marked with DW_AT_external or any variable that
8557          lives in a namespace.  [Variables in anonymous namespaces
8558          require prefixing, but they are not DW_AT_external.]  */
8559
8560       if (dwarf2_attr (die, DW_AT_specification, cu))
8561         {
8562           struct dwarf2_cu *spec_cu = cu;
8563
8564           return die_needs_namespace (die_specification (die, &spec_cu),
8565                                       spec_cu);
8566         }
8567
8568       attr = dwarf2_attr (die, DW_AT_external, cu);
8569       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8570           && die->parent->tag != DW_TAG_module)
8571         return 0;
8572       /* A variable in a lexical block of some kind does not need a
8573          namespace, even though in C++ such variables may be external
8574          and have a mangled name.  */
8575       if (die->parent->tag ==  DW_TAG_lexical_block
8576           || die->parent->tag ==  DW_TAG_try_block
8577           || die->parent->tag ==  DW_TAG_catch_block
8578           || die->parent->tag == DW_TAG_subprogram)
8579         return 0;
8580       return 1;
8581
8582     default:
8583       return 0;
8584     }
8585 }
8586
8587 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8588    compute the physname for the object, which include a method's:
8589    - formal parameters (C++),
8590    - receiver type (Go),
8591
8592    The term "physname" is a bit confusing.
8593    For C++, for example, it is the demangled name.
8594    For Go, for example, it's the mangled name.
8595
8596    For Ada, return the DIE's linkage name rather than the fully qualified
8597    name.  PHYSNAME is ignored..
8598
8599    The result is allocated on the objfile_obstack and canonicalized.  */
8600
8601 static const char *
8602 dwarf2_compute_name (const char *name,
8603                      struct die_info *die, struct dwarf2_cu *cu,
8604                      int physname)
8605 {
8606   struct objfile *objfile = cu->objfile;
8607
8608   if (name == NULL)
8609     name = dwarf2_name (die, cu);
8610
8611   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8612      but otherwise compute it by typename_concat inside GDB.
8613      FIXME: Actually this is not really true, or at least not always true.
8614      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8615      Fortran names because there is no mangling standard.  So new_symbol_full
8616      will set the demangled name to the result of dwarf2_full_name, and it is
8617      the demangled name that GDB uses if it exists.  */
8618   if (cu->language == language_ada
8619       || (cu->language == language_fortran && physname))
8620     {
8621       /* For Ada unit, we prefer the linkage name over the name, as
8622          the former contains the exported name, which the user expects
8623          to be able to reference.  Ideally, we want the user to be able
8624          to reference this entity using either natural or linkage name,
8625          but we haven't started looking at this enhancement yet.  */
8626       const char *linkage_name;
8627
8628       linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8629       if (linkage_name == NULL)
8630         linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8631       if (linkage_name != NULL)
8632         return linkage_name;
8633     }
8634
8635   /* These are the only languages we know how to qualify names in.  */
8636   if (name != NULL
8637       && (cu->language == language_cplus
8638           || cu->language == language_fortran || cu->language == language_d
8639           || cu->language == language_rust))
8640     {
8641       if (die_needs_namespace (die, cu))
8642         {
8643           long length;
8644           const char *prefix;
8645           const char *canonical_name = NULL;
8646
8647           string_file buf;
8648
8649           prefix = determine_prefix (die, cu);
8650           if (*prefix != '\0')
8651             {
8652               char *prefixed_name = typename_concat (NULL, prefix, name,
8653                                                      physname, cu);
8654
8655               buf.puts (prefixed_name);
8656               xfree (prefixed_name);
8657             }
8658           else
8659             buf.puts (name);
8660
8661           /* Template parameters may be specified in the DIE's DW_AT_name, or
8662              as children with DW_TAG_template_type_param or
8663              DW_TAG_value_type_param.  If the latter, add them to the name
8664              here.  If the name already has template parameters, then
8665              skip this step; some versions of GCC emit both, and
8666              it is more efficient to use the pre-computed name.
8667
8668              Something to keep in mind about this process: it is very
8669              unlikely, or in some cases downright impossible, to produce
8670              something that will match the mangled name of a function.
8671              If the definition of the function has the same debug info,
8672              we should be able to match up with it anyway.  But fallbacks
8673              using the minimal symbol, for instance to find a method
8674              implemented in a stripped copy of libstdc++, will not work.
8675              If we do not have debug info for the definition, we will have to
8676              match them up some other way.
8677
8678              When we do name matching there is a related problem with function
8679              templates; two instantiated function templates are allowed to
8680              differ only by their return types, which we do not add here.  */
8681
8682           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8683             {
8684               struct attribute *attr;
8685               struct die_info *child;
8686               int first = 1;
8687
8688               die->building_fullname = 1;
8689
8690               for (child = die->child; child != NULL; child = child->sibling)
8691                 {
8692                   struct type *type;
8693                   LONGEST value;
8694                   const gdb_byte *bytes;
8695                   struct dwarf2_locexpr_baton *baton;
8696                   struct value *v;
8697
8698                   if (child->tag != DW_TAG_template_type_param
8699                       && child->tag != DW_TAG_template_value_param)
8700                     continue;
8701
8702                   if (first)
8703                     {
8704                       buf.puts ("<");
8705                       first = 0;
8706                     }
8707                   else
8708                     buf.puts (", ");
8709
8710                   attr = dwarf2_attr (child, DW_AT_type, cu);
8711                   if (attr == NULL)
8712                     {
8713                       complaint (&symfile_complaints,
8714                                  _("template parameter missing DW_AT_type"));
8715                       buf.puts ("UNKNOWN_TYPE");
8716                       continue;
8717                     }
8718                   type = die_type (child, cu);
8719
8720                   if (child->tag == DW_TAG_template_type_param)
8721                     {
8722                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8723                       continue;
8724                     }
8725
8726                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8727                   if (attr == NULL)
8728                     {
8729                       complaint (&symfile_complaints,
8730                                  _("template parameter missing "
8731                                    "DW_AT_const_value"));
8732                       buf.puts ("UNKNOWN_VALUE");
8733                       continue;
8734                     }
8735
8736                   dwarf2_const_value_attr (attr, type, name,
8737                                            &cu->comp_unit_obstack, cu,
8738                                            &value, &bytes, &baton);
8739
8740                   if (TYPE_NOSIGN (type))
8741                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8742                        changed, this can use value_print instead.  */
8743                     c_printchar (value, type, &buf);
8744                   else
8745                     {
8746                       struct value_print_options opts;
8747
8748                       if (baton != NULL)
8749                         v = dwarf2_evaluate_loc_desc (type, NULL,
8750                                                       baton->data,
8751                                                       baton->size,
8752                                                       baton->per_cu);
8753                       else if (bytes != NULL)
8754                         {
8755                           v = allocate_value (type);
8756                           memcpy (value_contents_writeable (v), bytes,
8757                                   TYPE_LENGTH (type));
8758                         }
8759                       else
8760                         v = value_from_longest (type, value);
8761
8762                       /* Specify decimal so that we do not depend on
8763                          the radix.  */
8764                       get_formatted_print_options (&opts, 'd');
8765                       opts.raw = 1;
8766                       value_print (v, &buf, &opts);
8767                       release_value (v);
8768                       value_free (v);
8769                     }
8770                 }
8771
8772               die->building_fullname = 0;
8773
8774               if (!first)
8775                 {
8776                   /* Close the argument list, with a space if necessary
8777                      (nested templates).  */
8778                   if (!buf.empty () && buf.string ().back () == '>')
8779                     buf.puts (" >");
8780                   else
8781                     buf.puts (">");
8782                 }
8783             }
8784
8785           /* For C++ methods, append formal parameter type
8786              information, if PHYSNAME.  */
8787
8788           if (physname && die->tag == DW_TAG_subprogram
8789               && cu->language == language_cplus)
8790             {
8791               struct type *type = read_type_die (die, cu);
8792
8793               c_type_print_args (type, &buf, 1, cu->language,
8794                                  &type_print_raw_options);
8795
8796               if (cu->language == language_cplus)
8797                 {
8798                   /* Assume that an artificial first parameter is
8799                      "this", but do not crash if it is not.  RealView
8800                      marks unnamed (and thus unused) parameters as
8801                      artificial; there is no way to differentiate
8802                      the two cases.  */
8803                   if (TYPE_NFIELDS (type) > 0
8804                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8805                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8806                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8807                                                                         0))))
8808                     buf.puts (" const");
8809                 }
8810             }
8811
8812           const std::string &intermediate_name = buf.string ();
8813
8814           if (cu->language == language_cplus)
8815             canonical_name
8816               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8817                                           &objfile->per_bfd->storage_obstack);
8818
8819           /* If we only computed INTERMEDIATE_NAME, or if
8820              INTERMEDIATE_NAME is already canonical, then we need to
8821              copy it to the appropriate obstack.  */
8822           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8823             name = ((const char *)
8824                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8825                                    intermediate_name.c_str (),
8826                                    intermediate_name.length ()));
8827           else
8828             name = canonical_name;
8829         }
8830     }
8831
8832   return name;
8833 }
8834
8835 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8836    If scope qualifiers are appropriate they will be added.  The result
8837    will be allocated on the storage_obstack, or NULL if the DIE does
8838    not have a name.  NAME may either be from a previous call to
8839    dwarf2_name or NULL.
8840
8841    The output string will be canonicalized (if C++).  */
8842
8843 static const char *
8844 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8845 {
8846   return dwarf2_compute_name (name, die, cu, 0);
8847 }
8848
8849 /* Construct a physname for the given DIE in CU.  NAME may either be
8850    from a previous call to dwarf2_name or NULL.  The result will be
8851    allocated on the objfile_objstack or NULL if the DIE does not have a
8852    name.
8853
8854    The output string will be canonicalized (if C++).  */
8855
8856 static const char *
8857 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8858 {
8859   struct objfile *objfile = cu->objfile;
8860   const char *retval, *mangled = NULL, *canon = NULL;
8861   struct cleanup *back_to;
8862   int need_copy = 1;
8863
8864   /* In this case dwarf2_compute_name is just a shortcut not building anything
8865      on its own.  */
8866   if (!die_needs_namespace (die, cu))
8867     return dwarf2_compute_name (name, die, cu, 1);
8868
8869   back_to = make_cleanup (null_cleanup, NULL);
8870
8871   mangled = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8872   if (mangled == NULL)
8873     mangled = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8874
8875   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
8876      See https://github.com/rust-lang/rust/issues/32925.  */
8877   if (cu->language == language_rust && mangled != NULL
8878       && strchr (mangled, '{') != NULL)
8879     mangled = NULL;
8880
8881   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8882      has computed.  */
8883   if (mangled != NULL)
8884     {
8885       char *demangled;
8886
8887       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8888          type.  It is easier for GDB users to search for such functions as
8889          `name(params)' than `long name(params)'.  In such case the minimal
8890          symbol names do not match the full symbol names but for template
8891          functions there is never a need to look up their definition from their
8892          declaration so the only disadvantage remains the minimal symbol
8893          variant `long name(params)' does not have the proper inferior type.
8894          */
8895
8896       if (cu->language == language_go)
8897         {
8898           /* This is a lie, but we already lie to the caller new_symbol_full.
8899              new_symbol_full assumes we return the mangled name.
8900              This just undoes that lie until things are cleaned up.  */
8901           demangled = NULL;
8902         }
8903       else
8904         {
8905           demangled = gdb_demangle (mangled,
8906                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
8907         }
8908       if (demangled)
8909         {
8910           make_cleanup (xfree, demangled);
8911           canon = demangled;
8912         }
8913       else
8914         {
8915           canon = mangled;
8916           need_copy = 0;
8917         }
8918     }
8919
8920   if (canon == NULL || check_physname)
8921     {
8922       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8923
8924       if (canon != NULL && strcmp (physname, canon) != 0)
8925         {
8926           /* It may not mean a bug in GDB.  The compiler could also
8927              compute DW_AT_linkage_name incorrectly.  But in such case
8928              GDB would need to be bug-to-bug compatible.  */
8929
8930           complaint (&symfile_complaints,
8931                      _("Computed physname <%s> does not match demangled <%s> "
8932                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8933                      physname, canon, mangled, to_underlying (die->sect_off),
8934                      objfile_name (objfile));
8935
8936           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8937              is available here - over computed PHYSNAME.  It is safer
8938              against both buggy GDB and buggy compilers.  */
8939
8940           retval = canon;
8941         }
8942       else
8943         {
8944           retval = physname;
8945           need_copy = 0;
8946         }
8947     }
8948   else
8949     retval = canon;
8950
8951   if (need_copy)
8952     retval = ((const char *)
8953               obstack_copy0 (&objfile->per_bfd->storage_obstack,
8954                              retval, strlen (retval)));
8955
8956   do_cleanups (back_to);
8957   return retval;
8958 }
8959
8960 /* Inspect DIE in CU for a namespace alias.  If one exists, record
8961    a new symbol for it.
8962
8963    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
8964
8965 static int
8966 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
8967 {
8968   struct attribute *attr;
8969
8970   /* If the die does not have a name, this is not a namespace
8971      alias.  */
8972   attr = dwarf2_attr (die, DW_AT_name, cu);
8973   if (attr != NULL)
8974     {
8975       int num;
8976       struct die_info *d = die;
8977       struct dwarf2_cu *imported_cu = cu;
8978
8979       /* If the compiler has nested DW_AT_imported_declaration DIEs,
8980          keep inspecting DIEs until we hit the underlying import.  */
8981 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
8982       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
8983         {
8984           attr = dwarf2_attr (d, DW_AT_import, cu);
8985           if (attr == NULL)
8986             break;
8987
8988           d = follow_die_ref (d, attr, &imported_cu);
8989           if (d->tag != DW_TAG_imported_declaration)
8990             break;
8991         }
8992
8993       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
8994         {
8995           complaint (&symfile_complaints,
8996                      _("DIE at 0x%x has too many recursively imported "
8997                        "declarations"), to_underlying (d->sect_off));
8998           return 0;
8999         }
9000
9001       if (attr != NULL)
9002         {
9003           struct type *type;
9004           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9005
9006           type = get_die_type_at_offset (sect_off, cu->per_cu);
9007           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9008             {
9009               /* This declaration is a global namespace alias.  Add
9010                  a symbol for it whose type is the aliased namespace.  */
9011               new_symbol (die, type, cu);
9012               return 1;
9013             }
9014         }
9015     }
9016
9017   return 0;
9018 }
9019
9020 /* Return the using directives repository (global or local?) to use in the
9021    current context for LANGUAGE.
9022
9023    For Ada, imported declarations can materialize renamings, which *may* be
9024    global.  However it is impossible (for now?) in DWARF to distinguish
9025    "external" imported declarations and "static" ones.  As all imported
9026    declarations seem to be static in all other languages, make them all CU-wide
9027    global only in Ada.  */
9028
9029 static struct using_direct **
9030 using_directives (enum language language)
9031 {
9032   if (language == language_ada && context_stack_depth == 0)
9033     return &global_using_directives;
9034   else
9035     return &local_using_directives;
9036 }
9037
9038 /* Read the import statement specified by the given die and record it.  */
9039
9040 static void
9041 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9042 {
9043   struct objfile *objfile = cu->objfile;
9044   struct attribute *import_attr;
9045   struct die_info *imported_die, *child_die;
9046   struct dwarf2_cu *imported_cu;
9047   const char *imported_name;
9048   const char *imported_name_prefix;
9049   const char *canonical_name;
9050   const char *import_alias;
9051   const char *imported_declaration = NULL;
9052   const char *import_prefix;
9053   VEC (const_char_ptr) *excludes = NULL;
9054   struct cleanup *cleanups;
9055
9056   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9057   if (import_attr == NULL)
9058     {
9059       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9060                  dwarf_tag_name (die->tag));
9061       return;
9062     }
9063
9064   imported_cu = cu;
9065   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9066   imported_name = dwarf2_name (imported_die, imported_cu);
9067   if (imported_name == NULL)
9068     {
9069       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9070
9071         The import in the following code:
9072         namespace A
9073           {
9074             typedef int B;
9075           }
9076
9077         int main ()
9078           {
9079             using A::B;
9080             B b;
9081             return b;
9082           }
9083
9084         ...
9085          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9086             <52>   DW_AT_decl_file   : 1
9087             <53>   DW_AT_decl_line   : 6
9088             <54>   DW_AT_import      : <0x75>
9089          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9090             <59>   DW_AT_name        : B
9091             <5b>   DW_AT_decl_file   : 1
9092             <5c>   DW_AT_decl_line   : 2
9093             <5d>   DW_AT_type        : <0x6e>
9094         ...
9095          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9096             <76>   DW_AT_byte_size   : 4
9097             <77>   DW_AT_encoding    : 5        (signed)
9098
9099         imports the wrong die ( 0x75 instead of 0x58 ).
9100         This case will be ignored until the gcc bug is fixed.  */
9101       return;
9102     }
9103
9104   /* Figure out the local name after import.  */
9105   import_alias = dwarf2_name (die, cu);
9106
9107   /* Figure out where the statement is being imported to.  */
9108   import_prefix = determine_prefix (die, cu);
9109
9110   /* Figure out what the scope of the imported die is and prepend it
9111      to the name of the imported die.  */
9112   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9113
9114   if (imported_die->tag != DW_TAG_namespace
9115       && imported_die->tag != DW_TAG_module)
9116     {
9117       imported_declaration = imported_name;
9118       canonical_name = imported_name_prefix;
9119     }
9120   else if (strlen (imported_name_prefix) > 0)
9121     canonical_name = obconcat (&objfile->objfile_obstack,
9122                                imported_name_prefix,
9123                                (cu->language == language_d ? "." : "::"),
9124                                imported_name, (char *) NULL);
9125   else
9126     canonical_name = imported_name;
9127
9128   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9129
9130   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9131     for (child_die = die->child; child_die && child_die->tag;
9132          child_die = sibling_die (child_die))
9133       {
9134         /* DWARF-4: A Fortran use statement with a “rename list” may be
9135            represented by an imported module entry with an import attribute
9136            referring to the module and owned entries corresponding to those
9137            entities that are renamed as part of being imported.  */
9138
9139         if (child_die->tag != DW_TAG_imported_declaration)
9140           {
9141             complaint (&symfile_complaints,
9142                        _("child DW_TAG_imported_declaration expected "
9143                          "- DIE at 0x%x [in module %s]"),
9144                        to_underlying (child_die->sect_off), objfile_name (objfile));
9145             continue;
9146           }
9147
9148         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9149         if (import_attr == NULL)
9150           {
9151             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9152                        dwarf_tag_name (child_die->tag));
9153             continue;
9154           }
9155
9156         imported_cu = cu;
9157         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9158                                               &imported_cu);
9159         imported_name = dwarf2_name (imported_die, imported_cu);
9160         if (imported_name == NULL)
9161           {
9162             complaint (&symfile_complaints,
9163                        _("child DW_TAG_imported_declaration has unknown "
9164                          "imported name - DIE at 0x%x [in module %s]"),
9165                        to_underlying (child_die->sect_off), objfile_name (objfile));
9166             continue;
9167           }
9168
9169         VEC_safe_push (const_char_ptr, excludes, imported_name);
9170
9171         process_die (child_die, cu);
9172       }
9173
9174   add_using_directive (using_directives (cu->language),
9175                        import_prefix,
9176                        canonical_name,
9177                        import_alias,
9178                        imported_declaration,
9179                        excludes,
9180                        0,
9181                        &objfile->objfile_obstack);
9182
9183   do_cleanups (cleanups);
9184 }
9185
9186 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9187    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9188    this, it was first present in GCC release 4.3.0.  */
9189
9190 static int
9191 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9192 {
9193   if (!cu->checked_producer)
9194     check_producer (cu);
9195
9196   return cu->producer_is_gcc_lt_4_3;
9197 }
9198
9199 static file_and_directory
9200 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9201 {
9202   file_and_directory res;
9203
9204   /* Find the filename.  Do not use dwarf2_name here, since the filename
9205      is not a source language identifier.  */
9206   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9207   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9208
9209   if (res.comp_dir == NULL
9210       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9211       && IS_ABSOLUTE_PATH (res.name))
9212     {
9213       res.comp_dir_storage = ldirname (res.name);
9214       if (!res.comp_dir_storage.empty ())
9215         res.comp_dir = res.comp_dir_storage.c_str ();
9216     }
9217   if (res.comp_dir != NULL)
9218     {
9219       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9220          directory, get rid of it.  */
9221       const char *cp = strchr (res.comp_dir, ':');
9222
9223       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9224         res.comp_dir = cp + 1;
9225     }
9226
9227   if (res.name == NULL)
9228     res.name = "<unknown>";
9229
9230   return res;
9231 }
9232
9233 /* Handle DW_AT_stmt_list for a compilation unit.
9234    DIE is the DW_TAG_compile_unit die for CU.
9235    COMP_DIR is the compilation directory.  LOWPC is passed to
9236    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9237
9238 static void
9239 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9240                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9241 {
9242   struct objfile *objfile = dwarf2_per_objfile->objfile;
9243   struct attribute *attr;
9244   struct line_header line_header_local;
9245   hashval_t line_header_local_hash;
9246   unsigned u;
9247   void **slot;
9248   int decode_mapping;
9249
9250   gdb_assert (! cu->per_cu->is_debug_types);
9251
9252   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9253   if (attr == NULL)
9254     return;
9255
9256   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9257
9258   /* The line header hash table is only created if needed (it exists to
9259      prevent redundant reading of the line table for partial_units).
9260      If we're given a partial_unit, we'll need it.  If we're given a
9261      compile_unit, then use the line header hash table if it's already
9262      created, but don't create one just yet.  */
9263
9264   if (dwarf2_per_objfile->line_header_hash == NULL
9265       && die->tag == DW_TAG_partial_unit)
9266     {
9267       dwarf2_per_objfile->line_header_hash
9268         = htab_create_alloc_ex (127, line_header_hash_voidp,
9269                                 line_header_eq_voidp,
9270                                 free_line_header_voidp,
9271                                 &objfile->objfile_obstack,
9272                                 hashtab_obstack_allocate,
9273                                 dummy_obstack_deallocate);
9274     }
9275
9276   line_header_local.sect_off = line_offset;
9277   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9278   line_header_local_hash = line_header_hash (&line_header_local);
9279   if (dwarf2_per_objfile->line_header_hash != NULL)
9280     {
9281       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9282                                        &line_header_local,
9283                                        line_header_local_hash, NO_INSERT);
9284
9285       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9286          is not present in *SLOT (since if there is something in *SLOT then
9287          it will be for a partial_unit).  */
9288       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9289         {
9290           gdb_assert (*slot != NULL);
9291           cu->line_header = (struct line_header *) *slot;
9292           return;
9293         }
9294     }
9295
9296   /* dwarf_decode_line_header does not yet provide sufficient information.
9297      We always have to call also dwarf_decode_lines for it.  */
9298   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9299   if (lh == NULL)
9300     return;
9301   cu->line_header = lh.get ();
9302
9303   if (dwarf2_per_objfile->line_header_hash == NULL)
9304     slot = NULL;
9305   else
9306     {
9307       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9308                                        &line_header_local,
9309                                        line_header_local_hash, INSERT);
9310       gdb_assert (slot != NULL);
9311     }
9312   if (slot != NULL && *slot == NULL)
9313     {
9314       /* This newly decoded line number information unit will be owned
9315          by line_header_hash hash table.  */
9316       *slot = cu->line_header;
9317     }
9318   else
9319     {
9320       /* We cannot free any current entry in (*slot) as that struct line_header
9321          may be already used by multiple CUs.  Create only temporary decoded
9322          line_header for this CU - it may happen at most once for each line
9323          number information unit.  And if we're not using line_header_hash
9324          then this is what we want as well.  */
9325       gdb_assert (die->tag != DW_TAG_partial_unit);
9326     }
9327   decode_mapping = (die->tag != DW_TAG_partial_unit);
9328   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9329                       decode_mapping);
9330
9331   lh.release ();
9332 }
9333
9334 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9335
9336 static void
9337 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9338 {
9339   struct objfile *objfile = dwarf2_per_objfile->objfile;
9340   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9341   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9342   CORE_ADDR highpc = ((CORE_ADDR) 0);
9343   struct attribute *attr;
9344   struct die_info *child_die;
9345   CORE_ADDR baseaddr;
9346
9347   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9348
9349   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9350
9351   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9352      from finish_block.  */
9353   if (lowpc == ((CORE_ADDR) -1))
9354     lowpc = highpc;
9355   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9356
9357   file_and_directory fnd = find_file_and_directory (die, cu);
9358
9359   prepare_one_comp_unit (cu, die, cu->language);
9360
9361   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9362      standardised yet.  As a workaround for the language detection we fall
9363      back to the DW_AT_producer string.  */
9364   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9365     cu->language = language_opencl;
9366
9367   /* Similar hack for Go.  */
9368   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9369     set_cu_language (DW_LANG_Go, cu);
9370
9371   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9372
9373   /* Decode line number information if present.  We do this before
9374      processing child DIEs, so that the line header table is available
9375      for DW_AT_decl_file.  */
9376   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9377
9378   /* Process all dies in compilation unit.  */
9379   if (die->child != NULL)
9380     {
9381       child_die = die->child;
9382       while (child_die && child_die->tag)
9383         {
9384           process_die (child_die, cu);
9385           child_die = sibling_die (child_die);
9386         }
9387     }
9388
9389   /* Decode macro information, if present.  Dwarf 2 macro information
9390      refers to information in the line number info statement program
9391      header, so we can only read it if we've read the header
9392      successfully.  */
9393   attr = dwarf2_attr (die, DW_AT_macros, cu);
9394   if (attr == NULL)
9395     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9396   if (attr && cu->line_header)
9397     {
9398       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9399         complaint (&symfile_complaints,
9400                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9401
9402       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9403     }
9404   else
9405     {
9406       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9407       if (attr && cu->line_header)
9408         {
9409           unsigned int macro_offset = DW_UNSND (attr);
9410
9411           dwarf_decode_macros (cu, macro_offset, 0);
9412         }
9413     }
9414 }
9415
9416 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9417    Create the set of symtabs used by this TU, or if this TU is sharing
9418    symtabs with another TU and the symtabs have already been created
9419    then restore those symtabs in the line header.
9420    We don't need the pc/line-number mapping for type units.  */
9421
9422 static void
9423 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9424 {
9425   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9426   struct type_unit_group *tu_group;
9427   int first_time;
9428   struct attribute *attr;
9429   unsigned int i;
9430   struct signatured_type *sig_type;
9431
9432   gdb_assert (per_cu->is_debug_types);
9433   sig_type = (struct signatured_type *) per_cu;
9434
9435   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9436
9437   /* If we're using .gdb_index (includes -readnow) then
9438      per_cu->type_unit_group may not have been set up yet.  */
9439   if (sig_type->type_unit_group == NULL)
9440     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9441   tu_group = sig_type->type_unit_group;
9442
9443   /* If we've already processed this stmt_list there's no real need to
9444      do it again, we could fake it and just recreate the part we need
9445      (file name,index -> symtab mapping).  If data shows this optimization
9446      is useful we can do it then.  */
9447   first_time = tu_group->compunit_symtab == NULL;
9448
9449   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9450      debug info.  */
9451   line_header_up lh;
9452   if (attr != NULL)
9453     {
9454       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9455       lh = dwarf_decode_line_header (line_offset, cu);
9456     }
9457   if (lh == NULL)
9458     {
9459       if (first_time)
9460         dwarf2_start_symtab (cu, "", NULL, 0);
9461       else
9462         {
9463           gdb_assert (tu_group->symtabs == NULL);
9464           restart_symtab (tu_group->compunit_symtab, "", 0);
9465         }
9466       return;
9467     }
9468
9469   cu->line_header = lh.get ();
9470
9471   if (first_time)
9472     {
9473       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9474
9475       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9476          still initializing it, and our caller (a few levels up)
9477          process_full_type_unit still needs to know if this is the first
9478          time.  */
9479
9480       tu_group->num_symtabs = lh->file_names.size ();
9481       tu_group->symtabs = XNEWVEC (struct symtab *, lh->file_names.size ());
9482
9483       for (i = 0; i < lh->file_names.size (); ++i)
9484         {
9485           file_entry &fe = lh->file_names[i];
9486
9487           dwarf2_start_subfile (fe.name, fe.include_dir (lh.get ()));
9488
9489           if (current_subfile->symtab == NULL)
9490             {
9491               /* NOTE: start_subfile will recognize when it's been passed
9492                  a file it has already seen.  So we can't assume there's a
9493                  simple mapping from lh->file_names to subfiles, plus
9494                  lh->file_names may contain dups.  */
9495               current_subfile->symtab
9496                 = allocate_symtab (cust, current_subfile->name);
9497             }
9498
9499           fe.symtab = current_subfile->symtab;
9500           tu_group->symtabs[i] = fe.symtab;
9501         }
9502     }
9503   else
9504     {
9505       restart_symtab (tu_group->compunit_symtab, "", 0);
9506
9507       for (i = 0; i < lh->file_names.size (); ++i)
9508         {
9509           struct file_entry *fe = &lh->file_names[i];
9510
9511           fe->symtab = tu_group->symtabs[i];
9512         }
9513     }
9514
9515   lh.release ();
9516
9517   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9518      so they don't have a "real" (so to speak) symtab anyway.
9519      There is later code that will assign the main symtab to all symbols
9520      that don't have one.  We need to handle the case of a symbol with a
9521      missing symtab (DW_AT_decl_file) anyway.  */
9522 }
9523
9524 /* Process DW_TAG_type_unit.
9525    For TUs we want to skip the first top level sibling if it's not the
9526    actual type being defined by this TU.  In this case the first top
9527    level sibling is there to provide context only.  */
9528
9529 static void
9530 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9531 {
9532   struct die_info *child_die;
9533
9534   prepare_one_comp_unit (cu, die, language_minimal);
9535
9536   /* Initialize (or reinitialize) the machinery for building symtabs.
9537      We do this before processing child DIEs, so that the line header table
9538      is available for DW_AT_decl_file.  */
9539   setup_type_unit_groups (die, cu);
9540
9541   if (die->child != NULL)
9542     {
9543       child_die = die->child;
9544       while (child_die && child_die->tag)
9545         {
9546           process_die (child_die, cu);
9547           child_die = sibling_die (child_die);
9548         }
9549     }
9550 }
9551 \f
9552 /* DWO/DWP files.
9553
9554    http://gcc.gnu.org/wiki/DebugFission
9555    http://gcc.gnu.org/wiki/DebugFissionDWP
9556
9557    To simplify handling of both DWO files ("object" files with the DWARF info)
9558    and DWP files (a file with the DWOs packaged up into one file), we treat
9559    DWP files as having a collection of virtual DWO files.  */
9560
9561 static hashval_t
9562 hash_dwo_file (const void *item)
9563 {
9564   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9565   hashval_t hash;
9566
9567   hash = htab_hash_string (dwo_file->dwo_name);
9568   if (dwo_file->comp_dir != NULL)
9569     hash += htab_hash_string (dwo_file->comp_dir);
9570   return hash;
9571 }
9572
9573 static int
9574 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9575 {
9576   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9577   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9578
9579   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9580     return 0;
9581   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9582     return lhs->comp_dir == rhs->comp_dir;
9583   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9584 }
9585
9586 /* Allocate a hash table for DWO files.  */
9587
9588 static htab_t
9589 allocate_dwo_file_hash_table (void)
9590 {
9591   struct objfile *objfile = dwarf2_per_objfile->objfile;
9592
9593   return htab_create_alloc_ex (41,
9594                                hash_dwo_file,
9595                                eq_dwo_file,
9596                                NULL,
9597                                &objfile->objfile_obstack,
9598                                hashtab_obstack_allocate,
9599                                dummy_obstack_deallocate);
9600 }
9601
9602 /* Lookup DWO file DWO_NAME.  */
9603
9604 static void **
9605 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9606 {
9607   struct dwo_file find_entry;
9608   void **slot;
9609
9610   if (dwarf2_per_objfile->dwo_files == NULL)
9611     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9612
9613   memset (&find_entry, 0, sizeof (find_entry));
9614   find_entry.dwo_name = dwo_name;
9615   find_entry.comp_dir = comp_dir;
9616   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9617
9618   return slot;
9619 }
9620
9621 static hashval_t
9622 hash_dwo_unit (const void *item)
9623 {
9624   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9625
9626   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9627   return dwo_unit->signature;
9628 }
9629
9630 static int
9631 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9632 {
9633   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9634   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9635
9636   /* The signature is assumed to be unique within the DWO file.
9637      So while object file CU dwo_id's always have the value zero,
9638      that's OK, assuming each object file DWO file has only one CU,
9639      and that's the rule for now.  */
9640   return lhs->signature == rhs->signature;
9641 }
9642
9643 /* Allocate a hash table for DWO CUs,TUs.
9644    There is one of these tables for each of CUs,TUs for each DWO file.  */
9645
9646 static htab_t
9647 allocate_dwo_unit_table (struct objfile *objfile)
9648 {
9649   /* Start out with a pretty small number.
9650      Generally DWO files contain only one CU and maybe some TUs.  */
9651   return htab_create_alloc_ex (3,
9652                                hash_dwo_unit,
9653                                eq_dwo_unit,
9654                                NULL,
9655                                &objfile->objfile_obstack,
9656                                hashtab_obstack_allocate,
9657                                dummy_obstack_deallocate);
9658 }
9659
9660 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9661
9662 struct create_dwo_cu_data
9663 {
9664   struct dwo_file *dwo_file;
9665   struct dwo_unit dwo_unit;
9666 };
9667
9668 /* die_reader_func for create_dwo_cu.  */
9669
9670 static void
9671 create_dwo_cu_reader (const struct die_reader_specs *reader,
9672                       const gdb_byte *info_ptr,
9673                       struct die_info *comp_unit_die,
9674                       int has_children,
9675                       void *datap)
9676 {
9677   struct dwarf2_cu *cu = reader->cu;
9678   sect_offset sect_off = cu->per_cu->sect_off;
9679   struct dwarf2_section_info *section = cu->per_cu->section;
9680   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9681   struct dwo_file *dwo_file = data->dwo_file;
9682   struct dwo_unit *dwo_unit = &data->dwo_unit;
9683   struct attribute *attr;
9684
9685   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9686   if (attr == NULL)
9687     {
9688       complaint (&symfile_complaints,
9689                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9690                    " its dwo_id [in module %s]"),
9691                  to_underlying (sect_off), dwo_file->dwo_name);
9692       return;
9693     }
9694
9695   dwo_unit->dwo_file = dwo_file;
9696   dwo_unit->signature = DW_UNSND (attr);
9697   dwo_unit->section = section;
9698   dwo_unit->sect_off = sect_off;
9699   dwo_unit->length = cu->per_cu->length;
9700
9701   if (dwarf_read_debug)
9702     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9703                         to_underlying (sect_off),
9704                         hex_string (dwo_unit->signature));
9705 }
9706
9707 /* Create the dwo_unit for the lone CU in DWO_FILE.
9708    Note: This function processes DWO files only, not DWP files.  */
9709
9710 static struct dwo_unit *
9711 create_dwo_cu (struct dwo_file *dwo_file)
9712 {
9713   struct objfile *objfile = dwarf2_per_objfile->objfile;
9714   struct dwarf2_section_info *section = &dwo_file->sections.info;
9715   const gdb_byte *info_ptr, *end_ptr;
9716   struct create_dwo_cu_data create_dwo_cu_data;
9717   struct dwo_unit *dwo_unit;
9718
9719   dwarf2_read_section (objfile, section);
9720   info_ptr = section->buffer;
9721
9722   if (info_ptr == NULL)
9723     return NULL;
9724
9725   if (dwarf_read_debug)
9726     {
9727       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9728                           get_section_name (section),
9729                           get_section_file_name (section));
9730     }
9731
9732   create_dwo_cu_data.dwo_file = dwo_file;
9733   dwo_unit = NULL;
9734
9735   end_ptr = info_ptr + section->size;
9736   while (info_ptr < end_ptr)
9737     {
9738       struct dwarf2_per_cu_data per_cu;
9739
9740       memset (&create_dwo_cu_data.dwo_unit, 0,
9741               sizeof (create_dwo_cu_data.dwo_unit));
9742       memset (&per_cu, 0, sizeof (per_cu));
9743       per_cu.objfile = objfile;
9744       per_cu.is_debug_types = 0;
9745       per_cu.sect_off = sect_offset (info_ptr - section->buffer);
9746       per_cu.section = section;
9747
9748       init_cutu_and_read_dies_no_follow (&per_cu, dwo_file,
9749                                          create_dwo_cu_reader,
9750                                          &create_dwo_cu_data);
9751
9752       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9753         {
9754           /* If we've already found one, complain.  We only support one
9755              because having more than one requires hacking the dwo_name of
9756              each to match, which is highly unlikely to happen.  */
9757           if (dwo_unit != NULL)
9758             {
9759               complaint (&symfile_complaints,
9760                          _("Multiple CUs in DWO file %s [in module %s]"),
9761                          dwo_file->dwo_name, objfile_name (objfile));
9762               break;
9763             }
9764
9765           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9766           *dwo_unit = create_dwo_cu_data.dwo_unit;
9767         }
9768
9769       info_ptr += per_cu.length;
9770     }
9771
9772   return dwo_unit;
9773 }
9774
9775 /* DWP file .debug_{cu,tu}_index section format:
9776    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9777
9778    DWP Version 1:
9779
9780    Both index sections have the same format, and serve to map a 64-bit
9781    signature to a set of section numbers.  Each section begins with a header,
9782    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9783    indexes, and a pool of 32-bit section numbers.  The index sections will be
9784    aligned at 8-byte boundaries in the file.
9785
9786    The index section header consists of:
9787
9788     V, 32 bit version number
9789     -, 32 bits unused
9790     N, 32 bit number of compilation units or type units in the index
9791     M, 32 bit number of slots in the hash table
9792
9793    Numbers are recorded using the byte order of the application binary.
9794
9795    The hash table begins at offset 16 in the section, and consists of an array
9796    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9797    order of the application binary).  Unused slots in the hash table are 0.
9798    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9799
9800    The parallel table begins immediately after the hash table
9801    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9802    array of 32-bit indexes (using the byte order of the application binary),
9803    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9804    table contains a 32-bit index into the pool of section numbers.  For unused
9805    hash table slots, the corresponding entry in the parallel table will be 0.
9806
9807    The pool of section numbers begins immediately following the hash table
9808    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9809    section numbers consists of an array of 32-bit words (using the byte order
9810    of the application binary).  Each item in the array is indexed starting
9811    from 0.  The hash table entry provides the index of the first section
9812    number in the set.  Additional section numbers in the set follow, and the
9813    set is terminated by a 0 entry (section number 0 is not used in ELF).
9814
9815    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9816    section must be the first entry in the set, and the .debug_abbrev.dwo must
9817    be the second entry. Other members of the set may follow in any order.
9818
9819    ---
9820
9821    DWP Version 2:
9822
9823    DWP Version 2 combines all the .debug_info, etc. sections into one,
9824    and the entries in the index tables are now offsets into these sections.
9825    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9826    section.
9827
9828    Index Section Contents:
9829     Header
9830     Hash Table of Signatures   dwp_hash_table.hash_table
9831     Parallel Table of Indices  dwp_hash_table.unit_table
9832     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9833     Table of Section Sizes     dwp_hash_table.v2.sizes
9834
9835    The index section header consists of:
9836
9837     V, 32 bit version number
9838     L, 32 bit number of columns in the table of section offsets
9839     N, 32 bit number of compilation units or type units in the index
9840     M, 32 bit number of slots in the hash table
9841
9842    Numbers are recorded using the byte order of the application binary.
9843
9844    The hash table has the same format as version 1.
9845    The parallel table of indices has the same format as version 1,
9846    except that the entries are origin-1 indices into the table of sections
9847    offsets and the table of section sizes.
9848
9849    The table of offsets begins immediately following the parallel table
9850    (at offset 16 + 12 * M from the beginning of the section).  The table is
9851    a two-dimensional array of 32-bit words (using the byte order of the
9852    application binary), with L columns and N+1 rows, in row-major order.
9853    Each row in the array is indexed starting from 0.  The first row provides
9854    a key to the remaining rows: each column in this row provides an identifier
9855    for a debug section, and the offsets in the same column of subsequent rows
9856    refer to that section.  The section identifiers are:
9857
9858     DW_SECT_INFO         1  .debug_info.dwo
9859     DW_SECT_TYPES        2  .debug_types.dwo
9860     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9861     DW_SECT_LINE         4  .debug_line.dwo
9862     DW_SECT_LOC          5  .debug_loc.dwo
9863     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9864     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9865     DW_SECT_MACRO        8  .debug_macro.dwo
9866
9867    The offsets provided by the CU and TU index sections are the base offsets
9868    for the contributions made by each CU or TU to the corresponding section
9869    in the package file.  Each CU and TU header contains an abbrev_offset
9870    field, used to find the abbreviations table for that CU or TU within the
9871    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9872    be interpreted as relative to the base offset given in the index section.
9873    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9874    should be interpreted as relative to the base offset for .debug_line.dwo,
9875    and offsets into other debug sections obtained from DWARF attributes should
9876    also be interpreted as relative to the corresponding base offset.
9877
9878    The table of sizes begins immediately following the table of offsets.
9879    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9880    with L columns and N rows, in row-major order.  Each row in the array is
9881    indexed starting from 1 (row 0 is shared by the two tables).
9882
9883    ---
9884
9885    Hash table lookup is handled the same in version 1 and 2:
9886
9887    We assume that N and M will not exceed 2^32 - 1.
9888    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9889
9890    Given a 64-bit compilation unit signature or a type signature S, an entry
9891    in the hash table is located as follows:
9892
9893    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9894       the low-order k bits all set to 1.
9895
9896    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9897
9898    3) If the hash table entry at index H matches the signature, use that
9899       entry.  If the hash table entry at index H is unused (all zeroes),
9900       terminate the search: the signature is not present in the table.
9901
9902    4) Let H = (H + H') modulo M. Repeat at Step 3.
9903
9904    Because M > N and H' and M are relatively prime, the search is guaranteed
9905    to stop at an unused slot or find the match.  */
9906
9907 /* Create a hash table to map DWO IDs to their CU/TU entry in
9908    .debug_{info,types}.dwo in DWP_FILE.
9909    Returns NULL if there isn't one.
9910    Note: This function processes DWP files only, not DWO files.  */
9911
9912 static struct dwp_hash_table *
9913 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9914 {
9915   struct objfile *objfile = dwarf2_per_objfile->objfile;
9916   bfd *dbfd = dwp_file->dbfd;
9917   const gdb_byte *index_ptr, *index_end;
9918   struct dwarf2_section_info *index;
9919   uint32_t version, nr_columns, nr_units, nr_slots;
9920   struct dwp_hash_table *htab;
9921
9922   if (is_debug_types)
9923     index = &dwp_file->sections.tu_index;
9924   else
9925     index = &dwp_file->sections.cu_index;
9926
9927   if (dwarf2_section_empty_p (index))
9928     return NULL;
9929   dwarf2_read_section (objfile, index);
9930
9931   index_ptr = index->buffer;
9932   index_end = index_ptr + index->size;
9933
9934   version = read_4_bytes (dbfd, index_ptr);
9935   index_ptr += 4;
9936   if (version == 2)
9937     nr_columns = read_4_bytes (dbfd, index_ptr);
9938   else
9939     nr_columns = 0;
9940   index_ptr += 4;
9941   nr_units = read_4_bytes (dbfd, index_ptr);
9942   index_ptr += 4;
9943   nr_slots = read_4_bytes (dbfd, index_ptr);
9944   index_ptr += 4;
9945
9946   if (version != 1 && version != 2)
9947     {
9948       error (_("Dwarf Error: unsupported DWP file version (%s)"
9949                " [in module %s]"),
9950              pulongest (version), dwp_file->name);
9951     }
9952   if (nr_slots != (nr_slots & -nr_slots))
9953     {
9954       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9955                " is not power of 2 [in module %s]"),
9956              pulongest (nr_slots), dwp_file->name);
9957     }
9958
9959   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9960   htab->version = version;
9961   htab->nr_columns = nr_columns;
9962   htab->nr_units = nr_units;
9963   htab->nr_slots = nr_slots;
9964   htab->hash_table = index_ptr;
9965   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9966
9967   /* Exit early if the table is empty.  */
9968   if (nr_slots == 0 || nr_units == 0
9969       || (version == 2 && nr_columns == 0))
9970     {
9971       /* All must be zero.  */
9972       if (nr_slots != 0 || nr_units != 0
9973           || (version == 2 && nr_columns != 0))
9974         {
9975           complaint (&symfile_complaints,
9976                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9977                        " all zero [in modules %s]"),
9978                      dwp_file->name);
9979         }
9980       return htab;
9981     }
9982
9983   if (version == 1)
9984     {
9985       htab->section_pool.v1.indices =
9986         htab->unit_table + sizeof (uint32_t) * nr_slots;
9987       /* It's harder to decide whether the section is too small in v1.
9988          V1 is deprecated anyway so we punt.  */
9989     }
9990   else
9991     {
9992       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9993       int *ids = htab->section_pool.v2.section_ids;
9994       /* Reverse map for error checking.  */
9995       int ids_seen[DW_SECT_MAX + 1];
9996       int i;
9997
9998       if (nr_columns < 2)
9999         {
10000           error (_("Dwarf Error: bad DWP hash table, too few columns"
10001                    " in section table [in module %s]"),
10002                  dwp_file->name);
10003         }
10004       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10005         {
10006           error (_("Dwarf Error: bad DWP hash table, too many columns"
10007                    " in section table [in module %s]"),
10008                  dwp_file->name);
10009         }
10010       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10011       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10012       for (i = 0; i < nr_columns; ++i)
10013         {
10014           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10015
10016           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10017             {
10018               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10019                        " in section table [in module %s]"),
10020                      id, dwp_file->name);
10021             }
10022           if (ids_seen[id] != -1)
10023             {
10024               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10025                        " id %d in section table [in module %s]"),
10026                      id, dwp_file->name);
10027             }
10028           ids_seen[id] = i;
10029           ids[i] = id;
10030         }
10031       /* Must have exactly one info or types section.  */
10032       if (((ids_seen[DW_SECT_INFO] != -1)
10033            + (ids_seen[DW_SECT_TYPES] != -1))
10034           != 1)
10035         {
10036           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10037                    " DWO info/types section [in module %s]"),
10038                  dwp_file->name);
10039         }
10040       /* Must have an abbrev section.  */
10041       if (ids_seen[DW_SECT_ABBREV] == -1)
10042         {
10043           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10044                    " section [in module %s]"),
10045                  dwp_file->name);
10046         }
10047       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10048       htab->section_pool.v2.sizes =
10049         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10050                                          * nr_units * nr_columns);
10051       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10052                                           * nr_units * nr_columns))
10053           > index_end)
10054         {
10055           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10056                    " [in module %s]"),
10057                  dwp_file->name);
10058         }
10059     }
10060
10061   return htab;
10062 }
10063
10064 /* Update SECTIONS with the data from SECTP.
10065
10066    This function is like the other "locate" section routines that are
10067    passed to bfd_map_over_sections, but in this context the sections to
10068    read comes from the DWP V1 hash table, not the full ELF section table.
10069
10070    The result is non-zero for success, or zero if an error was found.  */
10071
10072 static int
10073 locate_v1_virtual_dwo_sections (asection *sectp,
10074                                 struct virtual_v1_dwo_sections *sections)
10075 {
10076   const struct dwop_section_names *names = &dwop_section_names;
10077
10078   if (section_is_p (sectp->name, &names->abbrev_dwo))
10079     {
10080       /* There can be only one.  */
10081       if (sections->abbrev.s.section != NULL)
10082         return 0;
10083       sections->abbrev.s.section = sectp;
10084       sections->abbrev.size = bfd_get_section_size (sectp);
10085     }
10086   else if (section_is_p (sectp->name, &names->info_dwo)
10087            || section_is_p (sectp->name, &names->types_dwo))
10088     {
10089       /* There can be only one.  */
10090       if (sections->info_or_types.s.section != NULL)
10091         return 0;
10092       sections->info_or_types.s.section = sectp;
10093       sections->info_or_types.size = bfd_get_section_size (sectp);
10094     }
10095   else if (section_is_p (sectp->name, &names->line_dwo))
10096     {
10097       /* There can be only one.  */
10098       if (sections->line.s.section != NULL)
10099         return 0;
10100       sections->line.s.section = sectp;
10101       sections->line.size = bfd_get_section_size (sectp);
10102     }
10103   else if (section_is_p (sectp->name, &names->loc_dwo))
10104     {
10105       /* There can be only one.  */
10106       if (sections->loc.s.section != NULL)
10107         return 0;
10108       sections->loc.s.section = sectp;
10109       sections->loc.size = bfd_get_section_size (sectp);
10110     }
10111   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10112     {
10113       /* There can be only one.  */
10114       if (sections->macinfo.s.section != NULL)
10115         return 0;
10116       sections->macinfo.s.section = sectp;
10117       sections->macinfo.size = bfd_get_section_size (sectp);
10118     }
10119   else if (section_is_p (sectp->name, &names->macro_dwo))
10120     {
10121       /* There can be only one.  */
10122       if (sections->macro.s.section != NULL)
10123         return 0;
10124       sections->macro.s.section = sectp;
10125       sections->macro.size = bfd_get_section_size (sectp);
10126     }
10127   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10128     {
10129       /* There can be only one.  */
10130       if (sections->str_offsets.s.section != NULL)
10131         return 0;
10132       sections->str_offsets.s.section = sectp;
10133       sections->str_offsets.size = bfd_get_section_size (sectp);
10134     }
10135   else
10136     {
10137       /* No other kind of section is valid.  */
10138       return 0;
10139     }
10140
10141   return 1;
10142 }
10143
10144 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10145    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10146    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10147    This is for DWP version 1 files.  */
10148
10149 static struct dwo_unit *
10150 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10151                            uint32_t unit_index,
10152                            const char *comp_dir,
10153                            ULONGEST signature, int is_debug_types)
10154 {
10155   struct objfile *objfile = dwarf2_per_objfile->objfile;
10156   const struct dwp_hash_table *dwp_htab =
10157     is_debug_types ? dwp_file->tus : dwp_file->cus;
10158   bfd *dbfd = dwp_file->dbfd;
10159   const char *kind = is_debug_types ? "TU" : "CU";
10160   struct dwo_file *dwo_file;
10161   struct dwo_unit *dwo_unit;
10162   struct virtual_v1_dwo_sections sections;
10163   void **dwo_file_slot;
10164   char *virtual_dwo_name;
10165   struct cleanup *cleanups;
10166   int i;
10167
10168   gdb_assert (dwp_file->version == 1);
10169
10170   if (dwarf_read_debug)
10171     {
10172       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10173                           kind,
10174                           pulongest (unit_index), hex_string (signature),
10175                           dwp_file->name);
10176     }
10177
10178   /* Fetch the sections of this DWO unit.
10179      Put a limit on the number of sections we look for so that bad data
10180      doesn't cause us to loop forever.  */
10181
10182 #define MAX_NR_V1_DWO_SECTIONS \
10183   (1 /* .debug_info or .debug_types */ \
10184    + 1 /* .debug_abbrev */ \
10185    + 1 /* .debug_line */ \
10186    + 1 /* .debug_loc */ \
10187    + 1 /* .debug_str_offsets */ \
10188    + 1 /* .debug_macro or .debug_macinfo */ \
10189    + 1 /* trailing zero */)
10190
10191   memset (&sections, 0, sizeof (sections));
10192   cleanups = make_cleanup (null_cleanup, 0);
10193
10194   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10195     {
10196       asection *sectp;
10197       uint32_t section_nr =
10198         read_4_bytes (dbfd,
10199                       dwp_htab->section_pool.v1.indices
10200                       + (unit_index + i) * sizeof (uint32_t));
10201
10202       if (section_nr == 0)
10203         break;
10204       if (section_nr >= dwp_file->num_sections)
10205         {
10206           error (_("Dwarf Error: bad DWP hash table, section number too large"
10207                    " [in module %s]"),
10208                  dwp_file->name);
10209         }
10210
10211       sectp = dwp_file->elf_sections[section_nr];
10212       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10213         {
10214           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10215                    " [in module %s]"),
10216                  dwp_file->name);
10217         }
10218     }
10219
10220   if (i < 2
10221       || dwarf2_section_empty_p (&sections.info_or_types)
10222       || dwarf2_section_empty_p (&sections.abbrev))
10223     {
10224       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10225                " [in module %s]"),
10226              dwp_file->name);
10227     }
10228   if (i == MAX_NR_V1_DWO_SECTIONS)
10229     {
10230       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10231                " [in module %s]"),
10232              dwp_file->name);
10233     }
10234
10235   /* It's easier for the rest of the code if we fake a struct dwo_file and
10236      have dwo_unit "live" in that.  At least for now.
10237
10238      The DWP file can be made up of a random collection of CUs and TUs.
10239      However, for each CU + set of TUs that came from the same original DWO
10240      file, we can combine them back into a virtual DWO file to save space
10241      (fewer struct dwo_file objects to allocate).  Remember that for really
10242      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10243
10244   virtual_dwo_name =
10245     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10246                 get_section_id (&sections.abbrev),
10247                 get_section_id (&sections.line),
10248                 get_section_id (&sections.loc),
10249                 get_section_id (&sections.str_offsets));
10250   make_cleanup (xfree, virtual_dwo_name);
10251   /* Can we use an existing virtual DWO file?  */
10252   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10253   /* Create one if necessary.  */
10254   if (*dwo_file_slot == NULL)
10255     {
10256       if (dwarf_read_debug)
10257         {
10258           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10259                               virtual_dwo_name);
10260         }
10261       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10262       dwo_file->dwo_name
10263         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10264                                         virtual_dwo_name,
10265                                         strlen (virtual_dwo_name));
10266       dwo_file->comp_dir = comp_dir;
10267       dwo_file->sections.abbrev = sections.abbrev;
10268       dwo_file->sections.line = sections.line;
10269       dwo_file->sections.loc = sections.loc;
10270       dwo_file->sections.macinfo = sections.macinfo;
10271       dwo_file->sections.macro = sections.macro;
10272       dwo_file->sections.str_offsets = sections.str_offsets;
10273       /* The "str" section is global to the entire DWP file.  */
10274       dwo_file->sections.str = dwp_file->sections.str;
10275       /* The info or types section is assigned below to dwo_unit,
10276          there's no need to record it in dwo_file.
10277          Also, we can't simply record type sections in dwo_file because
10278          we record a pointer into the vector in dwo_unit.  As we collect more
10279          types we'll grow the vector and eventually have to reallocate space
10280          for it, invalidating all copies of pointers into the previous
10281          contents.  */
10282       *dwo_file_slot = dwo_file;
10283     }
10284   else
10285     {
10286       if (dwarf_read_debug)
10287         {
10288           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10289                               virtual_dwo_name);
10290         }
10291       dwo_file = (struct dwo_file *) *dwo_file_slot;
10292     }
10293   do_cleanups (cleanups);
10294
10295   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10296   dwo_unit->dwo_file = dwo_file;
10297   dwo_unit->signature = signature;
10298   dwo_unit->section =
10299     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10300   *dwo_unit->section = sections.info_or_types;
10301   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10302
10303   return dwo_unit;
10304 }
10305
10306 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10307    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10308    piece within that section used by a TU/CU, return a virtual section
10309    of just that piece.  */
10310
10311 static struct dwarf2_section_info
10312 create_dwp_v2_section (struct dwarf2_section_info *section,
10313                        bfd_size_type offset, bfd_size_type size)
10314 {
10315   struct dwarf2_section_info result;
10316   asection *sectp;
10317
10318   gdb_assert (section != NULL);
10319   gdb_assert (!section->is_virtual);
10320
10321   memset (&result, 0, sizeof (result));
10322   result.s.containing_section = section;
10323   result.is_virtual = 1;
10324
10325   if (size == 0)
10326     return result;
10327
10328   sectp = get_section_bfd_section (section);
10329
10330   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10331      bounds of the real section.  This is a pretty-rare event, so just
10332      flag an error (easier) instead of a warning and trying to cope.  */
10333   if (sectp == NULL
10334       || offset + size > bfd_get_section_size (sectp))
10335     {
10336       bfd *abfd = sectp->owner;
10337
10338       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10339                " in section %s [in module %s]"),
10340              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10341              objfile_name (dwarf2_per_objfile->objfile));
10342     }
10343
10344   result.virtual_offset = offset;
10345   result.size = size;
10346   return result;
10347 }
10348
10349 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10350    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10351    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10352    This is for DWP version 2 files.  */
10353
10354 static struct dwo_unit *
10355 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10356                            uint32_t unit_index,
10357                            const char *comp_dir,
10358                            ULONGEST signature, int is_debug_types)
10359 {
10360   struct objfile *objfile = dwarf2_per_objfile->objfile;
10361   const struct dwp_hash_table *dwp_htab =
10362     is_debug_types ? dwp_file->tus : dwp_file->cus;
10363   bfd *dbfd = dwp_file->dbfd;
10364   const char *kind = is_debug_types ? "TU" : "CU";
10365   struct dwo_file *dwo_file;
10366   struct dwo_unit *dwo_unit;
10367   struct virtual_v2_dwo_sections sections;
10368   void **dwo_file_slot;
10369   char *virtual_dwo_name;
10370   struct cleanup *cleanups;
10371   int i;
10372
10373   gdb_assert (dwp_file->version == 2);
10374
10375   if (dwarf_read_debug)
10376     {
10377       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10378                           kind,
10379                           pulongest (unit_index), hex_string (signature),
10380                           dwp_file->name);
10381     }
10382
10383   /* Fetch the section offsets of this DWO unit.  */
10384
10385   memset (&sections, 0, sizeof (sections));
10386   cleanups = make_cleanup (null_cleanup, 0);
10387
10388   for (i = 0; i < dwp_htab->nr_columns; ++i)
10389     {
10390       uint32_t offset = read_4_bytes (dbfd,
10391                                       dwp_htab->section_pool.v2.offsets
10392                                       + (((unit_index - 1) * dwp_htab->nr_columns
10393                                           + i)
10394                                          * sizeof (uint32_t)));
10395       uint32_t size = read_4_bytes (dbfd,
10396                                     dwp_htab->section_pool.v2.sizes
10397                                     + (((unit_index - 1) * dwp_htab->nr_columns
10398                                         + i)
10399                                        * sizeof (uint32_t)));
10400
10401       switch (dwp_htab->section_pool.v2.section_ids[i])
10402         {
10403         case DW_SECT_INFO:
10404         case DW_SECT_TYPES:
10405           sections.info_or_types_offset = offset;
10406           sections.info_or_types_size = size;
10407           break;
10408         case DW_SECT_ABBREV:
10409           sections.abbrev_offset = offset;
10410           sections.abbrev_size = size;
10411           break;
10412         case DW_SECT_LINE:
10413           sections.line_offset = offset;
10414           sections.line_size = size;
10415           break;
10416         case DW_SECT_LOC:
10417           sections.loc_offset = offset;
10418           sections.loc_size = size;
10419           break;
10420         case DW_SECT_STR_OFFSETS:
10421           sections.str_offsets_offset = offset;
10422           sections.str_offsets_size = size;
10423           break;
10424         case DW_SECT_MACINFO:
10425           sections.macinfo_offset = offset;
10426           sections.macinfo_size = size;
10427           break;
10428         case DW_SECT_MACRO:
10429           sections.macro_offset = offset;
10430           sections.macro_size = size;
10431           break;
10432         }
10433     }
10434
10435   /* It's easier for the rest of the code if we fake a struct dwo_file and
10436      have dwo_unit "live" in that.  At least for now.
10437
10438      The DWP file can be made up of a random collection of CUs and TUs.
10439      However, for each CU + set of TUs that came from the same original DWO
10440      file, we can combine them back into a virtual DWO file to save space
10441      (fewer struct dwo_file objects to allocate).  Remember that for really
10442      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10443
10444   virtual_dwo_name =
10445     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10446                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10447                 (long) (sections.line_size ? sections.line_offset : 0),
10448                 (long) (sections.loc_size ? sections.loc_offset : 0),
10449                 (long) (sections.str_offsets_size
10450                         ? sections.str_offsets_offset : 0));
10451   make_cleanup (xfree, virtual_dwo_name);
10452   /* Can we use an existing virtual DWO file?  */
10453   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10454   /* Create one if necessary.  */
10455   if (*dwo_file_slot == NULL)
10456     {
10457       if (dwarf_read_debug)
10458         {
10459           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10460                               virtual_dwo_name);
10461         }
10462       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10463       dwo_file->dwo_name
10464         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10465                                         virtual_dwo_name,
10466                                         strlen (virtual_dwo_name));
10467       dwo_file->comp_dir = comp_dir;
10468       dwo_file->sections.abbrev =
10469         create_dwp_v2_section (&dwp_file->sections.abbrev,
10470                                sections.abbrev_offset, sections.abbrev_size);
10471       dwo_file->sections.line =
10472         create_dwp_v2_section (&dwp_file->sections.line,
10473                                sections.line_offset, sections.line_size);
10474       dwo_file->sections.loc =
10475         create_dwp_v2_section (&dwp_file->sections.loc,
10476                                sections.loc_offset, sections.loc_size);
10477       dwo_file->sections.macinfo =
10478         create_dwp_v2_section (&dwp_file->sections.macinfo,
10479                                sections.macinfo_offset, sections.macinfo_size);
10480       dwo_file->sections.macro =
10481         create_dwp_v2_section (&dwp_file->sections.macro,
10482                                sections.macro_offset, sections.macro_size);
10483       dwo_file->sections.str_offsets =
10484         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10485                                sections.str_offsets_offset,
10486                                sections.str_offsets_size);
10487       /* The "str" section is global to the entire DWP file.  */
10488       dwo_file->sections.str = dwp_file->sections.str;
10489       /* The info or types section is assigned below to dwo_unit,
10490          there's no need to record it in dwo_file.
10491          Also, we can't simply record type sections in dwo_file because
10492          we record a pointer into the vector in dwo_unit.  As we collect more
10493          types we'll grow the vector and eventually have to reallocate space
10494          for it, invalidating all copies of pointers into the previous
10495          contents.  */
10496       *dwo_file_slot = dwo_file;
10497     }
10498   else
10499     {
10500       if (dwarf_read_debug)
10501         {
10502           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10503                               virtual_dwo_name);
10504         }
10505       dwo_file = (struct dwo_file *) *dwo_file_slot;
10506     }
10507   do_cleanups (cleanups);
10508
10509   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10510   dwo_unit->dwo_file = dwo_file;
10511   dwo_unit->signature = signature;
10512   dwo_unit->section =
10513     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10514   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10515                                               ? &dwp_file->sections.types
10516                                               : &dwp_file->sections.info,
10517                                               sections.info_or_types_offset,
10518                                               sections.info_or_types_size);
10519   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10520
10521   return dwo_unit;
10522 }
10523
10524 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10525    Returns NULL if the signature isn't found.  */
10526
10527 static struct dwo_unit *
10528 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10529                         ULONGEST signature, int is_debug_types)
10530 {
10531   const struct dwp_hash_table *dwp_htab =
10532     is_debug_types ? dwp_file->tus : dwp_file->cus;
10533   bfd *dbfd = dwp_file->dbfd;
10534   uint32_t mask = dwp_htab->nr_slots - 1;
10535   uint32_t hash = signature & mask;
10536   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10537   unsigned int i;
10538   void **slot;
10539   struct dwo_unit find_dwo_cu;
10540
10541   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10542   find_dwo_cu.signature = signature;
10543   slot = htab_find_slot (is_debug_types
10544                          ? dwp_file->loaded_tus
10545                          : dwp_file->loaded_cus,
10546                          &find_dwo_cu, INSERT);
10547
10548   if (*slot != NULL)
10549     return (struct dwo_unit *) *slot;
10550
10551   /* Use a for loop so that we don't loop forever on bad debug info.  */
10552   for (i = 0; i < dwp_htab->nr_slots; ++i)
10553     {
10554       ULONGEST signature_in_table;
10555
10556       signature_in_table =
10557         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10558       if (signature_in_table == signature)
10559         {
10560           uint32_t unit_index =
10561             read_4_bytes (dbfd,
10562                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10563
10564           if (dwp_file->version == 1)
10565             {
10566               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10567                                                  comp_dir, signature,
10568                                                  is_debug_types);
10569             }
10570           else
10571             {
10572               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10573                                                  comp_dir, signature,
10574                                                  is_debug_types);
10575             }
10576           return (struct dwo_unit *) *slot;
10577         }
10578       if (signature_in_table == 0)
10579         return NULL;
10580       hash = (hash + hash2) & mask;
10581     }
10582
10583   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10584            " [in module %s]"),
10585          dwp_file->name);
10586 }
10587
10588 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10589    Open the file specified by FILE_NAME and hand it off to BFD for
10590    preliminary analysis.  Return a newly initialized bfd *, which
10591    includes a canonicalized copy of FILE_NAME.
10592    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10593    SEARCH_CWD is true if the current directory is to be searched.
10594    It will be searched before debug-file-directory.
10595    If successful, the file is added to the bfd include table of the
10596    objfile's bfd (see gdb_bfd_record_inclusion).
10597    If unable to find/open the file, return NULL.
10598    NOTE: This function is derived from symfile_bfd_open.  */
10599
10600 static gdb_bfd_ref_ptr
10601 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10602 {
10603   int desc, flags;
10604   char *absolute_name;
10605   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10606      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10607      to debug_file_directory.  */
10608   char *search_path;
10609   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10610
10611   if (search_cwd)
10612     {
10613       if (*debug_file_directory != '\0')
10614         search_path = concat (".", dirname_separator_string,
10615                               debug_file_directory, (char *) NULL);
10616       else
10617         search_path = xstrdup (".");
10618     }
10619   else
10620     search_path = xstrdup (debug_file_directory);
10621
10622   flags = OPF_RETURN_REALPATH;
10623   if (is_dwp)
10624     flags |= OPF_SEARCH_IN_PATH;
10625   desc = openp (search_path, flags, file_name,
10626                 O_RDONLY | O_BINARY, &absolute_name);
10627   xfree (search_path);
10628   if (desc < 0)
10629     return NULL;
10630
10631   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10632   xfree (absolute_name);
10633   if (sym_bfd == NULL)
10634     return NULL;
10635   bfd_set_cacheable (sym_bfd.get (), 1);
10636
10637   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10638     return NULL;
10639
10640   /* Success.  Record the bfd as having been included by the objfile's bfd.
10641      This is important because things like demangled_names_hash lives in the
10642      objfile's per_bfd space and may have references to things like symbol
10643      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10644   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10645
10646   return sym_bfd;
10647 }
10648
10649 /* Try to open DWO file FILE_NAME.
10650    COMP_DIR is the DW_AT_comp_dir attribute.
10651    The result is the bfd handle of the file.
10652    If there is a problem finding or opening the file, return NULL.
10653    Upon success, the canonicalized path of the file is stored in the bfd,
10654    same as symfile_bfd_open.  */
10655
10656 static gdb_bfd_ref_ptr
10657 open_dwo_file (const char *file_name, const char *comp_dir)
10658 {
10659   if (IS_ABSOLUTE_PATH (file_name))
10660     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10661
10662   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10663
10664   if (comp_dir != NULL)
10665     {
10666       char *path_to_try = concat (comp_dir, SLASH_STRING,
10667                                   file_name, (char *) NULL);
10668
10669       /* NOTE: If comp_dir is a relative path, this will also try the
10670          search path, which seems useful.  */
10671       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10672                                                 1 /*search_cwd*/));
10673       xfree (path_to_try);
10674       if (abfd != NULL)
10675         return abfd;
10676     }
10677
10678   /* That didn't work, try debug-file-directory, which, despite its name,
10679      is a list of paths.  */
10680
10681   if (*debug_file_directory == '\0')
10682     return NULL;
10683
10684   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10685 }
10686
10687 /* This function is mapped across the sections and remembers the offset and
10688    size of each of the DWO debugging sections we are interested in.  */
10689
10690 static void
10691 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10692 {
10693   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10694   const struct dwop_section_names *names = &dwop_section_names;
10695
10696   if (section_is_p (sectp->name, &names->abbrev_dwo))
10697     {
10698       dwo_sections->abbrev.s.section = sectp;
10699       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10700     }
10701   else if (section_is_p (sectp->name, &names->info_dwo))
10702     {
10703       dwo_sections->info.s.section = sectp;
10704       dwo_sections->info.size = bfd_get_section_size (sectp);
10705     }
10706   else if (section_is_p (sectp->name, &names->line_dwo))
10707     {
10708       dwo_sections->line.s.section = sectp;
10709       dwo_sections->line.size = bfd_get_section_size (sectp);
10710     }
10711   else if (section_is_p (sectp->name, &names->loc_dwo))
10712     {
10713       dwo_sections->loc.s.section = sectp;
10714       dwo_sections->loc.size = bfd_get_section_size (sectp);
10715     }
10716   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10717     {
10718       dwo_sections->macinfo.s.section = sectp;
10719       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10720     }
10721   else if (section_is_p (sectp->name, &names->macro_dwo))
10722     {
10723       dwo_sections->macro.s.section = sectp;
10724       dwo_sections->macro.size = bfd_get_section_size (sectp);
10725     }
10726   else if (section_is_p (sectp->name, &names->str_dwo))
10727     {
10728       dwo_sections->str.s.section = sectp;
10729       dwo_sections->str.size = bfd_get_section_size (sectp);
10730     }
10731   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10732     {
10733       dwo_sections->str_offsets.s.section = sectp;
10734       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10735     }
10736   else if (section_is_p (sectp->name, &names->types_dwo))
10737     {
10738       struct dwarf2_section_info type_section;
10739
10740       memset (&type_section, 0, sizeof (type_section));
10741       type_section.s.section = sectp;
10742       type_section.size = bfd_get_section_size (sectp);
10743       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10744                      &type_section);
10745     }
10746 }
10747
10748 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10749    by PER_CU.  This is for the non-DWP case.
10750    The result is NULL if DWO_NAME can't be found.  */
10751
10752 static struct dwo_file *
10753 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10754                         const char *dwo_name, const char *comp_dir)
10755 {
10756   struct objfile *objfile = dwarf2_per_objfile->objfile;
10757   struct dwo_file *dwo_file;
10758   struct cleanup *cleanups;
10759
10760   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10761   if (dbfd == NULL)
10762     {
10763       if (dwarf_read_debug)
10764         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10765       return NULL;
10766     }
10767   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10768   dwo_file->dwo_name = dwo_name;
10769   dwo_file->comp_dir = comp_dir;
10770   dwo_file->dbfd = dbfd.release ();
10771
10772   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10773
10774   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10775                          &dwo_file->sections);
10776
10777   dwo_file->cu = create_dwo_cu (dwo_file);
10778
10779   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10780                                  dwo_file->tus);
10781
10782   discard_cleanups (cleanups);
10783
10784   if (dwarf_read_debug)
10785     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10786
10787   return dwo_file;
10788 }
10789
10790 /* This function is mapped across the sections and remembers the offset and
10791    size of each of the DWP debugging sections common to version 1 and 2 that
10792    we are interested in.  */
10793
10794 static void
10795 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10796                                    void *dwp_file_ptr)
10797 {
10798   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10799   const struct dwop_section_names *names = &dwop_section_names;
10800   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10801
10802   /* Record the ELF section number for later lookup: this is what the
10803      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10804   gdb_assert (elf_section_nr < dwp_file->num_sections);
10805   dwp_file->elf_sections[elf_section_nr] = sectp;
10806
10807   /* Look for specific sections that we need.  */
10808   if (section_is_p (sectp->name, &names->str_dwo))
10809     {
10810       dwp_file->sections.str.s.section = sectp;
10811       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10812     }
10813   else if (section_is_p (sectp->name, &names->cu_index))
10814     {
10815       dwp_file->sections.cu_index.s.section = sectp;
10816       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10817     }
10818   else if (section_is_p (sectp->name, &names->tu_index))
10819     {
10820       dwp_file->sections.tu_index.s.section = sectp;
10821       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10822     }
10823 }
10824
10825 /* This function is mapped across the sections and remembers the offset and
10826    size of each of the DWP version 2 debugging sections that we are interested
10827    in.  This is split into a separate function because we don't know if we
10828    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10829
10830 static void
10831 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10832 {
10833   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10834   const struct dwop_section_names *names = &dwop_section_names;
10835   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10836
10837   /* Record the ELF section number for later lookup: this is what the
10838      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10839   gdb_assert (elf_section_nr < dwp_file->num_sections);
10840   dwp_file->elf_sections[elf_section_nr] = sectp;
10841
10842   /* Look for specific sections that we need.  */
10843   if (section_is_p (sectp->name, &names->abbrev_dwo))
10844     {
10845       dwp_file->sections.abbrev.s.section = sectp;
10846       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10847     }
10848   else if (section_is_p (sectp->name, &names->info_dwo))
10849     {
10850       dwp_file->sections.info.s.section = sectp;
10851       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10852     }
10853   else if (section_is_p (sectp->name, &names->line_dwo))
10854     {
10855       dwp_file->sections.line.s.section = sectp;
10856       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10857     }
10858   else if (section_is_p (sectp->name, &names->loc_dwo))
10859     {
10860       dwp_file->sections.loc.s.section = sectp;
10861       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10862     }
10863   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10864     {
10865       dwp_file->sections.macinfo.s.section = sectp;
10866       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10867     }
10868   else if (section_is_p (sectp->name, &names->macro_dwo))
10869     {
10870       dwp_file->sections.macro.s.section = sectp;
10871       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10872     }
10873   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10874     {
10875       dwp_file->sections.str_offsets.s.section = sectp;
10876       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10877     }
10878   else if (section_is_p (sectp->name, &names->types_dwo))
10879     {
10880       dwp_file->sections.types.s.section = sectp;
10881       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10882     }
10883 }
10884
10885 /* Hash function for dwp_file loaded CUs/TUs.  */
10886
10887 static hashval_t
10888 hash_dwp_loaded_cutus (const void *item)
10889 {
10890   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10891
10892   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10893   return dwo_unit->signature;
10894 }
10895
10896 /* Equality function for dwp_file loaded CUs/TUs.  */
10897
10898 static int
10899 eq_dwp_loaded_cutus (const void *a, const void *b)
10900 {
10901   const struct dwo_unit *dua = (const struct dwo_unit *) a;
10902   const struct dwo_unit *dub = (const struct dwo_unit *) b;
10903
10904   return dua->signature == dub->signature;
10905 }
10906
10907 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10908
10909 static htab_t
10910 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10911 {
10912   return htab_create_alloc_ex (3,
10913                                hash_dwp_loaded_cutus,
10914                                eq_dwp_loaded_cutus,
10915                                NULL,
10916                                &objfile->objfile_obstack,
10917                                hashtab_obstack_allocate,
10918                                dummy_obstack_deallocate);
10919 }
10920
10921 /* Try to open DWP file FILE_NAME.
10922    The result is the bfd handle of the file.
10923    If there is a problem finding or opening the file, return NULL.
10924    Upon success, the canonicalized path of the file is stored in the bfd,
10925    same as symfile_bfd_open.  */
10926
10927 static gdb_bfd_ref_ptr
10928 open_dwp_file (const char *file_name)
10929 {
10930   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
10931                                             1 /*search_cwd*/));
10932   if (abfd != NULL)
10933     return abfd;
10934
10935   /* Work around upstream bug 15652.
10936      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10937      [Whether that's a "bug" is debatable, but it is getting in our way.]
10938      We have no real idea where the dwp file is, because gdb's realpath-ing
10939      of the executable's path may have discarded the needed info.
10940      [IWBN if the dwp file name was recorded in the executable, akin to
10941      .gnu_debuglink, but that doesn't exist yet.]
10942      Strip the directory from FILE_NAME and search again.  */
10943   if (*debug_file_directory != '\0')
10944     {
10945       /* Don't implicitly search the current directory here.
10946          If the user wants to search "." to handle this case,
10947          it must be added to debug-file-directory.  */
10948       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10949                                  0 /*search_cwd*/);
10950     }
10951
10952   return NULL;
10953 }
10954
10955 /* Initialize the use of the DWP file for the current objfile.
10956    By convention the name of the DWP file is ${objfile}.dwp.
10957    The result is NULL if it can't be found.  */
10958
10959 static struct dwp_file *
10960 open_and_init_dwp_file (void)
10961 {
10962   struct objfile *objfile = dwarf2_per_objfile->objfile;
10963   struct dwp_file *dwp_file;
10964
10965   /* Try to find first .dwp for the binary file before any symbolic links
10966      resolving.  */
10967
10968   /* If the objfile is a debug file, find the name of the real binary
10969      file and get the name of dwp file from there.  */
10970   std::string dwp_name;
10971   if (objfile->separate_debug_objfile_backlink != NULL)
10972     {
10973       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
10974       const char *backlink_basename = lbasename (backlink->original_name);
10975
10976       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
10977     }
10978   else
10979     dwp_name = objfile->original_name;
10980
10981   dwp_name += ".dwp";
10982
10983   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
10984   if (dbfd == NULL
10985       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10986     {
10987       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10988       dwp_name = objfile_name (objfile);
10989       dwp_name += ".dwp";
10990       dbfd = open_dwp_file (dwp_name.c_str ());
10991     }
10992
10993   if (dbfd == NULL)
10994     {
10995       if (dwarf_read_debug)
10996         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
10997       return NULL;
10998     }
10999   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11000   dwp_file->name = bfd_get_filename (dbfd.get ());
11001   dwp_file->dbfd = dbfd.release ();
11002
11003   /* +1: section 0 is unused */
11004   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11005   dwp_file->elf_sections =
11006     OBSTACK_CALLOC (&objfile->objfile_obstack,
11007                     dwp_file->num_sections, asection *);
11008
11009   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11010                          dwp_file);
11011
11012   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11013
11014   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11015
11016   /* The DWP file version is stored in the hash table.  Oh well.  */
11017   if (dwp_file->cus->version != dwp_file->tus->version)
11018     {
11019       /* Technically speaking, we should try to limp along, but this is
11020          pretty bizarre.  We use pulongest here because that's the established
11021          portability solution (e.g, we cannot use %u for uint32_t).  */
11022       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11023                " TU version %s [in DWP file %s]"),
11024              pulongest (dwp_file->cus->version),
11025              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11026     }
11027   dwp_file->version = dwp_file->cus->version;
11028
11029   if (dwp_file->version == 2)
11030     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11031                            dwp_file);
11032
11033   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11034   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11035
11036   if (dwarf_read_debug)
11037     {
11038       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11039       fprintf_unfiltered (gdb_stdlog,
11040                           "    %s CUs, %s TUs\n",
11041                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11042                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11043     }
11044
11045   return dwp_file;
11046 }
11047
11048 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11049
11050 static struct dwp_file *
11051 get_dwp_file (void)
11052 {
11053   if (! dwarf2_per_objfile->dwp_checked)
11054     {
11055       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11056       dwarf2_per_objfile->dwp_checked = 1;
11057     }
11058   return dwarf2_per_objfile->dwp_file;
11059 }
11060
11061 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11062    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11063    or in the DWP file for the objfile, referenced by THIS_UNIT.
11064    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11065    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11066
11067    This is called, for example, when wanting to read a variable with a
11068    complex location.  Therefore we don't want to do file i/o for every call.
11069    Therefore we don't want to look for a DWO file on every call.
11070    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11071    then we check if we've already seen DWO_NAME, and only THEN do we check
11072    for a DWO file.
11073
11074    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11075    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11076
11077 static struct dwo_unit *
11078 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11079                  const char *dwo_name, const char *comp_dir,
11080                  ULONGEST signature, int is_debug_types)
11081 {
11082   struct objfile *objfile = dwarf2_per_objfile->objfile;
11083   const char *kind = is_debug_types ? "TU" : "CU";
11084   void **dwo_file_slot;
11085   struct dwo_file *dwo_file;
11086   struct dwp_file *dwp_file;
11087
11088   /* First see if there's a DWP file.
11089      If we have a DWP file but didn't find the DWO inside it, don't
11090      look for the original DWO file.  It makes gdb behave differently
11091      depending on whether one is debugging in the build tree.  */
11092
11093   dwp_file = get_dwp_file ();
11094   if (dwp_file != NULL)
11095     {
11096       const struct dwp_hash_table *dwp_htab =
11097         is_debug_types ? dwp_file->tus : dwp_file->cus;
11098
11099       if (dwp_htab != NULL)
11100         {
11101           struct dwo_unit *dwo_cutu =
11102             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11103                                     signature, is_debug_types);
11104
11105           if (dwo_cutu != NULL)
11106             {
11107               if (dwarf_read_debug)
11108                 {
11109                   fprintf_unfiltered (gdb_stdlog,
11110                                       "Virtual DWO %s %s found: @%s\n",
11111                                       kind, hex_string (signature),
11112                                       host_address_to_string (dwo_cutu));
11113                 }
11114               return dwo_cutu;
11115             }
11116         }
11117     }
11118   else
11119     {
11120       /* No DWP file, look for the DWO file.  */
11121
11122       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11123       if (*dwo_file_slot == NULL)
11124         {
11125           /* Read in the file and build a table of the CUs/TUs it contains.  */
11126           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11127         }
11128       /* NOTE: This will be NULL if unable to open the file.  */
11129       dwo_file = (struct dwo_file *) *dwo_file_slot;
11130
11131       if (dwo_file != NULL)
11132         {
11133           struct dwo_unit *dwo_cutu = NULL;
11134
11135           if (is_debug_types && dwo_file->tus)
11136             {
11137               struct dwo_unit find_dwo_cutu;
11138
11139               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11140               find_dwo_cutu.signature = signature;
11141               dwo_cutu
11142                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11143             }
11144           else if (!is_debug_types && dwo_file->cu)
11145             {
11146               if (signature == dwo_file->cu->signature)
11147                 dwo_cutu = dwo_file->cu;
11148             }
11149
11150           if (dwo_cutu != NULL)
11151             {
11152               if (dwarf_read_debug)
11153                 {
11154                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11155                                       kind, dwo_name, hex_string (signature),
11156                                       host_address_to_string (dwo_cutu));
11157                 }
11158               return dwo_cutu;
11159             }
11160         }
11161     }
11162
11163   /* We didn't find it.  This could mean a dwo_id mismatch, or
11164      someone deleted the DWO/DWP file, or the search path isn't set up
11165      correctly to find the file.  */
11166
11167   if (dwarf_read_debug)
11168     {
11169       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11170                           kind, dwo_name, hex_string (signature));
11171     }
11172
11173   /* This is a warning and not a complaint because it can be caused by
11174      pilot error (e.g., user accidentally deleting the DWO).  */
11175   {
11176     /* Print the name of the DWP file if we looked there, helps the user
11177        better diagnose the problem.  */
11178     char *dwp_text = NULL;
11179     struct cleanup *cleanups;
11180
11181     if (dwp_file != NULL)
11182       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11183     cleanups = make_cleanup (xfree, dwp_text);
11184
11185     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11186                " [in module %s]"),
11187              kind, dwo_name, hex_string (signature),
11188              dwp_text != NULL ? dwp_text : "",
11189              this_unit->is_debug_types ? "TU" : "CU",
11190              to_underlying (this_unit->sect_off), objfile_name (objfile));
11191
11192     do_cleanups (cleanups);
11193   }
11194   return NULL;
11195 }
11196
11197 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11198    See lookup_dwo_cutu_unit for details.  */
11199
11200 static struct dwo_unit *
11201 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11202                       const char *dwo_name, const char *comp_dir,
11203                       ULONGEST signature)
11204 {
11205   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11206 }
11207
11208 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11209    See lookup_dwo_cutu_unit for details.  */
11210
11211 static struct dwo_unit *
11212 lookup_dwo_type_unit (struct signatured_type *this_tu,
11213                       const char *dwo_name, const char *comp_dir)
11214 {
11215   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11216 }
11217
11218 /* Traversal function for queue_and_load_all_dwo_tus.  */
11219
11220 static int
11221 queue_and_load_dwo_tu (void **slot, void *info)
11222 {
11223   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11224   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11225   ULONGEST signature = dwo_unit->signature;
11226   struct signatured_type *sig_type =
11227     lookup_dwo_signatured_type (per_cu->cu, signature);
11228
11229   if (sig_type != NULL)
11230     {
11231       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11232
11233       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11234          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11235          while processing PER_CU.  */
11236       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11237         load_full_type_unit (sig_cu);
11238       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11239     }
11240
11241   return 1;
11242 }
11243
11244 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11245    The DWO may have the only definition of the type, though it may not be
11246    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11247    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11248
11249 static void
11250 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11251 {
11252   struct dwo_unit *dwo_unit;
11253   struct dwo_file *dwo_file;
11254
11255   gdb_assert (!per_cu->is_debug_types);
11256   gdb_assert (get_dwp_file () == NULL);
11257   gdb_assert (per_cu->cu != NULL);
11258
11259   dwo_unit = per_cu->cu->dwo_unit;
11260   gdb_assert (dwo_unit != NULL);
11261
11262   dwo_file = dwo_unit->dwo_file;
11263   if (dwo_file->tus != NULL)
11264     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11265 }
11266
11267 /* Free all resources associated with DWO_FILE.
11268    Close the DWO file and munmap the sections.
11269    All memory should be on the objfile obstack.  */
11270
11271 static void
11272 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11273 {
11274
11275   /* Note: dbfd is NULL for virtual DWO files.  */
11276   gdb_bfd_unref (dwo_file->dbfd);
11277
11278   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11279 }
11280
11281 /* Wrapper for free_dwo_file for use in cleanups.  */
11282
11283 static void
11284 free_dwo_file_cleanup (void *arg)
11285 {
11286   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11287   struct objfile *objfile = dwarf2_per_objfile->objfile;
11288
11289   free_dwo_file (dwo_file, objfile);
11290 }
11291
11292 /* Traversal function for free_dwo_files.  */
11293
11294 static int
11295 free_dwo_file_from_slot (void **slot, void *info)
11296 {
11297   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11298   struct objfile *objfile = (struct objfile *) info;
11299
11300   free_dwo_file (dwo_file, objfile);
11301
11302   return 1;
11303 }
11304
11305 /* Free all resources associated with DWO_FILES.  */
11306
11307 static void
11308 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11309 {
11310   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11311 }
11312 \f
11313 /* Read in various DIEs.  */
11314
11315 /* qsort helper for inherit_abstract_dies.  */
11316
11317 static int
11318 unsigned_int_compar (const void *ap, const void *bp)
11319 {
11320   unsigned int a = *(unsigned int *) ap;
11321   unsigned int b = *(unsigned int *) bp;
11322
11323   return (a > b) - (b > a);
11324 }
11325
11326 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11327    Inherit only the children of the DW_AT_abstract_origin DIE not being
11328    already referenced by DW_AT_abstract_origin from the children of the
11329    current DIE.  */
11330
11331 static void
11332 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11333 {
11334   struct die_info *child_die;
11335   unsigned die_children_count;
11336   /* CU offsets which were referenced by children of the current DIE.  */
11337   sect_offset *offsets;
11338   sect_offset *offsets_end, *offsetp;
11339   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11340   struct die_info *origin_die;
11341   /* Iterator of the ORIGIN_DIE children.  */
11342   struct die_info *origin_child_die;
11343   struct cleanup *cleanups;
11344   struct attribute *attr;
11345   struct dwarf2_cu *origin_cu;
11346   struct pending **origin_previous_list_in_scope;
11347
11348   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11349   if (!attr)
11350     return;
11351
11352   /* Note that following die references may follow to a die in a
11353      different cu.  */
11354
11355   origin_cu = cu;
11356   origin_die = follow_die_ref (die, attr, &origin_cu);
11357
11358   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11359      symbols in.  */
11360   origin_previous_list_in_scope = origin_cu->list_in_scope;
11361   origin_cu->list_in_scope = cu->list_in_scope;
11362
11363   if (die->tag != origin_die->tag
11364       && !(die->tag == DW_TAG_inlined_subroutine
11365            && origin_die->tag == DW_TAG_subprogram))
11366     complaint (&symfile_complaints,
11367                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11368                to_underlying (die->sect_off),
11369                to_underlying (origin_die->sect_off));
11370
11371   child_die = die->child;
11372   die_children_count = 0;
11373   while (child_die && child_die->tag)
11374     {
11375       child_die = sibling_die (child_die);
11376       die_children_count++;
11377     }
11378   offsets = XNEWVEC (sect_offset, die_children_count);
11379   cleanups = make_cleanup (xfree, offsets);
11380
11381   offsets_end = offsets;
11382   for (child_die = die->child;
11383        child_die && child_die->tag;
11384        child_die = sibling_die (child_die))
11385     {
11386       struct die_info *child_origin_die;
11387       struct dwarf2_cu *child_origin_cu;
11388
11389       /* We are trying to process concrete instance entries:
11390          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11391          it's not relevant to our analysis here. i.e. detecting DIEs that are
11392          present in the abstract instance but not referenced in the concrete
11393          one.  */
11394       if (child_die->tag == DW_TAG_call_site
11395           || child_die->tag == DW_TAG_GNU_call_site)
11396         continue;
11397
11398       /* For each CHILD_DIE, find the corresponding child of
11399          ORIGIN_DIE.  If there is more than one layer of
11400          DW_AT_abstract_origin, follow them all; there shouldn't be,
11401          but GCC versions at least through 4.4 generate this (GCC PR
11402          40573).  */
11403       child_origin_die = child_die;
11404       child_origin_cu = cu;
11405       while (1)
11406         {
11407           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11408                               child_origin_cu);
11409           if (attr == NULL)
11410             break;
11411           child_origin_die = follow_die_ref (child_origin_die, attr,
11412                                              &child_origin_cu);
11413         }
11414
11415       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11416          counterpart may exist.  */
11417       if (child_origin_die != child_die)
11418         {
11419           if (child_die->tag != child_origin_die->tag
11420               && !(child_die->tag == DW_TAG_inlined_subroutine
11421                    && child_origin_die->tag == DW_TAG_subprogram))
11422             complaint (&symfile_complaints,
11423                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11424                          "different tags"),
11425                        to_underlying (child_die->sect_off),
11426                        to_underlying (child_origin_die->sect_off));
11427           if (child_origin_die->parent != origin_die)
11428             complaint (&symfile_complaints,
11429                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11430                          "different parents"),
11431                        to_underlying (child_die->sect_off),
11432                        to_underlying (child_origin_die->sect_off));
11433           else
11434             *offsets_end++ = child_origin_die->sect_off;
11435         }
11436     }
11437   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11438          unsigned_int_compar);
11439   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11440     if (offsetp[-1] == *offsetp)
11441       complaint (&symfile_complaints,
11442                  _("Multiple children of DIE 0x%x refer "
11443                    "to DIE 0x%x as their abstract origin"),
11444                  to_underlying (die->sect_off), to_underlying (*offsetp));
11445
11446   offsetp = offsets;
11447   origin_child_die = origin_die->child;
11448   while (origin_child_die && origin_child_die->tag)
11449     {
11450       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11451       while (offsetp < offsets_end
11452              && *offsetp < origin_child_die->sect_off)
11453         offsetp++;
11454       if (offsetp >= offsets_end
11455           || *offsetp > origin_child_die->sect_off)
11456         {
11457           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11458              Check whether we're already processing ORIGIN_CHILD_DIE.
11459              This can happen with mutually referenced abstract_origins.
11460              PR 16581.  */
11461           if (!origin_child_die->in_process)
11462             process_die (origin_child_die, origin_cu);
11463         }
11464       origin_child_die = sibling_die (origin_child_die);
11465     }
11466   origin_cu->list_in_scope = origin_previous_list_in_scope;
11467
11468   do_cleanups (cleanups);
11469 }
11470
11471 static void
11472 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11473 {
11474   struct objfile *objfile = cu->objfile;
11475   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11476   struct context_stack *newobj;
11477   CORE_ADDR lowpc;
11478   CORE_ADDR highpc;
11479   struct die_info *child_die;
11480   struct attribute *attr, *call_line, *call_file;
11481   const char *name;
11482   CORE_ADDR baseaddr;
11483   struct block *block;
11484   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11485   VEC (symbolp) *template_args = NULL;
11486   struct template_symbol *templ_func = NULL;
11487
11488   if (inlined_func)
11489     {
11490       /* If we do not have call site information, we can't show the
11491          caller of this inlined function.  That's too confusing, so
11492          only use the scope for local variables.  */
11493       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11494       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11495       if (call_line == NULL || call_file == NULL)
11496         {
11497           read_lexical_block_scope (die, cu);
11498           return;
11499         }
11500     }
11501
11502   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11503
11504   name = dwarf2_name (die, cu);
11505
11506   /* Ignore functions with missing or empty names.  These are actually
11507      illegal according to the DWARF standard.  */
11508   if (name == NULL)
11509     {
11510       complaint (&symfile_complaints,
11511                  _("missing name for subprogram DIE at %d"),
11512                  to_underlying (die->sect_off));
11513       return;
11514     }
11515
11516   /* Ignore functions with missing or invalid low and high pc attributes.  */
11517   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11518       <= PC_BOUNDS_INVALID)
11519     {
11520       attr = dwarf2_attr (die, DW_AT_external, cu);
11521       if (!attr || !DW_UNSND (attr))
11522         complaint (&symfile_complaints,
11523                    _("cannot get low and high bounds "
11524                      "for subprogram DIE at %d"),
11525                    to_underlying (die->sect_off));
11526       return;
11527     }
11528
11529   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11530   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11531
11532   /* If we have any template arguments, then we must allocate a
11533      different sort of symbol.  */
11534   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11535     {
11536       if (child_die->tag == DW_TAG_template_type_param
11537           || child_die->tag == DW_TAG_template_value_param)
11538         {
11539           templ_func = allocate_template_symbol (objfile);
11540           templ_func->base.is_cplus_template_function = 1;
11541           break;
11542         }
11543     }
11544
11545   newobj = push_context (0, lowpc);
11546   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11547                                (struct symbol *) templ_func);
11548
11549   /* If there is a location expression for DW_AT_frame_base, record
11550      it.  */
11551   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11552   if (attr)
11553     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11554
11555   /* If there is a location for the static link, record it.  */
11556   newobj->static_link = NULL;
11557   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11558   if (attr)
11559     {
11560       newobj->static_link
11561         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11562       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11563     }
11564
11565   cu->list_in_scope = &local_symbols;
11566
11567   if (die->child != NULL)
11568     {
11569       child_die = die->child;
11570       while (child_die && child_die->tag)
11571         {
11572           if (child_die->tag == DW_TAG_template_type_param
11573               || child_die->tag == DW_TAG_template_value_param)
11574             {
11575               struct symbol *arg = new_symbol (child_die, NULL, cu);
11576
11577               if (arg != NULL)
11578                 VEC_safe_push (symbolp, template_args, arg);
11579             }
11580           else
11581             process_die (child_die, cu);
11582           child_die = sibling_die (child_die);
11583         }
11584     }
11585
11586   inherit_abstract_dies (die, cu);
11587
11588   /* If we have a DW_AT_specification, we might need to import using
11589      directives from the context of the specification DIE.  See the
11590      comment in determine_prefix.  */
11591   if (cu->language == language_cplus
11592       && dwarf2_attr (die, DW_AT_specification, cu))
11593     {
11594       struct dwarf2_cu *spec_cu = cu;
11595       struct die_info *spec_die = die_specification (die, &spec_cu);
11596
11597       while (spec_die)
11598         {
11599           child_die = spec_die->child;
11600           while (child_die && child_die->tag)
11601             {
11602               if (child_die->tag == DW_TAG_imported_module)
11603                 process_die (child_die, spec_cu);
11604               child_die = sibling_die (child_die);
11605             }
11606
11607           /* In some cases, GCC generates specification DIEs that
11608              themselves contain DW_AT_specification attributes.  */
11609           spec_die = die_specification (spec_die, &spec_cu);
11610         }
11611     }
11612
11613   newobj = pop_context ();
11614   /* Make a block for the local symbols within.  */
11615   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11616                         newobj->static_link, lowpc, highpc);
11617
11618   /* For C++, set the block's scope.  */
11619   if ((cu->language == language_cplus
11620        || cu->language == language_fortran
11621        || cu->language == language_d
11622        || cu->language == language_rust)
11623       && cu->processing_has_namespace_info)
11624     block_set_scope (block, determine_prefix (die, cu),
11625                      &objfile->objfile_obstack);
11626
11627   /* If we have address ranges, record them.  */
11628   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11629
11630   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11631
11632   /* Attach template arguments to function.  */
11633   if (! VEC_empty (symbolp, template_args))
11634     {
11635       gdb_assert (templ_func != NULL);
11636
11637       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11638       templ_func->template_arguments
11639         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11640                      templ_func->n_template_arguments);
11641       memcpy (templ_func->template_arguments,
11642               VEC_address (symbolp, template_args),
11643               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11644       VEC_free (symbolp, template_args);
11645     }
11646
11647   /* In C++, we can have functions nested inside functions (e.g., when
11648      a function declares a class that has methods).  This means that
11649      when we finish processing a function scope, we may need to go
11650      back to building a containing block's symbol lists.  */
11651   local_symbols = newobj->locals;
11652   local_using_directives = newobj->local_using_directives;
11653
11654   /* If we've finished processing a top-level function, subsequent
11655      symbols go in the file symbol list.  */
11656   if (outermost_context_p ())
11657     cu->list_in_scope = &file_symbols;
11658 }
11659
11660 /* Process all the DIES contained within a lexical block scope.  Start
11661    a new scope, process the dies, and then close the scope.  */
11662
11663 static void
11664 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11665 {
11666   struct objfile *objfile = cu->objfile;
11667   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11668   struct context_stack *newobj;
11669   CORE_ADDR lowpc, highpc;
11670   struct die_info *child_die;
11671   CORE_ADDR baseaddr;
11672
11673   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11674
11675   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11676   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11677      as multiple lexical blocks?  Handling children in a sane way would
11678      be nasty.  Might be easier to properly extend generic blocks to
11679      describe ranges.  */
11680   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11681     {
11682     case PC_BOUNDS_NOT_PRESENT:
11683       /* DW_TAG_lexical_block has no attributes, process its children as if
11684          there was no wrapping by that DW_TAG_lexical_block.
11685          GCC does no longer produces such DWARF since GCC r224161.  */
11686       for (child_die = die->child;
11687            child_die != NULL && child_die->tag;
11688            child_die = sibling_die (child_die))
11689         process_die (child_die, cu);
11690       return;
11691     case PC_BOUNDS_INVALID:
11692       return;
11693     }
11694   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11695   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11696
11697   push_context (0, lowpc);
11698   if (die->child != NULL)
11699     {
11700       child_die = die->child;
11701       while (child_die && child_die->tag)
11702         {
11703           process_die (child_die, cu);
11704           child_die = sibling_die (child_die);
11705         }
11706     }
11707   inherit_abstract_dies (die, cu);
11708   newobj = pop_context ();
11709
11710   if (local_symbols != NULL || local_using_directives != NULL)
11711     {
11712       struct block *block
11713         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11714                         newobj->start_addr, highpc);
11715
11716       /* Note that recording ranges after traversing children, as we
11717          do here, means that recording a parent's ranges entails
11718          walking across all its children's ranges as they appear in
11719          the address map, which is quadratic behavior.
11720
11721          It would be nicer to record the parent's ranges before
11722          traversing its children, simply overriding whatever you find
11723          there.  But since we don't even decide whether to create a
11724          block until after we've traversed its children, that's hard
11725          to do.  */
11726       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11727     }
11728   local_symbols = newobj->locals;
11729   local_using_directives = newobj->local_using_directives;
11730 }
11731
11732 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11733
11734 static void
11735 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11736 {
11737   struct objfile *objfile = cu->objfile;
11738   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11739   CORE_ADDR pc, baseaddr;
11740   struct attribute *attr;
11741   struct call_site *call_site, call_site_local;
11742   void **slot;
11743   int nparams;
11744   struct die_info *child_die;
11745
11746   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11747
11748   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11749   if (attr == NULL)
11750     {
11751       /* This was a pre-DWARF-5 GNU extension alias
11752          for DW_AT_call_return_pc.  */
11753       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11754     }
11755   if (!attr)
11756     {
11757       complaint (&symfile_complaints,
11758                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11759                    "DIE 0x%x [in module %s]"),
11760                  to_underlying (die->sect_off), objfile_name (objfile));
11761       return;
11762     }
11763   pc = attr_value_as_address (attr) + baseaddr;
11764   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11765
11766   if (cu->call_site_htab == NULL)
11767     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11768                                                NULL, &objfile->objfile_obstack,
11769                                                hashtab_obstack_allocate, NULL);
11770   call_site_local.pc = pc;
11771   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11772   if (*slot != NULL)
11773     {
11774       complaint (&symfile_complaints,
11775                  _("Duplicate PC %s for DW_TAG_call_site "
11776                    "DIE 0x%x [in module %s]"),
11777                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11778                  objfile_name (objfile));
11779       return;
11780     }
11781
11782   /* Count parameters at the caller.  */
11783
11784   nparams = 0;
11785   for (child_die = die->child; child_die && child_die->tag;
11786        child_die = sibling_die (child_die))
11787     {
11788       if (child_die->tag != DW_TAG_call_site_parameter
11789           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11790         {
11791           complaint (&symfile_complaints,
11792                      _("Tag %d is not DW_TAG_call_site_parameter in "
11793                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11794                      child_die->tag, to_underlying (child_die->sect_off),
11795                      objfile_name (objfile));
11796           continue;
11797         }
11798
11799       nparams++;
11800     }
11801
11802   call_site
11803     = ((struct call_site *)
11804        obstack_alloc (&objfile->objfile_obstack,
11805                       sizeof (*call_site)
11806                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11807   *slot = call_site;
11808   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11809   call_site->pc = pc;
11810
11811   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11812       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11813     {
11814       struct die_info *func_die;
11815
11816       /* Skip also over DW_TAG_inlined_subroutine.  */
11817       for (func_die = die->parent;
11818            func_die && func_die->tag != DW_TAG_subprogram
11819            && func_die->tag != DW_TAG_subroutine_type;
11820            func_die = func_die->parent);
11821
11822       /* DW_AT_call_all_calls is a superset
11823          of DW_AT_call_all_tail_calls.  */
11824       if (func_die
11825           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11826           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11827           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11828           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11829         {
11830           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11831              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11832              both the initial caller containing the real return address PC and
11833              the final callee containing the current PC of a chain of tail
11834              calls do not need to have the tail call list complete.  But any
11835              function candidate for a virtual tail call frame searched via
11836              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11837              determined unambiguously.  */
11838         }
11839       else
11840         {
11841           struct type *func_type = NULL;
11842
11843           if (func_die)
11844             func_type = get_die_type (func_die, cu);
11845           if (func_type != NULL)
11846             {
11847               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11848
11849               /* Enlist this call site to the function.  */
11850               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11851               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11852             }
11853           else
11854             complaint (&symfile_complaints,
11855                        _("Cannot find function owning DW_TAG_call_site "
11856                          "DIE 0x%x [in module %s]"),
11857                        to_underlying (die->sect_off), objfile_name (objfile));
11858         }
11859     }
11860
11861   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11862   if (attr == NULL)
11863     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11864   if (attr == NULL)
11865     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11866   if (attr == NULL)
11867     {
11868       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
11869       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11870     }
11871   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11872   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11873     /* Keep NULL DWARF_BLOCK.  */;
11874   else if (attr_form_is_block (attr))
11875     {
11876       struct dwarf2_locexpr_baton *dlbaton;
11877
11878       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
11879       dlbaton->data = DW_BLOCK (attr)->data;
11880       dlbaton->size = DW_BLOCK (attr)->size;
11881       dlbaton->per_cu = cu->per_cu;
11882
11883       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11884     }
11885   else if (attr_form_is_ref (attr))
11886     {
11887       struct dwarf2_cu *target_cu = cu;
11888       struct die_info *target_die;
11889
11890       target_die = follow_die_ref (die, attr, &target_cu);
11891       gdb_assert (target_cu->objfile == objfile);
11892       if (die_is_declaration (target_die, target_cu))
11893         {
11894           const char *target_physname;
11895
11896           /* Prefer the mangled name; otherwise compute the demangled one.  */
11897           target_physname = dwarf2_string_attr (target_die,
11898                                                 DW_AT_linkage_name,
11899                                                 target_cu);
11900           if (target_physname == NULL)
11901             target_physname = dwarf2_string_attr (target_die,
11902                                                  DW_AT_MIPS_linkage_name,
11903                                                  target_cu);
11904           if (target_physname == NULL)
11905             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11906           if (target_physname == NULL)
11907             complaint (&symfile_complaints,
11908                        _("DW_AT_call_target target DIE has invalid "
11909                          "physname, for referencing DIE 0x%x [in module %s]"),
11910                        to_underlying (die->sect_off), objfile_name (objfile));
11911           else
11912             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11913         }
11914       else
11915         {
11916           CORE_ADDR lowpc;
11917
11918           /* DW_AT_entry_pc should be preferred.  */
11919           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
11920               <= PC_BOUNDS_INVALID)
11921             complaint (&symfile_complaints,
11922                        _("DW_AT_call_target target DIE has invalid "
11923                          "low pc, for referencing DIE 0x%x [in module %s]"),
11924                        to_underlying (die->sect_off), objfile_name (objfile));
11925           else
11926             {
11927               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11928               SET_FIELD_PHYSADDR (call_site->target, lowpc);
11929             }
11930         }
11931     }
11932   else
11933     complaint (&symfile_complaints,
11934                _("DW_TAG_call_site DW_AT_call_target is neither "
11935                  "block nor reference, for DIE 0x%x [in module %s]"),
11936                to_underlying (die->sect_off), objfile_name (objfile));
11937
11938   call_site->per_cu = cu->per_cu;
11939
11940   for (child_die = die->child;
11941        child_die && child_die->tag;
11942        child_die = sibling_die (child_die))
11943     {
11944       struct call_site_parameter *parameter;
11945       struct attribute *loc, *origin;
11946
11947       if (child_die->tag != DW_TAG_call_site_parameter
11948           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11949         {
11950           /* Already printed the complaint above.  */
11951           continue;
11952         }
11953
11954       gdb_assert (call_site->parameter_count < nparams);
11955       parameter = &call_site->parameter[call_site->parameter_count];
11956
11957       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11958          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11959          register is contained in DW_AT_call_value.  */
11960
11961       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11962       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
11963       if (origin == NULL)
11964         {
11965           /* This was a pre-DWARF-5 GNU extension alias
11966              for DW_AT_call_parameter.  */
11967           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11968         }
11969       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11970         {
11971           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11972
11973           sect_offset sect_off
11974             = (sect_offset) dwarf2_get_ref_die_offset (origin);
11975           if (!offset_in_cu_p (&cu->header, sect_off))
11976             {
11977               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11978                  binding can be done only inside one CU.  Such referenced DIE
11979                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11980               complaint (&symfile_complaints,
11981                          _("DW_AT_call_parameter offset is not in CU for "
11982                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11983                          to_underlying (child_die->sect_off),
11984                          objfile_name (objfile));
11985               continue;
11986             }
11987           parameter->u.param_cu_off
11988             = (cu_offset) (sect_off - cu->header.sect_off);
11989         }
11990       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11991         {
11992           complaint (&symfile_complaints,
11993                      _("No DW_FORM_block* DW_AT_location for "
11994                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11995                      to_underlying (child_die->sect_off), objfile_name (objfile));
11996           continue;
11997         }
11998       else
11999         {
12000           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12001             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12002           if (parameter->u.dwarf_reg != -1)
12003             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12004           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12005                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12006                                              &parameter->u.fb_offset))
12007             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12008           else
12009             {
12010               complaint (&symfile_complaints,
12011                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12012                            "for DW_FORM_block* DW_AT_location is supported for "
12013                            "DW_TAG_call_site child DIE 0x%x "
12014                            "[in module %s]"),
12015                          to_underlying (child_die->sect_off),
12016                          objfile_name (objfile));
12017               continue;
12018             }
12019         }
12020
12021       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12022       if (attr == NULL)
12023         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12024       if (!attr_form_is_block (attr))
12025         {
12026           complaint (&symfile_complaints,
12027                      _("No DW_FORM_block* DW_AT_call_value for "
12028                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12029                      to_underlying (child_die->sect_off),
12030                      objfile_name (objfile));
12031           continue;
12032         }
12033       parameter->value = DW_BLOCK (attr)->data;
12034       parameter->value_size = DW_BLOCK (attr)->size;
12035
12036       /* Parameters are not pre-cleared by memset above.  */
12037       parameter->data_value = NULL;
12038       parameter->data_value_size = 0;
12039       call_site->parameter_count++;
12040
12041       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12042       if (attr == NULL)
12043         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12044       if (attr)
12045         {
12046           if (!attr_form_is_block (attr))
12047             complaint (&symfile_complaints,
12048                        _("No DW_FORM_block* DW_AT_call_data_value for "
12049                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12050                        to_underlying (child_die->sect_off),
12051                        objfile_name (objfile));
12052           else
12053             {
12054               parameter->data_value = DW_BLOCK (attr)->data;
12055               parameter->data_value_size = DW_BLOCK (attr)->size;
12056             }
12057         }
12058     }
12059 }
12060
12061 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12062    reading .debug_rnglists.
12063    Callback's type should be:
12064     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12065    Return true if the attributes are present and valid, otherwise,
12066    return false.  */
12067
12068 template <typename Callback>
12069 static bool
12070 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12071                          Callback &&callback)
12072 {
12073   struct objfile *objfile = cu->objfile;
12074   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12075   struct comp_unit_head *cu_header = &cu->header;
12076   bfd *obfd = objfile->obfd;
12077   unsigned int addr_size = cu_header->addr_size;
12078   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12079   /* Base address selection entry.  */
12080   CORE_ADDR base;
12081   int found_base;
12082   unsigned int dummy;
12083   const gdb_byte *buffer;
12084   CORE_ADDR low = 0;
12085   CORE_ADDR high = 0;
12086   CORE_ADDR baseaddr;
12087   bool overflow = false;
12088
12089   found_base = cu->base_known;
12090   base = cu->base_address;
12091
12092   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12093   if (offset >= dwarf2_per_objfile->rnglists.size)
12094     {
12095       complaint (&symfile_complaints,
12096                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12097                  offset);
12098       return false;
12099     }
12100   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12101
12102   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12103
12104   while (1)
12105     {
12106       /* Initialize it due to a false compiler warning.  */
12107       CORE_ADDR range_beginning = 0, range_end = 0;
12108       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12109                                  + dwarf2_per_objfile->rnglists.size);
12110       unsigned int bytes_read;
12111
12112       if (buffer == buf_end)
12113         {
12114           overflow = true;
12115           break;
12116         }
12117       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12118       switch (rlet)
12119         {
12120         case DW_RLE_end_of_list:
12121           break;
12122         case DW_RLE_base_address:
12123           if (buffer + cu->header.addr_size > buf_end)
12124             {
12125               overflow = true;
12126               break;
12127             }
12128           base = read_address (obfd, buffer, cu, &bytes_read);
12129           found_base = 1;
12130           buffer += bytes_read;
12131           break;
12132         case DW_RLE_start_length:
12133           if (buffer + cu->header.addr_size > buf_end)
12134             {
12135               overflow = true;
12136               break;
12137             }
12138           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12139           buffer += bytes_read;
12140           range_end = (range_beginning
12141                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12142           buffer += bytes_read;
12143           if (buffer > buf_end)
12144             {
12145               overflow = true;
12146               break;
12147             }
12148           break;
12149         case DW_RLE_offset_pair:
12150           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12151           buffer += bytes_read;
12152           if (buffer > buf_end)
12153             {
12154               overflow = true;
12155               break;
12156             }
12157           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12158           buffer += bytes_read;
12159           if (buffer > buf_end)
12160             {
12161               overflow = true;
12162               break;
12163             }
12164           break;
12165         case DW_RLE_start_end:
12166           if (buffer + 2 * cu->header.addr_size > buf_end)
12167             {
12168               overflow = true;
12169               break;
12170             }
12171           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12172           buffer += bytes_read;
12173           range_end = read_address (obfd, buffer, cu, &bytes_read);
12174           buffer += bytes_read;
12175           break;
12176         default:
12177           complaint (&symfile_complaints,
12178                      _("Invalid .debug_rnglists data (no base address)"));
12179           return false;
12180         }
12181       if (rlet == DW_RLE_end_of_list || overflow)
12182         break;
12183       if (rlet == DW_RLE_base_address)
12184         continue;
12185
12186       if (!found_base)
12187         {
12188           /* We have no valid base address for the ranges
12189              data.  */
12190           complaint (&symfile_complaints,
12191                      _("Invalid .debug_rnglists data (no base address)"));
12192           return false;
12193         }
12194
12195       if (range_beginning > range_end)
12196         {
12197           /* Inverted range entries are invalid.  */
12198           complaint (&symfile_complaints,
12199                      _("Invalid .debug_rnglists data (inverted range)"));
12200           return false;
12201         }
12202
12203       /* Empty range entries have no effect.  */
12204       if (range_beginning == range_end)
12205         continue;
12206
12207       range_beginning += base;
12208       range_end += base;
12209
12210       /* A not-uncommon case of bad debug info.
12211          Don't pollute the addrmap with bad data.  */
12212       if (range_beginning + baseaddr == 0
12213           && !dwarf2_per_objfile->has_section_at_zero)
12214         {
12215           complaint (&symfile_complaints,
12216                      _(".debug_rnglists entry has start address of zero"
12217                        " [in module %s]"), objfile_name (objfile));
12218           continue;
12219         }
12220
12221       callback (range_beginning, range_end);
12222     }
12223
12224   if (overflow)
12225     {
12226       complaint (&symfile_complaints,
12227                  _("Offset %d is not terminated "
12228                    "for DW_AT_ranges attribute"),
12229                  offset);
12230       return false;
12231     }
12232
12233   return true;
12234 }
12235
12236 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12237    Callback's type should be:
12238     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12239    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12240
12241 template <typename Callback>
12242 static int
12243 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12244                        Callback &&callback)
12245 {
12246   struct objfile *objfile = cu->objfile;
12247   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12248   struct comp_unit_head *cu_header = &cu->header;
12249   bfd *obfd = objfile->obfd;
12250   unsigned int addr_size = cu_header->addr_size;
12251   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12252   /* Base address selection entry.  */
12253   CORE_ADDR base;
12254   int found_base;
12255   unsigned int dummy;
12256   const gdb_byte *buffer;
12257   CORE_ADDR baseaddr;
12258
12259   if (cu_header->version >= 5)
12260     return dwarf2_rnglists_process (offset, cu, callback);
12261
12262   found_base = cu->base_known;
12263   base = cu->base_address;
12264
12265   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12266   if (offset >= dwarf2_per_objfile->ranges.size)
12267     {
12268       complaint (&symfile_complaints,
12269                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12270                  offset);
12271       return 0;
12272     }
12273   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12274
12275   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12276
12277   while (1)
12278     {
12279       CORE_ADDR range_beginning, range_end;
12280
12281       range_beginning = read_address (obfd, buffer, cu, &dummy);
12282       buffer += addr_size;
12283       range_end = read_address (obfd, buffer, cu, &dummy);
12284       buffer += addr_size;
12285       offset += 2 * addr_size;
12286
12287       /* An end of list marker is a pair of zero addresses.  */
12288       if (range_beginning == 0 && range_end == 0)
12289         /* Found the end of list entry.  */
12290         break;
12291
12292       /* Each base address selection entry is a pair of 2 values.
12293          The first is the largest possible address, the second is
12294          the base address.  Check for a base address here.  */
12295       if ((range_beginning & mask) == mask)
12296         {
12297           /* If we found the largest possible address, then we already
12298              have the base address in range_end.  */
12299           base = range_end;
12300           found_base = 1;
12301           continue;
12302         }
12303
12304       if (!found_base)
12305         {
12306           /* We have no valid base address for the ranges
12307              data.  */
12308           complaint (&symfile_complaints,
12309                      _("Invalid .debug_ranges data (no base address)"));
12310           return 0;
12311         }
12312
12313       if (range_beginning > range_end)
12314         {
12315           /* Inverted range entries are invalid.  */
12316           complaint (&symfile_complaints,
12317                      _("Invalid .debug_ranges data (inverted range)"));
12318           return 0;
12319         }
12320
12321       /* Empty range entries have no effect.  */
12322       if (range_beginning == range_end)
12323         continue;
12324
12325       range_beginning += base;
12326       range_end += base;
12327
12328       /* A not-uncommon case of bad debug info.
12329          Don't pollute the addrmap with bad data.  */
12330       if (range_beginning + baseaddr == 0
12331           && !dwarf2_per_objfile->has_section_at_zero)
12332         {
12333           complaint (&symfile_complaints,
12334                      _(".debug_ranges entry has start address of zero"
12335                        " [in module %s]"), objfile_name (objfile));
12336           continue;
12337         }
12338
12339       callback (range_beginning, range_end);
12340     }
12341
12342   return 1;
12343 }
12344
12345 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12346    Return 1 if the attributes are present and valid, otherwise, return 0.
12347    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12348
12349 static int
12350 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12351                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12352                     struct partial_symtab *ranges_pst)
12353 {
12354   struct objfile *objfile = cu->objfile;
12355   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12356   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12357                                        SECT_OFF_TEXT (objfile));
12358   int low_set = 0;
12359   CORE_ADDR low = 0;
12360   CORE_ADDR high = 0;
12361   int retval;
12362
12363   retval = dwarf2_ranges_process (offset, cu,
12364     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12365     {
12366       if (ranges_pst != NULL)
12367         {
12368           CORE_ADDR lowpc;
12369           CORE_ADDR highpc;
12370
12371           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12372                                               range_beginning + baseaddr);
12373           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12374                                                range_end + baseaddr);
12375           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12376                              ranges_pst);
12377         }
12378
12379       /* FIXME: This is recording everything as a low-high
12380          segment of consecutive addresses.  We should have a
12381          data structure for discontiguous block ranges
12382          instead.  */
12383       if (! low_set)
12384         {
12385           low = range_beginning;
12386           high = range_end;
12387           low_set = 1;
12388         }
12389       else
12390         {
12391           if (range_beginning < low)
12392             low = range_beginning;
12393           if (range_end > high)
12394             high = range_end;
12395         }
12396     });
12397   if (!retval)
12398     return 0;
12399
12400   if (! low_set)
12401     /* If the first entry is an end-of-list marker, the range
12402        describes an empty scope, i.e. no instructions.  */
12403     return 0;
12404
12405   if (low_return)
12406     *low_return = low;
12407   if (high_return)
12408     *high_return = high;
12409   return 1;
12410 }
12411
12412 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12413    definition for the return value.  *LOWPC and *HIGHPC are set iff
12414    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12415
12416 static enum pc_bounds_kind
12417 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12418                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12419                       struct partial_symtab *pst)
12420 {
12421   struct attribute *attr;
12422   struct attribute *attr_high;
12423   CORE_ADDR low = 0;
12424   CORE_ADDR high = 0;
12425   enum pc_bounds_kind ret;
12426
12427   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12428   if (attr_high)
12429     {
12430       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12431       if (attr)
12432         {
12433           low = attr_value_as_address (attr);
12434           high = attr_value_as_address (attr_high);
12435           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12436             high += low;
12437         }
12438       else
12439         /* Found high w/o low attribute.  */
12440         return PC_BOUNDS_INVALID;
12441
12442       /* Found consecutive range of addresses.  */
12443       ret = PC_BOUNDS_HIGH_LOW;
12444     }
12445   else
12446     {
12447       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12448       if (attr != NULL)
12449         {
12450           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12451              We take advantage of the fact that DW_AT_ranges does not appear
12452              in DW_TAG_compile_unit of DWO files.  */
12453           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12454           unsigned int ranges_offset = (DW_UNSND (attr)
12455                                         + (need_ranges_base
12456                                            ? cu->ranges_base
12457                                            : 0));
12458
12459           /* Value of the DW_AT_ranges attribute is the offset in the
12460              .debug_ranges section.  */
12461           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12462             return PC_BOUNDS_INVALID;
12463           /* Found discontinuous range of addresses.  */
12464           ret = PC_BOUNDS_RANGES;
12465         }
12466       else
12467         return PC_BOUNDS_NOT_PRESENT;
12468     }
12469
12470   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12471   if (high <= low)
12472     return PC_BOUNDS_INVALID;
12473
12474   /* When using the GNU linker, .gnu.linkonce. sections are used to
12475      eliminate duplicate copies of functions and vtables and such.
12476      The linker will arbitrarily choose one and discard the others.
12477      The AT_*_pc values for such functions refer to local labels in
12478      these sections.  If the section from that file was discarded, the
12479      labels are not in the output, so the relocs get a value of 0.
12480      If this is a discarded function, mark the pc bounds as invalid,
12481      so that GDB will ignore it.  */
12482   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12483     return PC_BOUNDS_INVALID;
12484
12485   *lowpc = low;
12486   if (highpc)
12487     *highpc = high;
12488   return ret;
12489 }
12490
12491 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12492    its low and high PC addresses.  Do nothing if these addresses could not
12493    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12494    and HIGHPC to the high address if greater than HIGHPC.  */
12495
12496 static void
12497 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12498                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12499                                  struct dwarf2_cu *cu)
12500 {
12501   CORE_ADDR low, high;
12502   struct die_info *child = die->child;
12503
12504   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12505     {
12506       *lowpc = std::min (*lowpc, low);
12507       *highpc = std::max (*highpc, high);
12508     }
12509
12510   /* If the language does not allow nested subprograms (either inside
12511      subprograms or lexical blocks), we're done.  */
12512   if (cu->language != language_ada)
12513     return;
12514
12515   /* Check all the children of the given DIE.  If it contains nested
12516      subprograms, then check their pc bounds.  Likewise, we need to
12517      check lexical blocks as well, as they may also contain subprogram
12518      definitions.  */
12519   while (child && child->tag)
12520     {
12521       if (child->tag == DW_TAG_subprogram
12522           || child->tag == DW_TAG_lexical_block)
12523         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12524       child = sibling_die (child);
12525     }
12526 }
12527
12528 /* Get the low and high pc's represented by the scope DIE, and store
12529    them in *LOWPC and *HIGHPC.  If the correct values can't be
12530    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12531
12532 static void
12533 get_scope_pc_bounds (struct die_info *die,
12534                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12535                      struct dwarf2_cu *cu)
12536 {
12537   CORE_ADDR best_low = (CORE_ADDR) -1;
12538   CORE_ADDR best_high = (CORE_ADDR) 0;
12539   CORE_ADDR current_low, current_high;
12540
12541   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12542       >= PC_BOUNDS_RANGES)
12543     {
12544       best_low = current_low;
12545       best_high = current_high;
12546     }
12547   else
12548     {
12549       struct die_info *child = die->child;
12550
12551       while (child && child->tag)
12552         {
12553           switch (child->tag) {
12554           case DW_TAG_subprogram:
12555             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12556             break;
12557           case DW_TAG_namespace:
12558           case DW_TAG_module:
12559             /* FIXME: carlton/2004-01-16: Should we do this for
12560                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12561                that current GCC's always emit the DIEs corresponding
12562                to definitions of methods of classes as children of a
12563                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12564                the DIEs giving the declarations, which could be
12565                anywhere).  But I don't see any reason why the
12566                standards says that they have to be there.  */
12567             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12568
12569             if (current_low != ((CORE_ADDR) -1))
12570               {
12571                 best_low = std::min (best_low, current_low);
12572                 best_high = std::max (best_high, current_high);
12573               }
12574             break;
12575           default:
12576             /* Ignore.  */
12577             break;
12578           }
12579
12580           child = sibling_die (child);
12581         }
12582     }
12583
12584   *lowpc = best_low;
12585   *highpc = best_high;
12586 }
12587
12588 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12589    in DIE.  */
12590
12591 static void
12592 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12593                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12594 {
12595   struct objfile *objfile = cu->objfile;
12596   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12597   struct attribute *attr;
12598   struct attribute *attr_high;
12599
12600   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12601   if (attr_high)
12602     {
12603       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12604       if (attr)
12605         {
12606           CORE_ADDR low = attr_value_as_address (attr);
12607           CORE_ADDR high = attr_value_as_address (attr_high);
12608
12609           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12610             high += low;
12611
12612           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12613           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12614           record_block_range (block, low, high - 1);
12615         }
12616     }
12617
12618   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12619   if (attr)
12620     {
12621       bfd *obfd = objfile->obfd;
12622       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12623          We take advantage of the fact that DW_AT_ranges does not appear
12624          in DW_TAG_compile_unit of DWO files.  */
12625       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12626
12627       /* The value of the DW_AT_ranges attribute is the offset of the
12628          address range list in the .debug_ranges section.  */
12629       unsigned long offset = (DW_UNSND (attr)
12630                               + (need_ranges_base ? cu->ranges_base : 0));
12631       const gdb_byte *buffer;
12632
12633       /* For some target architectures, but not others, the
12634          read_address function sign-extends the addresses it returns.
12635          To recognize base address selection entries, we need a
12636          mask.  */
12637       unsigned int addr_size = cu->header.addr_size;
12638       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12639
12640       /* The base address, to which the next pair is relative.  Note
12641          that this 'base' is a DWARF concept: most entries in a range
12642          list are relative, to reduce the number of relocs against the
12643          debugging information.  This is separate from this function's
12644          'baseaddr' argument, which GDB uses to relocate debugging
12645          information from a shared library based on the address at
12646          which the library was loaded.  */
12647       CORE_ADDR base = cu->base_address;
12648       int base_known = cu->base_known;
12649
12650       dwarf2_ranges_process (offset, cu,
12651         [&] (CORE_ADDR start, CORE_ADDR end)
12652         {
12653           start += baseaddr;
12654           end += baseaddr;
12655           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12656           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12657           record_block_range (block, start, end - 1);
12658         });
12659     }
12660 }
12661
12662 /* Check whether the producer field indicates either of GCC < 4.6, or the
12663    Intel C/C++ compiler, and cache the result in CU.  */
12664
12665 static void
12666 check_producer (struct dwarf2_cu *cu)
12667 {
12668   int major, minor;
12669
12670   if (cu->producer == NULL)
12671     {
12672       /* For unknown compilers expect their behavior is DWARF version
12673          compliant.
12674
12675          GCC started to support .debug_types sections by -gdwarf-4 since
12676          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12677          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12678          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12679          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12680     }
12681   else if (producer_is_gcc (cu->producer, &major, &minor))
12682     {
12683       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12684       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12685     }
12686   else if (startswith (cu->producer, "Intel(R) C"))
12687     cu->producer_is_icc = 1;
12688   else
12689     {
12690       /* For other non-GCC compilers, expect their behavior is DWARF version
12691          compliant.  */
12692     }
12693
12694   cu->checked_producer = 1;
12695 }
12696
12697 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12698    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12699    during 4.6.0 experimental.  */
12700
12701 static int
12702 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12703 {
12704   if (!cu->checked_producer)
12705     check_producer (cu);
12706
12707   return cu->producer_is_gxx_lt_4_6;
12708 }
12709
12710 /* Return the default accessibility type if it is not overriden by
12711    DW_AT_accessibility.  */
12712
12713 static enum dwarf_access_attribute
12714 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12715 {
12716   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12717     {
12718       /* The default DWARF 2 accessibility for members is public, the default
12719          accessibility for inheritance is private.  */
12720
12721       if (die->tag != DW_TAG_inheritance)
12722         return DW_ACCESS_public;
12723       else
12724         return DW_ACCESS_private;
12725     }
12726   else
12727     {
12728       /* DWARF 3+ defines the default accessibility a different way.  The same
12729          rules apply now for DW_TAG_inheritance as for the members and it only
12730          depends on the container kind.  */
12731
12732       if (die->parent->tag == DW_TAG_class_type)
12733         return DW_ACCESS_private;
12734       else
12735         return DW_ACCESS_public;
12736     }
12737 }
12738
12739 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12740    offset.  If the attribute was not found return 0, otherwise return
12741    1.  If it was found but could not properly be handled, set *OFFSET
12742    to 0.  */
12743
12744 static int
12745 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12746                              LONGEST *offset)
12747 {
12748   struct attribute *attr;
12749
12750   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12751   if (attr != NULL)
12752     {
12753       *offset = 0;
12754
12755       /* Note that we do not check for a section offset first here.
12756          This is because DW_AT_data_member_location is new in DWARF 4,
12757          so if we see it, we can assume that a constant form is really
12758          a constant and not a section offset.  */
12759       if (attr_form_is_constant (attr))
12760         *offset = dwarf2_get_attr_constant_value (attr, 0);
12761       else if (attr_form_is_section_offset (attr))
12762         dwarf2_complex_location_expr_complaint ();
12763       else if (attr_form_is_block (attr))
12764         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12765       else
12766         dwarf2_complex_location_expr_complaint ();
12767
12768       return 1;
12769     }
12770
12771   return 0;
12772 }
12773
12774 /* Add an aggregate field to the field list.  */
12775
12776 static void
12777 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12778                   struct dwarf2_cu *cu)
12779 {
12780   struct objfile *objfile = cu->objfile;
12781   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12782   struct nextfield *new_field;
12783   struct attribute *attr;
12784   struct field *fp;
12785   const char *fieldname = "";
12786
12787   /* Allocate a new field list entry and link it in.  */
12788   new_field = XNEW (struct nextfield);
12789   make_cleanup (xfree, new_field);
12790   memset (new_field, 0, sizeof (struct nextfield));
12791
12792   if (die->tag == DW_TAG_inheritance)
12793     {
12794       new_field->next = fip->baseclasses;
12795       fip->baseclasses = new_field;
12796     }
12797   else
12798     {
12799       new_field->next = fip->fields;
12800       fip->fields = new_field;
12801     }
12802   fip->nfields++;
12803
12804   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12805   if (attr)
12806     new_field->accessibility = DW_UNSND (attr);
12807   else
12808     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12809   if (new_field->accessibility != DW_ACCESS_public)
12810     fip->non_public_fields = 1;
12811
12812   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12813   if (attr)
12814     new_field->virtuality = DW_UNSND (attr);
12815   else
12816     new_field->virtuality = DW_VIRTUALITY_none;
12817
12818   fp = &new_field->field;
12819
12820   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12821     {
12822       LONGEST offset;
12823
12824       /* Data member other than a C++ static data member.  */
12825
12826       /* Get type of field.  */
12827       fp->type = die_type (die, cu);
12828
12829       SET_FIELD_BITPOS (*fp, 0);
12830
12831       /* Get bit size of field (zero if none).  */
12832       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12833       if (attr)
12834         {
12835           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12836         }
12837       else
12838         {
12839           FIELD_BITSIZE (*fp) = 0;
12840         }
12841
12842       /* Get bit offset of field.  */
12843       if (handle_data_member_location (die, cu, &offset))
12844         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12845       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12846       if (attr)
12847         {
12848           if (gdbarch_bits_big_endian (gdbarch))
12849             {
12850               /* For big endian bits, the DW_AT_bit_offset gives the
12851                  additional bit offset from the MSB of the containing
12852                  anonymous object to the MSB of the field.  We don't
12853                  have to do anything special since we don't need to
12854                  know the size of the anonymous object.  */
12855               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12856             }
12857           else
12858             {
12859               /* For little endian bits, compute the bit offset to the
12860                  MSB of the anonymous object, subtract off the number of
12861                  bits from the MSB of the field to the MSB of the
12862                  object, and then subtract off the number of bits of
12863                  the field itself.  The result is the bit offset of
12864                  the LSB of the field.  */
12865               int anonymous_size;
12866               int bit_offset = DW_UNSND (attr);
12867
12868               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12869               if (attr)
12870                 {
12871                   /* The size of the anonymous object containing
12872                      the bit field is explicit, so use the
12873                      indicated size (in bytes).  */
12874                   anonymous_size = DW_UNSND (attr);
12875                 }
12876               else
12877                 {
12878                   /* The size of the anonymous object containing
12879                      the bit field must be inferred from the type
12880                      attribute of the data member containing the
12881                      bit field.  */
12882                   anonymous_size = TYPE_LENGTH (fp->type);
12883                 }
12884               SET_FIELD_BITPOS (*fp,
12885                                 (FIELD_BITPOS (*fp)
12886                                  + anonymous_size * bits_per_byte
12887                                  - bit_offset - FIELD_BITSIZE (*fp)));
12888             }
12889         }
12890       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
12891       if (attr != NULL)
12892         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
12893                                 + dwarf2_get_attr_constant_value (attr, 0)));
12894
12895       /* Get name of field.  */
12896       fieldname = dwarf2_name (die, cu);
12897       if (fieldname == NULL)
12898         fieldname = "";
12899
12900       /* The name is already allocated along with this objfile, so we don't
12901          need to duplicate it for the type.  */
12902       fp->name = fieldname;
12903
12904       /* Change accessibility for artificial fields (e.g. virtual table
12905          pointer or virtual base class pointer) to private.  */
12906       if (dwarf2_attr (die, DW_AT_artificial, cu))
12907         {
12908           FIELD_ARTIFICIAL (*fp) = 1;
12909           new_field->accessibility = DW_ACCESS_private;
12910           fip->non_public_fields = 1;
12911         }
12912     }
12913   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12914     {
12915       /* C++ static member.  */
12916
12917       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12918          is a declaration, but all versions of G++ as of this writing
12919          (so through at least 3.2.1) incorrectly generate
12920          DW_TAG_variable tags.  */
12921
12922       const char *physname;
12923
12924       /* Get name of field.  */
12925       fieldname = dwarf2_name (die, cu);
12926       if (fieldname == NULL)
12927         return;
12928
12929       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12930       if (attr
12931           /* Only create a symbol if this is an external value.
12932              new_symbol checks this and puts the value in the global symbol
12933              table, which we want.  If it is not external, new_symbol
12934              will try to put the value in cu->list_in_scope which is wrong.  */
12935           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12936         {
12937           /* A static const member, not much different than an enum as far as
12938              we're concerned, except that we can support more types.  */
12939           new_symbol (die, NULL, cu);
12940         }
12941
12942       /* Get physical name.  */
12943       physname = dwarf2_physname (fieldname, die, cu);
12944
12945       /* The name is already allocated along with this objfile, so we don't
12946          need to duplicate it for the type.  */
12947       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12948       FIELD_TYPE (*fp) = die_type (die, cu);
12949       FIELD_NAME (*fp) = fieldname;
12950     }
12951   else if (die->tag == DW_TAG_inheritance)
12952     {
12953       LONGEST offset;
12954
12955       /* C++ base class field.  */
12956       if (handle_data_member_location (die, cu, &offset))
12957         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12958       FIELD_BITSIZE (*fp) = 0;
12959       FIELD_TYPE (*fp) = die_type (die, cu);
12960       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12961       fip->nbaseclasses++;
12962     }
12963 }
12964
12965 /* Add a typedef defined in the scope of the FIP's class.  */
12966
12967 static void
12968 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12969                     struct dwarf2_cu *cu)
12970 {
12971   struct typedef_field_list *new_field;
12972   struct typedef_field *fp;
12973
12974   /* Allocate a new field list entry and link it in.  */
12975   new_field = XCNEW (struct typedef_field_list);
12976   make_cleanup (xfree, new_field);
12977
12978   gdb_assert (die->tag == DW_TAG_typedef);
12979
12980   fp = &new_field->field;
12981
12982   /* Get name of field.  */
12983   fp->name = dwarf2_name (die, cu);
12984   if (fp->name == NULL)
12985     return;
12986
12987   fp->type = read_type_die (die, cu);
12988
12989   new_field->next = fip->typedef_field_list;
12990   fip->typedef_field_list = new_field;
12991   fip->typedef_field_list_count++;
12992 }
12993
12994 /* Create the vector of fields, and attach it to the type.  */
12995
12996 static void
12997 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12998                               struct dwarf2_cu *cu)
12999 {
13000   int nfields = fip->nfields;
13001
13002   /* Record the field count, allocate space for the array of fields,
13003      and create blank accessibility bitfields if necessary.  */
13004   TYPE_NFIELDS (type) = nfields;
13005   TYPE_FIELDS (type) = (struct field *)
13006     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13007   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13008
13009   if (fip->non_public_fields && cu->language != language_ada)
13010     {
13011       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13012
13013       TYPE_FIELD_PRIVATE_BITS (type) =
13014         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13015       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13016
13017       TYPE_FIELD_PROTECTED_BITS (type) =
13018         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13019       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13020
13021       TYPE_FIELD_IGNORE_BITS (type) =
13022         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13023       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13024     }
13025
13026   /* If the type has baseclasses, allocate and clear a bit vector for
13027      TYPE_FIELD_VIRTUAL_BITS.  */
13028   if (fip->nbaseclasses && cu->language != language_ada)
13029     {
13030       int num_bytes = B_BYTES (fip->nbaseclasses);
13031       unsigned char *pointer;
13032
13033       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13034       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13035       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13036       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13037       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13038     }
13039
13040   /* Copy the saved-up fields into the field vector.  Start from the head of
13041      the list, adding to the tail of the field array, so that they end up in
13042      the same order in the array in which they were added to the list.  */
13043   while (nfields-- > 0)
13044     {
13045       struct nextfield *fieldp;
13046
13047       if (fip->fields)
13048         {
13049           fieldp = fip->fields;
13050           fip->fields = fieldp->next;
13051         }
13052       else
13053         {
13054           fieldp = fip->baseclasses;
13055           fip->baseclasses = fieldp->next;
13056         }
13057
13058       TYPE_FIELD (type, nfields) = fieldp->field;
13059       switch (fieldp->accessibility)
13060         {
13061         case DW_ACCESS_private:
13062           if (cu->language != language_ada)
13063             SET_TYPE_FIELD_PRIVATE (type, nfields);
13064           break;
13065
13066         case DW_ACCESS_protected:
13067           if (cu->language != language_ada)
13068             SET_TYPE_FIELD_PROTECTED (type, nfields);
13069           break;
13070
13071         case DW_ACCESS_public:
13072           break;
13073
13074         default:
13075           /* Unknown accessibility.  Complain and treat it as public.  */
13076           {
13077             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13078                        fieldp->accessibility);
13079           }
13080           break;
13081         }
13082       if (nfields < fip->nbaseclasses)
13083         {
13084           switch (fieldp->virtuality)
13085             {
13086             case DW_VIRTUALITY_virtual:
13087             case DW_VIRTUALITY_pure_virtual:
13088               if (cu->language == language_ada)
13089                 error (_("unexpected virtuality in component of Ada type"));
13090               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13091               break;
13092             }
13093         }
13094     }
13095 }
13096
13097 /* Return true if this member function is a constructor, false
13098    otherwise.  */
13099
13100 static int
13101 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13102 {
13103   const char *fieldname;
13104   const char *type_name;
13105   int len;
13106
13107   if (die->parent == NULL)
13108     return 0;
13109
13110   if (die->parent->tag != DW_TAG_structure_type
13111       && die->parent->tag != DW_TAG_union_type
13112       && die->parent->tag != DW_TAG_class_type)
13113     return 0;
13114
13115   fieldname = dwarf2_name (die, cu);
13116   type_name = dwarf2_name (die->parent, cu);
13117   if (fieldname == NULL || type_name == NULL)
13118     return 0;
13119
13120   len = strlen (fieldname);
13121   return (strncmp (fieldname, type_name, len) == 0
13122           && (type_name[len] == '\0' || type_name[len] == '<'));
13123 }
13124
13125 /* Add a member function to the proper fieldlist.  */
13126
13127 static void
13128 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13129                       struct type *type, struct dwarf2_cu *cu)
13130 {
13131   struct objfile *objfile = cu->objfile;
13132   struct attribute *attr;
13133   struct fnfieldlist *flp;
13134   int i;
13135   struct fn_field *fnp;
13136   const char *fieldname;
13137   struct nextfnfield *new_fnfield;
13138   struct type *this_type;
13139   enum dwarf_access_attribute accessibility;
13140
13141   if (cu->language == language_ada)
13142     error (_("unexpected member function in Ada type"));
13143
13144   /* Get name of member function.  */
13145   fieldname = dwarf2_name (die, cu);
13146   if (fieldname == NULL)
13147     return;
13148
13149   /* Look up member function name in fieldlist.  */
13150   for (i = 0; i < fip->nfnfields; i++)
13151     {
13152       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13153         break;
13154     }
13155
13156   /* Create new list element if necessary.  */
13157   if (i < fip->nfnfields)
13158     flp = &fip->fnfieldlists[i];
13159   else
13160     {
13161       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13162         {
13163           fip->fnfieldlists = (struct fnfieldlist *)
13164             xrealloc (fip->fnfieldlists,
13165                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13166                       * sizeof (struct fnfieldlist));
13167           if (fip->nfnfields == 0)
13168             make_cleanup (free_current_contents, &fip->fnfieldlists);
13169         }
13170       flp = &fip->fnfieldlists[fip->nfnfields];
13171       flp->name = fieldname;
13172       flp->length = 0;
13173       flp->head = NULL;
13174       i = fip->nfnfields++;
13175     }
13176
13177   /* Create a new member function field and chain it to the field list
13178      entry.  */
13179   new_fnfield = XNEW (struct nextfnfield);
13180   make_cleanup (xfree, new_fnfield);
13181   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13182   new_fnfield->next = flp->head;
13183   flp->head = new_fnfield;
13184   flp->length++;
13185
13186   /* Fill in the member function field info.  */
13187   fnp = &new_fnfield->fnfield;
13188
13189   /* Delay processing of the physname until later.  */
13190   if (cu->language == language_cplus)
13191     {
13192       add_to_method_list (type, i, flp->length - 1, fieldname,
13193                           die, cu);
13194     }
13195   else
13196     {
13197       const char *physname = dwarf2_physname (fieldname, die, cu);
13198       fnp->physname = physname ? physname : "";
13199     }
13200
13201   fnp->type = alloc_type (objfile);
13202   this_type = read_type_die (die, cu);
13203   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13204     {
13205       int nparams = TYPE_NFIELDS (this_type);
13206
13207       /* TYPE is the domain of this method, and THIS_TYPE is the type
13208            of the method itself (TYPE_CODE_METHOD).  */
13209       smash_to_method_type (fnp->type, type,
13210                             TYPE_TARGET_TYPE (this_type),
13211                             TYPE_FIELDS (this_type),
13212                             TYPE_NFIELDS (this_type),
13213                             TYPE_VARARGS (this_type));
13214
13215       /* Handle static member functions.
13216          Dwarf2 has no clean way to discern C++ static and non-static
13217          member functions.  G++ helps GDB by marking the first
13218          parameter for non-static member functions (which is the this
13219          pointer) as artificial.  We obtain this information from
13220          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13221       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13222         fnp->voffset = VOFFSET_STATIC;
13223     }
13224   else
13225     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13226                dwarf2_full_name (fieldname, die, cu));
13227
13228   /* Get fcontext from DW_AT_containing_type if present.  */
13229   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13230     fnp->fcontext = die_containing_type (die, cu);
13231
13232   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13233      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13234
13235   /* Get accessibility.  */
13236   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13237   if (attr)
13238     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13239   else
13240     accessibility = dwarf2_default_access_attribute (die, cu);
13241   switch (accessibility)
13242     {
13243     case DW_ACCESS_private:
13244       fnp->is_private = 1;
13245       break;
13246     case DW_ACCESS_protected:
13247       fnp->is_protected = 1;
13248       break;
13249     }
13250
13251   /* Check for artificial methods.  */
13252   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13253   if (attr && DW_UNSND (attr) != 0)
13254     fnp->is_artificial = 1;
13255
13256   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13257
13258   /* Get index in virtual function table if it is a virtual member
13259      function.  For older versions of GCC, this is an offset in the
13260      appropriate virtual table, as specified by DW_AT_containing_type.
13261      For everyone else, it is an expression to be evaluated relative
13262      to the object address.  */
13263
13264   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13265   if (attr)
13266     {
13267       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13268         {
13269           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13270             {
13271               /* Old-style GCC.  */
13272               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13273             }
13274           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13275                    || (DW_BLOCK (attr)->size > 1
13276                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13277                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13278             {
13279               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13280               if ((fnp->voffset % cu->header.addr_size) != 0)
13281                 dwarf2_complex_location_expr_complaint ();
13282               else
13283                 fnp->voffset /= cu->header.addr_size;
13284               fnp->voffset += 2;
13285             }
13286           else
13287             dwarf2_complex_location_expr_complaint ();
13288
13289           if (!fnp->fcontext)
13290             {
13291               /* If there is no `this' field and no DW_AT_containing_type,
13292                  we cannot actually find a base class context for the
13293                  vtable!  */
13294               if (TYPE_NFIELDS (this_type) == 0
13295                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13296                 {
13297                   complaint (&symfile_complaints,
13298                              _("cannot determine context for virtual member "
13299                                "function \"%s\" (offset %d)"),
13300                              fieldname, to_underlying (die->sect_off));
13301                 }
13302               else
13303                 {
13304                   fnp->fcontext
13305                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13306                 }
13307             }
13308         }
13309       else if (attr_form_is_section_offset (attr))
13310         {
13311           dwarf2_complex_location_expr_complaint ();
13312         }
13313       else
13314         {
13315           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13316                                                  fieldname);
13317         }
13318     }
13319   else
13320     {
13321       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13322       if (attr && DW_UNSND (attr))
13323         {
13324           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13325           complaint (&symfile_complaints,
13326                      _("Member function \"%s\" (offset %d) is virtual "
13327                        "but the vtable offset is not specified"),
13328                      fieldname, to_underlying (die->sect_off));
13329           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13330           TYPE_CPLUS_DYNAMIC (type) = 1;
13331         }
13332     }
13333 }
13334
13335 /* Create the vector of member function fields, and attach it to the type.  */
13336
13337 static void
13338 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13339                                  struct dwarf2_cu *cu)
13340 {
13341   struct fnfieldlist *flp;
13342   int i;
13343
13344   if (cu->language == language_ada)
13345     error (_("unexpected member functions in Ada type"));
13346
13347   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13348   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13349     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13350
13351   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13352     {
13353       struct nextfnfield *nfp = flp->head;
13354       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13355       int k;
13356
13357       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13358       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13359       fn_flp->fn_fields = (struct fn_field *)
13360         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13361       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13362         fn_flp->fn_fields[k] = nfp->fnfield;
13363     }
13364
13365   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13366 }
13367
13368 /* Returns non-zero if NAME is the name of a vtable member in CU's
13369    language, zero otherwise.  */
13370 static int
13371 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13372 {
13373   static const char vptr[] = "_vptr";
13374   static const char vtable[] = "vtable";
13375
13376   /* Look for the C++ form of the vtable.  */
13377   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13378     return 1;
13379
13380   return 0;
13381 }
13382
13383 /* GCC outputs unnamed structures that are really pointers to member
13384    functions, with the ABI-specified layout.  If TYPE describes
13385    such a structure, smash it into a member function type.
13386
13387    GCC shouldn't do this; it should just output pointer to member DIEs.
13388    This is GCC PR debug/28767.  */
13389
13390 static void
13391 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13392 {
13393   struct type *pfn_type, *self_type, *new_type;
13394
13395   /* Check for a structure with no name and two children.  */
13396   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13397     return;
13398
13399   /* Check for __pfn and __delta members.  */
13400   if (TYPE_FIELD_NAME (type, 0) == NULL
13401       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13402       || TYPE_FIELD_NAME (type, 1) == NULL
13403       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13404     return;
13405
13406   /* Find the type of the method.  */
13407   pfn_type = TYPE_FIELD_TYPE (type, 0);
13408   if (pfn_type == NULL
13409       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13410       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13411     return;
13412
13413   /* Look for the "this" argument.  */
13414   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13415   if (TYPE_NFIELDS (pfn_type) == 0
13416       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13417       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13418     return;
13419
13420   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13421   new_type = alloc_type (objfile);
13422   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13423                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13424                         TYPE_VARARGS (pfn_type));
13425   smash_to_methodptr_type (type, new_type);
13426 }
13427
13428 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13429    (icc).  */
13430
13431 static int
13432 producer_is_icc (struct dwarf2_cu *cu)
13433 {
13434   if (!cu->checked_producer)
13435     check_producer (cu);
13436
13437   return cu->producer_is_icc;
13438 }
13439
13440 /* Called when we find the DIE that starts a structure or union scope
13441    (definition) to create a type for the structure or union.  Fill in
13442    the type's name and general properties; the members will not be
13443    processed until process_structure_scope.  A symbol table entry for
13444    the type will also not be done until process_structure_scope (assuming
13445    the type has a name).
13446
13447    NOTE: we need to call these functions regardless of whether or not the
13448    DIE has a DW_AT_name attribute, since it might be an anonymous
13449    structure or union.  This gets the type entered into our set of
13450    user defined types.  */
13451
13452 static struct type *
13453 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13454 {
13455   struct objfile *objfile = cu->objfile;
13456   struct type *type;
13457   struct attribute *attr;
13458   const char *name;
13459
13460   /* If the definition of this type lives in .debug_types, read that type.
13461      Don't follow DW_AT_specification though, that will take us back up
13462      the chain and we want to go down.  */
13463   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13464   if (attr)
13465     {
13466       type = get_DW_AT_signature_type (die, attr, cu);
13467
13468       /* The type's CU may not be the same as CU.
13469          Ensure TYPE is recorded with CU in die_type_hash.  */
13470       return set_die_type (die, type, cu);
13471     }
13472
13473   type = alloc_type (objfile);
13474   INIT_CPLUS_SPECIFIC (type);
13475
13476   name = dwarf2_name (die, cu);
13477   if (name != NULL)
13478     {
13479       if (cu->language == language_cplus
13480           || cu->language == language_d
13481           || cu->language == language_rust)
13482         {
13483           const char *full_name = dwarf2_full_name (name, die, cu);
13484
13485           /* dwarf2_full_name might have already finished building the DIE's
13486              type.  If so, there is no need to continue.  */
13487           if (get_die_type (die, cu) != NULL)
13488             return get_die_type (die, cu);
13489
13490           TYPE_TAG_NAME (type) = full_name;
13491           if (die->tag == DW_TAG_structure_type
13492               || die->tag == DW_TAG_class_type)
13493             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13494         }
13495       else
13496         {
13497           /* The name is already allocated along with this objfile, so
13498              we don't need to duplicate it for the type.  */
13499           TYPE_TAG_NAME (type) = name;
13500           if (die->tag == DW_TAG_class_type)
13501             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13502         }
13503     }
13504
13505   if (die->tag == DW_TAG_structure_type)
13506     {
13507       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13508     }
13509   else if (die->tag == DW_TAG_union_type)
13510     {
13511       TYPE_CODE (type) = TYPE_CODE_UNION;
13512     }
13513   else
13514     {
13515       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13516     }
13517
13518   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13519     TYPE_DECLARED_CLASS (type) = 1;
13520
13521   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13522   if (attr)
13523     {
13524       if (attr_form_is_constant (attr))
13525         TYPE_LENGTH (type) = DW_UNSND (attr);
13526       else
13527         {
13528           /* For the moment, dynamic type sizes are not supported
13529              by GDB's struct type.  The actual size is determined
13530              on-demand when resolving the type of a given object,
13531              so set the type's length to zero for now.  Otherwise,
13532              we record an expression as the length, and that expression
13533              could lead to a very large value, which could eventually
13534              lead to us trying to allocate that much memory when creating
13535              a value of that type.  */
13536           TYPE_LENGTH (type) = 0;
13537         }
13538     }
13539   else
13540     {
13541       TYPE_LENGTH (type) = 0;
13542     }
13543
13544   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13545     {
13546       /* ICC does not output the required DW_AT_declaration
13547          on incomplete types, but gives them a size of zero.  */
13548       TYPE_STUB (type) = 1;
13549     }
13550   else
13551     TYPE_STUB_SUPPORTED (type) = 1;
13552
13553   if (die_is_declaration (die, cu))
13554     TYPE_STUB (type) = 1;
13555   else if (attr == NULL && die->child == NULL
13556            && producer_is_realview (cu->producer))
13557     /* RealView does not output the required DW_AT_declaration
13558        on incomplete types.  */
13559     TYPE_STUB (type) = 1;
13560
13561   /* We need to add the type field to the die immediately so we don't
13562      infinitely recurse when dealing with pointers to the structure
13563      type within the structure itself.  */
13564   set_die_type (die, type, cu);
13565
13566   /* set_die_type should be already done.  */
13567   set_descriptive_type (type, die, cu);
13568
13569   return type;
13570 }
13571
13572 /* Finish creating a structure or union type, including filling in
13573    its members and creating a symbol for it.  */
13574
13575 static void
13576 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13577 {
13578   struct objfile *objfile = cu->objfile;
13579   struct die_info *child_die;
13580   struct type *type;
13581
13582   type = get_die_type (die, cu);
13583   if (type == NULL)
13584     type = read_structure_type (die, cu);
13585
13586   if (die->child != NULL && ! die_is_declaration (die, cu))
13587     {
13588       struct field_info fi;
13589       VEC (symbolp) *template_args = NULL;
13590       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13591
13592       memset (&fi, 0, sizeof (struct field_info));
13593
13594       child_die = die->child;
13595
13596       while (child_die && child_die->tag)
13597         {
13598           if (child_die->tag == DW_TAG_member
13599               || child_die->tag == DW_TAG_variable)
13600             {
13601               /* NOTE: carlton/2002-11-05: A C++ static data member
13602                  should be a DW_TAG_member that is a declaration, but
13603                  all versions of G++ as of this writing (so through at
13604                  least 3.2.1) incorrectly generate DW_TAG_variable
13605                  tags for them instead.  */
13606               dwarf2_add_field (&fi, child_die, cu);
13607             }
13608           else if (child_die->tag == DW_TAG_subprogram)
13609             {
13610               /* Rust doesn't have member functions in the C++ sense.
13611                  However, it does emit ordinary functions as children
13612                  of a struct DIE.  */
13613               if (cu->language == language_rust)
13614                 read_func_scope (child_die, cu);
13615               else
13616                 {
13617                   /* C++ member function.  */
13618                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13619                 }
13620             }
13621           else if (child_die->tag == DW_TAG_inheritance)
13622             {
13623               /* C++ base class field.  */
13624               dwarf2_add_field (&fi, child_die, cu);
13625             }
13626           else if (child_die->tag == DW_TAG_typedef)
13627             dwarf2_add_typedef (&fi, child_die, cu);
13628           else if (child_die->tag == DW_TAG_template_type_param
13629                    || child_die->tag == DW_TAG_template_value_param)
13630             {
13631               struct symbol *arg = new_symbol (child_die, NULL, cu);
13632
13633               if (arg != NULL)
13634                 VEC_safe_push (symbolp, template_args, arg);
13635             }
13636
13637           child_die = sibling_die (child_die);
13638         }
13639
13640       /* Attach template arguments to type.  */
13641       if (! VEC_empty (symbolp, template_args))
13642         {
13643           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13644           TYPE_N_TEMPLATE_ARGUMENTS (type)
13645             = VEC_length (symbolp, template_args);
13646           TYPE_TEMPLATE_ARGUMENTS (type)
13647             = XOBNEWVEC (&objfile->objfile_obstack,
13648                          struct symbol *,
13649                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13650           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13651                   VEC_address (symbolp, template_args),
13652                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13653                    * sizeof (struct symbol *)));
13654           VEC_free (symbolp, template_args);
13655         }
13656
13657       /* Attach fields and member functions to the type.  */
13658       if (fi.nfields)
13659         dwarf2_attach_fields_to_type (&fi, type, cu);
13660       if (fi.nfnfields)
13661         {
13662           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13663
13664           /* Get the type which refers to the base class (possibly this
13665              class itself) which contains the vtable pointer for the current
13666              class from the DW_AT_containing_type attribute.  This use of
13667              DW_AT_containing_type is a GNU extension.  */
13668
13669           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13670             {
13671               struct type *t = die_containing_type (die, cu);
13672
13673               set_type_vptr_basetype (type, t);
13674               if (type == t)
13675                 {
13676                   int i;
13677
13678                   /* Our own class provides vtbl ptr.  */
13679                   for (i = TYPE_NFIELDS (t) - 1;
13680                        i >= TYPE_N_BASECLASSES (t);
13681                        --i)
13682                     {
13683                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13684
13685                       if (is_vtable_name (fieldname, cu))
13686                         {
13687                           set_type_vptr_fieldno (type, i);
13688                           break;
13689                         }
13690                     }
13691
13692                   /* Complain if virtual function table field not found.  */
13693                   if (i < TYPE_N_BASECLASSES (t))
13694                     complaint (&symfile_complaints,
13695                                _("virtual function table pointer "
13696                                  "not found when defining class '%s'"),
13697                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13698                                "");
13699                 }
13700               else
13701                 {
13702                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13703                 }
13704             }
13705           else if (cu->producer
13706                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13707             {
13708               /* The IBM XLC compiler does not provide direct indication
13709                  of the containing type, but the vtable pointer is
13710                  always named __vfp.  */
13711
13712               int i;
13713
13714               for (i = TYPE_NFIELDS (type) - 1;
13715                    i >= TYPE_N_BASECLASSES (type);
13716                    --i)
13717                 {
13718                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13719                     {
13720                       set_type_vptr_fieldno (type, i);
13721                       set_type_vptr_basetype (type, type);
13722                       break;
13723                     }
13724                 }
13725             }
13726         }
13727
13728       /* Copy fi.typedef_field_list linked list elements content into the
13729          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13730       if (fi.typedef_field_list)
13731         {
13732           int i = fi.typedef_field_list_count;
13733
13734           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13735           TYPE_TYPEDEF_FIELD_ARRAY (type)
13736             = ((struct typedef_field *)
13737                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13738           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13739
13740           /* Reverse the list order to keep the debug info elements order.  */
13741           while (--i >= 0)
13742             {
13743               struct typedef_field *dest, *src;
13744
13745               dest = &TYPE_TYPEDEF_FIELD (type, i);
13746               src = &fi.typedef_field_list->field;
13747               fi.typedef_field_list = fi.typedef_field_list->next;
13748               *dest = *src;
13749             }
13750         }
13751
13752       do_cleanups (back_to);
13753     }
13754
13755   quirk_gcc_member_function_pointer (type, objfile);
13756
13757   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13758      snapshots) has been known to create a die giving a declaration
13759      for a class that has, as a child, a die giving a definition for a
13760      nested class.  So we have to process our children even if the
13761      current die is a declaration.  Normally, of course, a declaration
13762      won't have any children at all.  */
13763
13764   child_die = die->child;
13765
13766   while (child_die != NULL && child_die->tag)
13767     {
13768       if (child_die->tag == DW_TAG_member
13769           || child_die->tag == DW_TAG_variable
13770           || child_die->tag == DW_TAG_inheritance
13771           || child_die->tag == DW_TAG_template_value_param
13772           || child_die->tag == DW_TAG_template_type_param)
13773         {
13774           /* Do nothing.  */
13775         }
13776       else
13777         process_die (child_die, cu);
13778
13779       child_die = sibling_die (child_die);
13780     }
13781
13782   /* Do not consider external references.  According to the DWARF standard,
13783      these DIEs are identified by the fact that they have no byte_size
13784      attribute, and a declaration attribute.  */
13785   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13786       || !die_is_declaration (die, cu))
13787     new_symbol (die, type, cu);
13788 }
13789
13790 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13791    update TYPE using some information only available in DIE's children.  */
13792
13793 static void
13794 update_enumeration_type_from_children (struct die_info *die,
13795                                        struct type *type,
13796                                        struct dwarf2_cu *cu)
13797 {
13798   struct obstack obstack;
13799   struct die_info *child_die;
13800   int unsigned_enum = 1;
13801   int flag_enum = 1;
13802   ULONGEST mask = 0;
13803   struct cleanup *old_chain;
13804
13805   obstack_init (&obstack);
13806   old_chain = make_cleanup_obstack_free (&obstack);
13807
13808   for (child_die = die->child;
13809        child_die != NULL && child_die->tag;
13810        child_die = sibling_die (child_die))
13811     {
13812       struct attribute *attr;
13813       LONGEST value;
13814       const gdb_byte *bytes;
13815       struct dwarf2_locexpr_baton *baton;
13816       const char *name;
13817
13818       if (child_die->tag != DW_TAG_enumerator)
13819         continue;
13820
13821       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13822       if (attr == NULL)
13823         continue;
13824
13825       name = dwarf2_name (child_die, cu);
13826       if (name == NULL)
13827         name = "<anonymous enumerator>";
13828
13829       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13830                                &value, &bytes, &baton);
13831       if (value < 0)
13832         {
13833           unsigned_enum = 0;
13834           flag_enum = 0;
13835         }
13836       else if ((mask & value) != 0)
13837         flag_enum = 0;
13838       else
13839         mask |= value;
13840
13841       /* If we already know that the enum type is neither unsigned, nor
13842          a flag type, no need to look at the rest of the enumerates.  */
13843       if (!unsigned_enum && !flag_enum)
13844         break;
13845     }
13846
13847   if (unsigned_enum)
13848     TYPE_UNSIGNED (type) = 1;
13849   if (flag_enum)
13850     TYPE_FLAG_ENUM (type) = 1;
13851
13852   do_cleanups (old_chain);
13853 }
13854
13855 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13856    complete the type's fields yet, or create any symbols.  */
13857
13858 static struct type *
13859 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13860 {
13861   struct objfile *objfile = cu->objfile;
13862   struct type *type;
13863   struct attribute *attr;
13864   const char *name;
13865
13866   /* If the definition of this type lives in .debug_types, read that type.
13867      Don't follow DW_AT_specification though, that will take us back up
13868      the chain and we want to go down.  */
13869   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13870   if (attr)
13871     {
13872       type = get_DW_AT_signature_type (die, attr, cu);
13873
13874       /* The type's CU may not be the same as CU.
13875          Ensure TYPE is recorded with CU in die_type_hash.  */
13876       return set_die_type (die, type, cu);
13877     }
13878
13879   type = alloc_type (objfile);
13880
13881   TYPE_CODE (type) = TYPE_CODE_ENUM;
13882   name = dwarf2_full_name (NULL, die, cu);
13883   if (name != NULL)
13884     TYPE_TAG_NAME (type) = name;
13885
13886   attr = dwarf2_attr (die, DW_AT_type, cu);
13887   if (attr != NULL)
13888     {
13889       struct type *underlying_type = die_type (die, cu);
13890
13891       TYPE_TARGET_TYPE (type) = underlying_type;
13892     }
13893
13894   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13895   if (attr)
13896     {
13897       TYPE_LENGTH (type) = DW_UNSND (attr);
13898     }
13899   else
13900     {
13901       TYPE_LENGTH (type) = 0;
13902     }
13903
13904   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13905      declared as private in the package spec, and then defined only
13906      inside the package body.  Such types are known as Taft Amendment
13907      Types.  When another package uses such a type, an incomplete DIE
13908      may be generated by the compiler.  */
13909   if (die_is_declaration (die, cu))
13910     TYPE_STUB (type) = 1;
13911
13912   /* Finish the creation of this type by using the enum's children.
13913      We must call this even when the underlying type has been provided
13914      so that we can determine if we're looking at a "flag" enum.  */
13915   update_enumeration_type_from_children (die, type, cu);
13916
13917   /* If this type has an underlying type that is not a stub, then we
13918      may use its attributes.  We always use the "unsigned" attribute
13919      in this situation, because ordinarily we guess whether the type
13920      is unsigned -- but the guess can be wrong and the underlying type
13921      can tell us the reality.  However, we defer to a local size
13922      attribute if one exists, because this lets the compiler override
13923      the underlying type if needed.  */
13924   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
13925     {
13926       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
13927       if (TYPE_LENGTH (type) == 0)
13928         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
13929     }
13930
13931   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
13932
13933   return set_die_type (die, type, cu);
13934 }
13935
13936 /* Given a pointer to a die which begins an enumeration, process all
13937    the dies that define the members of the enumeration, and create the
13938    symbol for the enumeration type.
13939
13940    NOTE: We reverse the order of the element list.  */
13941
13942 static void
13943 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
13944 {
13945   struct type *this_type;
13946
13947   this_type = get_die_type (die, cu);
13948   if (this_type == NULL)
13949     this_type = read_enumeration_type (die, cu);
13950
13951   if (die->child != NULL)
13952     {
13953       struct die_info *child_die;
13954       struct symbol *sym;
13955       struct field *fields = NULL;
13956       int num_fields = 0;
13957       const char *name;
13958
13959       child_die = die->child;
13960       while (child_die && child_die->tag)
13961         {
13962           if (child_die->tag != DW_TAG_enumerator)
13963             {
13964               process_die (child_die, cu);
13965             }
13966           else
13967             {
13968               name = dwarf2_name (child_die, cu);
13969               if (name)
13970                 {
13971                   sym = new_symbol (child_die, this_type, cu);
13972
13973                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13974                     {
13975                       fields = (struct field *)
13976                         xrealloc (fields,
13977                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13978                                   * sizeof (struct field));
13979                     }
13980
13981                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13982                   FIELD_TYPE (fields[num_fields]) = NULL;
13983                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13984                   FIELD_BITSIZE (fields[num_fields]) = 0;
13985
13986                   num_fields++;
13987                 }
13988             }
13989
13990           child_die = sibling_die (child_die);
13991         }
13992
13993       if (num_fields)
13994         {
13995           TYPE_NFIELDS (this_type) = num_fields;
13996           TYPE_FIELDS (this_type) = (struct field *)
13997             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13998           memcpy (TYPE_FIELDS (this_type), fields,
13999                   sizeof (struct field) * num_fields);
14000           xfree (fields);
14001         }
14002     }
14003
14004   /* If we are reading an enum from a .debug_types unit, and the enum
14005      is a declaration, and the enum is not the signatured type in the
14006      unit, then we do not want to add a symbol for it.  Adding a
14007      symbol would in some cases obscure the true definition of the
14008      enum, giving users an incomplete type when the definition is
14009      actually available.  Note that we do not want to do this for all
14010      enums which are just declarations, because C++0x allows forward
14011      enum declarations.  */
14012   if (cu->per_cu->is_debug_types
14013       && die_is_declaration (die, cu))
14014     {
14015       struct signatured_type *sig_type;
14016
14017       sig_type = (struct signatured_type *) cu->per_cu;
14018       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14019       if (sig_type->type_offset_in_section != die->sect_off)
14020         return;
14021     }
14022
14023   new_symbol (die, this_type, cu);
14024 }
14025
14026 /* Extract all information from a DW_TAG_array_type DIE and put it in
14027    the DIE's type field.  For now, this only handles one dimensional
14028    arrays.  */
14029
14030 static struct type *
14031 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14032 {
14033   struct objfile *objfile = cu->objfile;
14034   struct die_info *child_die;
14035   struct type *type;
14036   struct type *element_type, *range_type, *index_type;
14037   struct type **range_types = NULL;
14038   struct attribute *attr;
14039   int ndim = 0;
14040   struct cleanup *back_to;
14041   const char *name;
14042   unsigned int bit_stride = 0;
14043
14044   element_type = die_type (die, cu);
14045
14046   /* The die_type call above may have already set the type for this DIE.  */
14047   type = get_die_type (die, cu);
14048   if (type)
14049     return type;
14050
14051   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14052   if (attr != NULL)
14053     bit_stride = DW_UNSND (attr) * 8;
14054
14055   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14056   if (attr != NULL)
14057     bit_stride = DW_UNSND (attr);
14058
14059   /* Irix 6.2 native cc creates array types without children for
14060      arrays with unspecified length.  */
14061   if (die->child == NULL)
14062     {
14063       index_type = objfile_type (objfile)->builtin_int;
14064       range_type = create_static_range_type (NULL, index_type, 0, -1);
14065       type = create_array_type_with_stride (NULL, element_type, range_type,
14066                                             bit_stride);
14067       return set_die_type (die, type, cu);
14068     }
14069
14070   back_to = make_cleanup (null_cleanup, NULL);
14071   child_die = die->child;
14072   while (child_die && child_die->tag)
14073     {
14074       if (child_die->tag == DW_TAG_subrange_type)
14075         {
14076           struct type *child_type = read_type_die (child_die, cu);
14077
14078           if (child_type != NULL)
14079             {
14080               /* The range type was succesfully read.  Save it for the
14081                  array type creation.  */
14082               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14083                 {
14084                   range_types = (struct type **)
14085                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14086                               * sizeof (struct type *));
14087                   if (ndim == 0)
14088                     make_cleanup (free_current_contents, &range_types);
14089                 }
14090               range_types[ndim++] = child_type;
14091             }
14092         }
14093       child_die = sibling_die (child_die);
14094     }
14095
14096   /* Dwarf2 dimensions are output from left to right, create the
14097      necessary array types in backwards order.  */
14098
14099   type = element_type;
14100
14101   if (read_array_order (die, cu) == DW_ORD_col_major)
14102     {
14103       int i = 0;
14104
14105       while (i < ndim)
14106         type = create_array_type_with_stride (NULL, type, range_types[i++],
14107                                               bit_stride);
14108     }
14109   else
14110     {
14111       while (ndim-- > 0)
14112         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14113                                               bit_stride);
14114     }
14115
14116   /* Understand Dwarf2 support for vector types (like they occur on
14117      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14118      array type.  This is not part of the Dwarf2/3 standard yet, but a
14119      custom vendor extension.  The main difference between a regular
14120      array and the vector variant is that vectors are passed by value
14121      to functions.  */
14122   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14123   if (attr)
14124     make_vector_type (type);
14125
14126   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14127      implementation may choose to implement triple vectors using this
14128      attribute.  */
14129   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14130   if (attr)
14131     {
14132       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14133         TYPE_LENGTH (type) = DW_UNSND (attr);
14134       else
14135         complaint (&symfile_complaints,
14136                    _("DW_AT_byte_size for array type smaller "
14137                      "than the total size of elements"));
14138     }
14139
14140   name = dwarf2_name (die, cu);
14141   if (name)
14142     TYPE_NAME (type) = name;
14143
14144   /* Install the type in the die.  */
14145   set_die_type (die, type, cu);
14146
14147   /* set_die_type should be already done.  */
14148   set_descriptive_type (type, die, cu);
14149
14150   do_cleanups (back_to);
14151
14152   return type;
14153 }
14154
14155 static enum dwarf_array_dim_ordering
14156 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14157 {
14158   struct attribute *attr;
14159
14160   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14161
14162   if (attr)
14163     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14164
14165   /* GNU F77 is a special case, as at 08/2004 array type info is the
14166      opposite order to the dwarf2 specification, but data is still
14167      laid out as per normal fortran.
14168
14169      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14170      version checking.  */
14171
14172   if (cu->language == language_fortran
14173       && cu->producer && strstr (cu->producer, "GNU F77"))
14174     {
14175       return DW_ORD_row_major;
14176     }
14177
14178   switch (cu->language_defn->la_array_ordering)
14179     {
14180     case array_column_major:
14181       return DW_ORD_col_major;
14182     case array_row_major:
14183     default:
14184       return DW_ORD_row_major;
14185     };
14186 }
14187
14188 /* Extract all information from a DW_TAG_set_type DIE and put it in
14189    the DIE's type field.  */
14190
14191 static struct type *
14192 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14193 {
14194   struct type *domain_type, *set_type;
14195   struct attribute *attr;
14196
14197   domain_type = die_type (die, cu);
14198
14199   /* The die_type call above may have already set the type for this DIE.  */
14200   set_type = get_die_type (die, cu);
14201   if (set_type)
14202     return set_type;
14203
14204   set_type = create_set_type (NULL, domain_type);
14205
14206   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14207   if (attr)
14208     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14209
14210   return set_die_type (die, set_type, cu);
14211 }
14212
14213 /* A helper for read_common_block that creates a locexpr baton.
14214    SYM is the symbol which we are marking as computed.
14215    COMMON_DIE is the DIE for the common block.
14216    COMMON_LOC is the location expression attribute for the common
14217    block itself.
14218    MEMBER_LOC is the location expression attribute for the particular
14219    member of the common block that we are processing.
14220    CU is the CU from which the above come.  */
14221
14222 static void
14223 mark_common_block_symbol_computed (struct symbol *sym,
14224                                    struct die_info *common_die,
14225                                    struct attribute *common_loc,
14226                                    struct attribute *member_loc,
14227                                    struct dwarf2_cu *cu)
14228 {
14229   struct objfile *objfile = dwarf2_per_objfile->objfile;
14230   struct dwarf2_locexpr_baton *baton;
14231   gdb_byte *ptr;
14232   unsigned int cu_off;
14233   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14234   LONGEST offset = 0;
14235
14236   gdb_assert (common_loc && member_loc);
14237   gdb_assert (attr_form_is_block (common_loc));
14238   gdb_assert (attr_form_is_block (member_loc)
14239               || attr_form_is_constant (member_loc));
14240
14241   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14242   baton->per_cu = cu->per_cu;
14243   gdb_assert (baton->per_cu);
14244
14245   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14246
14247   if (attr_form_is_constant (member_loc))
14248     {
14249       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14250       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14251     }
14252   else
14253     baton->size += DW_BLOCK (member_loc)->size;
14254
14255   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14256   baton->data = ptr;
14257
14258   *ptr++ = DW_OP_call4;
14259   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14260   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14261   ptr += 4;
14262
14263   if (attr_form_is_constant (member_loc))
14264     {
14265       *ptr++ = DW_OP_addr;
14266       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14267       ptr += cu->header.addr_size;
14268     }
14269   else
14270     {
14271       /* We have to copy the data here, because DW_OP_call4 will only
14272          use a DW_AT_location attribute.  */
14273       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14274       ptr += DW_BLOCK (member_loc)->size;
14275     }
14276
14277   *ptr++ = DW_OP_plus;
14278   gdb_assert (ptr - baton->data == baton->size);
14279
14280   SYMBOL_LOCATION_BATON (sym) = baton;
14281   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14282 }
14283
14284 /* Create appropriate locally-scoped variables for all the
14285    DW_TAG_common_block entries.  Also create a struct common_block
14286    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14287    is used to sepate the common blocks name namespace from regular
14288    variable names.  */
14289
14290 static void
14291 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14292 {
14293   struct attribute *attr;
14294
14295   attr = dwarf2_attr (die, DW_AT_location, cu);
14296   if (attr)
14297     {
14298       /* Support the .debug_loc offsets.  */
14299       if (attr_form_is_block (attr))
14300         {
14301           /* Ok.  */
14302         }
14303       else if (attr_form_is_section_offset (attr))
14304         {
14305           dwarf2_complex_location_expr_complaint ();
14306           attr = NULL;
14307         }
14308       else
14309         {
14310           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14311                                                  "common block member");
14312           attr = NULL;
14313         }
14314     }
14315
14316   if (die->child != NULL)
14317     {
14318       struct objfile *objfile = cu->objfile;
14319       struct die_info *child_die;
14320       size_t n_entries = 0, size;
14321       struct common_block *common_block;
14322       struct symbol *sym;
14323
14324       for (child_die = die->child;
14325            child_die && child_die->tag;
14326            child_die = sibling_die (child_die))
14327         ++n_entries;
14328
14329       size = (sizeof (struct common_block)
14330               + (n_entries - 1) * sizeof (struct symbol *));
14331       common_block
14332         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14333                                                  size);
14334       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14335       common_block->n_entries = 0;
14336
14337       for (child_die = die->child;
14338            child_die && child_die->tag;
14339            child_die = sibling_die (child_die))
14340         {
14341           /* Create the symbol in the DW_TAG_common_block block in the current
14342              symbol scope.  */
14343           sym = new_symbol (child_die, NULL, cu);
14344           if (sym != NULL)
14345             {
14346               struct attribute *member_loc;
14347
14348               common_block->contents[common_block->n_entries++] = sym;
14349
14350               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14351                                         cu);
14352               if (member_loc)
14353                 {
14354                   /* GDB has handled this for a long time, but it is
14355                      not specified by DWARF.  It seems to have been
14356                      emitted by gfortran at least as recently as:
14357                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14358                   complaint (&symfile_complaints,
14359                              _("Variable in common block has "
14360                                "DW_AT_data_member_location "
14361                                "- DIE at 0x%x [in module %s]"),
14362                              to_underlying (child_die->sect_off),
14363                              objfile_name (cu->objfile));
14364
14365                   if (attr_form_is_section_offset (member_loc))
14366                     dwarf2_complex_location_expr_complaint ();
14367                   else if (attr_form_is_constant (member_loc)
14368                            || attr_form_is_block (member_loc))
14369                     {
14370                       if (attr)
14371                         mark_common_block_symbol_computed (sym, die, attr,
14372                                                            member_loc, cu);
14373                     }
14374                   else
14375                     dwarf2_complex_location_expr_complaint ();
14376                 }
14377             }
14378         }
14379
14380       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14381       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14382     }
14383 }
14384
14385 /* Create a type for a C++ namespace.  */
14386
14387 static struct type *
14388 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14389 {
14390   struct objfile *objfile = cu->objfile;
14391   const char *previous_prefix, *name;
14392   int is_anonymous;
14393   struct type *type;
14394
14395   /* For extensions, reuse the type of the original namespace.  */
14396   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14397     {
14398       struct die_info *ext_die;
14399       struct dwarf2_cu *ext_cu = cu;
14400
14401       ext_die = dwarf2_extension (die, &ext_cu);
14402       type = read_type_die (ext_die, ext_cu);
14403
14404       /* EXT_CU may not be the same as CU.
14405          Ensure TYPE is recorded with CU in die_type_hash.  */
14406       return set_die_type (die, type, cu);
14407     }
14408
14409   name = namespace_name (die, &is_anonymous, cu);
14410
14411   /* Now build the name of the current namespace.  */
14412
14413   previous_prefix = determine_prefix (die, cu);
14414   if (previous_prefix[0] != '\0')
14415     name = typename_concat (&objfile->objfile_obstack,
14416                             previous_prefix, name, 0, cu);
14417
14418   /* Create the type.  */
14419   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14420   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14421
14422   return set_die_type (die, type, cu);
14423 }
14424
14425 /* Read a namespace scope.  */
14426
14427 static void
14428 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14429 {
14430   struct objfile *objfile = cu->objfile;
14431   int is_anonymous;
14432
14433   /* Add a symbol associated to this if we haven't seen the namespace
14434      before.  Also, add a using directive if it's an anonymous
14435      namespace.  */
14436
14437   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14438     {
14439       struct type *type;
14440
14441       type = read_type_die (die, cu);
14442       new_symbol (die, type, cu);
14443
14444       namespace_name (die, &is_anonymous, cu);
14445       if (is_anonymous)
14446         {
14447           const char *previous_prefix = determine_prefix (die, cu);
14448
14449           add_using_directive (using_directives (cu->language),
14450                                previous_prefix, TYPE_NAME (type), NULL,
14451                                NULL, NULL, 0, &objfile->objfile_obstack);
14452         }
14453     }
14454
14455   if (die->child != NULL)
14456     {
14457       struct die_info *child_die = die->child;
14458
14459       while (child_die && child_die->tag)
14460         {
14461           process_die (child_die, cu);
14462           child_die = sibling_die (child_die);
14463         }
14464     }
14465 }
14466
14467 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14468    imported module.  Still we need that type as local Fortran "use ... only"
14469    declaration imports depend on the created type in determine_prefix.  */
14470
14471 static struct type *
14472 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14473 {
14474   struct objfile *objfile = cu->objfile;
14475   const char *module_name;
14476   struct type *type;
14477
14478   module_name = dwarf2_name (die, cu);
14479   if (!module_name)
14480     complaint (&symfile_complaints,
14481                _("DW_TAG_module has no name, offset 0x%x"),
14482                to_underlying (die->sect_off));
14483   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14484
14485   /* determine_prefix uses TYPE_TAG_NAME.  */
14486   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14487
14488   return set_die_type (die, type, cu);
14489 }
14490
14491 /* Read a Fortran module.  */
14492
14493 static void
14494 read_module (struct die_info *die, struct dwarf2_cu *cu)
14495 {
14496   struct die_info *child_die = die->child;
14497   struct type *type;
14498
14499   type = read_type_die (die, cu);
14500   new_symbol (die, type, cu);
14501
14502   while (child_die && child_die->tag)
14503     {
14504       process_die (child_die, cu);
14505       child_die = sibling_die (child_die);
14506     }
14507 }
14508
14509 /* Return the name of the namespace represented by DIE.  Set
14510    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14511    namespace.  */
14512
14513 static const char *
14514 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14515 {
14516   struct die_info *current_die;
14517   const char *name = NULL;
14518
14519   /* Loop through the extensions until we find a name.  */
14520
14521   for (current_die = die;
14522        current_die != NULL;
14523        current_die = dwarf2_extension (die, &cu))
14524     {
14525       /* We don't use dwarf2_name here so that we can detect the absence
14526          of a name -> anonymous namespace.  */
14527       name = dwarf2_string_attr (die, DW_AT_name, cu);
14528
14529       if (name != NULL)
14530         break;
14531     }
14532
14533   /* Is it an anonymous namespace?  */
14534
14535   *is_anonymous = (name == NULL);
14536   if (*is_anonymous)
14537     name = CP_ANONYMOUS_NAMESPACE_STR;
14538
14539   return name;
14540 }
14541
14542 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14543    the user defined type vector.  */
14544
14545 static struct type *
14546 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14547 {
14548   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14549   struct comp_unit_head *cu_header = &cu->header;
14550   struct type *type;
14551   struct attribute *attr_byte_size;
14552   struct attribute *attr_address_class;
14553   int byte_size, addr_class;
14554   struct type *target_type;
14555
14556   target_type = die_type (die, cu);
14557
14558   /* The die_type call above may have already set the type for this DIE.  */
14559   type = get_die_type (die, cu);
14560   if (type)
14561     return type;
14562
14563   type = lookup_pointer_type (target_type);
14564
14565   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14566   if (attr_byte_size)
14567     byte_size = DW_UNSND (attr_byte_size);
14568   else
14569     byte_size = cu_header->addr_size;
14570
14571   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14572   if (attr_address_class)
14573     addr_class = DW_UNSND (attr_address_class);
14574   else
14575     addr_class = DW_ADDR_none;
14576
14577   /* If the pointer size or address class is different than the
14578      default, create a type variant marked as such and set the
14579      length accordingly.  */
14580   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14581     {
14582       if (gdbarch_address_class_type_flags_p (gdbarch))
14583         {
14584           int type_flags;
14585
14586           type_flags = gdbarch_address_class_type_flags
14587                          (gdbarch, byte_size, addr_class);
14588           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14589                       == 0);
14590           type = make_type_with_address_space (type, type_flags);
14591         }
14592       else if (TYPE_LENGTH (type) != byte_size)
14593         {
14594           complaint (&symfile_complaints,
14595                      _("invalid pointer size %d"), byte_size);
14596         }
14597       else
14598         {
14599           /* Should we also complain about unhandled address classes?  */
14600         }
14601     }
14602
14603   TYPE_LENGTH (type) = byte_size;
14604   return set_die_type (die, type, cu);
14605 }
14606
14607 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14608    the user defined type vector.  */
14609
14610 static struct type *
14611 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14612 {
14613   struct type *type;
14614   struct type *to_type;
14615   struct type *domain;
14616
14617   to_type = die_type (die, cu);
14618   domain = die_containing_type (die, cu);
14619
14620   /* The calls above may have already set the type for this DIE.  */
14621   type = get_die_type (die, cu);
14622   if (type)
14623     return type;
14624
14625   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14626     type = lookup_methodptr_type (to_type);
14627   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14628     {
14629       struct type *new_type = alloc_type (cu->objfile);
14630
14631       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14632                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14633                             TYPE_VARARGS (to_type));
14634       type = lookup_methodptr_type (new_type);
14635     }
14636   else
14637     type = lookup_memberptr_type (to_type, domain);
14638
14639   return set_die_type (die, type, cu);
14640 }
14641
14642 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14643    the user defined type vector.  */
14644
14645 static struct type *
14646 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14647                           enum type_code refcode)
14648 {
14649   struct comp_unit_head *cu_header = &cu->header;
14650   struct type *type, *target_type;
14651   struct attribute *attr;
14652
14653   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14654
14655   target_type = die_type (die, cu);
14656
14657   /* The die_type call above may have already set the type for this DIE.  */
14658   type = get_die_type (die, cu);
14659   if (type)
14660     return type;
14661
14662   type = lookup_reference_type (target_type, refcode);
14663   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14664   if (attr)
14665     {
14666       TYPE_LENGTH (type) = DW_UNSND (attr);
14667     }
14668   else
14669     {
14670       TYPE_LENGTH (type) = cu_header->addr_size;
14671     }
14672   return set_die_type (die, type, cu);
14673 }
14674
14675 /* Add the given cv-qualifiers to the element type of the array.  GCC
14676    outputs DWARF type qualifiers that apply to an array, not the
14677    element type.  But GDB relies on the array element type to carry
14678    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14679    specification.  */
14680
14681 static struct type *
14682 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14683                    struct type *base_type, int cnst, int voltl)
14684 {
14685   struct type *el_type, *inner_array;
14686
14687   base_type = copy_type (base_type);
14688   inner_array = base_type;
14689
14690   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14691     {
14692       TYPE_TARGET_TYPE (inner_array) =
14693         copy_type (TYPE_TARGET_TYPE (inner_array));
14694       inner_array = TYPE_TARGET_TYPE (inner_array);
14695     }
14696
14697   el_type = TYPE_TARGET_TYPE (inner_array);
14698   cnst |= TYPE_CONST (el_type);
14699   voltl |= TYPE_VOLATILE (el_type);
14700   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14701
14702   return set_die_type (die, base_type, cu);
14703 }
14704
14705 static struct type *
14706 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14707 {
14708   struct type *base_type, *cv_type;
14709
14710   base_type = die_type (die, cu);
14711
14712   /* The die_type call above may have already set the type for this DIE.  */
14713   cv_type = get_die_type (die, cu);
14714   if (cv_type)
14715     return cv_type;
14716
14717   /* In case the const qualifier is applied to an array type, the element type
14718      is so qualified, not the array type (section 6.7.3 of C99).  */
14719   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14720     return add_array_cv_type (die, cu, base_type, 1, 0);
14721
14722   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14723   return set_die_type (die, cv_type, cu);
14724 }
14725
14726 static struct type *
14727 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14728 {
14729   struct type *base_type, *cv_type;
14730
14731   base_type = die_type (die, cu);
14732
14733   /* The die_type call above may have already set the type for this DIE.  */
14734   cv_type = get_die_type (die, cu);
14735   if (cv_type)
14736     return cv_type;
14737
14738   /* In case the volatile qualifier is applied to an array type, the
14739      element type is so qualified, not the array type (section 6.7.3
14740      of C99).  */
14741   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14742     return add_array_cv_type (die, cu, base_type, 0, 1);
14743
14744   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14745   return set_die_type (die, cv_type, cu);
14746 }
14747
14748 /* Handle DW_TAG_restrict_type.  */
14749
14750 static struct type *
14751 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14752 {
14753   struct type *base_type, *cv_type;
14754
14755   base_type = die_type (die, cu);
14756
14757   /* The die_type call above may have already set the type for this DIE.  */
14758   cv_type = get_die_type (die, cu);
14759   if (cv_type)
14760     return cv_type;
14761
14762   cv_type = make_restrict_type (base_type);
14763   return set_die_type (die, cv_type, cu);
14764 }
14765
14766 /* Handle DW_TAG_atomic_type.  */
14767
14768 static struct type *
14769 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14770 {
14771   struct type *base_type, *cv_type;
14772
14773   base_type = die_type (die, cu);
14774
14775   /* The die_type call above may have already set the type for this DIE.  */
14776   cv_type = get_die_type (die, cu);
14777   if (cv_type)
14778     return cv_type;
14779
14780   cv_type = make_atomic_type (base_type);
14781   return set_die_type (die, cv_type, cu);
14782 }
14783
14784 /* Extract all information from a DW_TAG_string_type DIE and add to
14785    the user defined type vector.  It isn't really a user defined type,
14786    but it behaves like one, with other DIE's using an AT_user_def_type
14787    attribute to reference it.  */
14788
14789 static struct type *
14790 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14791 {
14792   struct objfile *objfile = cu->objfile;
14793   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14794   struct type *type, *range_type, *index_type, *char_type;
14795   struct attribute *attr;
14796   unsigned int length;
14797
14798   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14799   if (attr)
14800     {
14801       length = DW_UNSND (attr);
14802     }
14803   else
14804     {
14805       /* Check for the DW_AT_byte_size attribute.  */
14806       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14807       if (attr)
14808         {
14809           length = DW_UNSND (attr);
14810         }
14811       else
14812         {
14813           length = 1;
14814         }
14815     }
14816
14817   index_type = objfile_type (objfile)->builtin_int;
14818   range_type = create_static_range_type (NULL, index_type, 1, length);
14819   char_type = language_string_char_type (cu->language_defn, gdbarch);
14820   type = create_string_type (NULL, char_type, range_type);
14821
14822   return set_die_type (die, type, cu);
14823 }
14824
14825 /* Assuming that DIE corresponds to a function, returns nonzero
14826    if the function is prototyped.  */
14827
14828 static int
14829 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14830 {
14831   struct attribute *attr;
14832
14833   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14834   if (attr && (DW_UNSND (attr) != 0))
14835     return 1;
14836
14837   /* The DWARF standard implies that the DW_AT_prototyped attribute
14838      is only meaninful for C, but the concept also extends to other
14839      languages that allow unprototyped functions (Eg: Objective C).
14840      For all other languages, assume that functions are always
14841      prototyped.  */
14842   if (cu->language != language_c
14843       && cu->language != language_objc
14844       && cu->language != language_opencl)
14845     return 1;
14846
14847   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14848      prototyped and unprototyped functions; default to prototyped,
14849      since that is more common in modern code (and RealView warns
14850      about unprototyped functions).  */
14851   if (producer_is_realview (cu->producer))
14852     return 1;
14853
14854   return 0;
14855 }
14856
14857 /* Handle DIES due to C code like:
14858
14859    struct foo
14860    {
14861    int (*funcp)(int a, long l);
14862    int b;
14863    };
14864
14865    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14866
14867 static struct type *
14868 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14869 {
14870   struct objfile *objfile = cu->objfile;
14871   struct type *type;            /* Type that this function returns.  */
14872   struct type *ftype;           /* Function that returns above type.  */
14873   struct attribute *attr;
14874
14875   type = die_type (die, cu);
14876
14877   /* The die_type call above may have already set the type for this DIE.  */
14878   ftype = get_die_type (die, cu);
14879   if (ftype)
14880     return ftype;
14881
14882   ftype = lookup_function_type (type);
14883
14884   if (prototyped_function_p (die, cu))
14885     TYPE_PROTOTYPED (ftype) = 1;
14886
14887   /* Store the calling convention in the type if it's available in
14888      the subroutine die.  Otherwise set the calling convention to
14889      the default value DW_CC_normal.  */
14890   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14891   if (attr)
14892     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14893   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14894     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14895   else
14896     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14897
14898   /* Record whether the function returns normally to its caller or not
14899      if the DWARF producer set that information.  */
14900   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
14901   if (attr && (DW_UNSND (attr) != 0))
14902     TYPE_NO_RETURN (ftype) = 1;
14903
14904   /* We need to add the subroutine type to the die immediately so
14905      we don't infinitely recurse when dealing with parameters
14906      declared as the same subroutine type.  */
14907   set_die_type (die, ftype, cu);
14908
14909   if (die->child != NULL)
14910     {
14911       struct type *void_type = objfile_type (objfile)->builtin_void;
14912       struct die_info *child_die;
14913       int nparams, iparams;
14914
14915       /* Count the number of parameters.
14916          FIXME: GDB currently ignores vararg functions, but knows about
14917          vararg member functions.  */
14918       nparams = 0;
14919       child_die = die->child;
14920       while (child_die && child_die->tag)
14921         {
14922           if (child_die->tag == DW_TAG_formal_parameter)
14923             nparams++;
14924           else if (child_die->tag == DW_TAG_unspecified_parameters)
14925             TYPE_VARARGS (ftype) = 1;
14926           child_die = sibling_die (child_die);
14927         }
14928
14929       /* Allocate storage for parameters and fill them in.  */
14930       TYPE_NFIELDS (ftype) = nparams;
14931       TYPE_FIELDS (ftype) = (struct field *)
14932         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
14933
14934       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
14935          even if we error out during the parameters reading below.  */
14936       for (iparams = 0; iparams < nparams; iparams++)
14937         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
14938
14939       iparams = 0;
14940       child_die = die->child;
14941       while (child_die && child_die->tag)
14942         {
14943           if (child_die->tag == DW_TAG_formal_parameter)
14944             {
14945               struct type *arg_type;
14946
14947               /* DWARF version 2 has no clean way to discern C++
14948                  static and non-static member functions.  G++ helps
14949                  GDB by marking the first parameter for non-static
14950                  member functions (which is the this pointer) as
14951                  artificial.  We pass this information to
14952                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
14953
14954                  DWARF version 3 added DW_AT_object_pointer, which GCC
14955                  4.5 does not yet generate.  */
14956               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
14957               if (attr)
14958                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
14959               else
14960                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
14961               arg_type = die_type (child_die, cu);
14962
14963               /* RealView does not mark THIS as const, which the testsuite
14964                  expects.  GCC marks THIS as const in method definitions,
14965                  but not in the class specifications (GCC PR 43053).  */
14966               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
14967                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
14968                 {
14969                   int is_this = 0;
14970                   struct dwarf2_cu *arg_cu = cu;
14971                   const char *name = dwarf2_name (child_die, cu);
14972
14973                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
14974                   if (attr)
14975                     {
14976                       /* If the compiler emits this, use it.  */
14977                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
14978                         is_this = 1;
14979                     }
14980                   else if (name && strcmp (name, "this") == 0)
14981                     /* Function definitions will have the argument names.  */
14982                     is_this = 1;
14983                   else if (name == NULL && iparams == 0)
14984                     /* Declarations may not have the names, so like
14985                        elsewhere in GDB, assume an artificial first
14986                        argument is "this".  */
14987                     is_this = 1;
14988
14989                   if (is_this)
14990                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
14991                                              arg_type, 0);
14992                 }
14993
14994               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
14995               iparams++;
14996             }
14997           child_die = sibling_die (child_die);
14998         }
14999     }
15000
15001   return ftype;
15002 }
15003
15004 static struct type *
15005 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15006 {
15007   struct objfile *objfile = cu->objfile;
15008   const char *name = NULL;
15009   struct type *this_type, *target_type;
15010
15011   name = dwarf2_full_name (NULL, die, cu);
15012   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15013   TYPE_TARGET_STUB (this_type) = 1;
15014   set_die_type (die, this_type, cu);
15015   target_type = die_type (die, cu);
15016   if (target_type != this_type)
15017     TYPE_TARGET_TYPE (this_type) = target_type;
15018   else
15019     {
15020       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15021          spec and cause infinite loops in GDB.  */
15022       complaint (&symfile_complaints,
15023                  _("Self-referential DW_TAG_typedef "
15024                    "- DIE at 0x%x [in module %s]"),
15025                  to_underlying (die->sect_off), objfile_name (objfile));
15026       TYPE_TARGET_TYPE (this_type) = NULL;
15027     }
15028   return this_type;
15029 }
15030
15031 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15032    (which may be different from NAME) to the architecture back-end to allow
15033    it to guess the correct format if necessary.  */
15034
15035 static struct type *
15036 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15037                         const char *name_hint)
15038 {
15039   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15040   const struct floatformat **format;
15041   struct type *type;
15042
15043   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15044   if (format)
15045     type = init_float_type (objfile, bits, name, format);
15046   else
15047     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15048
15049   return type;
15050 }
15051
15052 /* Find a representation of a given base type and install
15053    it in the TYPE field of the die.  */
15054
15055 static struct type *
15056 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15057 {
15058   struct objfile *objfile = cu->objfile;
15059   struct type *type;
15060   struct attribute *attr;
15061   int encoding = 0, bits = 0;
15062   const char *name;
15063
15064   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15065   if (attr)
15066     {
15067       encoding = DW_UNSND (attr);
15068     }
15069   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15070   if (attr)
15071     {
15072       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15073     }
15074   name = dwarf2_name (die, cu);
15075   if (!name)
15076     {
15077       complaint (&symfile_complaints,
15078                  _("DW_AT_name missing from DW_TAG_base_type"));
15079     }
15080
15081   switch (encoding)
15082     {
15083       case DW_ATE_address:
15084         /* Turn DW_ATE_address into a void * pointer.  */
15085         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15086         type = init_pointer_type (objfile, bits, name, type);
15087         break;
15088       case DW_ATE_boolean:
15089         type = init_boolean_type (objfile, bits, 1, name);
15090         break;
15091       case DW_ATE_complex_float:
15092         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15093         type = init_complex_type (objfile, name, type);
15094         break;
15095       case DW_ATE_decimal_float:
15096         type = init_decfloat_type (objfile, bits, name);
15097         break;
15098       case DW_ATE_float:
15099         type = dwarf2_init_float_type (objfile, bits, name, name);
15100         break;
15101       case DW_ATE_signed:
15102         type = init_integer_type (objfile, bits, 0, name);
15103         break;
15104       case DW_ATE_unsigned:
15105         if (cu->language == language_fortran
15106             && name
15107             && startswith (name, "character("))
15108           type = init_character_type (objfile, bits, 1, name);
15109         else
15110           type = init_integer_type (objfile, bits, 1, name);
15111         break;
15112       case DW_ATE_signed_char:
15113         if (cu->language == language_ada || cu->language == language_m2
15114             || cu->language == language_pascal
15115             || cu->language == language_fortran)
15116           type = init_character_type (objfile, bits, 0, name);
15117         else
15118           type = init_integer_type (objfile, bits, 0, name);
15119         break;
15120       case DW_ATE_unsigned_char:
15121         if (cu->language == language_ada || cu->language == language_m2
15122             || cu->language == language_pascal
15123             || cu->language == language_fortran
15124             || cu->language == language_rust)
15125           type = init_character_type (objfile, bits, 1, name);
15126         else
15127           type = init_integer_type (objfile, bits, 1, name);
15128         break;
15129       case DW_ATE_UTF:
15130         {
15131           gdbarch *arch = get_objfile_arch (objfile);
15132
15133           if (bits == 16)
15134             type = builtin_type (arch)->builtin_char16;
15135           else if (bits == 32)
15136             type = builtin_type (arch)->builtin_char32;
15137           else
15138             {
15139               complaint (&symfile_complaints,
15140                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15141                          bits);
15142               type = init_integer_type (objfile, bits, 1, name);
15143             }
15144           return set_die_type (die, type, cu);
15145         }
15146         break;
15147
15148       default:
15149         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15150                    dwarf_type_encoding_name (encoding));
15151         type = init_type (objfile, TYPE_CODE_ERROR,
15152                           bits / TARGET_CHAR_BIT, name);
15153         break;
15154     }
15155
15156   if (name && strcmp (name, "char") == 0)
15157     TYPE_NOSIGN (type) = 1;
15158
15159   return set_die_type (die, type, cu);
15160 }
15161
15162 /* Parse dwarf attribute if it's a block, reference or constant and put the
15163    resulting value of the attribute into struct bound_prop.
15164    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15165
15166 static int
15167 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15168                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15169 {
15170   struct dwarf2_property_baton *baton;
15171   struct obstack *obstack = &cu->objfile->objfile_obstack;
15172
15173   if (attr == NULL || prop == NULL)
15174     return 0;
15175
15176   if (attr_form_is_block (attr))
15177     {
15178       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15179       baton->referenced_type = NULL;
15180       baton->locexpr.per_cu = cu->per_cu;
15181       baton->locexpr.size = DW_BLOCK (attr)->size;
15182       baton->locexpr.data = DW_BLOCK (attr)->data;
15183       prop->data.baton = baton;
15184       prop->kind = PROP_LOCEXPR;
15185       gdb_assert (prop->data.baton != NULL);
15186     }
15187   else if (attr_form_is_ref (attr))
15188     {
15189       struct dwarf2_cu *target_cu = cu;
15190       struct die_info *target_die;
15191       struct attribute *target_attr;
15192
15193       target_die = follow_die_ref (die, attr, &target_cu);
15194       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15195       if (target_attr == NULL)
15196         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15197                                    target_cu);
15198       if (target_attr == NULL)
15199         return 0;
15200
15201       switch (target_attr->name)
15202         {
15203           case DW_AT_location:
15204             if (attr_form_is_section_offset (target_attr))
15205               {
15206                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15207                 baton->referenced_type = die_type (target_die, target_cu);
15208                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15209                 prop->data.baton = baton;
15210                 prop->kind = PROP_LOCLIST;
15211                 gdb_assert (prop->data.baton != NULL);
15212               }
15213             else if (attr_form_is_block (target_attr))
15214               {
15215                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15216                 baton->referenced_type = die_type (target_die, target_cu);
15217                 baton->locexpr.per_cu = cu->per_cu;
15218                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15219                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15220                 prop->data.baton = baton;
15221                 prop->kind = PROP_LOCEXPR;
15222                 gdb_assert (prop->data.baton != NULL);
15223               }
15224             else
15225               {
15226                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15227                                                        "dynamic property");
15228                 return 0;
15229               }
15230             break;
15231           case DW_AT_data_member_location:
15232             {
15233               LONGEST offset;
15234
15235               if (!handle_data_member_location (target_die, target_cu,
15236                                                 &offset))
15237                 return 0;
15238
15239               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15240               baton->referenced_type = read_type_die (target_die->parent,
15241                                                       target_cu);
15242               baton->offset_info.offset = offset;
15243               baton->offset_info.type = die_type (target_die, target_cu);
15244               prop->data.baton = baton;
15245               prop->kind = PROP_ADDR_OFFSET;
15246               break;
15247             }
15248         }
15249     }
15250   else if (attr_form_is_constant (attr))
15251     {
15252       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15253       prop->kind = PROP_CONST;
15254     }
15255   else
15256     {
15257       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15258                                              dwarf2_name (die, cu));
15259       return 0;
15260     }
15261
15262   return 1;
15263 }
15264
15265 /* Read the given DW_AT_subrange DIE.  */
15266
15267 static struct type *
15268 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15269 {
15270   struct type *base_type, *orig_base_type;
15271   struct type *range_type;
15272   struct attribute *attr;
15273   struct dynamic_prop low, high;
15274   int low_default_is_valid;
15275   int high_bound_is_count = 0;
15276   const char *name;
15277   LONGEST negative_mask;
15278
15279   orig_base_type = die_type (die, cu);
15280   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15281      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15282      creating the range type, but we use the result of check_typedef
15283      when examining properties of the type.  */
15284   base_type = check_typedef (orig_base_type);
15285
15286   /* The die_type call above may have already set the type for this DIE.  */
15287   range_type = get_die_type (die, cu);
15288   if (range_type)
15289     return range_type;
15290
15291   low.kind = PROP_CONST;
15292   high.kind = PROP_CONST;
15293   high.data.const_val = 0;
15294
15295   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15296      omitting DW_AT_lower_bound.  */
15297   switch (cu->language)
15298     {
15299     case language_c:
15300     case language_cplus:
15301       low.data.const_val = 0;
15302       low_default_is_valid = 1;
15303       break;
15304     case language_fortran:
15305       low.data.const_val = 1;
15306       low_default_is_valid = 1;
15307       break;
15308     case language_d:
15309     case language_objc:
15310     case language_rust:
15311       low.data.const_val = 0;
15312       low_default_is_valid = (cu->header.version >= 4);
15313       break;
15314     case language_ada:
15315     case language_m2:
15316     case language_pascal:
15317       low.data.const_val = 1;
15318       low_default_is_valid = (cu->header.version >= 4);
15319       break;
15320     default:
15321       low.data.const_val = 0;
15322       low_default_is_valid = 0;
15323       break;
15324     }
15325
15326   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15327   if (attr)
15328     attr_to_dynamic_prop (attr, die, cu, &low);
15329   else if (!low_default_is_valid)
15330     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15331                                       "- DIE at 0x%x [in module %s]"),
15332                to_underlying (die->sect_off), objfile_name (cu->objfile));
15333
15334   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15335   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15336     {
15337       attr = dwarf2_attr (die, DW_AT_count, cu);
15338       if (attr_to_dynamic_prop (attr, die, cu, &high))
15339         {
15340           /* If bounds are constant do the final calculation here.  */
15341           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15342             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15343           else
15344             high_bound_is_count = 1;
15345         }
15346     }
15347
15348   /* Dwarf-2 specifications explicitly allows to create subrange types
15349      without specifying a base type.
15350      In that case, the base type must be set to the type of
15351      the lower bound, upper bound or count, in that order, if any of these
15352      three attributes references an object that has a type.
15353      If no base type is found, the Dwarf-2 specifications say that
15354      a signed integer type of size equal to the size of an address should
15355      be used.
15356      For the following C code: `extern char gdb_int [];'
15357      GCC produces an empty range DIE.
15358      FIXME: muller/2010-05-28: Possible references to object for low bound,
15359      high bound or count are not yet handled by this code.  */
15360   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15361     {
15362       struct objfile *objfile = cu->objfile;
15363       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15364       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15365       struct type *int_type = objfile_type (objfile)->builtin_int;
15366
15367       /* Test "int", "long int", and "long long int" objfile types,
15368          and select the first one having a size above or equal to the
15369          architecture address size.  */
15370       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15371         base_type = int_type;
15372       else
15373         {
15374           int_type = objfile_type (objfile)->builtin_long;
15375           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15376             base_type = int_type;
15377           else
15378             {
15379               int_type = objfile_type (objfile)->builtin_long_long;
15380               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15381                 base_type = int_type;
15382             }
15383         }
15384     }
15385
15386   /* Normally, the DWARF producers are expected to use a signed
15387      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15388      But this is unfortunately not always the case, as witnessed
15389      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15390      is used instead.  To work around that ambiguity, we treat
15391      the bounds as signed, and thus sign-extend their values, when
15392      the base type is signed.  */
15393   negative_mask =
15394     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15395   if (low.kind == PROP_CONST
15396       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15397     low.data.const_val |= negative_mask;
15398   if (high.kind == PROP_CONST
15399       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15400     high.data.const_val |= negative_mask;
15401
15402   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15403
15404   if (high_bound_is_count)
15405     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15406
15407   /* Ada expects an empty array on no boundary attributes.  */
15408   if (attr == NULL && cu->language != language_ada)
15409     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15410
15411   name = dwarf2_name (die, cu);
15412   if (name)
15413     TYPE_NAME (range_type) = name;
15414
15415   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15416   if (attr)
15417     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15418
15419   set_die_type (die, range_type, cu);
15420
15421   /* set_die_type should be already done.  */
15422   set_descriptive_type (range_type, die, cu);
15423
15424   return range_type;
15425 }
15426
15427 static struct type *
15428 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15429 {
15430   struct type *type;
15431
15432   /* For now, we only support the C meaning of an unspecified type: void.  */
15433
15434   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15435   TYPE_NAME (type) = dwarf2_name (die, cu);
15436
15437   return set_die_type (die, type, cu);
15438 }
15439
15440 /* Read a single die and all its descendents.  Set the die's sibling
15441    field to NULL; set other fields in the die correctly, and set all
15442    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15443    location of the info_ptr after reading all of those dies.  PARENT
15444    is the parent of the die in question.  */
15445
15446 static struct die_info *
15447 read_die_and_children (const struct die_reader_specs *reader,
15448                        const gdb_byte *info_ptr,
15449                        const gdb_byte **new_info_ptr,
15450                        struct die_info *parent)
15451 {
15452   struct die_info *die;
15453   const gdb_byte *cur_ptr;
15454   int has_children;
15455
15456   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15457   if (die == NULL)
15458     {
15459       *new_info_ptr = cur_ptr;
15460       return NULL;
15461     }
15462   store_in_ref_table (die, reader->cu);
15463
15464   if (has_children)
15465     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15466   else
15467     {
15468       die->child = NULL;
15469       *new_info_ptr = cur_ptr;
15470     }
15471
15472   die->sibling = NULL;
15473   die->parent = parent;
15474   return die;
15475 }
15476
15477 /* Read a die, all of its descendents, and all of its siblings; set
15478    all of the fields of all of the dies correctly.  Arguments are as
15479    in read_die_and_children.  */
15480
15481 static struct die_info *
15482 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15483                          const gdb_byte *info_ptr,
15484                          const gdb_byte **new_info_ptr,
15485                          struct die_info *parent)
15486 {
15487   struct die_info *first_die, *last_sibling;
15488   const gdb_byte *cur_ptr;
15489
15490   cur_ptr = info_ptr;
15491   first_die = last_sibling = NULL;
15492
15493   while (1)
15494     {
15495       struct die_info *die
15496         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15497
15498       if (die == NULL)
15499         {
15500           *new_info_ptr = cur_ptr;
15501           return first_die;
15502         }
15503
15504       if (!first_die)
15505         first_die = die;
15506       else
15507         last_sibling->sibling = die;
15508
15509       last_sibling = die;
15510     }
15511 }
15512
15513 /* Read a die, all of its descendents, and all of its siblings; set
15514    all of the fields of all of the dies correctly.  Arguments are as
15515    in read_die_and_children.
15516    This the main entry point for reading a DIE and all its children.  */
15517
15518 static struct die_info *
15519 read_die_and_siblings (const struct die_reader_specs *reader,
15520                        const gdb_byte *info_ptr,
15521                        const gdb_byte **new_info_ptr,
15522                        struct die_info *parent)
15523 {
15524   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15525                                                   new_info_ptr, parent);
15526
15527   if (dwarf_die_debug)
15528     {
15529       fprintf_unfiltered (gdb_stdlog,
15530                           "Read die from %s@0x%x of %s:\n",
15531                           get_section_name (reader->die_section),
15532                           (unsigned) (info_ptr - reader->die_section->buffer),
15533                           bfd_get_filename (reader->abfd));
15534       dump_die (die, dwarf_die_debug);
15535     }
15536
15537   return die;
15538 }
15539
15540 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15541    attributes.
15542    The caller is responsible for filling in the extra attributes
15543    and updating (*DIEP)->num_attrs.
15544    Set DIEP to point to a newly allocated die with its information,
15545    except for its child, sibling, and parent fields.
15546    Set HAS_CHILDREN to tell whether the die has children or not.  */
15547
15548 static const gdb_byte *
15549 read_full_die_1 (const struct die_reader_specs *reader,
15550                  struct die_info **diep, const gdb_byte *info_ptr,
15551                  int *has_children, int num_extra_attrs)
15552 {
15553   unsigned int abbrev_number, bytes_read, i;
15554   struct abbrev_info *abbrev;
15555   struct die_info *die;
15556   struct dwarf2_cu *cu = reader->cu;
15557   bfd *abfd = reader->abfd;
15558
15559   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15560   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15561   info_ptr += bytes_read;
15562   if (!abbrev_number)
15563     {
15564       *diep = NULL;
15565       *has_children = 0;
15566       return info_ptr;
15567     }
15568
15569   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15570   if (!abbrev)
15571     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15572            abbrev_number,
15573            bfd_get_filename (abfd));
15574
15575   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15576   die->sect_off = sect_off;
15577   die->tag = abbrev->tag;
15578   die->abbrev = abbrev_number;
15579
15580   /* Make the result usable.
15581      The caller needs to update num_attrs after adding the extra
15582      attributes.  */
15583   die->num_attrs = abbrev->num_attrs;
15584
15585   for (i = 0; i < abbrev->num_attrs; ++i)
15586     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15587                                info_ptr);
15588
15589   *diep = die;
15590   *has_children = abbrev->has_children;
15591   return info_ptr;
15592 }
15593
15594 /* Read a die and all its attributes.
15595    Set DIEP to point to a newly allocated die with its information,
15596    except for its child, sibling, and parent fields.
15597    Set HAS_CHILDREN to tell whether the die has children or not.  */
15598
15599 static const gdb_byte *
15600 read_full_die (const struct die_reader_specs *reader,
15601                struct die_info **diep, const gdb_byte *info_ptr,
15602                int *has_children)
15603 {
15604   const gdb_byte *result;
15605
15606   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15607
15608   if (dwarf_die_debug)
15609     {
15610       fprintf_unfiltered (gdb_stdlog,
15611                           "Read die from %s@0x%x of %s:\n",
15612                           get_section_name (reader->die_section),
15613                           (unsigned) (info_ptr - reader->die_section->buffer),
15614                           bfd_get_filename (reader->abfd));
15615       dump_die (*diep, dwarf_die_debug);
15616     }
15617
15618   return result;
15619 }
15620 \f
15621 /* Abbreviation tables.
15622
15623    In DWARF version 2, the description of the debugging information is
15624    stored in a separate .debug_abbrev section.  Before we read any
15625    dies from a section we read in all abbreviations and install them
15626    in a hash table.  */
15627
15628 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15629
15630 static struct abbrev_info *
15631 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15632 {
15633   struct abbrev_info *abbrev;
15634
15635   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15636   memset (abbrev, 0, sizeof (struct abbrev_info));
15637
15638   return abbrev;
15639 }
15640
15641 /* Add an abbreviation to the table.  */
15642
15643 static void
15644 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15645                          unsigned int abbrev_number,
15646                          struct abbrev_info *abbrev)
15647 {
15648   unsigned int hash_number;
15649
15650   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15651   abbrev->next = abbrev_table->abbrevs[hash_number];
15652   abbrev_table->abbrevs[hash_number] = abbrev;
15653 }
15654
15655 /* Look up an abbrev in the table.
15656    Returns NULL if the abbrev is not found.  */
15657
15658 static struct abbrev_info *
15659 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15660                             unsigned int abbrev_number)
15661 {
15662   unsigned int hash_number;
15663   struct abbrev_info *abbrev;
15664
15665   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15666   abbrev = abbrev_table->abbrevs[hash_number];
15667
15668   while (abbrev)
15669     {
15670       if (abbrev->number == abbrev_number)
15671         return abbrev;
15672       abbrev = abbrev->next;
15673     }
15674   return NULL;
15675 }
15676
15677 /* Read in an abbrev table.  */
15678
15679 static struct abbrev_table *
15680 abbrev_table_read_table (struct dwarf2_section_info *section,
15681                          sect_offset sect_off)
15682 {
15683   struct objfile *objfile = dwarf2_per_objfile->objfile;
15684   bfd *abfd = get_section_bfd_owner (section);
15685   struct abbrev_table *abbrev_table;
15686   const gdb_byte *abbrev_ptr;
15687   struct abbrev_info *cur_abbrev;
15688   unsigned int abbrev_number, bytes_read, abbrev_name;
15689   unsigned int abbrev_form;
15690   struct attr_abbrev *cur_attrs;
15691   unsigned int allocated_attrs;
15692
15693   abbrev_table = XNEW (struct abbrev_table);
15694   abbrev_table->sect_off = sect_off;
15695   obstack_init (&abbrev_table->abbrev_obstack);
15696   abbrev_table->abbrevs =
15697     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15698                ABBREV_HASH_SIZE);
15699   memset (abbrev_table->abbrevs, 0,
15700           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15701
15702   dwarf2_read_section (objfile, section);
15703   abbrev_ptr = section->buffer + to_underlying (sect_off);
15704   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15705   abbrev_ptr += bytes_read;
15706
15707   allocated_attrs = ATTR_ALLOC_CHUNK;
15708   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15709
15710   /* Loop until we reach an abbrev number of 0.  */
15711   while (abbrev_number)
15712     {
15713       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15714
15715       /* read in abbrev header */
15716       cur_abbrev->number = abbrev_number;
15717       cur_abbrev->tag
15718         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15719       abbrev_ptr += bytes_read;
15720       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15721       abbrev_ptr += 1;
15722
15723       /* now read in declarations */
15724       for (;;)
15725         {
15726           LONGEST implicit_const;
15727
15728           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15729           abbrev_ptr += bytes_read;
15730           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15731           abbrev_ptr += bytes_read;
15732           if (abbrev_form == DW_FORM_implicit_const)
15733             {
15734               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15735                                                    &bytes_read);
15736               abbrev_ptr += bytes_read;
15737             }
15738           else
15739             {
15740               /* Initialize it due to a false compiler warning.  */
15741               implicit_const = -1;
15742             }
15743
15744           if (abbrev_name == 0)
15745             break;
15746
15747           if (cur_abbrev->num_attrs == allocated_attrs)
15748             {
15749               allocated_attrs += ATTR_ALLOC_CHUNK;
15750               cur_attrs
15751                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15752             }
15753
15754           cur_attrs[cur_abbrev->num_attrs].name
15755             = (enum dwarf_attribute) abbrev_name;
15756           cur_attrs[cur_abbrev->num_attrs].form
15757             = (enum dwarf_form) abbrev_form;
15758           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15759           ++cur_abbrev->num_attrs;
15760         }
15761
15762       cur_abbrev->attrs =
15763         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15764                    cur_abbrev->num_attrs);
15765       memcpy (cur_abbrev->attrs, cur_attrs,
15766               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15767
15768       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15769
15770       /* Get next abbreviation.
15771          Under Irix6 the abbreviations for a compilation unit are not
15772          always properly terminated with an abbrev number of 0.
15773          Exit loop if we encounter an abbreviation which we have
15774          already read (which means we are about to read the abbreviations
15775          for the next compile unit) or if the end of the abbreviation
15776          table is reached.  */
15777       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15778         break;
15779       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15780       abbrev_ptr += bytes_read;
15781       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15782         break;
15783     }
15784
15785   xfree (cur_attrs);
15786   return abbrev_table;
15787 }
15788
15789 /* Free the resources held by ABBREV_TABLE.  */
15790
15791 static void
15792 abbrev_table_free (struct abbrev_table *abbrev_table)
15793 {
15794   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15795   xfree (abbrev_table);
15796 }
15797
15798 /* Same as abbrev_table_free but as a cleanup.
15799    We pass in a pointer to the pointer to the table so that we can
15800    set the pointer to NULL when we're done.  It also simplifies
15801    build_type_psymtabs_1.  */
15802
15803 static void
15804 abbrev_table_free_cleanup (void *table_ptr)
15805 {
15806   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15807
15808   if (*abbrev_table_ptr != NULL)
15809     abbrev_table_free (*abbrev_table_ptr);
15810   *abbrev_table_ptr = NULL;
15811 }
15812
15813 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15814
15815 static void
15816 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15817                      struct dwarf2_section_info *abbrev_section)
15818 {
15819   cu->abbrev_table =
15820     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15821 }
15822
15823 /* Release the memory used by the abbrev table for a compilation unit.  */
15824
15825 static void
15826 dwarf2_free_abbrev_table (void *ptr_to_cu)
15827 {
15828   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15829
15830   if (cu->abbrev_table != NULL)
15831     abbrev_table_free (cu->abbrev_table);
15832   /* Set this to NULL so that we SEGV if we try to read it later,
15833      and also because free_comp_unit verifies this is NULL.  */
15834   cu->abbrev_table = NULL;
15835 }
15836 \f
15837 /* Returns nonzero if TAG represents a type that we might generate a partial
15838    symbol for.  */
15839
15840 static int
15841 is_type_tag_for_partial (int tag)
15842 {
15843   switch (tag)
15844     {
15845 #if 0
15846     /* Some types that would be reasonable to generate partial symbols for,
15847        that we don't at present.  */
15848     case DW_TAG_array_type:
15849     case DW_TAG_file_type:
15850     case DW_TAG_ptr_to_member_type:
15851     case DW_TAG_set_type:
15852     case DW_TAG_string_type:
15853     case DW_TAG_subroutine_type:
15854 #endif
15855     case DW_TAG_base_type:
15856     case DW_TAG_class_type:
15857     case DW_TAG_interface_type:
15858     case DW_TAG_enumeration_type:
15859     case DW_TAG_structure_type:
15860     case DW_TAG_subrange_type:
15861     case DW_TAG_typedef:
15862     case DW_TAG_union_type:
15863       return 1;
15864     default:
15865       return 0;
15866     }
15867 }
15868
15869 /* Load all DIEs that are interesting for partial symbols into memory.  */
15870
15871 static struct partial_die_info *
15872 load_partial_dies (const struct die_reader_specs *reader,
15873                    const gdb_byte *info_ptr, int building_psymtab)
15874 {
15875   struct dwarf2_cu *cu = reader->cu;
15876   struct objfile *objfile = cu->objfile;
15877   struct partial_die_info *part_die;
15878   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15879   struct abbrev_info *abbrev;
15880   unsigned int bytes_read;
15881   unsigned int load_all = 0;
15882   int nesting_level = 1;
15883
15884   parent_die = NULL;
15885   last_die = NULL;
15886
15887   gdb_assert (cu->per_cu != NULL);
15888   if (cu->per_cu->load_all_dies)
15889     load_all = 1;
15890
15891   cu->partial_dies
15892     = htab_create_alloc_ex (cu->header.length / 12,
15893                             partial_die_hash,
15894                             partial_die_eq,
15895                             NULL,
15896                             &cu->comp_unit_obstack,
15897                             hashtab_obstack_allocate,
15898                             dummy_obstack_deallocate);
15899
15900   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
15901
15902   while (1)
15903     {
15904       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
15905
15906       /* A NULL abbrev means the end of a series of children.  */
15907       if (abbrev == NULL)
15908         {
15909           if (--nesting_level == 0)
15910             {
15911               /* PART_DIE was probably the last thing allocated on the
15912                  comp_unit_obstack, so we could call obstack_free
15913                  here.  We don't do that because the waste is small,
15914                  and will be cleaned up when we're done with this
15915                  compilation unit.  This way, we're also more robust
15916                  against other users of the comp_unit_obstack.  */
15917               return first_die;
15918             }
15919           info_ptr += bytes_read;
15920           last_die = parent_die;
15921           parent_die = parent_die->die_parent;
15922           continue;
15923         }
15924
15925       /* Check for template arguments.  We never save these; if
15926          they're seen, we just mark the parent, and go on our way.  */
15927       if (parent_die != NULL
15928           && cu->language == language_cplus
15929           && (abbrev->tag == DW_TAG_template_type_param
15930               || abbrev->tag == DW_TAG_template_value_param))
15931         {
15932           parent_die->has_template_arguments = 1;
15933
15934           if (!load_all)
15935             {
15936               /* We don't need a partial DIE for the template argument.  */
15937               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15938               continue;
15939             }
15940         }
15941
15942       /* We only recurse into c++ subprograms looking for template arguments.
15943          Skip their other children.  */
15944       if (!load_all
15945           && cu->language == language_cplus
15946           && parent_die != NULL
15947           && parent_die->tag == DW_TAG_subprogram)
15948         {
15949           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15950           continue;
15951         }
15952
15953       /* Check whether this DIE is interesting enough to save.  Normally
15954          we would not be interested in members here, but there may be
15955          later variables referencing them via DW_AT_specification (for
15956          static members).  */
15957       if (!load_all
15958           && !is_type_tag_for_partial (abbrev->tag)
15959           && abbrev->tag != DW_TAG_constant
15960           && abbrev->tag != DW_TAG_enumerator
15961           && abbrev->tag != DW_TAG_subprogram
15962           && abbrev->tag != DW_TAG_lexical_block
15963           && abbrev->tag != DW_TAG_variable
15964           && abbrev->tag != DW_TAG_namespace
15965           && abbrev->tag != DW_TAG_module
15966           && abbrev->tag != DW_TAG_member
15967           && abbrev->tag != DW_TAG_imported_unit
15968           && abbrev->tag != DW_TAG_imported_declaration)
15969         {
15970           /* Otherwise we skip to the next sibling, if any.  */
15971           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15972           continue;
15973         }
15974
15975       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
15976                                    info_ptr);
15977
15978       /* This two-pass algorithm for processing partial symbols has a
15979          high cost in cache pressure.  Thus, handle some simple cases
15980          here which cover the majority of C partial symbols.  DIEs
15981          which neither have specification tags in them, nor could have
15982          specification tags elsewhere pointing at them, can simply be
15983          processed and discarded.
15984
15985          This segment is also optional; scan_partial_symbols and
15986          add_partial_symbol will handle these DIEs if we chain
15987          them in normally.  When compilers which do not emit large
15988          quantities of duplicate debug information are more common,
15989          this code can probably be removed.  */
15990
15991       /* Any complete simple types at the top level (pretty much all
15992          of them, for a language without namespaces), can be processed
15993          directly.  */
15994       if (parent_die == NULL
15995           && part_die->has_specification == 0
15996           && part_die->is_declaration == 0
15997           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
15998               || part_die->tag == DW_TAG_base_type
15999               || part_die->tag == DW_TAG_subrange_type))
16000         {
16001           if (building_psymtab && part_die->name != NULL)
16002             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16003                                  VAR_DOMAIN, LOC_TYPEDEF,
16004                                  &objfile->static_psymbols,
16005                                  0, cu->language, objfile);
16006           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16007           continue;
16008         }
16009
16010       /* The exception for DW_TAG_typedef with has_children above is
16011          a workaround of GCC PR debug/47510.  In the case of this complaint
16012          type_name_no_tag_or_error will error on such types later.
16013
16014          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16015          it could not find the child DIEs referenced later, this is checked
16016          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16017
16018       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16019         complaint (&symfile_complaints,
16020                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16021                      "- DIE at 0x%x [in module %s]"),
16022                    to_underlying (part_die->sect_off), objfile_name (objfile));
16023
16024       /* If we're at the second level, and we're an enumerator, and
16025          our parent has no specification (meaning possibly lives in a
16026          namespace elsewhere), then we can add the partial symbol now
16027          instead of queueing it.  */
16028       if (part_die->tag == DW_TAG_enumerator
16029           && parent_die != NULL
16030           && parent_die->die_parent == NULL
16031           && parent_die->tag == DW_TAG_enumeration_type
16032           && parent_die->has_specification == 0)
16033         {
16034           if (part_die->name == NULL)
16035             complaint (&symfile_complaints,
16036                        _("malformed enumerator DIE ignored"));
16037           else if (building_psymtab)
16038             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16039                                  VAR_DOMAIN, LOC_CONST,
16040                                  cu->language == language_cplus
16041                                  ? &objfile->global_psymbols
16042                                  : &objfile->static_psymbols,
16043                                  0, cu->language, objfile);
16044
16045           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16046           continue;
16047         }
16048
16049       /* We'll save this DIE so link it in.  */
16050       part_die->die_parent = parent_die;
16051       part_die->die_sibling = NULL;
16052       part_die->die_child = NULL;
16053
16054       if (last_die && last_die == parent_die)
16055         last_die->die_child = part_die;
16056       else if (last_die)
16057         last_die->die_sibling = part_die;
16058
16059       last_die = part_die;
16060
16061       if (first_die == NULL)
16062         first_die = part_die;
16063
16064       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16065          find interesting need to be in the hash table, because we
16066          also have the parent/sibling/child chains; only those that we
16067          might refer to by offset later during partial symbol reading.
16068
16069          For now this means things that might have be the target of a
16070          DW_AT_specification, DW_AT_abstract_origin, or
16071          DW_AT_extension.  DW_AT_extension will refer only to
16072          namespaces; DW_AT_abstract_origin refers to functions (and
16073          many things under the function DIE, but we do not recurse
16074          into function DIEs during partial symbol reading) and
16075          possibly variables as well; DW_AT_specification refers to
16076          declarations.  Declarations ought to have the DW_AT_declaration
16077          flag.  It happens that GCC forgets to put it in sometimes, but
16078          only for functions, not for types.
16079
16080          Adding more things than necessary to the hash table is harmless
16081          except for the performance cost.  Adding too few will result in
16082          wasted time in find_partial_die, when we reread the compilation
16083          unit with load_all_dies set.  */
16084
16085       if (load_all
16086           || abbrev->tag == DW_TAG_constant
16087           || abbrev->tag == DW_TAG_subprogram
16088           || abbrev->tag == DW_TAG_variable
16089           || abbrev->tag == DW_TAG_namespace
16090           || part_die->is_declaration)
16091         {
16092           void **slot;
16093
16094           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16095                                            to_underlying (part_die->sect_off),
16096                                            INSERT);
16097           *slot = part_die;
16098         }
16099
16100       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16101
16102       /* For some DIEs we want to follow their children (if any).  For C
16103          we have no reason to follow the children of structures; for other
16104          languages we have to, so that we can get at method physnames
16105          to infer fully qualified class names, for DW_AT_specification,
16106          and for C++ template arguments.  For C++, we also look one level
16107          inside functions to find template arguments (if the name of the
16108          function does not already contain the template arguments).
16109
16110          For Ada, we need to scan the children of subprograms and lexical
16111          blocks as well because Ada allows the definition of nested
16112          entities that could be interesting for the debugger, such as
16113          nested subprograms for instance.  */
16114       if (last_die->has_children
16115           && (load_all
16116               || last_die->tag == DW_TAG_namespace
16117               || last_die->tag == DW_TAG_module
16118               || last_die->tag == DW_TAG_enumeration_type
16119               || (cu->language == language_cplus
16120                   && last_die->tag == DW_TAG_subprogram
16121                   && (last_die->name == NULL
16122                       || strchr (last_die->name, '<') == NULL))
16123               || (cu->language != language_c
16124                   && (last_die->tag == DW_TAG_class_type
16125                       || last_die->tag == DW_TAG_interface_type
16126                       || last_die->tag == DW_TAG_structure_type
16127                       || last_die->tag == DW_TAG_union_type))
16128               || (cu->language == language_ada
16129                   && (last_die->tag == DW_TAG_subprogram
16130                       || last_die->tag == DW_TAG_lexical_block))))
16131         {
16132           nesting_level++;
16133           parent_die = last_die;
16134           continue;
16135         }
16136
16137       /* Otherwise we skip to the next sibling, if any.  */
16138       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16139
16140       /* Back to the top, do it again.  */
16141     }
16142 }
16143
16144 /* Read a minimal amount of information into the minimal die structure.  */
16145
16146 static const gdb_byte *
16147 read_partial_die (const struct die_reader_specs *reader,
16148                   struct partial_die_info *part_die,
16149                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16150                   const gdb_byte *info_ptr)
16151 {
16152   struct dwarf2_cu *cu = reader->cu;
16153   struct objfile *objfile = cu->objfile;
16154   const gdb_byte *buffer = reader->buffer;
16155   unsigned int i;
16156   struct attribute attr;
16157   int has_low_pc_attr = 0;
16158   int has_high_pc_attr = 0;
16159   int high_pc_relative = 0;
16160
16161   memset (part_die, 0, sizeof (struct partial_die_info));
16162
16163   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16164
16165   info_ptr += abbrev_len;
16166
16167   if (abbrev == NULL)
16168     return info_ptr;
16169
16170   part_die->tag = abbrev->tag;
16171   part_die->has_children = abbrev->has_children;
16172
16173   for (i = 0; i < abbrev->num_attrs; ++i)
16174     {
16175       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16176
16177       /* Store the data if it is of an attribute we want to keep in a
16178          partial symbol table.  */
16179       switch (attr.name)
16180         {
16181         case DW_AT_name:
16182           switch (part_die->tag)
16183             {
16184             case DW_TAG_compile_unit:
16185             case DW_TAG_partial_unit:
16186             case DW_TAG_type_unit:
16187               /* Compilation units have a DW_AT_name that is a filename, not
16188                  a source language identifier.  */
16189             case DW_TAG_enumeration_type:
16190             case DW_TAG_enumerator:
16191               /* These tags always have simple identifiers already; no need
16192                  to canonicalize them.  */
16193               part_die->name = DW_STRING (&attr);
16194               break;
16195             default:
16196               part_die->name
16197                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16198                                             &objfile->per_bfd->storage_obstack);
16199               break;
16200             }
16201           break;
16202         case DW_AT_linkage_name:
16203         case DW_AT_MIPS_linkage_name:
16204           /* Note that both forms of linkage name might appear.  We
16205              assume they will be the same, and we only store the last
16206              one we see.  */
16207           if (cu->language == language_ada)
16208             part_die->name = DW_STRING (&attr);
16209           part_die->linkage_name = DW_STRING (&attr);
16210           break;
16211         case DW_AT_low_pc:
16212           has_low_pc_attr = 1;
16213           part_die->lowpc = attr_value_as_address (&attr);
16214           break;
16215         case DW_AT_high_pc:
16216           has_high_pc_attr = 1;
16217           part_die->highpc = attr_value_as_address (&attr);
16218           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16219                 high_pc_relative = 1;
16220           break;
16221         case DW_AT_location:
16222           /* Support the .debug_loc offsets.  */
16223           if (attr_form_is_block (&attr))
16224             {
16225                part_die->d.locdesc = DW_BLOCK (&attr);
16226             }
16227           else if (attr_form_is_section_offset (&attr))
16228             {
16229               dwarf2_complex_location_expr_complaint ();
16230             }
16231           else
16232             {
16233               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16234                                                      "partial symbol information");
16235             }
16236           break;
16237         case DW_AT_external:
16238           part_die->is_external = DW_UNSND (&attr);
16239           break;
16240         case DW_AT_declaration:
16241           part_die->is_declaration = DW_UNSND (&attr);
16242           break;
16243         case DW_AT_type:
16244           part_die->has_type = 1;
16245           break;
16246         case DW_AT_abstract_origin:
16247         case DW_AT_specification:
16248         case DW_AT_extension:
16249           part_die->has_specification = 1;
16250           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16251           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16252                                    || cu->per_cu->is_dwz);
16253           break;
16254         case DW_AT_sibling:
16255           /* Ignore absolute siblings, they might point outside of
16256              the current compile unit.  */
16257           if (attr.form == DW_FORM_ref_addr)
16258             complaint (&symfile_complaints,
16259                        _("ignoring absolute DW_AT_sibling"));
16260           else
16261             {
16262               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16263               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16264
16265               if (sibling_ptr < info_ptr)
16266                 complaint (&symfile_complaints,
16267                            _("DW_AT_sibling points backwards"));
16268               else if (sibling_ptr > reader->buffer_end)
16269                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16270               else
16271                 part_die->sibling = sibling_ptr;
16272             }
16273           break;
16274         case DW_AT_byte_size:
16275           part_die->has_byte_size = 1;
16276           break;
16277         case DW_AT_const_value:
16278           part_die->has_const_value = 1;
16279           break;
16280         case DW_AT_calling_convention:
16281           /* DWARF doesn't provide a way to identify a program's source-level
16282              entry point.  DW_AT_calling_convention attributes are only meant
16283              to describe functions' calling conventions.
16284
16285              However, because it's a necessary piece of information in
16286              Fortran, and before DWARF 4 DW_CC_program was the only
16287              piece of debugging information whose definition refers to
16288              a 'main program' at all, several compilers marked Fortran
16289              main programs with DW_CC_program --- even when those
16290              functions use the standard calling conventions.
16291
16292              Although DWARF now specifies a way to provide this
16293              information, we support this practice for backward
16294              compatibility.  */
16295           if (DW_UNSND (&attr) == DW_CC_program
16296               && cu->language == language_fortran)
16297             part_die->main_subprogram = 1;
16298           break;
16299         case DW_AT_inline:
16300           if (DW_UNSND (&attr) == DW_INL_inlined
16301               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16302             part_die->may_be_inlined = 1;
16303           break;
16304
16305         case DW_AT_import:
16306           if (part_die->tag == DW_TAG_imported_unit)
16307             {
16308               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16309               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16310                                   || cu->per_cu->is_dwz);
16311             }
16312           break;
16313
16314         case DW_AT_main_subprogram:
16315           part_die->main_subprogram = DW_UNSND (&attr);
16316           break;
16317
16318         default:
16319           break;
16320         }
16321     }
16322
16323   if (high_pc_relative)
16324     part_die->highpc += part_die->lowpc;
16325
16326   if (has_low_pc_attr && has_high_pc_attr)
16327     {
16328       /* When using the GNU linker, .gnu.linkonce. sections are used to
16329          eliminate duplicate copies of functions and vtables and such.
16330          The linker will arbitrarily choose one and discard the others.
16331          The AT_*_pc values for such functions refer to local labels in
16332          these sections.  If the section from that file was discarded, the
16333          labels are not in the output, so the relocs get a value of 0.
16334          If this is a discarded function, mark the pc bounds as invalid,
16335          so that GDB will ignore it.  */
16336       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16337         {
16338           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16339
16340           complaint (&symfile_complaints,
16341                      _("DW_AT_low_pc %s is zero "
16342                        "for DIE at 0x%x [in module %s]"),
16343                      paddress (gdbarch, part_die->lowpc),
16344                      to_underlying (part_die->sect_off), objfile_name (objfile));
16345         }
16346       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16347       else if (part_die->lowpc >= part_die->highpc)
16348         {
16349           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16350
16351           complaint (&symfile_complaints,
16352                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16353                        "for DIE at 0x%x [in module %s]"),
16354                      paddress (gdbarch, part_die->lowpc),
16355                      paddress (gdbarch, part_die->highpc),
16356                      to_underlying (part_die->sect_off),
16357                      objfile_name (objfile));
16358         }
16359       else
16360         part_die->has_pc_info = 1;
16361     }
16362
16363   return info_ptr;
16364 }
16365
16366 /* Find a cached partial DIE at OFFSET in CU.  */
16367
16368 static struct partial_die_info *
16369 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16370 {
16371   struct partial_die_info *lookup_die = NULL;
16372   struct partial_die_info part_die;
16373
16374   part_die.sect_off = sect_off;
16375   lookup_die = ((struct partial_die_info *)
16376                 htab_find_with_hash (cu->partial_dies, &part_die,
16377                                      to_underlying (sect_off)));
16378
16379   return lookup_die;
16380 }
16381
16382 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16383    except in the case of .debug_types DIEs which do not reference
16384    outside their CU (they do however referencing other types via
16385    DW_FORM_ref_sig8).  */
16386
16387 static struct partial_die_info *
16388 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16389 {
16390   struct objfile *objfile = cu->objfile;
16391   struct dwarf2_per_cu_data *per_cu = NULL;
16392   struct partial_die_info *pd = NULL;
16393
16394   if (offset_in_dwz == cu->per_cu->is_dwz
16395       && offset_in_cu_p (&cu->header, sect_off))
16396     {
16397       pd = find_partial_die_in_comp_unit (sect_off, cu);
16398       if (pd != NULL)
16399         return pd;
16400       /* We missed recording what we needed.
16401          Load all dies and try again.  */
16402       per_cu = cu->per_cu;
16403     }
16404   else
16405     {
16406       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16407       if (cu->per_cu->is_debug_types)
16408         {
16409           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16410                    " external reference to offset 0x%x [in module %s].\n"),
16411                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16412                  bfd_get_filename (objfile->obfd));
16413         }
16414       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16415                                                  objfile);
16416
16417       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16418         load_partial_comp_unit (per_cu);
16419
16420       per_cu->cu->last_used = 0;
16421       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16422     }
16423
16424   /* If we didn't find it, and not all dies have been loaded,
16425      load them all and try again.  */
16426
16427   if (pd == NULL && per_cu->load_all_dies == 0)
16428     {
16429       per_cu->load_all_dies = 1;
16430
16431       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16432          THIS_CU->cu may already be in use.  So we can't just free it and
16433          replace its DIEs with the ones we read in.  Instead, we leave those
16434          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16435          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16436          set.  */
16437       load_partial_comp_unit (per_cu);
16438
16439       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16440     }
16441
16442   if (pd == NULL)
16443     internal_error (__FILE__, __LINE__,
16444                     _("could not find partial DIE 0x%x "
16445                       "in cache [from module %s]\n"),
16446                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16447   return pd;
16448 }
16449
16450 /* See if we can figure out if the class lives in a namespace.  We do
16451    this by looking for a member function; its demangled name will
16452    contain namespace info, if there is any.  */
16453
16454 static void
16455 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16456                                   struct dwarf2_cu *cu)
16457 {
16458   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16459      what template types look like, because the demangler
16460      frequently doesn't give the same name as the debug info.  We
16461      could fix this by only using the demangled name to get the
16462      prefix (but see comment in read_structure_type).  */
16463
16464   struct partial_die_info *real_pdi;
16465   struct partial_die_info *child_pdi;
16466
16467   /* If this DIE (this DIE's specification, if any) has a parent, then
16468      we should not do this.  We'll prepend the parent's fully qualified
16469      name when we create the partial symbol.  */
16470
16471   real_pdi = struct_pdi;
16472   while (real_pdi->has_specification)
16473     real_pdi = find_partial_die (real_pdi->spec_offset,
16474                                  real_pdi->spec_is_dwz, cu);
16475
16476   if (real_pdi->die_parent != NULL)
16477     return;
16478
16479   for (child_pdi = struct_pdi->die_child;
16480        child_pdi != NULL;
16481        child_pdi = child_pdi->die_sibling)
16482     {
16483       if (child_pdi->tag == DW_TAG_subprogram
16484           && child_pdi->linkage_name != NULL)
16485         {
16486           char *actual_class_name
16487             = language_class_name_from_physname (cu->language_defn,
16488                                                  child_pdi->linkage_name);
16489           if (actual_class_name != NULL)
16490             {
16491               struct_pdi->name
16492                 = ((const char *)
16493                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16494                                   actual_class_name,
16495                                   strlen (actual_class_name)));
16496               xfree (actual_class_name);
16497             }
16498           break;
16499         }
16500     }
16501 }
16502
16503 /* Adjust PART_DIE before generating a symbol for it.  This function
16504    may set the is_external flag or change the DIE's name.  */
16505
16506 static void
16507 fixup_partial_die (struct partial_die_info *part_die,
16508                    struct dwarf2_cu *cu)
16509 {
16510   /* Once we've fixed up a die, there's no point in doing so again.
16511      This also avoids a memory leak if we were to call
16512      guess_partial_die_structure_name multiple times.  */
16513   if (part_die->fixup_called)
16514     return;
16515
16516   /* If we found a reference attribute and the DIE has no name, try
16517      to find a name in the referred to DIE.  */
16518
16519   if (part_die->name == NULL && part_die->has_specification)
16520     {
16521       struct partial_die_info *spec_die;
16522
16523       spec_die = find_partial_die (part_die->spec_offset,
16524                                    part_die->spec_is_dwz, cu);
16525
16526       fixup_partial_die (spec_die, cu);
16527
16528       if (spec_die->name)
16529         {
16530           part_die->name = spec_die->name;
16531
16532           /* Copy DW_AT_external attribute if it is set.  */
16533           if (spec_die->is_external)
16534             part_die->is_external = spec_die->is_external;
16535         }
16536     }
16537
16538   /* Set default names for some unnamed DIEs.  */
16539
16540   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16541     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16542
16543   /* If there is no parent die to provide a namespace, and there are
16544      children, see if we can determine the namespace from their linkage
16545      name.  */
16546   if (cu->language == language_cplus
16547       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16548       && part_die->die_parent == NULL
16549       && part_die->has_children
16550       && (part_die->tag == DW_TAG_class_type
16551           || part_die->tag == DW_TAG_structure_type
16552           || part_die->tag == DW_TAG_union_type))
16553     guess_partial_die_structure_name (part_die, cu);
16554
16555   /* GCC might emit a nameless struct or union that has a linkage
16556      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16557   if (part_die->name == NULL
16558       && (part_die->tag == DW_TAG_class_type
16559           || part_die->tag == DW_TAG_interface_type
16560           || part_die->tag == DW_TAG_structure_type
16561           || part_die->tag == DW_TAG_union_type)
16562       && part_die->linkage_name != NULL)
16563     {
16564       char *demangled;
16565
16566       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16567       if (demangled)
16568         {
16569           const char *base;
16570
16571           /* Strip any leading namespaces/classes, keep only the base name.
16572              DW_AT_name for named DIEs does not contain the prefixes.  */
16573           base = strrchr (demangled, ':');
16574           if (base && base > demangled && base[-1] == ':')
16575             base++;
16576           else
16577             base = demangled;
16578
16579           part_die->name
16580             = ((const char *)
16581                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16582                               base, strlen (base)));
16583           xfree (demangled);
16584         }
16585     }
16586
16587   part_die->fixup_called = 1;
16588 }
16589
16590 /* Read an attribute value described by an attribute form.  */
16591
16592 static const gdb_byte *
16593 read_attribute_value (const struct die_reader_specs *reader,
16594                       struct attribute *attr, unsigned form,
16595                       LONGEST implicit_const, const gdb_byte *info_ptr)
16596 {
16597   struct dwarf2_cu *cu = reader->cu;
16598   struct objfile *objfile = cu->objfile;
16599   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16600   bfd *abfd = reader->abfd;
16601   struct comp_unit_head *cu_header = &cu->header;
16602   unsigned int bytes_read;
16603   struct dwarf_block *blk;
16604
16605   attr->form = (enum dwarf_form) form;
16606   switch (form)
16607     {
16608     case DW_FORM_ref_addr:
16609       if (cu->header.version == 2)
16610         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16611       else
16612         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16613                                        &cu->header, &bytes_read);
16614       info_ptr += bytes_read;
16615       break;
16616     case DW_FORM_GNU_ref_alt:
16617       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16618       info_ptr += bytes_read;
16619       break;
16620     case DW_FORM_addr:
16621       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16622       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16623       info_ptr += bytes_read;
16624       break;
16625     case DW_FORM_block2:
16626       blk = dwarf_alloc_block (cu);
16627       blk->size = read_2_bytes (abfd, info_ptr);
16628       info_ptr += 2;
16629       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16630       info_ptr += blk->size;
16631       DW_BLOCK (attr) = blk;
16632       break;
16633     case DW_FORM_block4:
16634       blk = dwarf_alloc_block (cu);
16635       blk->size = read_4_bytes (abfd, info_ptr);
16636       info_ptr += 4;
16637       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16638       info_ptr += blk->size;
16639       DW_BLOCK (attr) = blk;
16640       break;
16641     case DW_FORM_data2:
16642       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16643       info_ptr += 2;
16644       break;
16645     case DW_FORM_data4:
16646       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16647       info_ptr += 4;
16648       break;
16649     case DW_FORM_data8:
16650       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16651       info_ptr += 8;
16652       break;
16653     case DW_FORM_data16:
16654       blk = dwarf_alloc_block (cu);
16655       blk->size = 16;
16656       blk->data = read_n_bytes (abfd, info_ptr, 16);
16657       info_ptr += 16;
16658       DW_BLOCK (attr) = blk;
16659       break;
16660     case DW_FORM_sec_offset:
16661       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16662       info_ptr += bytes_read;
16663       break;
16664     case DW_FORM_string:
16665       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16666       DW_STRING_IS_CANONICAL (attr) = 0;
16667       info_ptr += bytes_read;
16668       break;
16669     case DW_FORM_strp:
16670       if (!cu->per_cu->is_dwz)
16671         {
16672           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16673                                                    &bytes_read);
16674           DW_STRING_IS_CANONICAL (attr) = 0;
16675           info_ptr += bytes_read;
16676           break;
16677         }
16678       /* FALLTHROUGH */
16679     case DW_FORM_line_strp:
16680       if (!cu->per_cu->is_dwz)
16681         {
16682           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16683                                                         cu_header, &bytes_read);
16684           DW_STRING_IS_CANONICAL (attr) = 0;
16685           info_ptr += bytes_read;
16686           break;
16687         }
16688       /* FALLTHROUGH */
16689     case DW_FORM_GNU_strp_alt:
16690       {
16691         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16692         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16693                                           &bytes_read);
16694
16695         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16696         DW_STRING_IS_CANONICAL (attr) = 0;
16697         info_ptr += bytes_read;
16698       }
16699       break;
16700     case DW_FORM_exprloc:
16701     case DW_FORM_block:
16702       blk = dwarf_alloc_block (cu);
16703       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16704       info_ptr += bytes_read;
16705       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16706       info_ptr += blk->size;
16707       DW_BLOCK (attr) = blk;
16708       break;
16709     case DW_FORM_block1:
16710       blk = dwarf_alloc_block (cu);
16711       blk->size = read_1_byte (abfd, info_ptr);
16712       info_ptr += 1;
16713       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16714       info_ptr += blk->size;
16715       DW_BLOCK (attr) = blk;
16716       break;
16717     case DW_FORM_data1:
16718       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16719       info_ptr += 1;
16720       break;
16721     case DW_FORM_flag:
16722       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16723       info_ptr += 1;
16724       break;
16725     case DW_FORM_flag_present:
16726       DW_UNSND (attr) = 1;
16727       break;
16728     case DW_FORM_sdata:
16729       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16730       info_ptr += bytes_read;
16731       break;
16732     case DW_FORM_udata:
16733       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16734       info_ptr += bytes_read;
16735       break;
16736     case DW_FORM_ref1:
16737       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16738                          + read_1_byte (abfd, info_ptr));
16739       info_ptr += 1;
16740       break;
16741     case DW_FORM_ref2:
16742       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16743                          + read_2_bytes (abfd, info_ptr));
16744       info_ptr += 2;
16745       break;
16746     case DW_FORM_ref4:
16747       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16748                          + read_4_bytes (abfd, info_ptr));
16749       info_ptr += 4;
16750       break;
16751     case DW_FORM_ref8:
16752       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16753                          + read_8_bytes (abfd, info_ptr));
16754       info_ptr += 8;
16755       break;
16756     case DW_FORM_ref_sig8:
16757       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16758       info_ptr += 8;
16759       break;
16760     case DW_FORM_ref_udata:
16761       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16762                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16763       info_ptr += bytes_read;
16764       break;
16765     case DW_FORM_indirect:
16766       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16767       info_ptr += bytes_read;
16768       if (form == DW_FORM_implicit_const)
16769         {
16770           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16771           info_ptr += bytes_read;
16772         }
16773       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16774                                        info_ptr);
16775       break;
16776     case DW_FORM_implicit_const:
16777       DW_SND (attr) = implicit_const;
16778       break;
16779     case DW_FORM_GNU_addr_index:
16780       if (reader->dwo_file == NULL)
16781         {
16782           /* For now flag a hard error.
16783              Later we can turn this into a complaint.  */
16784           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16785                  dwarf_form_name (form),
16786                  bfd_get_filename (abfd));
16787         }
16788       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16789       info_ptr += bytes_read;
16790       break;
16791     case DW_FORM_GNU_str_index:
16792       if (reader->dwo_file == NULL)
16793         {
16794           /* For now flag a hard error.
16795              Later we can turn this into a complaint if warranted.  */
16796           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16797                  dwarf_form_name (form),
16798                  bfd_get_filename (abfd));
16799         }
16800       {
16801         ULONGEST str_index =
16802           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16803
16804         DW_STRING (attr) = read_str_index (reader, str_index);
16805         DW_STRING_IS_CANONICAL (attr) = 0;
16806         info_ptr += bytes_read;
16807       }
16808       break;
16809     default:
16810       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16811              dwarf_form_name (form),
16812              bfd_get_filename (abfd));
16813     }
16814
16815   /* Super hack.  */
16816   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16817     attr->form = DW_FORM_GNU_ref_alt;
16818
16819   /* We have seen instances where the compiler tried to emit a byte
16820      size attribute of -1 which ended up being encoded as an unsigned
16821      0xffffffff.  Although 0xffffffff is technically a valid size value,
16822      an object of this size seems pretty unlikely so we can relatively
16823      safely treat these cases as if the size attribute was invalid and
16824      treat them as zero by default.  */
16825   if (attr->name == DW_AT_byte_size
16826       && form == DW_FORM_data4
16827       && DW_UNSND (attr) >= 0xffffffff)
16828     {
16829       complaint
16830         (&symfile_complaints,
16831          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16832          hex_string (DW_UNSND (attr)));
16833       DW_UNSND (attr) = 0;
16834     }
16835
16836   return info_ptr;
16837 }
16838
16839 /* Read an attribute described by an abbreviated attribute.  */
16840
16841 static const gdb_byte *
16842 read_attribute (const struct die_reader_specs *reader,
16843                 struct attribute *attr, struct attr_abbrev *abbrev,
16844                 const gdb_byte *info_ptr)
16845 {
16846   attr->name = abbrev->name;
16847   return read_attribute_value (reader, attr, abbrev->form,
16848                                abbrev->implicit_const, info_ptr);
16849 }
16850
16851 /* Read dwarf information from a buffer.  */
16852
16853 static unsigned int
16854 read_1_byte (bfd *abfd, const gdb_byte *buf)
16855 {
16856   return bfd_get_8 (abfd, buf);
16857 }
16858
16859 static int
16860 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16861 {
16862   return bfd_get_signed_8 (abfd, buf);
16863 }
16864
16865 static unsigned int
16866 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16867 {
16868   return bfd_get_16 (abfd, buf);
16869 }
16870
16871 static int
16872 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16873 {
16874   return bfd_get_signed_16 (abfd, buf);
16875 }
16876
16877 static unsigned int
16878 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16879 {
16880   return bfd_get_32 (abfd, buf);
16881 }
16882
16883 static int
16884 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16885 {
16886   return bfd_get_signed_32 (abfd, buf);
16887 }
16888
16889 static ULONGEST
16890 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16891 {
16892   return bfd_get_64 (abfd, buf);
16893 }
16894
16895 static CORE_ADDR
16896 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16897               unsigned int *bytes_read)
16898 {
16899   struct comp_unit_head *cu_header = &cu->header;
16900   CORE_ADDR retval = 0;
16901
16902   if (cu_header->signed_addr_p)
16903     {
16904       switch (cu_header->addr_size)
16905         {
16906         case 2:
16907           retval = bfd_get_signed_16 (abfd, buf);
16908           break;
16909         case 4:
16910           retval = bfd_get_signed_32 (abfd, buf);
16911           break;
16912         case 8:
16913           retval = bfd_get_signed_64 (abfd, buf);
16914           break;
16915         default:
16916           internal_error (__FILE__, __LINE__,
16917                           _("read_address: bad switch, signed [in module %s]"),
16918                           bfd_get_filename (abfd));
16919         }
16920     }
16921   else
16922     {
16923       switch (cu_header->addr_size)
16924         {
16925         case 2:
16926           retval = bfd_get_16 (abfd, buf);
16927           break;
16928         case 4:
16929           retval = bfd_get_32 (abfd, buf);
16930           break;
16931         case 8:
16932           retval = bfd_get_64 (abfd, buf);
16933           break;
16934         default:
16935           internal_error (__FILE__, __LINE__,
16936                           _("read_address: bad switch, "
16937                             "unsigned [in module %s]"),
16938                           bfd_get_filename (abfd));
16939         }
16940     }
16941
16942   *bytes_read = cu_header->addr_size;
16943   return retval;
16944 }
16945
16946 /* Read the initial length from a section.  The (draft) DWARF 3
16947    specification allows the initial length to take up either 4 bytes
16948    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
16949    bytes describe the length and all offsets will be 8 bytes in length
16950    instead of 4.
16951
16952    An older, non-standard 64-bit format is also handled by this
16953    function.  The older format in question stores the initial length
16954    as an 8-byte quantity without an escape value.  Lengths greater
16955    than 2^32 aren't very common which means that the initial 4 bytes
16956    is almost always zero.  Since a length value of zero doesn't make
16957    sense for the 32-bit format, this initial zero can be considered to
16958    be an escape value which indicates the presence of the older 64-bit
16959    format.  As written, the code can't detect (old format) lengths
16960    greater than 4GB.  If it becomes necessary to handle lengths
16961    somewhat larger than 4GB, we could allow other small values (such
16962    as the non-sensical values of 1, 2, and 3) to also be used as
16963    escape values indicating the presence of the old format.
16964
16965    The value returned via bytes_read should be used to increment the
16966    relevant pointer after calling read_initial_length().
16967
16968    [ Note:  read_initial_length() and read_offset() are based on the
16969      document entitled "DWARF Debugging Information Format", revision
16970      3, draft 8, dated November 19, 2001.  This document was obtained
16971      from:
16972
16973         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
16974
16975      This document is only a draft and is subject to change.  (So beware.)
16976
16977      Details regarding the older, non-standard 64-bit format were
16978      determined empirically by examining 64-bit ELF files produced by
16979      the SGI toolchain on an IRIX 6.5 machine.
16980
16981      - Kevin, July 16, 2002
16982    ] */
16983
16984 static LONGEST
16985 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
16986 {
16987   LONGEST length = bfd_get_32 (abfd, buf);
16988
16989   if (length == 0xffffffff)
16990     {
16991       length = bfd_get_64 (abfd, buf + 4);
16992       *bytes_read = 12;
16993     }
16994   else if (length == 0)
16995     {
16996       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
16997       length = bfd_get_64 (abfd, buf);
16998       *bytes_read = 8;
16999     }
17000   else
17001     {
17002       *bytes_read = 4;
17003     }
17004
17005   return length;
17006 }
17007
17008 /* Cover function for read_initial_length.
17009    Returns the length of the object at BUF, and stores the size of the
17010    initial length in *BYTES_READ and stores the size that offsets will be in
17011    *OFFSET_SIZE.
17012    If the initial length size is not equivalent to that specified in
17013    CU_HEADER then issue a complaint.
17014    This is useful when reading non-comp-unit headers.  */
17015
17016 static LONGEST
17017 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17018                                         const struct comp_unit_head *cu_header,
17019                                         unsigned int *bytes_read,
17020                                         unsigned int *offset_size)
17021 {
17022   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17023
17024   gdb_assert (cu_header->initial_length_size == 4
17025               || cu_header->initial_length_size == 8
17026               || cu_header->initial_length_size == 12);
17027
17028   if (cu_header->initial_length_size != *bytes_read)
17029     complaint (&symfile_complaints,
17030                _("intermixed 32-bit and 64-bit DWARF sections"));
17031
17032   *offset_size = (*bytes_read == 4) ? 4 : 8;
17033   return length;
17034 }
17035
17036 /* Read an offset from the data stream.  The size of the offset is
17037    given by cu_header->offset_size.  */
17038
17039 static LONGEST
17040 read_offset (bfd *abfd, const gdb_byte *buf,
17041              const struct comp_unit_head *cu_header,
17042              unsigned int *bytes_read)
17043 {
17044   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17045
17046   *bytes_read = cu_header->offset_size;
17047   return offset;
17048 }
17049
17050 /* Read an offset from the data stream.  */
17051
17052 static LONGEST
17053 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17054 {
17055   LONGEST retval = 0;
17056
17057   switch (offset_size)
17058     {
17059     case 4:
17060       retval = bfd_get_32 (abfd, buf);
17061       break;
17062     case 8:
17063       retval = bfd_get_64 (abfd, buf);
17064       break;
17065     default:
17066       internal_error (__FILE__, __LINE__,
17067                       _("read_offset_1: bad switch [in module %s]"),
17068                       bfd_get_filename (abfd));
17069     }
17070
17071   return retval;
17072 }
17073
17074 static const gdb_byte *
17075 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17076 {
17077   /* If the size of a host char is 8 bits, we can return a pointer
17078      to the buffer, otherwise we have to copy the data to a buffer
17079      allocated on the temporary obstack.  */
17080   gdb_assert (HOST_CHAR_BIT == 8);
17081   return buf;
17082 }
17083
17084 static const char *
17085 read_direct_string (bfd *abfd, const gdb_byte *buf,
17086                     unsigned int *bytes_read_ptr)
17087 {
17088   /* If the size of a host char is 8 bits, we can return a pointer
17089      to the string, otherwise we have to copy the string to a buffer
17090      allocated on the temporary obstack.  */
17091   gdb_assert (HOST_CHAR_BIT == 8);
17092   if (*buf == '\0')
17093     {
17094       *bytes_read_ptr = 1;
17095       return NULL;
17096     }
17097   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17098   return (const char *) buf;
17099 }
17100
17101 /* Return pointer to string at section SECT offset STR_OFFSET with error
17102    reporting strings FORM_NAME and SECT_NAME.  */
17103
17104 static const char *
17105 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17106                                      struct dwarf2_section_info *sect,
17107                                      const char *form_name,
17108                                      const char *sect_name)
17109 {
17110   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17111   if (sect->buffer == NULL)
17112     error (_("%s used without %s section [in module %s]"),
17113            form_name, sect_name, bfd_get_filename (abfd));
17114   if (str_offset >= sect->size)
17115     error (_("%s pointing outside of %s section [in module %s]"),
17116            form_name, sect_name, bfd_get_filename (abfd));
17117   gdb_assert (HOST_CHAR_BIT == 8);
17118   if (sect->buffer[str_offset] == '\0')
17119     return NULL;
17120   return (const char *) (sect->buffer + str_offset);
17121 }
17122
17123 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17124
17125 static const char *
17126 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17127 {
17128   return read_indirect_string_at_offset_from (abfd, str_offset,
17129                                               &dwarf2_per_objfile->str,
17130                                               "DW_FORM_strp", ".debug_str");
17131 }
17132
17133 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17134
17135 static const char *
17136 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17137 {
17138   return read_indirect_string_at_offset_from (abfd, str_offset,
17139                                               &dwarf2_per_objfile->line_str,
17140                                               "DW_FORM_line_strp",
17141                                               ".debug_line_str");
17142 }
17143
17144 /* Read a string at offset STR_OFFSET in the .debug_str section from
17145    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17146    the string consists of a single NUL byte, return NULL; otherwise
17147    return a pointer to the string.  */
17148
17149 static const char *
17150 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17151 {
17152   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17153
17154   if (dwz->str.buffer == NULL)
17155     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17156              "section [in module %s]"),
17157            bfd_get_filename (dwz->dwz_bfd));
17158   if (str_offset >= dwz->str.size)
17159     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17160              ".debug_str section [in module %s]"),
17161            bfd_get_filename (dwz->dwz_bfd));
17162   gdb_assert (HOST_CHAR_BIT == 8);
17163   if (dwz->str.buffer[str_offset] == '\0')
17164     return NULL;
17165   return (const char *) (dwz->str.buffer + str_offset);
17166 }
17167
17168 /* Return pointer to string at .debug_str offset as read from BUF.
17169    BUF is assumed to be in a compilation unit described by CU_HEADER.
17170    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17171
17172 static const char *
17173 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17174                       const struct comp_unit_head *cu_header,
17175                       unsigned int *bytes_read_ptr)
17176 {
17177   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17178
17179   return read_indirect_string_at_offset (abfd, str_offset);
17180 }
17181
17182 /* Return pointer to string at .debug_line_str offset as read from BUF.
17183    BUF is assumed to be in a compilation unit described by CU_HEADER.
17184    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17185
17186 static const char *
17187 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17188                            const struct comp_unit_head *cu_header,
17189                            unsigned int *bytes_read_ptr)
17190 {
17191   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17192
17193   return read_indirect_line_string_at_offset (abfd, str_offset);
17194 }
17195
17196 ULONGEST
17197 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17198                           unsigned int *bytes_read_ptr)
17199 {
17200   ULONGEST result;
17201   unsigned int num_read;
17202   int shift;
17203   unsigned char byte;
17204
17205   result = 0;
17206   shift = 0;
17207   num_read = 0;
17208   while (1)
17209     {
17210       byte = bfd_get_8 (abfd, buf);
17211       buf++;
17212       num_read++;
17213       result |= ((ULONGEST) (byte & 127) << shift);
17214       if ((byte & 128) == 0)
17215         {
17216           break;
17217         }
17218       shift += 7;
17219     }
17220   *bytes_read_ptr = num_read;
17221   return result;
17222 }
17223
17224 static LONGEST
17225 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17226                     unsigned int *bytes_read_ptr)
17227 {
17228   LONGEST result;
17229   int shift, num_read;
17230   unsigned char byte;
17231
17232   result = 0;
17233   shift = 0;
17234   num_read = 0;
17235   while (1)
17236     {
17237       byte = bfd_get_8 (abfd, buf);
17238       buf++;
17239       num_read++;
17240       result |= ((LONGEST) (byte & 127) << shift);
17241       shift += 7;
17242       if ((byte & 128) == 0)
17243         {
17244           break;
17245         }
17246     }
17247   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17248     result |= -(((LONGEST) 1) << shift);
17249   *bytes_read_ptr = num_read;
17250   return result;
17251 }
17252
17253 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17254    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17255    ADDR_SIZE is the size of addresses from the CU header.  */
17256
17257 static CORE_ADDR
17258 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17259 {
17260   struct objfile *objfile = dwarf2_per_objfile->objfile;
17261   bfd *abfd = objfile->obfd;
17262   const gdb_byte *info_ptr;
17263
17264   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17265   if (dwarf2_per_objfile->addr.buffer == NULL)
17266     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17267            objfile_name (objfile));
17268   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17269     error (_("DW_FORM_addr_index pointing outside of "
17270              ".debug_addr section [in module %s]"),
17271            objfile_name (objfile));
17272   info_ptr = (dwarf2_per_objfile->addr.buffer
17273               + addr_base + addr_index * addr_size);
17274   if (addr_size == 4)
17275     return bfd_get_32 (abfd, info_ptr);
17276   else
17277     return bfd_get_64 (abfd, info_ptr);
17278 }
17279
17280 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17281
17282 static CORE_ADDR
17283 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17284 {
17285   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17286 }
17287
17288 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17289
17290 static CORE_ADDR
17291 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17292                              unsigned int *bytes_read)
17293 {
17294   bfd *abfd = cu->objfile->obfd;
17295   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17296
17297   return read_addr_index (cu, addr_index);
17298 }
17299
17300 /* Data structure to pass results from dwarf2_read_addr_index_reader
17301    back to dwarf2_read_addr_index.  */
17302
17303 struct dwarf2_read_addr_index_data
17304 {
17305   ULONGEST addr_base;
17306   int addr_size;
17307 };
17308
17309 /* die_reader_func for dwarf2_read_addr_index.  */
17310
17311 static void
17312 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17313                                const gdb_byte *info_ptr,
17314                                struct die_info *comp_unit_die,
17315                                int has_children,
17316                                void *data)
17317 {
17318   struct dwarf2_cu *cu = reader->cu;
17319   struct dwarf2_read_addr_index_data *aidata =
17320     (struct dwarf2_read_addr_index_data *) data;
17321
17322   aidata->addr_base = cu->addr_base;
17323   aidata->addr_size = cu->header.addr_size;
17324 }
17325
17326 /* Given an index in .debug_addr, fetch the value.
17327    NOTE: This can be called during dwarf expression evaluation,
17328    long after the debug information has been read, and thus per_cu->cu
17329    may no longer exist.  */
17330
17331 CORE_ADDR
17332 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17333                         unsigned int addr_index)
17334 {
17335   struct objfile *objfile = per_cu->objfile;
17336   struct dwarf2_cu *cu = per_cu->cu;
17337   ULONGEST addr_base;
17338   int addr_size;
17339
17340   /* This is intended to be called from outside this file.  */
17341   dw2_setup (objfile);
17342
17343   /* We need addr_base and addr_size.
17344      If we don't have PER_CU->cu, we have to get it.
17345      Nasty, but the alternative is storing the needed info in PER_CU,
17346      which at this point doesn't seem justified: it's not clear how frequently
17347      it would get used and it would increase the size of every PER_CU.
17348      Entry points like dwarf2_per_cu_addr_size do a similar thing
17349      so we're not in uncharted territory here.
17350      Alas we need to be a bit more complicated as addr_base is contained
17351      in the DIE.
17352
17353      We don't need to read the entire CU(/TU).
17354      We just need the header and top level die.
17355
17356      IWBN to use the aging mechanism to let us lazily later discard the CU.
17357      For now we skip this optimization.  */
17358
17359   if (cu != NULL)
17360     {
17361       addr_base = cu->addr_base;
17362       addr_size = cu->header.addr_size;
17363     }
17364   else
17365     {
17366       struct dwarf2_read_addr_index_data aidata;
17367
17368       /* Note: We can't use init_cutu_and_read_dies_simple here,
17369          we need addr_base.  */
17370       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17371                                dwarf2_read_addr_index_reader, &aidata);
17372       addr_base = aidata.addr_base;
17373       addr_size = aidata.addr_size;
17374     }
17375
17376   return read_addr_index_1 (addr_index, addr_base, addr_size);
17377 }
17378
17379 /* Given a DW_FORM_GNU_str_index, fetch the string.
17380    This is only used by the Fission support.  */
17381
17382 static const char *
17383 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17384 {
17385   struct objfile *objfile = dwarf2_per_objfile->objfile;
17386   const char *objf_name = objfile_name (objfile);
17387   bfd *abfd = objfile->obfd;
17388   struct dwarf2_cu *cu = reader->cu;
17389   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17390   struct dwarf2_section_info *str_offsets_section =
17391     &reader->dwo_file->sections.str_offsets;
17392   const gdb_byte *info_ptr;
17393   ULONGEST str_offset;
17394   static const char form_name[] = "DW_FORM_GNU_str_index";
17395
17396   dwarf2_read_section (objfile, str_section);
17397   dwarf2_read_section (objfile, str_offsets_section);
17398   if (str_section->buffer == NULL)
17399     error (_("%s used without .debug_str.dwo section"
17400              " in CU at offset 0x%x [in module %s]"),
17401            form_name, to_underlying (cu->header.sect_off), objf_name);
17402   if (str_offsets_section->buffer == NULL)
17403     error (_("%s used without .debug_str_offsets.dwo section"
17404              " in CU at offset 0x%x [in module %s]"),
17405            form_name, to_underlying (cu->header.sect_off), objf_name);
17406   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17407     error (_("%s pointing outside of .debug_str_offsets.dwo"
17408              " section in CU at offset 0x%x [in module %s]"),
17409            form_name, to_underlying (cu->header.sect_off), objf_name);
17410   info_ptr = (str_offsets_section->buffer
17411               + str_index * cu->header.offset_size);
17412   if (cu->header.offset_size == 4)
17413     str_offset = bfd_get_32 (abfd, info_ptr);
17414   else
17415     str_offset = bfd_get_64 (abfd, info_ptr);
17416   if (str_offset >= str_section->size)
17417     error (_("Offset from %s pointing outside of"
17418              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17419            form_name, to_underlying (cu->header.sect_off), objf_name);
17420   return (const char *) (str_section->buffer + str_offset);
17421 }
17422
17423 /* Return the length of an LEB128 number in BUF.  */
17424
17425 static int
17426 leb128_size (const gdb_byte *buf)
17427 {
17428   const gdb_byte *begin = buf;
17429   gdb_byte byte;
17430
17431   while (1)
17432     {
17433       byte = *buf++;
17434       if ((byte & 128) == 0)
17435         return buf - begin;
17436     }
17437 }
17438
17439 static void
17440 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17441 {
17442   switch (lang)
17443     {
17444     case DW_LANG_C89:
17445     case DW_LANG_C99:
17446     case DW_LANG_C11:
17447     case DW_LANG_C:
17448     case DW_LANG_UPC:
17449       cu->language = language_c;
17450       break;
17451     case DW_LANG_Java:
17452     case DW_LANG_C_plus_plus:
17453     case DW_LANG_C_plus_plus_11:
17454     case DW_LANG_C_plus_plus_14:
17455       cu->language = language_cplus;
17456       break;
17457     case DW_LANG_D:
17458       cu->language = language_d;
17459       break;
17460     case DW_LANG_Fortran77:
17461     case DW_LANG_Fortran90:
17462     case DW_LANG_Fortran95:
17463     case DW_LANG_Fortran03:
17464     case DW_LANG_Fortran08:
17465       cu->language = language_fortran;
17466       break;
17467     case DW_LANG_Go:
17468       cu->language = language_go;
17469       break;
17470     case DW_LANG_Mips_Assembler:
17471       cu->language = language_asm;
17472       break;
17473     case DW_LANG_Ada83:
17474     case DW_LANG_Ada95:
17475       cu->language = language_ada;
17476       break;
17477     case DW_LANG_Modula2:
17478       cu->language = language_m2;
17479       break;
17480     case DW_LANG_Pascal83:
17481       cu->language = language_pascal;
17482       break;
17483     case DW_LANG_ObjC:
17484       cu->language = language_objc;
17485       break;
17486     case DW_LANG_Rust:
17487     case DW_LANG_Rust_old:
17488       cu->language = language_rust;
17489       break;
17490     case DW_LANG_Cobol74:
17491     case DW_LANG_Cobol85:
17492     default:
17493       cu->language = language_minimal;
17494       break;
17495     }
17496   cu->language_defn = language_def (cu->language);
17497 }
17498
17499 /* Return the named attribute or NULL if not there.  */
17500
17501 static struct attribute *
17502 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17503 {
17504   for (;;)
17505     {
17506       unsigned int i;
17507       struct attribute *spec = NULL;
17508
17509       for (i = 0; i < die->num_attrs; ++i)
17510         {
17511           if (die->attrs[i].name == name)
17512             return &die->attrs[i];
17513           if (die->attrs[i].name == DW_AT_specification
17514               || die->attrs[i].name == DW_AT_abstract_origin)
17515             spec = &die->attrs[i];
17516         }
17517
17518       if (!spec)
17519         break;
17520
17521       die = follow_die_ref (die, spec, &cu);
17522     }
17523
17524   return NULL;
17525 }
17526
17527 /* Return the named attribute or NULL if not there,
17528    but do not follow DW_AT_specification, etc.
17529    This is for use in contexts where we're reading .debug_types dies.
17530    Following DW_AT_specification, DW_AT_abstract_origin will take us
17531    back up the chain, and we want to go down.  */
17532
17533 static struct attribute *
17534 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17535 {
17536   unsigned int i;
17537
17538   for (i = 0; i < die->num_attrs; ++i)
17539     if (die->attrs[i].name == name)
17540       return &die->attrs[i];
17541
17542   return NULL;
17543 }
17544
17545 /* Return the string associated with a string-typed attribute, or NULL if it
17546    is either not found or is of an incorrect type.  */
17547
17548 static const char *
17549 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17550 {
17551   struct attribute *attr;
17552   const char *str = NULL;
17553
17554   attr = dwarf2_attr (die, name, cu);
17555
17556   if (attr != NULL)
17557     {
17558       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17559           || attr->form == DW_FORM_string || attr->form == DW_FORM_GNU_strp_alt)
17560         str = DW_STRING (attr);
17561       else
17562         complaint (&symfile_complaints,
17563                    _("string type expected for attribute %s for "
17564                      "DIE at 0x%x in module %s"),
17565                    dwarf_attr_name (name), to_underlying (die->sect_off),
17566                    objfile_name (cu->objfile));
17567     }
17568
17569   return str;
17570 }
17571
17572 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17573    and holds a non-zero value.  This function should only be used for
17574    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17575
17576 static int
17577 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17578 {
17579   struct attribute *attr = dwarf2_attr (die, name, cu);
17580
17581   return (attr && DW_UNSND (attr));
17582 }
17583
17584 static int
17585 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17586 {
17587   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17588      which value is non-zero.  However, we have to be careful with
17589      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17590      (via dwarf2_flag_true_p) follows this attribute.  So we may
17591      end up accidently finding a declaration attribute that belongs
17592      to a different DIE referenced by the specification attribute,
17593      even though the given DIE does not have a declaration attribute.  */
17594   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17595           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17596 }
17597
17598 /* Return the die giving the specification for DIE, if there is
17599    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17600    containing the return value on output.  If there is no
17601    specification, but there is an abstract origin, that is
17602    returned.  */
17603
17604 static struct die_info *
17605 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17606 {
17607   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17608                                              *spec_cu);
17609
17610   if (spec_attr == NULL)
17611     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17612
17613   if (spec_attr == NULL)
17614     return NULL;
17615   else
17616     return follow_die_ref (die, spec_attr, spec_cu);
17617 }
17618
17619 /* Stub for free_line_header to match void * callback types.  */
17620
17621 static void
17622 free_line_header_voidp (void *arg)
17623 {
17624   struct line_header *lh = (struct line_header *) arg;
17625
17626   delete lh;
17627 }
17628
17629 void
17630 line_header::add_include_dir (const char *include_dir)
17631 {
17632   if (dwarf_line_debug >= 2)
17633     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17634                         include_dirs.size () + 1, include_dir);
17635
17636   include_dirs.push_back (include_dir);
17637 }
17638
17639 void
17640 line_header::add_file_name (const char *name,
17641                             dir_index d_index,
17642                             unsigned int mod_time,
17643                             unsigned int length)
17644 {
17645   if (dwarf_line_debug >= 2)
17646     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17647                         (unsigned) file_names.size () + 1, name);
17648
17649   file_names.emplace_back (name, d_index, mod_time, length);
17650 }
17651
17652 /* A convenience function to find the proper .debug_line section for a CU.  */
17653
17654 static struct dwarf2_section_info *
17655 get_debug_line_section (struct dwarf2_cu *cu)
17656 {
17657   struct dwarf2_section_info *section;
17658
17659   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17660      DWO file.  */
17661   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17662     section = &cu->dwo_unit->dwo_file->sections.line;
17663   else if (cu->per_cu->is_dwz)
17664     {
17665       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17666
17667       section = &dwz->line;
17668     }
17669   else
17670     section = &dwarf2_per_objfile->line;
17671
17672   return section;
17673 }
17674
17675 /* Read directory or file name entry format, starting with byte of
17676    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17677    entries count and the entries themselves in the described entry
17678    format.  */
17679
17680 static void
17681 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17682                         struct line_header *lh,
17683                         const struct comp_unit_head *cu_header,
17684                         void (*callback) (struct line_header *lh,
17685                                           const char *name,
17686                                           dir_index d_index,
17687                                           unsigned int mod_time,
17688                                           unsigned int length))
17689 {
17690   gdb_byte format_count, formati;
17691   ULONGEST data_count, datai;
17692   const gdb_byte *buf = *bufp;
17693   const gdb_byte *format_header_data;
17694   int i;
17695   unsigned int bytes_read;
17696
17697   format_count = read_1_byte (abfd, buf);
17698   buf += 1;
17699   format_header_data = buf;
17700   for (formati = 0; formati < format_count; formati++)
17701     {
17702       read_unsigned_leb128 (abfd, buf, &bytes_read);
17703       buf += bytes_read;
17704       read_unsigned_leb128 (abfd, buf, &bytes_read);
17705       buf += bytes_read;
17706     }
17707
17708   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17709   buf += bytes_read;
17710   for (datai = 0; datai < data_count; datai++)
17711     {
17712       const gdb_byte *format = format_header_data;
17713       struct file_entry fe;
17714
17715       for (formati = 0; formati < format_count; formati++)
17716         {
17717           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17718           format += bytes_read;
17719
17720           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17721           format += bytes_read;
17722
17723           gdb::optional<const char *> string;
17724           gdb::optional<unsigned int> uint;
17725
17726           switch (form)
17727             {
17728             case DW_FORM_string:
17729               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17730               buf += bytes_read;
17731               break;
17732
17733             case DW_FORM_line_strp:
17734               string.emplace (read_indirect_line_string (abfd, buf,
17735                                                          cu_header,
17736                                                          &bytes_read));
17737               buf += bytes_read;
17738               break;
17739
17740             case DW_FORM_data1:
17741               uint.emplace (read_1_byte (abfd, buf));
17742               buf += 1;
17743               break;
17744
17745             case DW_FORM_data2:
17746               uint.emplace (read_2_bytes (abfd, buf));
17747               buf += 2;
17748               break;
17749
17750             case DW_FORM_data4:
17751               uint.emplace (read_4_bytes (abfd, buf));
17752               buf += 4;
17753               break;
17754
17755             case DW_FORM_data8:
17756               uint.emplace (read_8_bytes (abfd, buf));
17757               buf += 8;
17758               break;
17759
17760             case DW_FORM_udata:
17761               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17762               buf += bytes_read;
17763               break;
17764
17765             case DW_FORM_block:
17766               /* It is valid only for DW_LNCT_timestamp which is ignored by
17767                  current GDB.  */
17768               break;
17769             }
17770
17771           switch (content_type)
17772             {
17773             case DW_LNCT_path:
17774               if (string.has_value ())
17775                 fe.name = *string;
17776               break;
17777             case DW_LNCT_directory_index:
17778               if (uint.has_value ())
17779                 fe.d_index = (dir_index) *uint;
17780               break;
17781             case DW_LNCT_timestamp:
17782               if (uint.has_value ())
17783                 fe.mod_time = *uint;
17784               break;
17785             case DW_LNCT_size:
17786               if (uint.has_value ())
17787                 fe.length = *uint;
17788               break;
17789             case DW_LNCT_MD5:
17790               break;
17791             default:
17792               complaint (&symfile_complaints,
17793                          _("Unknown format content type %s"),
17794                          pulongest (content_type));
17795             }
17796         }
17797
17798       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17799     }
17800
17801   *bufp = buf;
17802 }
17803
17804 /* Read the statement program header starting at OFFSET in
17805    .debug_line, or .debug_line.dwo.  Return a pointer
17806    to a struct line_header, allocated using xmalloc.
17807    Returns NULL if there is a problem reading the header, e.g., if it
17808    has a version we don't understand.
17809
17810    NOTE: the strings in the include directory and file name tables of
17811    the returned object point into the dwarf line section buffer,
17812    and must not be freed.  */
17813
17814 static line_header_up
17815 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17816 {
17817   const gdb_byte *line_ptr;
17818   unsigned int bytes_read, offset_size;
17819   int i;
17820   const char *cur_dir, *cur_file;
17821   struct dwarf2_section_info *section;
17822   bfd *abfd;
17823
17824   section = get_debug_line_section (cu);
17825   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17826   if (section->buffer == NULL)
17827     {
17828       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17829         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17830       else
17831         complaint (&symfile_complaints, _("missing .debug_line section"));
17832       return 0;
17833     }
17834
17835   /* We can't do this until we know the section is non-empty.
17836      Only then do we know we have such a section.  */
17837   abfd = get_section_bfd_owner (section);
17838
17839   /* Make sure that at least there's room for the total_length field.
17840      That could be 12 bytes long, but we're just going to fudge that.  */
17841   if (to_underlying (sect_off) + 4 >= section->size)
17842     {
17843       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17844       return 0;
17845     }
17846
17847   line_header_up lh (new line_header ());
17848
17849   lh->sect_off = sect_off;
17850   lh->offset_in_dwz = cu->per_cu->is_dwz;
17851
17852   line_ptr = section->buffer + to_underlying (sect_off);
17853
17854   /* Read in the header.  */
17855   lh->total_length =
17856     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17857                                             &bytes_read, &offset_size);
17858   line_ptr += bytes_read;
17859   if (line_ptr + lh->total_length > (section->buffer + section->size))
17860     {
17861       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17862       return 0;
17863     }
17864   lh->statement_program_end = line_ptr + lh->total_length;
17865   lh->version = read_2_bytes (abfd, line_ptr);
17866   line_ptr += 2;
17867   if (lh->version > 5)
17868     {
17869       /* This is a version we don't understand.  The format could have
17870          changed in ways we don't handle properly so just punt.  */
17871       complaint (&symfile_complaints,
17872                  _("unsupported version in .debug_line section"));
17873       return NULL;
17874     }
17875   if (lh->version >= 5)
17876     {
17877       gdb_byte segment_selector_size;
17878
17879       /* Skip address size.  */
17880       read_1_byte (abfd, line_ptr);
17881       line_ptr += 1;
17882
17883       segment_selector_size = read_1_byte (abfd, line_ptr);
17884       line_ptr += 1;
17885       if (segment_selector_size != 0)
17886         {
17887           complaint (&symfile_complaints,
17888                      _("unsupported segment selector size %u "
17889                        "in .debug_line section"),
17890                      segment_selector_size);
17891           return NULL;
17892         }
17893     }
17894   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17895   line_ptr += offset_size;
17896   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17897   line_ptr += 1;
17898   if (lh->version >= 4)
17899     {
17900       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
17901       line_ptr += 1;
17902     }
17903   else
17904     lh->maximum_ops_per_instruction = 1;
17905
17906   if (lh->maximum_ops_per_instruction == 0)
17907     {
17908       lh->maximum_ops_per_instruction = 1;
17909       complaint (&symfile_complaints,
17910                  _("invalid maximum_ops_per_instruction "
17911                    "in `.debug_line' section"));
17912     }
17913
17914   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
17915   line_ptr += 1;
17916   lh->line_base = read_1_signed_byte (abfd, line_ptr);
17917   line_ptr += 1;
17918   lh->line_range = read_1_byte (abfd, line_ptr);
17919   line_ptr += 1;
17920   lh->opcode_base = read_1_byte (abfd, line_ptr);
17921   line_ptr += 1;
17922   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
17923
17924   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
17925   for (i = 1; i < lh->opcode_base; ++i)
17926     {
17927       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
17928       line_ptr += 1;
17929     }
17930
17931   if (lh->version >= 5)
17932     {
17933       /* Read directory table.  */
17934       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
17935                               [] (struct line_header *lh, const char *name,
17936                                   dir_index d_index, unsigned int mod_time,
17937                                   unsigned int length)
17938         {
17939           lh->add_include_dir (name);
17940         });
17941
17942       /* Read file name table.  */
17943       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
17944                               [] (struct line_header *lh, const char *name,
17945                                   dir_index d_index, unsigned int mod_time,
17946                                   unsigned int length)
17947         {
17948           lh->add_file_name (name, d_index, mod_time, length);
17949         });
17950     }
17951   else
17952     {
17953       /* Read directory table.  */
17954       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
17955         {
17956           line_ptr += bytes_read;
17957           lh->add_include_dir (cur_dir);
17958         }
17959       line_ptr += bytes_read;
17960
17961       /* Read file name table.  */
17962       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
17963         {
17964           unsigned int mod_time, length;
17965           dir_index d_index;
17966
17967           line_ptr += bytes_read;
17968           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17969           line_ptr += bytes_read;
17970           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17971           line_ptr += bytes_read;
17972           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17973           line_ptr += bytes_read;
17974
17975           lh->add_file_name (cur_file, d_index, mod_time, length);
17976         }
17977       line_ptr += bytes_read;
17978     }
17979   lh->statement_program_start = line_ptr;
17980
17981   if (line_ptr > (section->buffer + section->size))
17982     complaint (&symfile_complaints,
17983                _("line number info header doesn't "
17984                  "fit in `.debug_line' section"));
17985
17986   return lh;
17987 }
17988
17989 /* Subroutine of dwarf_decode_lines to simplify it.
17990    Return the file name of the psymtab for included file FILE_INDEX
17991    in line header LH of PST.
17992    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17993    If space for the result is malloc'd, it will be freed by a cleanup.
17994    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
17995
17996    The function creates dangling cleanup registration.  */
17997
17998 static const char *
17999 psymtab_include_file_name (const struct line_header *lh, int file_index,
18000                            const struct partial_symtab *pst,
18001                            const char *comp_dir)
18002 {
18003   const file_entry &fe = lh->file_names[file_index];
18004   const char *include_name = fe.name;
18005   const char *include_name_to_compare = include_name;
18006   const char *pst_filename;
18007   char *copied_name = NULL;
18008   int file_is_pst;
18009
18010   const char *dir_name = fe.include_dir (lh);
18011
18012   if (!IS_ABSOLUTE_PATH (include_name)
18013       && (dir_name != NULL || comp_dir != NULL))
18014     {
18015       /* Avoid creating a duplicate psymtab for PST.
18016          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18017          Before we do the comparison, however, we need to account
18018          for DIR_NAME and COMP_DIR.
18019          First prepend dir_name (if non-NULL).  If we still don't
18020          have an absolute path prepend comp_dir (if non-NULL).
18021          However, the directory we record in the include-file's
18022          psymtab does not contain COMP_DIR (to match the
18023          corresponding symtab(s)).
18024
18025          Example:
18026
18027          bash$ cd /tmp
18028          bash$ gcc -g ./hello.c
18029          include_name = "hello.c"
18030          dir_name = "."
18031          DW_AT_comp_dir = comp_dir = "/tmp"
18032          DW_AT_name = "./hello.c"
18033
18034       */
18035
18036       if (dir_name != NULL)
18037         {
18038           char *tem = concat (dir_name, SLASH_STRING,
18039                               include_name, (char *)NULL);
18040
18041           make_cleanup (xfree, tem);
18042           include_name = tem;
18043           include_name_to_compare = include_name;
18044         }
18045       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18046         {
18047           char *tem = concat (comp_dir, SLASH_STRING,
18048                               include_name, (char *)NULL);
18049
18050           make_cleanup (xfree, tem);
18051           include_name_to_compare = tem;
18052         }
18053     }
18054
18055   pst_filename = pst->filename;
18056   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18057     {
18058       copied_name = concat (pst->dirname, SLASH_STRING,
18059                             pst_filename, (char *)NULL);
18060       pst_filename = copied_name;
18061     }
18062
18063   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18064
18065   if (copied_name != NULL)
18066     xfree (copied_name);
18067
18068   if (file_is_pst)
18069     return NULL;
18070   return include_name;
18071 }
18072
18073 /* State machine to track the state of the line number program.  */
18074
18075 class lnp_state_machine
18076 {
18077 public:
18078   /* Initialize a machine state for the start of a line number
18079      program.  */
18080   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18081
18082   file_entry *current_file ()
18083   {
18084     /* lh->file_names is 0-based, but the file name numbers in the
18085        statement program are 1-based.  */
18086     return m_line_header->file_name_at (m_file);
18087   }
18088
18089   /* Record the line in the state machine.  END_SEQUENCE is true if
18090      we're processing the end of a sequence.  */
18091   void record_line (bool end_sequence);
18092
18093   /* Check address and if invalid nop-out the rest of the lines in this
18094      sequence.  */
18095   void check_line_address (struct dwarf2_cu *cu,
18096                            const gdb_byte *line_ptr,
18097                            CORE_ADDR lowpc, CORE_ADDR address);
18098
18099   void handle_set_discriminator (unsigned int discriminator)
18100   {
18101     m_discriminator = discriminator;
18102     m_line_has_non_zero_discriminator |= discriminator != 0;
18103   }
18104
18105   /* Handle DW_LNE_set_address.  */
18106   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18107   {
18108     m_op_index = 0;
18109     address += baseaddr;
18110     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18111   }
18112
18113   /* Handle DW_LNS_advance_pc.  */
18114   void handle_advance_pc (CORE_ADDR adjust);
18115
18116   /* Handle a special opcode.  */
18117   void handle_special_opcode (unsigned char op_code);
18118
18119   /* Handle DW_LNS_advance_line.  */
18120   void handle_advance_line (int line_delta)
18121   {
18122     advance_line (line_delta);
18123   }
18124
18125   /* Handle DW_LNS_set_file.  */
18126   void handle_set_file (file_name_index file);
18127
18128   /* Handle DW_LNS_negate_stmt.  */
18129   void handle_negate_stmt ()
18130   {
18131     m_is_stmt = !m_is_stmt;
18132   }
18133
18134   /* Handle DW_LNS_const_add_pc.  */
18135   void handle_const_add_pc ();
18136
18137   /* Handle DW_LNS_fixed_advance_pc.  */
18138   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18139   {
18140     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18141     m_op_index = 0;
18142   }
18143
18144   /* Handle DW_LNS_copy.  */
18145   void handle_copy ()
18146   {
18147     record_line (false);
18148     m_discriminator = 0;
18149   }
18150
18151   /* Handle DW_LNE_end_sequence.  */
18152   void handle_end_sequence ()
18153   {
18154     m_record_line_callback = ::record_line;
18155   }
18156
18157 private:
18158   /* Advance the line by LINE_DELTA.  */
18159   void advance_line (int line_delta)
18160   {
18161     m_line += line_delta;
18162
18163     if (line_delta != 0)
18164       m_line_has_non_zero_discriminator = m_discriminator != 0;
18165   }
18166
18167   gdbarch *m_gdbarch;
18168
18169   /* True if we're recording lines.
18170      Otherwise we're building partial symtabs and are just interested in
18171      finding include files mentioned by the line number program.  */
18172   bool m_record_lines_p;
18173
18174   /* The line number header.  */
18175   line_header *m_line_header;
18176
18177   /* These are part of the standard DWARF line number state machine,
18178      and initialized according to the DWARF spec.  */
18179
18180   unsigned char m_op_index = 0;
18181   /* The line table index (1-based) of the current file.  */
18182   file_name_index m_file = (file_name_index) 1;
18183   unsigned int m_line = 1;
18184
18185   /* These are initialized in the constructor.  */
18186
18187   CORE_ADDR m_address;
18188   bool m_is_stmt;
18189   unsigned int m_discriminator;
18190
18191   /* Additional bits of state we need to track.  */
18192
18193   /* The last file that we called dwarf2_start_subfile for.
18194      This is only used for TLLs.  */
18195   unsigned int m_last_file = 0;
18196   /* The last file a line number was recorded for.  */
18197   struct subfile *m_last_subfile = NULL;
18198
18199   /* The function to call to record a line.  */
18200   record_line_ftype *m_record_line_callback = NULL;
18201
18202   /* The last line number that was recorded, used to coalesce
18203      consecutive entries for the same line.  This can happen, for
18204      example, when discriminators are present.  PR 17276.  */
18205   unsigned int m_last_line = 0;
18206   bool m_line_has_non_zero_discriminator = false;
18207 };
18208
18209 void
18210 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18211 {
18212   CORE_ADDR addr_adj = (((m_op_index + adjust)
18213                          / m_line_header->maximum_ops_per_instruction)
18214                         * m_line_header->minimum_instruction_length);
18215   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18216   m_op_index = ((m_op_index + adjust)
18217                 % m_line_header->maximum_ops_per_instruction);
18218 }
18219
18220 void
18221 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18222 {
18223   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18224   CORE_ADDR addr_adj = (((m_op_index
18225                           + (adj_opcode / m_line_header->line_range))
18226                          / m_line_header->maximum_ops_per_instruction)
18227                         * m_line_header->minimum_instruction_length);
18228   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18229   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18230                 % m_line_header->maximum_ops_per_instruction);
18231
18232   int line_delta = (m_line_header->line_base
18233                     + (adj_opcode % m_line_header->line_range));
18234   advance_line (line_delta);
18235   record_line (false);
18236   m_discriminator = 0;
18237 }
18238
18239 void
18240 lnp_state_machine::handle_set_file (file_name_index file)
18241 {
18242   m_file = file;
18243
18244   const file_entry *fe = current_file ();
18245   if (fe == NULL)
18246     dwarf2_debug_line_missing_file_complaint ();
18247   else if (m_record_lines_p)
18248     {
18249       const char *dir = fe->include_dir (m_line_header);
18250
18251       m_last_subfile = current_subfile;
18252       m_line_has_non_zero_discriminator = m_discriminator != 0;
18253       dwarf2_start_subfile (fe->name, dir);
18254     }
18255 }
18256
18257 void
18258 lnp_state_machine::handle_const_add_pc ()
18259 {
18260   CORE_ADDR adjust
18261     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18262
18263   CORE_ADDR addr_adj
18264     = (((m_op_index + adjust)
18265         / m_line_header->maximum_ops_per_instruction)
18266        * m_line_header->minimum_instruction_length);
18267
18268   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18269   m_op_index = ((m_op_index + adjust)
18270                 % m_line_header->maximum_ops_per_instruction);
18271 }
18272
18273 /* Ignore this record_line request.  */
18274
18275 static void
18276 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18277 {
18278   return;
18279 }
18280
18281 /* Return non-zero if we should add LINE to the line number table.
18282    LINE is the line to add, LAST_LINE is the last line that was added,
18283    LAST_SUBFILE is the subfile for LAST_LINE.
18284    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18285    had a non-zero discriminator.
18286
18287    We have to be careful in the presence of discriminators.
18288    E.g., for this line:
18289
18290      for (i = 0; i < 100000; i++);
18291
18292    clang can emit four line number entries for that one line,
18293    each with a different discriminator.
18294    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18295
18296    However, we want gdb to coalesce all four entries into one.
18297    Otherwise the user could stepi into the middle of the line and
18298    gdb would get confused about whether the pc really was in the
18299    middle of the line.
18300
18301    Things are further complicated by the fact that two consecutive
18302    line number entries for the same line is a heuristic used by gcc
18303    to denote the end of the prologue.  So we can't just discard duplicate
18304    entries, we have to be selective about it.  The heuristic we use is
18305    that we only collapse consecutive entries for the same line if at least
18306    one of those entries has a non-zero discriminator.  PR 17276.
18307
18308    Note: Addresses in the line number state machine can never go backwards
18309    within one sequence, thus this coalescing is ok.  */
18310
18311 static int
18312 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18313                      int line_has_non_zero_discriminator,
18314                      struct subfile *last_subfile)
18315 {
18316   if (current_subfile != last_subfile)
18317     return 1;
18318   if (line != last_line)
18319     return 1;
18320   /* Same line for the same file that we've seen already.
18321      As a last check, for pr 17276, only record the line if the line
18322      has never had a non-zero discriminator.  */
18323   if (!line_has_non_zero_discriminator)
18324     return 1;
18325   return 0;
18326 }
18327
18328 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18329    in the line table of subfile SUBFILE.  */
18330
18331 static void
18332 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18333                      unsigned int line, CORE_ADDR address,
18334                      record_line_ftype p_record_line)
18335 {
18336   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18337
18338   if (dwarf_line_debug)
18339     {
18340       fprintf_unfiltered (gdb_stdlog,
18341                           "Recording line %u, file %s, address %s\n",
18342                           line, lbasename (subfile->name),
18343                           paddress (gdbarch, address));
18344     }
18345
18346   (*p_record_line) (subfile, line, addr);
18347 }
18348
18349 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18350    Mark the end of a set of line number records.
18351    The arguments are the same as for dwarf_record_line_1.
18352    If SUBFILE is NULL the request is ignored.  */
18353
18354 static void
18355 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18356                    CORE_ADDR address, record_line_ftype p_record_line)
18357 {
18358   if (subfile == NULL)
18359     return;
18360
18361   if (dwarf_line_debug)
18362     {
18363       fprintf_unfiltered (gdb_stdlog,
18364                           "Finishing current line, file %s, address %s\n",
18365                           lbasename (subfile->name),
18366                           paddress (gdbarch, address));
18367     }
18368
18369   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18370 }
18371
18372 void
18373 lnp_state_machine::record_line (bool end_sequence)
18374 {
18375   if (dwarf_line_debug)
18376     {
18377       fprintf_unfiltered (gdb_stdlog,
18378                           "Processing actual line %u: file %u,"
18379                           " address %s, is_stmt %u, discrim %u\n",
18380                           m_line, to_underlying (m_file),
18381                           paddress (m_gdbarch, m_address),
18382                           m_is_stmt, m_discriminator);
18383     }
18384
18385   file_entry *fe = current_file ();
18386
18387   if (fe == NULL)
18388     dwarf2_debug_line_missing_file_complaint ();
18389   /* For now we ignore lines not starting on an instruction boundary.
18390      But not when processing end_sequence for compatibility with the
18391      previous version of the code.  */
18392   else if (m_op_index == 0 || end_sequence)
18393     {
18394       fe->included_p = 1;
18395       if (m_record_lines_p && m_is_stmt)
18396         {
18397           if (m_last_subfile != current_subfile || end_sequence)
18398             {
18399               dwarf_finish_line (m_gdbarch, m_last_subfile,
18400                                  m_address, m_record_line_callback);
18401             }
18402
18403           if (!end_sequence)
18404             {
18405               if (dwarf_record_line_p (m_line, m_last_line,
18406                                        m_line_has_non_zero_discriminator,
18407                                        m_last_subfile))
18408                 {
18409                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18410                                        m_line, m_address,
18411                                        m_record_line_callback);
18412                 }
18413               m_last_subfile = current_subfile;
18414               m_last_line = m_line;
18415             }
18416         }
18417     }
18418 }
18419
18420 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18421                                       bool record_lines_p)
18422 {
18423   m_gdbarch = arch;
18424   m_record_lines_p = record_lines_p;
18425   m_line_header = lh;
18426
18427   m_record_line_callback = ::record_line;
18428
18429   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18430      was a line entry for it so that the backend has a chance to adjust it
18431      and also record it in case it needs it.  This is currently used by MIPS
18432      code, cf. `mips_adjust_dwarf2_line'.  */
18433   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18434   m_is_stmt = lh->default_is_stmt;
18435   m_discriminator = 0;
18436 }
18437
18438 void
18439 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18440                                        const gdb_byte *line_ptr,
18441                                        CORE_ADDR lowpc, CORE_ADDR address)
18442 {
18443   /* If address < lowpc then it's not a usable value, it's outside the
18444      pc range of the CU.  However, we restrict the test to only address
18445      values of zero to preserve GDB's previous behaviour which is to
18446      handle the specific case of a function being GC'd by the linker.  */
18447
18448   if (address == 0 && address < lowpc)
18449     {
18450       /* This line table is for a function which has been
18451          GCd by the linker.  Ignore it.  PR gdb/12528 */
18452
18453       struct objfile *objfile = cu->objfile;
18454       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18455
18456       complaint (&symfile_complaints,
18457                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18458                  line_offset, objfile_name (objfile));
18459       m_record_line_callback = noop_record_line;
18460       /* Note: record_line_callback is left as noop_record_line until
18461          we see DW_LNE_end_sequence.  */
18462     }
18463 }
18464
18465 /* Subroutine of dwarf_decode_lines to simplify it.
18466    Process the line number information in LH.
18467    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18468    program in order to set included_p for every referenced header.  */
18469
18470 static void
18471 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18472                       const int decode_for_pst_p, CORE_ADDR lowpc)
18473 {
18474   const gdb_byte *line_ptr, *extended_end;
18475   const gdb_byte *line_end;
18476   unsigned int bytes_read, extended_len;
18477   unsigned char op_code, extended_op;
18478   CORE_ADDR baseaddr;
18479   struct objfile *objfile = cu->objfile;
18480   bfd *abfd = objfile->obfd;
18481   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18482   /* True if we're recording line info (as opposed to building partial
18483      symtabs and just interested in finding include files mentioned by
18484      the line number program).  */
18485   bool record_lines_p = !decode_for_pst_p;
18486
18487   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18488
18489   line_ptr = lh->statement_program_start;
18490   line_end = lh->statement_program_end;
18491
18492   /* Read the statement sequences until there's nothing left.  */
18493   while (line_ptr < line_end)
18494     {
18495       /* The DWARF line number program state machine.  Reset the state
18496          machine at the start of each sequence.  */
18497       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18498       bool end_sequence = false;
18499
18500       if (record_lines_p)
18501         {
18502           /* Start a subfile for the current file of the state
18503              machine.  */
18504           const file_entry *fe = state_machine.current_file ();
18505
18506           if (fe != NULL)
18507             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18508         }
18509
18510       /* Decode the table.  */
18511       while (line_ptr < line_end && !end_sequence)
18512         {
18513           op_code = read_1_byte (abfd, line_ptr);
18514           line_ptr += 1;
18515
18516           if (op_code >= lh->opcode_base)
18517             {
18518               /* Special opcode.  */
18519               state_machine.handle_special_opcode (op_code);
18520             }
18521           else switch (op_code)
18522             {
18523             case DW_LNS_extended_op:
18524               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18525                                                    &bytes_read);
18526               line_ptr += bytes_read;
18527               extended_end = line_ptr + extended_len;
18528               extended_op = read_1_byte (abfd, line_ptr);
18529               line_ptr += 1;
18530               switch (extended_op)
18531                 {
18532                 case DW_LNE_end_sequence:
18533                   state_machine.handle_end_sequence ();
18534                   end_sequence = true;
18535                   break;
18536                 case DW_LNE_set_address:
18537                   {
18538                     CORE_ADDR address
18539                       = read_address (abfd, line_ptr, cu, &bytes_read);
18540                     line_ptr += bytes_read;
18541
18542                     state_machine.check_line_address (cu, line_ptr,
18543                                                       lowpc, address);
18544                     state_machine.handle_set_address (baseaddr, address);
18545                   }
18546                   break;
18547                 case DW_LNE_define_file:
18548                   {
18549                     const char *cur_file;
18550                     unsigned int mod_time, length;
18551                     dir_index dindex;
18552
18553                     cur_file = read_direct_string (abfd, line_ptr,
18554                                                    &bytes_read);
18555                     line_ptr += bytes_read;
18556                     dindex = (dir_index)
18557                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18558                     line_ptr += bytes_read;
18559                     mod_time =
18560                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18561                     line_ptr += bytes_read;
18562                     length =
18563                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18564                     line_ptr += bytes_read;
18565                     lh->add_file_name (cur_file, dindex, mod_time, length);
18566                   }
18567                   break;
18568                 case DW_LNE_set_discriminator:
18569                   {
18570                     /* The discriminator is not interesting to the
18571                        debugger; just ignore it.  We still need to
18572                        check its value though:
18573                        if there are consecutive entries for the same
18574                        (non-prologue) line we want to coalesce them.
18575                        PR 17276.  */
18576                     unsigned int discr
18577                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18578                     line_ptr += bytes_read;
18579
18580                     state_machine.handle_set_discriminator (discr);
18581                   }
18582                   break;
18583                 default:
18584                   complaint (&symfile_complaints,
18585                              _("mangled .debug_line section"));
18586                   return;
18587                 }
18588               /* Make sure that we parsed the extended op correctly.  If e.g.
18589                  we expected a different address size than the producer used,
18590                  we may have read the wrong number of bytes.  */
18591               if (line_ptr != extended_end)
18592                 {
18593                   complaint (&symfile_complaints,
18594                              _("mangled .debug_line section"));
18595                   return;
18596                 }
18597               break;
18598             case DW_LNS_copy:
18599               state_machine.handle_copy ();
18600               break;
18601             case DW_LNS_advance_pc:
18602               {
18603                 CORE_ADDR adjust
18604                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18605                 line_ptr += bytes_read;
18606
18607                 state_machine.handle_advance_pc (adjust);
18608               }
18609               break;
18610             case DW_LNS_advance_line:
18611               {
18612                 int line_delta
18613                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18614                 line_ptr += bytes_read;
18615
18616                 state_machine.handle_advance_line (line_delta);
18617               }
18618               break;
18619             case DW_LNS_set_file:
18620               {
18621                 file_name_index file
18622                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18623                                                             &bytes_read);
18624                 line_ptr += bytes_read;
18625
18626                 state_machine.handle_set_file (file);
18627               }
18628               break;
18629             case DW_LNS_set_column:
18630               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18631               line_ptr += bytes_read;
18632               break;
18633             case DW_LNS_negate_stmt:
18634               state_machine.handle_negate_stmt ();
18635               break;
18636             case DW_LNS_set_basic_block:
18637               break;
18638             /* Add to the address register of the state machine the
18639                address increment value corresponding to special opcode
18640                255.  I.e., this value is scaled by the minimum
18641                instruction length since special opcode 255 would have
18642                scaled the increment.  */
18643             case DW_LNS_const_add_pc:
18644               state_machine.handle_const_add_pc ();
18645               break;
18646             case DW_LNS_fixed_advance_pc:
18647               {
18648                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18649                 line_ptr += 2;
18650
18651                 state_machine.handle_fixed_advance_pc (addr_adj);
18652               }
18653               break;
18654             default:
18655               {
18656                 /* Unknown standard opcode, ignore it.  */
18657                 int i;
18658
18659                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18660                   {
18661                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18662                     line_ptr += bytes_read;
18663                   }
18664               }
18665             }
18666         }
18667
18668       if (!end_sequence)
18669         dwarf2_debug_line_missing_end_sequence_complaint ();
18670
18671       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18672          in which case we still finish recording the last line).  */
18673       state_machine.record_line (true);
18674     }
18675 }
18676
18677 /* Decode the Line Number Program (LNP) for the given line_header
18678    structure and CU.  The actual information extracted and the type
18679    of structures created from the LNP depends on the value of PST.
18680
18681    1. If PST is NULL, then this procedure uses the data from the program
18682       to create all necessary symbol tables, and their linetables.
18683
18684    2. If PST is not NULL, this procedure reads the program to determine
18685       the list of files included by the unit represented by PST, and
18686       builds all the associated partial symbol tables.
18687
18688    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18689    It is used for relative paths in the line table.
18690    NOTE: When processing partial symtabs (pst != NULL),
18691    comp_dir == pst->dirname.
18692
18693    NOTE: It is important that psymtabs have the same file name (via strcmp)
18694    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18695    symtab we don't use it in the name of the psymtabs we create.
18696    E.g. expand_line_sal requires this when finding psymtabs to expand.
18697    A good testcase for this is mb-inline.exp.
18698
18699    LOWPC is the lowest address in CU (or 0 if not known).
18700
18701    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18702    for its PC<->lines mapping information.  Otherwise only the filename
18703    table is read in.  */
18704
18705 static void
18706 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18707                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18708                     CORE_ADDR lowpc, int decode_mapping)
18709 {
18710   struct objfile *objfile = cu->objfile;
18711   const int decode_for_pst_p = (pst != NULL);
18712
18713   if (decode_mapping)
18714     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18715
18716   if (decode_for_pst_p)
18717     {
18718       int file_index;
18719
18720       /* Now that we're done scanning the Line Header Program, we can
18721          create the psymtab of each included file.  */
18722       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18723         if (lh->file_names[file_index].included_p == 1)
18724           {
18725             const char *include_name =
18726               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18727             if (include_name != NULL)
18728               dwarf2_create_include_psymtab (include_name, pst, objfile);
18729           }
18730     }
18731   else
18732     {
18733       /* Make sure a symtab is created for every file, even files
18734          which contain only variables (i.e. no code with associated
18735          line numbers).  */
18736       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18737       int i;
18738
18739       for (i = 0; i < lh->file_names.size (); i++)
18740         {
18741           file_entry &fe = lh->file_names[i];
18742
18743           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18744
18745           if (current_subfile->symtab == NULL)
18746             {
18747               current_subfile->symtab
18748                 = allocate_symtab (cust, current_subfile->name);
18749             }
18750           fe.symtab = current_subfile->symtab;
18751         }
18752     }
18753 }
18754
18755 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18756    DIRNAME the name of the source directory which contains FILENAME
18757    or NULL if not known.
18758    This routine tries to keep line numbers from identical absolute and
18759    relative file names in a common subfile.
18760
18761    Using the `list' example from the GDB testsuite, which resides in
18762    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18763    of /srcdir/list0.c yields the following debugging information for list0.c:
18764
18765    DW_AT_name:          /srcdir/list0.c
18766    DW_AT_comp_dir:      /compdir
18767    files.files[0].name: list0.h
18768    files.files[0].dir:  /srcdir
18769    files.files[1].name: list0.c
18770    files.files[1].dir:  /srcdir
18771
18772    The line number information for list0.c has to end up in a single
18773    subfile, so that `break /srcdir/list0.c:1' works as expected.
18774    start_subfile will ensure that this happens provided that we pass the
18775    concatenation of files.files[1].dir and files.files[1].name as the
18776    subfile's name.  */
18777
18778 static void
18779 dwarf2_start_subfile (const char *filename, const char *dirname)
18780 {
18781   char *copy = NULL;
18782
18783   /* In order not to lose the line information directory,
18784      we concatenate it to the filename when it makes sense.
18785      Note that the Dwarf3 standard says (speaking of filenames in line
18786      information): ``The directory index is ignored for file names
18787      that represent full path names''.  Thus ignoring dirname in the
18788      `else' branch below isn't an issue.  */
18789
18790   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18791     {
18792       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18793       filename = copy;
18794     }
18795
18796   start_subfile (filename);
18797
18798   if (copy != NULL)
18799     xfree (copy);
18800 }
18801
18802 /* Start a symtab for DWARF.
18803    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18804
18805 static struct compunit_symtab *
18806 dwarf2_start_symtab (struct dwarf2_cu *cu,
18807                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18808 {
18809   struct compunit_symtab *cust
18810     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18811
18812   record_debugformat ("DWARF 2");
18813   record_producer (cu->producer);
18814
18815   /* We assume that we're processing GCC output.  */
18816   processing_gcc_compilation = 2;
18817
18818   cu->processing_has_namespace_info = 0;
18819
18820   return cust;
18821 }
18822
18823 static void
18824 var_decode_location (struct attribute *attr, struct symbol *sym,
18825                      struct dwarf2_cu *cu)
18826 {
18827   struct objfile *objfile = cu->objfile;
18828   struct comp_unit_head *cu_header = &cu->header;
18829
18830   /* NOTE drow/2003-01-30: There used to be a comment and some special
18831      code here to turn a symbol with DW_AT_external and a
18832      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18833      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18834      with some versions of binutils) where shared libraries could have
18835      relocations against symbols in their debug information - the
18836      minimal symbol would have the right address, but the debug info
18837      would not.  It's no longer necessary, because we will explicitly
18838      apply relocations when we read in the debug information now.  */
18839
18840   /* A DW_AT_location attribute with no contents indicates that a
18841      variable has been optimized away.  */
18842   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18843     {
18844       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18845       return;
18846     }
18847
18848   /* Handle one degenerate form of location expression specially, to
18849      preserve GDB's previous behavior when section offsets are
18850      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18851      then mark this symbol as LOC_STATIC.  */
18852
18853   if (attr_form_is_block (attr)
18854       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18855            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18856           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18857               && (DW_BLOCK (attr)->size
18858                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18859     {
18860       unsigned int dummy;
18861
18862       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18863         SYMBOL_VALUE_ADDRESS (sym) =
18864           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18865       else
18866         SYMBOL_VALUE_ADDRESS (sym) =
18867           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18868       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18869       fixup_symbol_section (sym, objfile);
18870       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18871                                               SYMBOL_SECTION (sym));
18872       return;
18873     }
18874
18875   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18876      expression evaluator, and use LOC_COMPUTED only when necessary
18877      (i.e. when the value of a register or memory location is
18878      referenced, or a thread-local block, etc.).  Then again, it might
18879      not be worthwhile.  I'm assuming that it isn't unless performance
18880      or memory numbers show me otherwise.  */
18881
18882   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18883
18884   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18885     cu->has_loclist = 1;
18886 }
18887
18888 /* Given a pointer to a DWARF information entry, figure out if we need
18889    to make a symbol table entry for it, and if so, create a new entry
18890    and return a pointer to it.
18891    If TYPE is NULL, determine symbol type from the die, otherwise
18892    used the passed type.
18893    If SPACE is not NULL, use it to hold the new symbol.  If it is
18894    NULL, allocate a new symbol on the objfile's obstack.  */
18895
18896 static struct symbol *
18897 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
18898                  struct symbol *space)
18899 {
18900   struct objfile *objfile = cu->objfile;
18901   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18902   struct symbol *sym = NULL;
18903   const char *name;
18904   struct attribute *attr = NULL;
18905   struct attribute *attr2 = NULL;
18906   CORE_ADDR baseaddr;
18907   struct pending **list_to_add = NULL;
18908
18909   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
18910
18911   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18912
18913   name = dwarf2_name (die, cu);
18914   if (name)
18915     {
18916       const char *linkagename;
18917       int suppress_add = 0;
18918
18919       if (space)
18920         sym = space;
18921       else
18922         sym = allocate_symbol (objfile);
18923       OBJSTAT (objfile, n_syms++);
18924
18925       /* Cache this symbol's name and the name's demangled form (if any).  */
18926       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
18927       linkagename = dwarf2_physname (name, die, cu);
18928       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
18929
18930       /* Fortran does not have mangling standard and the mangling does differ
18931          between gfortran, iFort etc.  */
18932       if (cu->language == language_fortran
18933           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
18934         symbol_set_demangled_name (&(sym->ginfo),
18935                                    dwarf2_full_name (name, die, cu),
18936                                    NULL);
18937
18938       /* Default assumptions.
18939          Use the passed type or decode it from the die.  */
18940       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
18941       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18942       if (type != NULL)
18943         SYMBOL_TYPE (sym) = type;
18944       else
18945         SYMBOL_TYPE (sym) = die_type (die, cu);
18946       attr = dwarf2_attr (die,
18947                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
18948                           cu);
18949       if (attr)
18950         {
18951           SYMBOL_LINE (sym) = DW_UNSND (attr);
18952         }
18953
18954       attr = dwarf2_attr (die,
18955                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
18956                           cu);
18957       if (attr)
18958         {
18959           file_name_index file_index = (file_name_index) DW_UNSND (attr);
18960           struct file_entry *fe;
18961
18962           if (cu->line_header != NULL)
18963             fe = cu->line_header->file_name_at (file_index);
18964           else
18965             fe = NULL;
18966
18967           if (fe == NULL)
18968             complaint (&symfile_complaints,
18969                        _("file index out of range"));
18970           else
18971             symbol_set_symtab (sym, fe->symtab);
18972         }
18973
18974       switch (die->tag)
18975         {
18976         case DW_TAG_label:
18977           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
18978           if (attr)
18979             {
18980               CORE_ADDR addr;
18981
18982               addr = attr_value_as_address (attr);
18983               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
18984               SYMBOL_VALUE_ADDRESS (sym) = addr;
18985             }
18986           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
18987           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
18988           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
18989           add_symbol_to_list (sym, cu->list_in_scope);
18990           break;
18991         case DW_TAG_subprogram:
18992           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
18993              finish_block.  */
18994           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
18995           attr2 = dwarf2_attr (die, DW_AT_external, cu);
18996           if ((attr2 && (DW_UNSND (attr2) != 0))
18997               || cu->language == language_ada)
18998             {
18999               /* Subprograms marked external are stored as a global symbol.
19000                  Ada subprograms, whether marked external or not, are always
19001                  stored as a global symbol, because we want to be able to
19002                  access them globally.  For instance, we want to be able
19003                  to break on a nested subprogram without having to
19004                  specify the context.  */
19005               list_to_add = &global_symbols;
19006             }
19007           else
19008             {
19009               list_to_add = cu->list_in_scope;
19010             }
19011           break;
19012         case DW_TAG_inlined_subroutine:
19013           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19014              finish_block.  */
19015           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19016           SYMBOL_INLINED (sym) = 1;
19017           list_to_add = cu->list_in_scope;
19018           break;
19019         case DW_TAG_template_value_param:
19020           suppress_add = 1;
19021           /* Fall through.  */
19022         case DW_TAG_constant:
19023         case DW_TAG_variable:
19024         case DW_TAG_member:
19025           /* Compilation with minimal debug info may result in
19026              variables with missing type entries.  Change the
19027              misleading `void' type to something sensible.  */
19028           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19029             SYMBOL_TYPE (sym)
19030               = objfile_type (objfile)->nodebug_data_symbol;
19031
19032           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19033           /* In the case of DW_TAG_member, we should only be called for
19034              static const members.  */
19035           if (die->tag == DW_TAG_member)
19036             {
19037               /* dwarf2_add_field uses die_is_declaration,
19038                  so we do the same.  */
19039               gdb_assert (die_is_declaration (die, cu));
19040               gdb_assert (attr);
19041             }
19042           if (attr)
19043             {
19044               dwarf2_const_value (attr, sym, cu);
19045               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19046               if (!suppress_add)
19047                 {
19048                   if (attr2 && (DW_UNSND (attr2) != 0))
19049                     list_to_add = &global_symbols;
19050                   else
19051                     list_to_add = cu->list_in_scope;
19052                 }
19053               break;
19054             }
19055           attr = dwarf2_attr (die, DW_AT_location, cu);
19056           if (attr)
19057             {
19058               var_decode_location (attr, sym, cu);
19059               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19060
19061               /* Fortran explicitly imports any global symbols to the local
19062                  scope by DW_TAG_common_block.  */
19063               if (cu->language == language_fortran && die->parent
19064                   && die->parent->tag == DW_TAG_common_block)
19065                 attr2 = NULL;
19066
19067               if (SYMBOL_CLASS (sym) == LOC_STATIC
19068                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19069                   && !dwarf2_per_objfile->has_section_at_zero)
19070                 {
19071                   /* When a static variable is eliminated by the linker,
19072                      the corresponding debug information is not stripped
19073                      out, but the variable address is set to null;
19074                      do not add such variables into symbol table.  */
19075                 }
19076               else if (attr2 && (DW_UNSND (attr2) != 0))
19077                 {
19078                   /* Workaround gfortran PR debug/40040 - it uses
19079                      DW_AT_location for variables in -fPIC libraries which may
19080                      get overriden by other libraries/executable and get
19081                      a different address.  Resolve it by the minimal symbol
19082                      which may come from inferior's executable using copy
19083                      relocation.  Make this workaround only for gfortran as for
19084                      other compilers GDB cannot guess the minimal symbol
19085                      Fortran mangling kind.  */
19086                   if (cu->language == language_fortran && die->parent
19087                       && die->parent->tag == DW_TAG_module
19088                       && cu->producer
19089                       && startswith (cu->producer, "GNU Fortran"))
19090                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19091
19092                   /* A variable with DW_AT_external is never static,
19093                      but it may be block-scoped.  */
19094                   list_to_add = (cu->list_in_scope == &file_symbols
19095                                  ? &global_symbols : cu->list_in_scope);
19096                 }
19097               else
19098                 list_to_add = cu->list_in_scope;
19099             }
19100           else
19101             {
19102               /* We do not know the address of this symbol.
19103                  If it is an external symbol and we have type information
19104                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19105                  The address of the variable will then be determined from
19106                  the minimal symbol table whenever the variable is
19107                  referenced.  */
19108               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19109
19110               /* Fortran explicitly imports any global symbols to the local
19111                  scope by DW_TAG_common_block.  */
19112               if (cu->language == language_fortran && die->parent
19113                   && die->parent->tag == DW_TAG_common_block)
19114                 {
19115                   /* SYMBOL_CLASS doesn't matter here because
19116                      read_common_block is going to reset it.  */
19117                   if (!suppress_add)
19118                     list_to_add = cu->list_in_scope;
19119                 }
19120               else if (attr2 && (DW_UNSND (attr2) != 0)
19121                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19122                 {
19123                   /* A variable with DW_AT_external is never static, but it
19124                      may be block-scoped.  */
19125                   list_to_add = (cu->list_in_scope == &file_symbols
19126                                  ? &global_symbols : cu->list_in_scope);
19127
19128                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19129                 }
19130               else if (!die_is_declaration (die, cu))
19131                 {
19132                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19133                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19134                   if (!suppress_add)
19135                     list_to_add = cu->list_in_scope;
19136                 }
19137             }
19138           break;
19139         case DW_TAG_formal_parameter:
19140           /* If we are inside a function, mark this as an argument.  If
19141              not, we might be looking at an argument to an inlined function
19142              when we do not have enough information to show inlined frames;
19143              pretend it's a local variable in that case so that the user can
19144              still see it.  */
19145           if (context_stack_depth > 0
19146               && context_stack[context_stack_depth - 1].name != NULL)
19147             SYMBOL_IS_ARGUMENT (sym) = 1;
19148           attr = dwarf2_attr (die, DW_AT_location, cu);
19149           if (attr)
19150             {
19151               var_decode_location (attr, sym, cu);
19152             }
19153           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19154           if (attr)
19155             {
19156               dwarf2_const_value (attr, sym, cu);
19157             }
19158
19159           list_to_add = cu->list_in_scope;
19160           break;
19161         case DW_TAG_unspecified_parameters:
19162           /* From varargs functions; gdb doesn't seem to have any
19163              interest in this information, so just ignore it for now.
19164              (FIXME?) */
19165           break;
19166         case DW_TAG_template_type_param:
19167           suppress_add = 1;
19168           /* Fall through.  */
19169         case DW_TAG_class_type:
19170         case DW_TAG_interface_type:
19171         case DW_TAG_structure_type:
19172         case DW_TAG_union_type:
19173         case DW_TAG_set_type:
19174         case DW_TAG_enumeration_type:
19175           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19176           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19177
19178           {
19179             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19180                really ever be static objects: otherwise, if you try
19181                to, say, break of a class's method and you're in a file
19182                which doesn't mention that class, it won't work unless
19183                the check for all static symbols in lookup_symbol_aux
19184                saves you.  See the OtherFileClass tests in
19185                gdb.c++/namespace.exp.  */
19186
19187             if (!suppress_add)
19188               {
19189                 list_to_add = (cu->list_in_scope == &file_symbols
19190                                && cu->language == language_cplus
19191                                ? &global_symbols : cu->list_in_scope);
19192
19193                 /* The semantics of C++ state that "struct foo {
19194                    ... }" also defines a typedef for "foo".  */
19195                 if (cu->language == language_cplus
19196                     || cu->language == language_ada
19197                     || cu->language == language_d
19198                     || cu->language == language_rust)
19199                   {
19200                     /* The symbol's name is already allocated along
19201                        with this objfile, so we don't need to
19202                        duplicate it for the type.  */
19203                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19204                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19205                   }
19206               }
19207           }
19208           break;
19209         case DW_TAG_typedef:
19210           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19211           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19212           list_to_add = cu->list_in_scope;
19213           break;
19214         case DW_TAG_base_type:
19215         case DW_TAG_subrange_type:
19216           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19217           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19218           list_to_add = cu->list_in_scope;
19219           break;
19220         case DW_TAG_enumerator:
19221           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19222           if (attr)
19223             {
19224               dwarf2_const_value (attr, sym, cu);
19225             }
19226           {
19227             /* NOTE: carlton/2003-11-10: See comment above in the
19228                DW_TAG_class_type, etc. block.  */
19229
19230             list_to_add = (cu->list_in_scope == &file_symbols
19231                            && cu->language == language_cplus
19232                            ? &global_symbols : cu->list_in_scope);
19233           }
19234           break;
19235         case DW_TAG_imported_declaration:
19236         case DW_TAG_namespace:
19237           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19238           list_to_add = &global_symbols;
19239           break;
19240         case DW_TAG_module:
19241           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19242           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19243           list_to_add = &global_symbols;
19244           break;
19245         case DW_TAG_common_block:
19246           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19247           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19248           add_symbol_to_list (sym, cu->list_in_scope);
19249           break;
19250         default:
19251           /* Not a tag we recognize.  Hopefully we aren't processing
19252              trash data, but since we must specifically ignore things
19253              we don't recognize, there is nothing else we should do at
19254              this point.  */
19255           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19256                      dwarf_tag_name (die->tag));
19257           break;
19258         }
19259
19260       if (suppress_add)
19261         {
19262           sym->hash_next = objfile->template_symbols;
19263           objfile->template_symbols = sym;
19264           list_to_add = NULL;
19265         }
19266
19267       if (list_to_add != NULL)
19268         add_symbol_to_list (sym, list_to_add);
19269
19270       /* For the benefit of old versions of GCC, check for anonymous
19271          namespaces based on the demangled name.  */
19272       if (!cu->processing_has_namespace_info
19273           && cu->language == language_cplus)
19274         cp_scan_for_anonymous_namespaces (sym, objfile);
19275     }
19276   return (sym);
19277 }
19278
19279 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19280
19281 static struct symbol *
19282 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19283 {
19284   return new_symbol_full (die, type, cu, NULL);
19285 }
19286
19287 /* Given an attr with a DW_FORM_dataN value in host byte order,
19288    zero-extend it as appropriate for the symbol's type.  The DWARF
19289    standard (v4) is not entirely clear about the meaning of using
19290    DW_FORM_dataN for a constant with a signed type, where the type is
19291    wider than the data.  The conclusion of a discussion on the DWARF
19292    list was that this is unspecified.  We choose to always zero-extend
19293    because that is the interpretation long in use by GCC.  */
19294
19295 static gdb_byte *
19296 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19297                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19298 {
19299   struct objfile *objfile = cu->objfile;
19300   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19301                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19302   LONGEST l = DW_UNSND (attr);
19303
19304   if (bits < sizeof (*value) * 8)
19305     {
19306       l &= ((LONGEST) 1 << bits) - 1;
19307       *value = l;
19308     }
19309   else if (bits == sizeof (*value) * 8)
19310     *value = l;
19311   else
19312     {
19313       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19314       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19315       return bytes;
19316     }
19317
19318   return NULL;
19319 }
19320
19321 /* Read a constant value from an attribute.  Either set *VALUE, or if
19322    the value does not fit in *VALUE, set *BYTES - either already
19323    allocated on the objfile obstack, or newly allocated on OBSTACK,
19324    or, set *BATON, if we translated the constant to a location
19325    expression.  */
19326
19327 static void
19328 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19329                          const char *name, struct obstack *obstack,
19330                          struct dwarf2_cu *cu,
19331                          LONGEST *value, const gdb_byte **bytes,
19332                          struct dwarf2_locexpr_baton **baton)
19333 {
19334   struct objfile *objfile = cu->objfile;
19335   struct comp_unit_head *cu_header = &cu->header;
19336   struct dwarf_block *blk;
19337   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19338                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19339
19340   *value = 0;
19341   *bytes = NULL;
19342   *baton = NULL;
19343
19344   switch (attr->form)
19345     {
19346     case DW_FORM_addr:
19347     case DW_FORM_GNU_addr_index:
19348       {
19349         gdb_byte *data;
19350
19351         if (TYPE_LENGTH (type) != cu_header->addr_size)
19352           dwarf2_const_value_length_mismatch_complaint (name,
19353                                                         cu_header->addr_size,
19354                                                         TYPE_LENGTH (type));
19355         /* Symbols of this form are reasonably rare, so we just
19356            piggyback on the existing location code rather than writing
19357            a new implementation of symbol_computed_ops.  */
19358         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19359         (*baton)->per_cu = cu->per_cu;
19360         gdb_assert ((*baton)->per_cu);
19361
19362         (*baton)->size = 2 + cu_header->addr_size;
19363         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19364         (*baton)->data = data;
19365
19366         data[0] = DW_OP_addr;
19367         store_unsigned_integer (&data[1], cu_header->addr_size,
19368                                 byte_order, DW_ADDR (attr));
19369         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19370       }
19371       break;
19372     case DW_FORM_string:
19373     case DW_FORM_strp:
19374     case DW_FORM_GNU_str_index:
19375     case DW_FORM_GNU_strp_alt:
19376       /* DW_STRING is already allocated on the objfile obstack, point
19377          directly to it.  */
19378       *bytes = (const gdb_byte *) DW_STRING (attr);
19379       break;
19380     case DW_FORM_block1:
19381     case DW_FORM_block2:
19382     case DW_FORM_block4:
19383     case DW_FORM_block:
19384     case DW_FORM_exprloc:
19385     case DW_FORM_data16:
19386       blk = DW_BLOCK (attr);
19387       if (TYPE_LENGTH (type) != blk->size)
19388         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19389                                                       TYPE_LENGTH (type));
19390       *bytes = blk->data;
19391       break;
19392
19393       /* The DW_AT_const_value attributes are supposed to carry the
19394          symbol's value "represented as it would be on the target
19395          architecture."  By the time we get here, it's already been
19396          converted to host endianness, so we just need to sign- or
19397          zero-extend it as appropriate.  */
19398     case DW_FORM_data1:
19399       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19400       break;
19401     case DW_FORM_data2:
19402       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19403       break;
19404     case DW_FORM_data4:
19405       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19406       break;
19407     case DW_FORM_data8:
19408       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19409       break;
19410
19411     case DW_FORM_sdata:
19412       *value = DW_SND (attr);
19413       break;
19414
19415     case DW_FORM_udata:
19416       *value = DW_UNSND (attr);
19417       break;
19418
19419     default:
19420       complaint (&symfile_complaints,
19421                  _("unsupported const value attribute form: '%s'"),
19422                  dwarf_form_name (attr->form));
19423       *value = 0;
19424       break;
19425     }
19426 }
19427
19428
19429 /* Copy constant value from an attribute to a symbol.  */
19430
19431 static void
19432 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19433                     struct dwarf2_cu *cu)
19434 {
19435   struct objfile *objfile = cu->objfile;
19436   LONGEST value;
19437   const gdb_byte *bytes;
19438   struct dwarf2_locexpr_baton *baton;
19439
19440   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19441                            SYMBOL_PRINT_NAME (sym),
19442                            &objfile->objfile_obstack, cu,
19443                            &value, &bytes, &baton);
19444
19445   if (baton != NULL)
19446     {
19447       SYMBOL_LOCATION_BATON (sym) = baton;
19448       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19449     }
19450   else if (bytes != NULL)
19451      {
19452       SYMBOL_VALUE_BYTES (sym) = bytes;
19453       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19454     }
19455   else
19456     {
19457       SYMBOL_VALUE (sym) = value;
19458       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19459     }
19460 }
19461
19462 /* Return the type of the die in question using its DW_AT_type attribute.  */
19463
19464 static struct type *
19465 die_type (struct die_info *die, struct dwarf2_cu *cu)
19466 {
19467   struct attribute *type_attr;
19468
19469   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19470   if (!type_attr)
19471     {
19472       /* A missing DW_AT_type represents a void type.  */
19473       return objfile_type (cu->objfile)->builtin_void;
19474     }
19475
19476   return lookup_die_type (die, type_attr, cu);
19477 }
19478
19479 /* True iff CU's producer generates GNAT Ada auxiliary information
19480    that allows to find parallel types through that information instead
19481    of having to do expensive parallel lookups by type name.  */
19482
19483 static int
19484 need_gnat_info (struct dwarf2_cu *cu)
19485 {
19486   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19487      of GNAT produces this auxiliary information, without any indication
19488      that it is produced.  Part of enhancing the FSF version of GNAT
19489      to produce that information will be to put in place an indicator
19490      that we can use in order to determine whether the descriptive type
19491      info is available or not.  One suggestion that has been made is
19492      to use a new attribute, attached to the CU die.  For now, assume
19493      that the descriptive type info is not available.  */
19494   return 0;
19495 }
19496
19497 /* Return the auxiliary type of the die in question using its
19498    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19499    attribute is not present.  */
19500
19501 static struct type *
19502 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19503 {
19504   struct attribute *type_attr;
19505
19506   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19507   if (!type_attr)
19508     return NULL;
19509
19510   return lookup_die_type (die, type_attr, cu);
19511 }
19512
19513 /* If DIE has a descriptive_type attribute, then set the TYPE's
19514    descriptive type accordingly.  */
19515
19516 static void
19517 set_descriptive_type (struct type *type, struct die_info *die,
19518                       struct dwarf2_cu *cu)
19519 {
19520   struct type *descriptive_type = die_descriptive_type (die, cu);
19521
19522   if (descriptive_type)
19523     {
19524       ALLOCATE_GNAT_AUX_TYPE (type);
19525       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19526     }
19527 }
19528
19529 /* Return the containing type of the die in question using its
19530    DW_AT_containing_type attribute.  */
19531
19532 static struct type *
19533 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19534 {
19535   struct attribute *type_attr;
19536
19537   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19538   if (!type_attr)
19539     error (_("Dwarf Error: Problem turning containing type into gdb type "
19540              "[in module %s]"), objfile_name (cu->objfile));
19541
19542   return lookup_die_type (die, type_attr, cu);
19543 }
19544
19545 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19546
19547 static struct type *
19548 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19549 {
19550   struct objfile *objfile = dwarf2_per_objfile->objfile;
19551   char *message, *saved;
19552
19553   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19554                         objfile_name (objfile),
19555                         to_underlying (cu->header.sect_off),
19556                         to_underlying (die->sect_off));
19557   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19558                                   message, strlen (message));
19559   xfree (message);
19560
19561   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19562 }
19563
19564 /* Look up the type of DIE in CU using its type attribute ATTR.
19565    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19566    DW_AT_containing_type.
19567    If there is no type substitute an error marker.  */
19568
19569 static struct type *
19570 lookup_die_type (struct die_info *die, const struct attribute *attr,
19571                  struct dwarf2_cu *cu)
19572 {
19573   struct objfile *objfile = cu->objfile;
19574   struct type *this_type;
19575
19576   gdb_assert (attr->name == DW_AT_type
19577               || attr->name == DW_AT_GNAT_descriptive_type
19578               || attr->name == DW_AT_containing_type);
19579
19580   /* First see if we have it cached.  */
19581
19582   if (attr->form == DW_FORM_GNU_ref_alt)
19583     {
19584       struct dwarf2_per_cu_data *per_cu;
19585       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19586
19587       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19588       this_type = get_die_type_at_offset (sect_off, per_cu);
19589     }
19590   else if (attr_form_is_ref (attr))
19591     {
19592       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19593
19594       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19595     }
19596   else if (attr->form == DW_FORM_ref_sig8)
19597     {
19598       ULONGEST signature = DW_SIGNATURE (attr);
19599
19600       return get_signatured_type (die, signature, cu);
19601     }
19602   else
19603     {
19604       complaint (&symfile_complaints,
19605                  _("Dwarf Error: Bad type attribute %s in DIE"
19606                    " at 0x%x [in module %s]"),
19607                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19608                  objfile_name (objfile));
19609       return build_error_marker_type (cu, die);
19610     }
19611
19612   /* If not cached we need to read it in.  */
19613
19614   if (this_type == NULL)
19615     {
19616       struct die_info *type_die = NULL;
19617       struct dwarf2_cu *type_cu = cu;
19618
19619       if (attr_form_is_ref (attr))
19620         type_die = follow_die_ref (die, attr, &type_cu);
19621       if (type_die == NULL)
19622         return build_error_marker_type (cu, die);
19623       /* If we find the type now, it's probably because the type came
19624          from an inter-CU reference and the type's CU got expanded before
19625          ours.  */
19626       this_type = read_type_die (type_die, type_cu);
19627     }
19628
19629   /* If we still don't have a type use an error marker.  */
19630
19631   if (this_type == NULL)
19632     return build_error_marker_type (cu, die);
19633
19634   return this_type;
19635 }
19636
19637 /* Return the type in DIE, CU.
19638    Returns NULL for invalid types.
19639
19640    This first does a lookup in die_type_hash,
19641    and only reads the die in if necessary.
19642
19643    NOTE: This can be called when reading in partial or full symbols.  */
19644
19645 static struct type *
19646 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19647 {
19648   struct type *this_type;
19649
19650   this_type = get_die_type (die, cu);
19651   if (this_type)
19652     return this_type;
19653
19654   return read_type_die_1 (die, cu);
19655 }
19656
19657 /* Read the type in DIE, CU.
19658    Returns NULL for invalid types.  */
19659
19660 static struct type *
19661 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19662 {
19663   struct type *this_type = NULL;
19664
19665   switch (die->tag)
19666     {
19667     case DW_TAG_class_type:
19668     case DW_TAG_interface_type:
19669     case DW_TAG_structure_type:
19670     case DW_TAG_union_type:
19671       this_type = read_structure_type (die, cu);
19672       break;
19673     case DW_TAG_enumeration_type:
19674       this_type = read_enumeration_type (die, cu);
19675       break;
19676     case DW_TAG_subprogram:
19677     case DW_TAG_subroutine_type:
19678     case DW_TAG_inlined_subroutine:
19679       this_type = read_subroutine_type (die, cu);
19680       break;
19681     case DW_TAG_array_type:
19682       this_type = read_array_type (die, cu);
19683       break;
19684     case DW_TAG_set_type:
19685       this_type = read_set_type (die, cu);
19686       break;
19687     case DW_TAG_pointer_type:
19688       this_type = read_tag_pointer_type (die, cu);
19689       break;
19690     case DW_TAG_ptr_to_member_type:
19691       this_type = read_tag_ptr_to_member_type (die, cu);
19692       break;
19693     case DW_TAG_reference_type:
19694       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19695       break;
19696     case DW_TAG_rvalue_reference_type:
19697       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19698       break;
19699     case DW_TAG_const_type:
19700       this_type = read_tag_const_type (die, cu);
19701       break;
19702     case DW_TAG_volatile_type:
19703       this_type = read_tag_volatile_type (die, cu);
19704       break;
19705     case DW_TAG_restrict_type:
19706       this_type = read_tag_restrict_type (die, cu);
19707       break;
19708     case DW_TAG_string_type:
19709       this_type = read_tag_string_type (die, cu);
19710       break;
19711     case DW_TAG_typedef:
19712       this_type = read_typedef (die, cu);
19713       break;
19714     case DW_TAG_subrange_type:
19715       this_type = read_subrange_type (die, cu);
19716       break;
19717     case DW_TAG_base_type:
19718       this_type = read_base_type (die, cu);
19719       break;
19720     case DW_TAG_unspecified_type:
19721       this_type = read_unspecified_type (die, cu);
19722       break;
19723     case DW_TAG_namespace:
19724       this_type = read_namespace_type (die, cu);
19725       break;
19726     case DW_TAG_module:
19727       this_type = read_module_type (die, cu);
19728       break;
19729     case DW_TAG_atomic_type:
19730       this_type = read_tag_atomic_type (die, cu);
19731       break;
19732     default:
19733       complaint (&symfile_complaints,
19734                  _("unexpected tag in read_type_die: '%s'"),
19735                  dwarf_tag_name (die->tag));
19736       break;
19737     }
19738
19739   return this_type;
19740 }
19741
19742 /* See if we can figure out if the class lives in a namespace.  We do
19743    this by looking for a member function; its demangled name will
19744    contain namespace info, if there is any.
19745    Return the computed name or NULL.
19746    Space for the result is allocated on the objfile's obstack.
19747    This is the full-die version of guess_partial_die_structure_name.
19748    In this case we know DIE has no useful parent.  */
19749
19750 static char *
19751 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19752 {
19753   struct die_info *spec_die;
19754   struct dwarf2_cu *spec_cu;
19755   struct die_info *child;
19756
19757   spec_cu = cu;
19758   spec_die = die_specification (die, &spec_cu);
19759   if (spec_die != NULL)
19760     {
19761       die = spec_die;
19762       cu = spec_cu;
19763     }
19764
19765   for (child = die->child;
19766        child != NULL;
19767        child = child->sibling)
19768     {
19769       if (child->tag == DW_TAG_subprogram)
19770         {
19771           const char *linkage_name;
19772
19773           linkage_name = dwarf2_string_attr (child, DW_AT_linkage_name, cu);
19774           if (linkage_name == NULL)
19775             linkage_name = dwarf2_string_attr (child, DW_AT_MIPS_linkage_name,
19776                                                cu);
19777           if (linkage_name != NULL)
19778             {
19779               char *actual_name
19780                 = language_class_name_from_physname (cu->language_defn,
19781                                                      linkage_name);
19782               char *name = NULL;
19783
19784               if (actual_name != NULL)
19785                 {
19786                   const char *die_name = dwarf2_name (die, cu);
19787
19788                   if (die_name != NULL
19789                       && strcmp (die_name, actual_name) != 0)
19790                     {
19791                       /* Strip off the class name from the full name.
19792                          We want the prefix.  */
19793                       int die_name_len = strlen (die_name);
19794                       int actual_name_len = strlen (actual_name);
19795
19796                       /* Test for '::' as a sanity check.  */
19797                       if (actual_name_len > die_name_len + 2
19798                           && actual_name[actual_name_len
19799                                          - die_name_len - 1] == ':')
19800                         name = (char *) obstack_copy0 (
19801                           &cu->objfile->per_bfd->storage_obstack,
19802                           actual_name, actual_name_len - die_name_len - 2);
19803                     }
19804                 }
19805               xfree (actual_name);
19806               return name;
19807             }
19808         }
19809     }
19810
19811   return NULL;
19812 }
19813
19814 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19815    prefix part in such case.  See
19816    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19817
19818 static const char *
19819 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19820 {
19821   struct attribute *attr;
19822   const char *base;
19823
19824   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19825       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19826     return NULL;
19827
19828   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19829     return NULL;
19830
19831   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19832   if (attr == NULL)
19833     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19834   if (attr == NULL || DW_STRING (attr) == NULL)
19835     return NULL;
19836
19837   /* dwarf2_name had to be already called.  */
19838   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19839
19840   /* Strip the base name, keep any leading namespaces/classes.  */
19841   base = strrchr (DW_STRING (attr), ':');
19842   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19843     return "";
19844
19845   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19846                                  DW_STRING (attr),
19847                                  &base[-1] - DW_STRING (attr));
19848 }
19849
19850 /* Return the name of the namespace/class that DIE is defined within,
19851    or "" if we can't tell.  The caller should not xfree the result.
19852
19853    For example, if we're within the method foo() in the following
19854    code:
19855
19856    namespace N {
19857      class C {
19858        void foo () {
19859        }
19860      };
19861    }
19862
19863    then determine_prefix on foo's die will return "N::C".  */
19864
19865 static const char *
19866 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19867 {
19868   struct die_info *parent, *spec_die;
19869   struct dwarf2_cu *spec_cu;
19870   struct type *parent_type;
19871   const char *retval;
19872
19873   if (cu->language != language_cplus
19874       && cu->language != language_fortran && cu->language != language_d
19875       && cu->language != language_rust)
19876     return "";
19877
19878   retval = anonymous_struct_prefix (die, cu);
19879   if (retval)
19880     return retval;
19881
19882   /* We have to be careful in the presence of DW_AT_specification.
19883      For example, with GCC 3.4, given the code
19884
19885      namespace N {
19886        void foo() {
19887          // Definition of N::foo.
19888        }
19889      }
19890
19891      then we'll have a tree of DIEs like this:
19892
19893      1: DW_TAG_compile_unit
19894        2: DW_TAG_namespace        // N
19895          3: DW_TAG_subprogram     // declaration of N::foo
19896        4: DW_TAG_subprogram       // definition of N::foo
19897             DW_AT_specification   // refers to die #3
19898
19899      Thus, when processing die #4, we have to pretend that we're in
19900      the context of its DW_AT_specification, namely the contex of die
19901      #3.  */
19902   spec_cu = cu;
19903   spec_die = die_specification (die, &spec_cu);
19904   if (spec_die == NULL)
19905     parent = die->parent;
19906   else
19907     {
19908       parent = spec_die->parent;
19909       cu = spec_cu;
19910     }
19911
19912   if (parent == NULL)
19913     return "";
19914   else if (parent->building_fullname)
19915     {
19916       const char *name;
19917       const char *parent_name;
19918
19919       /* It has been seen on RealView 2.2 built binaries,
19920          DW_TAG_template_type_param types actually _defined_ as
19921          children of the parent class:
19922
19923          enum E {};
19924          template class <class Enum> Class{};
19925          Class<enum E> class_e;
19926
19927          1: DW_TAG_class_type (Class)
19928            2: DW_TAG_enumeration_type (E)
19929              3: DW_TAG_enumerator (enum1:0)
19930              3: DW_TAG_enumerator (enum2:1)
19931              ...
19932            2: DW_TAG_template_type_param
19933               DW_AT_type  DW_FORM_ref_udata (E)
19934
19935          Besides being broken debug info, it can put GDB into an
19936          infinite loop.  Consider:
19937
19938          When we're building the full name for Class<E>, we'll start
19939          at Class, and go look over its template type parameters,
19940          finding E.  We'll then try to build the full name of E, and
19941          reach here.  We're now trying to build the full name of E,
19942          and look over the parent DIE for containing scope.  In the
19943          broken case, if we followed the parent DIE of E, we'd again
19944          find Class, and once again go look at its template type
19945          arguments, etc., etc.  Simply don't consider such parent die
19946          as source-level parent of this die (it can't be, the language
19947          doesn't allow it), and break the loop here.  */
19948       name = dwarf2_name (die, cu);
19949       parent_name = dwarf2_name (parent, cu);
19950       complaint (&symfile_complaints,
19951                  _("template param type '%s' defined within parent '%s'"),
19952                  name ? name : "<unknown>",
19953                  parent_name ? parent_name : "<unknown>");
19954       return "";
19955     }
19956   else
19957     switch (parent->tag)
19958       {
19959       case DW_TAG_namespace:
19960         parent_type = read_type_die (parent, cu);
19961         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
19962            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
19963            Work around this problem here.  */
19964         if (cu->language == language_cplus
19965             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
19966           return "";
19967         /* We give a name to even anonymous namespaces.  */
19968         return TYPE_TAG_NAME (parent_type);
19969       case DW_TAG_class_type:
19970       case DW_TAG_interface_type:
19971       case DW_TAG_structure_type:
19972       case DW_TAG_union_type:
19973       case DW_TAG_module:
19974         parent_type = read_type_die (parent, cu);
19975         if (TYPE_TAG_NAME (parent_type) != NULL)
19976           return TYPE_TAG_NAME (parent_type);
19977         else
19978           /* An anonymous structure is only allowed non-static data
19979              members; no typedefs, no member functions, et cetera.
19980              So it does not need a prefix.  */
19981           return "";
19982       case DW_TAG_compile_unit:
19983       case DW_TAG_partial_unit:
19984         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
19985         if (cu->language == language_cplus
19986             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
19987             && die->child != NULL
19988             && (die->tag == DW_TAG_class_type
19989                 || die->tag == DW_TAG_structure_type
19990                 || die->tag == DW_TAG_union_type))
19991           {
19992             char *name = guess_full_die_structure_name (die, cu);
19993             if (name != NULL)
19994               return name;
19995           }
19996         return "";
19997       case DW_TAG_enumeration_type:
19998         parent_type = read_type_die (parent, cu);
19999         if (TYPE_DECLARED_CLASS (parent_type))
20000           {
20001             if (TYPE_TAG_NAME (parent_type) != NULL)
20002               return TYPE_TAG_NAME (parent_type);
20003             return "";
20004           }
20005         /* Fall through.  */
20006       default:
20007         return determine_prefix (parent, cu);
20008       }
20009 }
20010
20011 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20012    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20013    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20014    an obconcat, otherwise allocate storage for the result.  The CU argument is
20015    used to determine the language and hence, the appropriate separator.  */
20016
20017 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20018
20019 static char *
20020 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20021                  int physname, struct dwarf2_cu *cu)
20022 {
20023   const char *lead = "";
20024   const char *sep;
20025
20026   if (suffix == NULL || suffix[0] == '\0'
20027       || prefix == NULL || prefix[0] == '\0')
20028     sep = "";
20029   else if (cu->language == language_d)
20030     {
20031       /* For D, the 'main' function could be defined in any module, but it
20032          should never be prefixed.  */
20033       if (strcmp (suffix, "D main") == 0)
20034         {
20035           prefix = "";
20036           sep = "";
20037         }
20038       else
20039         sep = ".";
20040     }
20041   else if (cu->language == language_fortran && physname)
20042     {
20043       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20044          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20045
20046       lead = "__";
20047       sep = "_MOD_";
20048     }
20049   else
20050     sep = "::";
20051
20052   if (prefix == NULL)
20053     prefix = "";
20054   if (suffix == NULL)
20055     suffix = "";
20056
20057   if (obs == NULL)
20058     {
20059       char *retval
20060         = ((char *)
20061            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20062
20063       strcpy (retval, lead);
20064       strcat (retval, prefix);
20065       strcat (retval, sep);
20066       strcat (retval, suffix);
20067       return retval;
20068     }
20069   else
20070     {
20071       /* We have an obstack.  */
20072       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20073     }
20074 }
20075
20076 /* Return sibling of die, NULL if no sibling.  */
20077
20078 static struct die_info *
20079 sibling_die (struct die_info *die)
20080 {
20081   return die->sibling;
20082 }
20083
20084 /* Get name of a die, return NULL if not found.  */
20085
20086 static const char *
20087 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20088                           struct obstack *obstack)
20089 {
20090   if (name && cu->language == language_cplus)
20091     {
20092       std::string canon_name = cp_canonicalize_string (name);
20093
20094       if (!canon_name.empty ())
20095         {
20096           if (canon_name != name)
20097             name = (const char *) obstack_copy0 (obstack,
20098                                                  canon_name.c_str (),
20099                                                  canon_name.length ());
20100         }
20101     }
20102
20103   return name;
20104 }
20105
20106 /* Get name of a die, return NULL if not found.
20107    Anonymous namespaces are converted to their magic string.  */
20108
20109 static const char *
20110 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20111 {
20112   struct attribute *attr;
20113
20114   attr = dwarf2_attr (die, DW_AT_name, cu);
20115   if ((!attr || !DW_STRING (attr))
20116       && die->tag != DW_TAG_namespace
20117       && die->tag != DW_TAG_class_type
20118       && die->tag != DW_TAG_interface_type
20119       && die->tag != DW_TAG_structure_type
20120       && die->tag != DW_TAG_union_type)
20121     return NULL;
20122
20123   switch (die->tag)
20124     {
20125     case DW_TAG_compile_unit:
20126     case DW_TAG_partial_unit:
20127       /* Compilation units have a DW_AT_name that is a filename, not
20128          a source language identifier.  */
20129     case DW_TAG_enumeration_type:
20130     case DW_TAG_enumerator:
20131       /* These tags always have simple identifiers already; no need
20132          to canonicalize them.  */
20133       return DW_STRING (attr);
20134
20135     case DW_TAG_namespace:
20136       if (attr != NULL && DW_STRING (attr) != NULL)
20137         return DW_STRING (attr);
20138       return CP_ANONYMOUS_NAMESPACE_STR;
20139
20140     case DW_TAG_class_type:
20141     case DW_TAG_interface_type:
20142     case DW_TAG_structure_type:
20143     case DW_TAG_union_type:
20144       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20145          structures or unions.  These were of the form "._%d" in GCC 4.1,
20146          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20147          and GCC 4.4.  We work around this problem by ignoring these.  */
20148       if (attr && DW_STRING (attr)
20149           && (startswith (DW_STRING (attr), "._")
20150               || startswith (DW_STRING (attr), "<anonymous")))
20151         return NULL;
20152
20153       /* GCC might emit a nameless typedef that has a linkage name.  See
20154          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20155       if (!attr || DW_STRING (attr) == NULL)
20156         {
20157           char *demangled = NULL;
20158
20159           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
20160           if (attr == NULL)
20161             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
20162
20163           if (attr == NULL || DW_STRING (attr) == NULL)
20164             return NULL;
20165
20166           /* Avoid demangling DW_STRING (attr) the second time on a second
20167              call for the same DIE.  */
20168           if (!DW_STRING_IS_CANONICAL (attr))
20169             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20170
20171           if (demangled)
20172             {
20173               const char *base;
20174
20175               /* FIXME: we already did this for the partial symbol... */
20176               DW_STRING (attr)
20177                 = ((const char *)
20178                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20179                                   demangled, strlen (demangled)));
20180               DW_STRING_IS_CANONICAL (attr) = 1;
20181               xfree (demangled);
20182
20183               /* Strip any leading namespaces/classes, keep only the base name.
20184                  DW_AT_name for named DIEs does not contain the prefixes.  */
20185               base = strrchr (DW_STRING (attr), ':');
20186               if (base && base > DW_STRING (attr) && base[-1] == ':')
20187                 return &base[1];
20188               else
20189                 return DW_STRING (attr);
20190             }
20191         }
20192       break;
20193
20194     default:
20195       break;
20196     }
20197
20198   if (!DW_STRING_IS_CANONICAL (attr))
20199     {
20200       DW_STRING (attr)
20201         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20202                                     &cu->objfile->per_bfd->storage_obstack);
20203       DW_STRING_IS_CANONICAL (attr) = 1;
20204     }
20205   return DW_STRING (attr);
20206 }
20207
20208 /* Return the die that this die in an extension of, or NULL if there
20209    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20210    containing the return value on output.  */
20211
20212 static struct die_info *
20213 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20214 {
20215   struct attribute *attr;
20216
20217   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20218   if (attr == NULL)
20219     return NULL;
20220
20221   return follow_die_ref (die, attr, ext_cu);
20222 }
20223
20224 /* Convert a DIE tag into its string name.  */
20225
20226 static const char *
20227 dwarf_tag_name (unsigned tag)
20228 {
20229   const char *name = get_DW_TAG_name (tag);
20230
20231   if (name == NULL)
20232     return "DW_TAG_<unknown>";
20233
20234   return name;
20235 }
20236
20237 /* Convert a DWARF attribute code into its string name.  */
20238
20239 static const char *
20240 dwarf_attr_name (unsigned attr)
20241 {
20242   const char *name;
20243
20244 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20245   if (attr == DW_AT_MIPS_fde)
20246     return "DW_AT_MIPS_fde";
20247 #else
20248   if (attr == DW_AT_HP_block_index)
20249     return "DW_AT_HP_block_index";
20250 #endif
20251
20252   name = get_DW_AT_name (attr);
20253
20254   if (name == NULL)
20255     return "DW_AT_<unknown>";
20256
20257   return name;
20258 }
20259
20260 /* Convert a DWARF value form code into its string name.  */
20261
20262 static const char *
20263 dwarf_form_name (unsigned form)
20264 {
20265   const char *name = get_DW_FORM_name (form);
20266
20267   if (name == NULL)
20268     return "DW_FORM_<unknown>";
20269
20270   return name;
20271 }
20272
20273 static const char *
20274 dwarf_bool_name (unsigned mybool)
20275 {
20276   if (mybool)
20277     return "TRUE";
20278   else
20279     return "FALSE";
20280 }
20281
20282 /* Convert a DWARF type code into its string name.  */
20283
20284 static const char *
20285 dwarf_type_encoding_name (unsigned enc)
20286 {
20287   const char *name = get_DW_ATE_name (enc);
20288
20289   if (name == NULL)
20290     return "DW_ATE_<unknown>";
20291
20292   return name;
20293 }
20294
20295 static void
20296 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20297 {
20298   unsigned int i;
20299
20300   print_spaces (indent, f);
20301   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20302                       dwarf_tag_name (die->tag), die->abbrev,
20303                       to_underlying (die->sect_off));
20304
20305   if (die->parent != NULL)
20306     {
20307       print_spaces (indent, f);
20308       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20309                           to_underlying (die->parent->sect_off));
20310     }
20311
20312   print_spaces (indent, f);
20313   fprintf_unfiltered (f, "  has children: %s\n",
20314            dwarf_bool_name (die->child != NULL));
20315
20316   print_spaces (indent, f);
20317   fprintf_unfiltered (f, "  attributes:\n");
20318
20319   for (i = 0; i < die->num_attrs; ++i)
20320     {
20321       print_spaces (indent, f);
20322       fprintf_unfiltered (f, "    %s (%s) ",
20323                dwarf_attr_name (die->attrs[i].name),
20324                dwarf_form_name (die->attrs[i].form));
20325
20326       switch (die->attrs[i].form)
20327         {
20328         case DW_FORM_addr:
20329         case DW_FORM_GNU_addr_index:
20330           fprintf_unfiltered (f, "address: ");
20331           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20332           break;
20333         case DW_FORM_block2:
20334         case DW_FORM_block4:
20335         case DW_FORM_block:
20336         case DW_FORM_block1:
20337           fprintf_unfiltered (f, "block: size %s",
20338                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20339           break;
20340         case DW_FORM_exprloc:
20341           fprintf_unfiltered (f, "expression: size %s",
20342                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20343           break;
20344         case DW_FORM_data16:
20345           fprintf_unfiltered (f, "constant of 16 bytes");
20346           break;
20347         case DW_FORM_ref_addr:
20348           fprintf_unfiltered (f, "ref address: ");
20349           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20350           break;
20351         case DW_FORM_GNU_ref_alt:
20352           fprintf_unfiltered (f, "alt ref address: ");
20353           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20354           break;
20355         case DW_FORM_ref1:
20356         case DW_FORM_ref2:
20357         case DW_FORM_ref4:
20358         case DW_FORM_ref8:
20359         case DW_FORM_ref_udata:
20360           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20361                               (long) (DW_UNSND (&die->attrs[i])));
20362           break;
20363         case DW_FORM_data1:
20364         case DW_FORM_data2:
20365         case DW_FORM_data4:
20366         case DW_FORM_data8:
20367         case DW_FORM_udata:
20368         case DW_FORM_sdata:
20369           fprintf_unfiltered (f, "constant: %s",
20370                               pulongest (DW_UNSND (&die->attrs[i])));
20371           break;
20372         case DW_FORM_sec_offset:
20373           fprintf_unfiltered (f, "section offset: %s",
20374                               pulongest (DW_UNSND (&die->attrs[i])));
20375           break;
20376         case DW_FORM_ref_sig8:
20377           fprintf_unfiltered (f, "signature: %s",
20378                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20379           break;
20380         case DW_FORM_string:
20381         case DW_FORM_strp:
20382         case DW_FORM_line_strp:
20383         case DW_FORM_GNU_str_index:
20384         case DW_FORM_GNU_strp_alt:
20385           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20386                    DW_STRING (&die->attrs[i])
20387                    ? DW_STRING (&die->attrs[i]) : "",
20388                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20389           break;
20390         case DW_FORM_flag:
20391           if (DW_UNSND (&die->attrs[i]))
20392             fprintf_unfiltered (f, "flag: TRUE");
20393           else
20394             fprintf_unfiltered (f, "flag: FALSE");
20395           break;
20396         case DW_FORM_flag_present:
20397           fprintf_unfiltered (f, "flag: TRUE");
20398           break;
20399         case DW_FORM_indirect:
20400           /* The reader will have reduced the indirect form to
20401              the "base form" so this form should not occur.  */
20402           fprintf_unfiltered (f, 
20403                               "unexpected attribute form: DW_FORM_indirect");
20404           break;
20405         default:
20406           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20407                    die->attrs[i].form);
20408           break;
20409         }
20410       fprintf_unfiltered (f, "\n");
20411     }
20412 }
20413
20414 static void
20415 dump_die_for_error (struct die_info *die)
20416 {
20417   dump_die_shallow (gdb_stderr, 0, die);
20418 }
20419
20420 static void
20421 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20422 {
20423   int indent = level * 4;
20424
20425   gdb_assert (die != NULL);
20426
20427   if (level >= max_level)
20428     return;
20429
20430   dump_die_shallow (f, indent, die);
20431
20432   if (die->child != NULL)
20433     {
20434       print_spaces (indent, f);
20435       fprintf_unfiltered (f, "  Children:");
20436       if (level + 1 < max_level)
20437         {
20438           fprintf_unfiltered (f, "\n");
20439           dump_die_1 (f, level + 1, max_level, die->child);
20440         }
20441       else
20442         {
20443           fprintf_unfiltered (f,
20444                               " [not printed, max nesting level reached]\n");
20445         }
20446     }
20447
20448   if (die->sibling != NULL && level > 0)
20449     {
20450       dump_die_1 (f, level, max_level, die->sibling);
20451     }
20452 }
20453
20454 /* This is called from the pdie macro in gdbinit.in.
20455    It's not static so gcc will keep a copy callable from gdb.  */
20456
20457 void
20458 dump_die (struct die_info *die, int max_level)
20459 {
20460   dump_die_1 (gdb_stdlog, 0, max_level, die);
20461 }
20462
20463 static void
20464 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20465 {
20466   void **slot;
20467
20468   slot = htab_find_slot_with_hash (cu->die_hash, die,
20469                                    to_underlying (die->sect_off),
20470                                    INSERT);
20471
20472   *slot = die;
20473 }
20474
20475 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20476    required kind.  */
20477
20478 static sect_offset
20479 dwarf2_get_ref_die_offset (const struct attribute *attr)
20480 {
20481   if (attr_form_is_ref (attr))
20482     return (sect_offset) DW_UNSND (attr);
20483
20484   complaint (&symfile_complaints,
20485              _("unsupported die ref attribute form: '%s'"),
20486              dwarf_form_name (attr->form));
20487   return {};
20488 }
20489
20490 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20491  * the value held by the attribute is not constant.  */
20492
20493 static LONGEST
20494 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20495 {
20496   if (attr->form == DW_FORM_sdata)
20497     return DW_SND (attr);
20498   else if (attr->form == DW_FORM_udata
20499            || attr->form == DW_FORM_data1
20500            || attr->form == DW_FORM_data2
20501            || attr->form == DW_FORM_data4
20502            || attr->form == DW_FORM_data8)
20503     return DW_UNSND (attr);
20504   else
20505     {
20506       /* For DW_FORM_data16 see attr_form_is_constant.  */
20507       complaint (&symfile_complaints,
20508                  _("Attribute value is not a constant (%s)"),
20509                  dwarf_form_name (attr->form));
20510       return default_value;
20511     }
20512 }
20513
20514 /* Follow reference or signature attribute ATTR of SRC_DIE.
20515    On entry *REF_CU is the CU of SRC_DIE.
20516    On exit *REF_CU is the CU of the result.  */
20517
20518 static struct die_info *
20519 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20520                        struct dwarf2_cu **ref_cu)
20521 {
20522   struct die_info *die;
20523
20524   if (attr_form_is_ref (attr))
20525     die = follow_die_ref (src_die, attr, ref_cu);
20526   else if (attr->form == DW_FORM_ref_sig8)
20527     die = follow_die_sig (src_die, attr, ref_cu);
20528   else
20529     {
20530       dump_die_for_error (src_die);
20531       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20532              objfile_name ((*ref_cu)->objfile));
20533     }
20534
20535   return die;
20536 }
20537
20538 /* Follow reference OFFSET.
20539    On entry *REF_CU is the CU of the source die referencing OFFSET.
20540    On exit *REF_CU is the CU of the result.
20541    Returns NULL if OFFSET is invalid.  */
20542
20543 static struct die_info *
20544 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20545                    struct dwarf2_cu **ref_cu)
20546 {
20547   struct die_info temp_die;
20548   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20549
20550   gdb_assert (cu->per_cu != NULL);
20551
20552   target_cu = cu;
20553
20554   if (cu->per_cu->is_debug_types)
20555     {
20556       /* .debug_types CUs cannot reference anything outside their CU.
20557          If they need to, they have to reference a signatured type via
20558          DW_FORM_ref_sig8.  */
20559       if (!offset_in_cu_p (&cu->header, sect_off))
20560         return NULL;
20561     }
20562   else if (offset_in_dwz != cu->per_cu->is_dwz
20563            || !offset_in_cu_p (&cu->header, sect_off))
20564     {
20565       struct dwarf2_per_cu_data *per_cu;
20566
20567       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20568                                                  cu->objfile);
20569
20570       /* If necessary, add it to the queue and load its DIEs.  */
20571       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20572         load_full_comp_unit (per_cu, cu->language);
20573
20574       target_cu = per_cu->cu;
20575     }
20576   else if (cu->dies == NULL)
20577     {
20578       /* We're loading full DIEs during partial symbol reading.  */
20579       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20580       load_full_comp_unit (cu->per_cu, language_minimal);
20581     }
20582
20583   *ref_cu = target_cu;
20584   temp_die.sect_off = sect_off;
20585   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20586                                                   &temp_die,
20587                                                   to_underlying (sect_off));
20588 }
20589
20590 /* Follow reference attribute ATTR of SRC_DIE.
20591    On entry *REF_CU is the CU of SRC_DIE.
20592    On exit *REF_CU is the CU of the result.  */
20593
20594 static struct die_info *
20595 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20596                 struct dwarf2_cu **ref_cu)
20597 {
20598   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20599   struct dwarf2_cu *cu = *ref_cu;
20600   struct die_info *die;
20601
20602   die = follow_die_offset (sect_off,
20603                            (attr->form == DW_FORM_GNU_ref_alt
20604                             || cu->per_cu->is_dwz),
20605                            ref_cu);
20606   if (!die)
20607     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20608            "at 0x%x [in module %s]"),
20609            to_underlying (sect_off), to_underlying (src_die->sect_off),
20610            objfile_name (cu->objfile));
20611
20612   return die;
20613 }
20614
20615 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20616    Returned value is intended for DW_OP_call*.  Returned
20617    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20618
20619 struct dwarf2_locexpr_baton
20620 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20621                                struct dwarf2_per_cu_data *per_cu,
20622                                CORE_ADDR (*get_frame_pc) (void *baton),
20623                                void *baton)
20624 {
20625   struct dwarf2_cu *cu;
20626   struct die_info *die;
20627   struct attribute *attr;
20628   struct dwarf2_locexpr_baton retval;
20629
20630   dw2_setup (per_cu->objfile);
20631
20632   if (per_cu->cu == NULL)
20633     load_cu (per_cu);
20634   cu = per_cu->cu;
20635   if (cu == NULL)
20636     {
20637       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20638          Instead just throw an error, not much else we can do.  */
20639       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20640              to_underlying (sect_off), objfile_name (per_cu->objfile));
20641     }
20642
20643   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20644   if (!die)
20645     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20646            to_underlying (sect_off), objfile_name (per_cu->objfile));
20647
20648   attr = dwarf2_attr (die, DW_AT_location, cu);
20649   if (!attr)
20650     {
20651       /* DWARF: "If there is no such attribute, then there is no effect.".
20652          DATA is ignored if SIZE is 0.  */
20653
20654       retval.data = NULL;
20655       retval.size = 0;
20656     }
20657   else if (attr_form_is_section_offset (attr))
20658     {
20659       struct dwarf2_loclist_baton loclist_baton;
20660       CORE_ADDR pc = (*get_frame_pc) (baton);
20661       size_t size;
20662
20663       fill_in_loclist_baton (cu, &loclist_baton, attr);
20664
20665       retval.data = dwarf2_find_location_expression (&loclist_baton,
20666                                                      &size, pc);
20667       retval.size = size;
20668     }
20669   else
20670     {
20671       if (!attr_form_is_block (attr))
20672         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20673                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20674                to_underlying (sect_off), objfile_name (per_cu->objfile));
20675
20676       retval.data = DW_BLOCK (attr)->data;
20677       retval.size = DW_BLOCK (attr)->size;
20678     }
20679   retval.per_cu = cu->per_cu;
20680
20681   age_cached_comp_units ();
20682
20683   return retval;
20684 }
20685
20686 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20687    offset.  */
20688
20689 struct dwarf2_locexpr_baton
20690 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20691                              struct dwarf2_per_cu_data *per_cu,
20692                              CORE_ADDR (*get_frame_pc) (void *baton),
20693                              void *baton)
20694 {
20695   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20696
20697   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20698 }
20699
20700 /* Write a constant of a given type as target-ordered bytes into
20701    OBSTACK.  */
20702
20703 static const gdb_byte *
20704 write_constant_as_bytes (struct obstack *obstack,
20705                          enum bfd_endian byte_order,
20706                          struct type *type,
20707                          ULONGEST value,
20708                          LONGEST *len)
20709 {
20710   gdb_byte *result;
20711
20712   *len = TYPE_LENGTH (type);
20713   result = (gdb_byte *) obstack_alloc (obstack, *len);
20714   store_unsigned_integer (result, *len, byte_order, value);
20715
20716   return result;
20717 }
20718
20719 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20720    pointer to the constant bytes and set LEN to the length of the
20721    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20722    does not have a DW_AT_const_value, return NULL.  */
20723
20724 const gdb_byte *
20725 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20726                              struct dwarf2_per_cu_data *per_cu,
20727                              struct obstack *obstack,
20728                              LONGEST *len)
20729 {
20730   struct dwarf2_cu *cu;
20731   struct die_info *die;
20732   struct attribute *attr;
20733   const gdb_byte *result = NULL;
20734   struct type *type;
20735   LONGEST value;
20736   enum bfd_endian byte_order;
20737
20738   dw2_setup (per_cu->objfile);
20739
20740   if (per_cu->cu == NULL)
20741     load_cu (per_cu);
20742   cu = per_cu->cu;
20743   if (cu == NULL)
20744     {
20745       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20746          Instead just throw an error, not much else we can do.  */
20747       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20748              to_underlying (sect_off), objfile_name (per_cu->objfile));
20749     }
20750
20751   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20752   if (!die)
20753     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20754            to_underlying (sect_off), objfile_name (per_cu->objfile));
20755
20756
20757   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20758   if (attr == NULL)
20759     return NULL;
20760
20761   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20762                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20763
20764   switch (attr->form)
20765     {
20766     case DW_FORM_addr:
20767     case DW_FORM_GNU_addr_index:
20768       {
20769         gdb_byte *tem;
20770
20771         *len = cu->header.addr_size;
20772         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20773         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20774         result = tem;
20775       }
20776       break;
20777     case DW_FORM_string:
20778     case DW_FORM_strp:
20779     case DW_FORM_GNU_str_index:
20780     case DW_FORM_GNU_strp_alt:
20781       /* DW_STRING is already allocated on the objfile obstack, point
20782          directly to it.  */
20783       result = (const gdb_byte *) DW_STRING (attr);
20784       *len = strlen (DW_STRING (attr));
20785       break;
20786     case DW_FORM_block1:
20787     case DW_FORM_block2:
20788     case DW_FORM_block4:
20789     case DW_FORM_block:
20790     case DW_FORM_exprloc:
20791     case DW_FORM_data16:
20792       result = DW_BLOCK (attr)->data;
20793       *len = DW_BLOCK (attr)->size;
20794       break;
20795
20796       /* The DW_AT_const_value attributes are supposed to carry the
20797          symbol's value "represented as it would be on the target
20798          architecture."  By the time we get here, it's already been
20799          converted to host endianness, so we just need to sign- or
20800          zero-extend it as appropriate.  */
20801     case DW_FORM_data1:
20802       type = die_type (die, cu);
20803       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20804       if (result == NULL)
20805         result = write_constant_as_bytes (obstack, byte_order,
20806                                           type, value, len);
20807       break;
20808     case DW_FORM_data2:
20809       type = die_type (die, cu);
20810       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20811       if (result == NULL)
20812         result = write_constant_as_bytes (obstack, byte_order,
20813                                           type, value, len);
20814       break;
20815     case DW_FORM_data4:
20816       type = die_type (die, cu);
20817       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20818       if (result == NULL)
20819         result = write_constant_as_bytes (obstack, byte_order,
20820                                           type, value, len);
20821       break;
20822     case DW_FORM_data8:
20823       type = die_type (die, cu);
20824       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20825       if (result == NULL)
20826         result = write_constant_as_bytes (obstack, byte_order,
20827                                           type, value, len);
20828       break;
20829
20830     case DW_FORM_sdata:
20831       type = die_type (die, cu);
20832       result = write_constant_as_bytes (obstack, byte_order,
20833                                         type, DW_SND (attr), len);
20834       break;
20835
20836     case DW_FORM_udata:
20837       type = die_type (die, cu);
20838       result = write_constant_as_bytes (obstack, byte_order,
20839                                         type, DW_UNSND (attr), len);
20840       break;
20841
20842     default:
20843       complaint (&symfile_complaints,
20844                  _("unsupported const value attribute form: '%s'"),
20845                  dwarf_form_name (attr->form));
20846       break;
20847     }
20848
20849   return result;
20850 }
20851
20852 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20853    valid type for this die is found.  */
20854
20855 struct type *
20856 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20857                                 struct dwarf2_per_cu_data *per_cu)
20858 {
20859   struct dwarf2_cu *cu;
20860   struct die_info *die;
20861
20862   dw2_setup (per_cu->objfile);
20863
20864   if (per_cu->cu == NULL)
20865     load_cu (per_cu);
20866   cu = per_cu->cu;
20867   if (!cu)
20868     return NULL;
20869
20870   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20871   if (!die)
20872     return NULL;
20873
20874   return die_type (die, cu);
20875 }
20876
20877 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20878    PER_CU.  */
20879
20880 struct type *
20881 dwarf2_get_die_type (cu_offset die_offset,
20882                      struct dwarf2_per_cu_data *per_cu)
20883 {
20884   dw2_setup (per_cu->objfile);
20885
20886   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
20887   return get_die_type_at_offset (die_offset_sect, per_cu);
20888 }
20889
20890 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
20891    On entry *REF_CU is the CU of SRC_DIE.
20892    On exit *REF_CU is the CU of the result.
20893    Returns NULL if the referenced DIE isn't found.  */
20894
20895 static struct die_info *
20896 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
20897                   struct dwarf2_cu **ref_cu)
20898 {
20899   struct die_info temp_die;
20900   struct dwarf2_cu *sig_cu;
20901   struct die_info *die;
20902
20903   /* While it might be nice to assert sig_type->type == NULL here,
20904      we can get here for DW_AT_imported_declaration where we need
20905      the DIE not the type.  */
20906
20907   /* If necessary, add it to the queue and load its DIEs.  */
20908
20909   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
20910     read_signatured_type (sig_type);
20911
20912   sig_cu = sig_type->per_cu.cu;
20913   gdb_assert (sig_cu != NULL);
20914   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
20915   temp_die.sect_off = sig_type->type_offset_in_section;
20916   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
20917                                                  to_underlying (temp_die.sect_off));
20918   if (die)
20919     {
20920       /* For .gdb_index version 7 keep track of included TUs.
20921          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
20922       if (dwarf2_per_objfile->index_table != NULL
20923           && dwarf2_per_objfile->index_table->version <= 7)
20924         {
20925           VEC_safe_push (dwarf2_per_cu_ptr,
20926                          (*ref_cu)->per_cu->imported_symtabs,
20927                          sig_cu->per_cu);
20928         }
20929
20930       *ref_cu = sig_cu;
20931       return die;
20932     }
20933
20934   return NULL;
20935 }
20936
20937 /* Follow signatured type referenced by ATTR in SRC_DIE.
20938    On entry *REF_CU is the CU of SRC_DIE.
20939    On exit *REF_CU is the CU of the result.
20940    The result is the DIE of the type.
20941    If the referenced type cannot be found an error is thrown.  */
20942
20943 static struct die_info *
20944 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
20945                 struct dwarf2_cu **ref_cu)
20946 {
20947   ULONGEST signature = DW_SIGNATURE (attr);
20948   struct signatured_type *sig_type;
20949   struct die_info *die;
20950
20951   gdb_assert (attr->form == DW_FORM_ref_sig8);
20952
20953   sig_type = lookup_signatured_type (*ref_cu, signature);
20954   /* sig_type will be NULL if the signatured type is missing from
20955      the debug info.  */
20956   if (sig_type == NULL)
20957     {
20958       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
20959                " from DIE at 0x%x [in module %s]"),
20960              hex_string (signature), to_underlying (src_die->sect_off),
20961              objfile_name ((*ref_cu)->objfile));
20962     }
20963
20964   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
20965   if (die == NULL)
20966     {
20967       dump_die_for_error (src_die);
20968       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
20969                " from DIE at 0x%x [in module %s]"),
20970              hex_string (signature), to_underlying (src_die->sect_off),
20971              objfile_name ((*ref_cu)->objfile));
20972     }
20973
20974   return die;
20975 }
20976
20977 /* Get the type specified by SIGNATURE referenced in DIE/CU,
20978    reading in and processing the type unit if necessary.  */
20979
20980 static struct type *
20981 get_signatured_type (struct die_info *die, ULONGEST signature,
20982                      struct dwarf2_cu *cu)
20983 {
20984   struct signatured_type *sig_type;
20985   struct dwarf2_cu *type_cu;
20986   struct die_info *type_die;
20987   struct type *type;
20988
20989   sig_type = lookup_signatured_type (cu, signature);
20990   /* sig_type will be NULL if the signatured type is missing from
20991      the debug info.  */
20992   if (sig_type == NULL)
20993     {
20994       complaint (&symfile_complaints,
20995                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
20996                    " from DIE at 0x%x [in module %s]"),
20997                  hex_string (signature), to_underlying (die->sect_off),
20998                  objfile_name (dwarf2_per_objfile->objfile));
20999       return build_error_marker_type (cu, die);
21000     }
21001
21002   /* If we already know the type we're done.  */
21003   if (sig_type->type != NULL)
21004     return sig_type->type;
21005
21006   type_cu = cu;
21007   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21008   if (type_die != NULL)
21009     {
21010       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21011          is created.  This is important, for example, because for c++ classes
21012          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21013       type = read_type_die (type_die, type_cu);
21014       if (type == NULL)
21015         {
21016           complaint (&symfile_complaints,
21017                      _("Dwarf Error: Cannot build signatured type %s"
21018                        " referenced from DIE at 0x%x [in module %s]"),
21019                      hex_string (signature), to_underlying (die->sect_off),
21020                      objfile_name (dwarf2_per_objfile->objfile));
21021           type = build_error_marker_type (cu, die);
21022         }
21023     }
21024   else
21025     {
21026       complaint (&symfile_complaints,
21027                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21028                    " from DIE at 0x%x [in module %s]"),
21029                  hex_string (signature), to_underlying (die->sect_off),
21030                  objfile_name (dwarf2_per_objfile->objfile));
21031       type = build_error_marker_type (cu, die);
21032     }
21033   sig_type->type = type;
21034
21035   return type;
21036 }
21037
21038 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21039    reading in and processing the type unit if necessary.  */
21040
21041 static struct type *
21042 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21043                           struct dwarf2_cu *cu) /* ARI: editCase function */
21044 {
21045   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21046   if (attr_form_is_ref (attr))
21047     {
21048       struct dwarf2_cu *type_cu = cu;
21049       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21050
21051       return read_type_die (type_die, type_cu);
21052     }
21053   else if (attr->form == DW_FORM_ref_sig8)
21054     {
21055       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21056     }
21057   else
21058     {
21059       complaint (&symfile_complaints,
21060                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21061                    " at 0x%x [in module %s]"),
21062                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21063                  objfile_name (dwarf2_per_objfile->objfile));
21064       return build_error_marker_type (cu, die);
21065     }
21066 }
21067
21068 /* Load the DIEs associated with type unit PER_CU into memory.  */
21069
21070 static void
21071 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21072 {
21073   struct signatured_type *sig_type;
21074
21075   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21076   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21077
21078   /* We have the per_cu, but we need the signatured_type.
21079      Fortunately this is an easy translation.  */
21080   gdb_assert (per_cu->is_debug_types);
21081   sig_type = (struct signatured_type *) per_cu;
21082
21083   gdb_assert (per_cu->cu == NULL);
21084
21085   read_signatured_type (sig_type);
21086
21087   gdb_assert (per_cu->cu != NULL);
21088 }
21089
21090 /* die_reader_func for read_signatured_type.
21091    This is identical to load_full_comp_unit_reader,
21092    but is kept separate for now.  */
21093
21094 static void
21095 read_signatured_type_reader (const struct die_reader_specs *reader,
21096                              const gdb_byte *info_ptr,
21097                              struct die_info *comp_unit_die,
21098                              int has_children,
21099                              void *data)
21100 {
21101   struct dwarf2_cu *cu = reader->cu;
21102
21103   gdb_assert (cu->die_hash == NULL);
21104   cu->die_hash =
21105     htab_create_alloc_ex (cu->header.length / 12,
21106                           die_hash,
21107                           die_eq,
21108                           NULL,
21109                           &cu->comp_unit_obstack,
21110                           hashtab_obstack_allocate,
21111                           dummy_obstack_deallocate);
21112
21113   if (has_children)
21114     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21115                                                   &info_ptr, comp_unit_die);
21116   cu->dies = comp_unit_die;
21117   /* comp_unit_die is not stored in die_hash, no need.  */
21118
21119   /* We try not to read any attributes in this function, because not
21120      all CUs needed for references have been loaded yet, and symbol
21121      table processing isn't initialized.  But we have to set the CU language,
21122      or we won't be able to build types correctly.
21123      Similarly, if we do not read the producer, we can not apply
21124      producer-specific interpretation.  */
21125   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21126 }
21127
21128 /* Read in a signatured type and build its CU and DIEs.
21129    If the type is a stub for the real type in a DWO file,
21130    read in the real type from the DWO file as well.  */
21131
21132 static void
21133 read_signatured_type (struct signatured_type *sig_type)
21134 {
21135   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21136
21137   gdb_assert (per_cu->is_debug_types);
21138   gdb_assert (per_cu->cu == NULL);
21139
21140   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21141                            read_signatured_type_reader, NULL);
21142   sig_type->per_cu.tu_read = 1;
21143 }
21144
21145 /* Decode simple location descriptions.
21146    Given a pointer to a dwarf block that defines a location, compute
21147    the location and return the value.
21148
21149    NOTE drow/2003-11-18: This function is called in two situations
21150    now: for the address of static or global variables (partial symbols
21151    only) and for offsets into structures which are expected to be
21152    (more or less) constant.  The partial symbol case should go away,
21153    and only the constant case should remain.  That will let this
21154    function complain more accurately.  A few special modes are allowed
21155    without complaint for global variables (for instance, global
21156    register values and thread-local values).
21157
21158    A location description containing no operations indicates that the
21159    object is optimized out.  The return value is 0 for that case.
21160    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21161    callers will only want a very basic result and this can become a
21162    complaint.
21163
21164    Note that stack[0] is unused except as a default error return.  */
21165
21166 static CORE_ADDR
21167 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21168 {
21169   struct objfile *objfile = cu->objfile;
21170   size_t i;
21171   size_t size = blk->size;
21172   const gdb_byte *data = blk->data;
21173   CORE_ADDR stack[64];
21174   int stacki;
21175   unsigned int bytes_read, unsnd;
21176   gdb_byte op;
21177
21178   i = 0;
21179   stacki = 0;
21180   stack[stacki] = 0;
21181   stack[++stacki] = 0;
21182
21183   while (i < size)
21184     {
21185       op = data[i++];
21186       switch (op)
21187         {
21188         case DW_OP_lit0:
21189         case DW_OP_lit1:
21190         case DW_OP_lit2:
21191         case DW_OP_lit3:
21192         case DW_OP_lit4:
21193         case DW_OP_lit5:
21194         case DW_OP_lit6:
21195         case DW_OP_lit7:
21196         case DW_OP_lit8:
21197         case DW_OP_lit9:
21198         case DW_OP_lit10:
21199         case DW_OP_lit11:
21200         case DW_OP_lit12:
21201         case DW_OP_lit13:
21202         case DW_OP_lit14:
21203         case DW_OP_lit15:
21204         case DW_OP_lit16:
21205         case DW_OP_lit17:
21206         case DW_OP_lit18:
21207         case DW_OP_lit19:
21208         case DW_OP_lit20:
21209         case DW_OP_lit21:
21210         case DW_OP_lit22:
21211         case DW_OP_lit23:
21212         case DW_OP_lit24:
21213         case DW_OP_lit25:
21214         case DW_OP_lit26:
21215         case DW_OP_lit27:
21216         case DW_OP_lit28:
21217         case DW_OP_lit29:
21218         case DW_OP_lit30:
21219         case DW_OP_lit31:
21220           stack[++stacki] = op - DW_OP_lit0;
21221           break;
21222
21223         case DW_OP_reg0:
21224         case DW_OP_reg1:
21225         case DW_OP_reg2:
21226         case DW_OP_reg3:
21227         case DW_OP_reg4:
21228         case DW_OP_reg5:
21229         case DW_OP_reg6:
21230         case DW_OP_reg7:
21231         case DW_OP_reg8:
21232         case DW_OP_reg9:
21233         case DW_OP_reg10:
21234         case DW_OP_reg11:
21235         case DW_OP_reg12:
21236         case DW_OP_reg13:
21237         case DW_OP_reg14:
21238         case DW_OP_reg15:
21239         case DW_OP_reg16:
21240         case DW_OP_reg17:
21241         case DW_OP_reg18:
21242         case DW_OP_reg19:
21243         case DW_OP_reg20:
21244         case DW_OP_reg21:
21245         case DW_OP_reg22:
21246         case DW_OP_reg23:
21247         case DW_OP_reg24:
21248         case DW_OP_reg25:
21249         case DW_OP_reg26:
21250         case DW_OP_reg27:
21251         case DW_OP_reg28:
21252         case DW_OP_reg29:
21253         case DW_OP_reg30:
21254         case DW_OP_reg31:
21255           stack[++stacki] = op - DW_OP_reg0;
21256           if (i < size)
21257             dwarf2_complex_location_expr_complaint ();
21258           break;
21259
21260         case DW_OP_regx:
21261           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21262           i += bytes_read;
21263           stack[++stacki] = unsnd;
21264           if (i < size)
21265             dwarf2_complex_location_expr_complaint ();
21266           break;
21267
21268         case DW_OP_addr:
21269           stack[++stacki] = read_address (objfile->obfd, &data[i],
21270                                           cu, &bytes_read);
21271           i += bytes_read;
21272           break;
21273
21274         case DW_OP_const1u:
21275           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21276           i += 1;
21277           break;
21278
21279         case DW_OP_const1s:
21280           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21281           i += 1;
21282           break;
21283
21284         case DW_OP_const2u:
21285           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21286           i += 2;
21287           break;
21288
21289         case DW_OP_const2s:
21290           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21291           i += 2;
21292           break;
21293
21294         case DW_OP_const4u:
21295           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21296           i += 4;
21297           break;
21298
21299         case DW_OP_const4s:
21300           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21301           i += 4;
21302           break;
21303
21304         case DW_OP_const8u:
21305           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21306           i += 8;
21307           break;
21308
21309         case DW_OP_constu:
21310           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21311                                                   &bytes_read);
21312           i += bytes_read;
21313           break;
21314
21315         case DW_OP_consts:
21316           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21317           i += bytes_read;
21318           break;
21319
21320         case DW_OP_dup:
21321           stack[stacki + 1] = stack[stacki];
21322           stacki++;
21323           break;
21324
21325         case DW_OP_plus:
21326           stack[stacki - 1] += stack[stacki];
21327           stacki--;
21328           break;
21329
21330         case DW_OP_plus_uconst:
21331           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21332                                                  &bytes_read);
21333           i += bytes_read;
21334           break;
21335
21336         case DW_OP_minus:
21337           stack[stacki - 1] -= stack[stacki];
21338           stacki--;
21339           break;
21340
21341         case DW_OP_deref:
21342           /* If we're not the last op, then we definitely can't encode
21343              this using GDB's address_class enum.  This is valid for partial
21344              global symbols, although the variable's address will be bogus
21345              in the psymtab.  */
21346           if (i < size)
21347             dwarf2_complex_location_expr_complaint ();
21348           break;
21349
21350         case DW_OP_GNU_push_tls_address:
21351         case DW_OP_form_tls_address:
21352           /* The top of the stack has the offset from the beginning
21353              of the thread control block at which the variable is located.  */
21354           /* Nothing should follow this operator, so the top of stack would
21355              be returned.  */
21356           /* This is valid for partial global symbols, but the variable's
21357              address will be bogus in the psymtab.  Make it always at least
21358              non-zero to not look as a variable garbage collected by linker
21359              which have DW_OP_addr 0.  */
21360           if (i < size)
21361             dwarf2_complex_location_expr_complaint ();
21362           stack[stacki]++;
21363           break;
21364
21365         case DW_OP_GNU_uninit:
21366           break;
21367
21368         case DW_OP_GNU_addr_index:
21369         case DW_OP_GNU_const_index:
21370           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21371                                                          &bytes_read);
21372           i += bytes_read;
21373           break;
21374
21375         default:
21376           {
21377             const char *name = get_DW_OP_name (op);
21378
21379             if (name)
21380               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21381                          name);
21382             else
21383               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21384                          op);
21385           }
21386
21387           return (stack[stacki]);
21388         }
21389
21390       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21391          outside of the allocated space.  Also enforce minimum>0.  */
21392       if (stacki >= ARRAY_SIZE (stack) - 1)
21393         {
21394           complaint (&symfile_complaints,
21395                      _("location description stack overflow"));
21396           return 0;
21397         }
21398
21399       if (stacki <= 0)
21400         {
21401           complaint (&symfile_complaints,
21402                      _("location description stack underflow"));
21403           return 0;
21404         }
21405     }
21406   return (stack[stacki]);
21407 }
21408
21409 /* memory allocation interface */
21410
21411 static struct dwarf_block *
21412 dwarf_alloc_block (struct dwarf2_cu *cu)
21413 {
21414   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21415 }
21416
21417 static struct die_info *
21418 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21419 {
21420   struct die_info *die;
21421   size_t size = sizeof (struct die_info);
21422
21423   if (num_attrs > 1)
21424     size += (num_attrs - 1) * sizeof (struct attribute);
21425
21426   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21427   memset (die, 0, sizeof (struct die_info));
21428   return (die);
21429 }
21430
21431 \f
21432 /* Macro support.  */
21433
21434 /* Return file name relative to the compilation directory of file number I in
21435    *LH's file name table.  The result is allocated using xmalloc; the caller is
21436    responsible for freeing it.  */
21437
21438 static char *
21439 file_file_name (int file, struct line_header *lh)
21440 {
21441   /* Is the file number a valid index into the line header's file name
21442      table?  Remember that file numbers start with one, not zero.  */
21443   if (1 <= file && file <= lh->file_names.size ())
21444     {
21445       const file_entry &fe = lh->file_names[file - 1];
21446
21447       if (!IS_ABSOLUTE_PATH (fe.name))
21448         {
21449           const char *dir = fe.include_dir (lh);
21450           if (dir != NULL)
21451             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21452         }
21453       return xstrdup (fe.name);
21454     }
21455   else
21456     {
21457       /* The compiler produced a bogus file number.  We can at least
21458          record the macro definitions made in the file, even if we
21459          won't be able to find the file by name.  */
21460       char fake_name[80];
21461
21462       xsnprintf (fake_name, sizeof (fake_name),
21463                  "<bad macro file number %d>", file);
21464
21465       complaint (&symfile_complaints,
21466                  _("bad file number in macro information (%d)"),
21467                  file);
21468
21469       return xstrdup (fake_name);
21470     }
21471 }
21472
21473 /* Return the full name of file number I in *LH's file name table.
21474    Use COMP_DIR as the name of the current directory of the
21475    compilation.  The result is allocated using xmalloc; the caller is
21476    responsible for freeing it.  */
21477 static char *
21478 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21479 {
21480   /* Is the file number a valid index into the line header's file name
21481      table?  Remember that file numbers start with one, not zero.  */
21482   if (1 <= file && file <= lh->file_names.size ())
21483     {
21484       char *relative = file_file_name (file, lh);
21485
21486       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21487         return relative;
21488       return reconcat (relative, comp_dir, SLASH_STRING,
21489                        relative, (char *) NULL);
21490     }
21491   else
21492     return file_file_name (file, lh);
21493 }
21494
21495
21496 static struct macro_source_file *
21497 macro_start_file (int file, int line,
21498                   struct macro_source_file *current_file,
21499                   struct line_header *lh)
21500 {
21501   /* File name relative to the compilation directory of this source file.  */
21502   char *file_name = file_file_name (file, lh);
21503
21504   if (! current_file)
21505     {
21506       /* Note: We don't create a macro table for this compilation unit
21507          at all until we actually get a filename.  */
21508       struct macro_table *macro_table = get_macro_table ();
21509
21510       /* If we have no current file, then this must be the start_file
21511          directive for the compilation unit's main source file.  */
21512       current_file = macro_set_main (macro_table, file_name);
21513       macro_define_special (macro_table);
21514     }
21515   else
21516     current_file = macro_include (current_file, line, file_name);
21517
21518   xfree (file_name);
21519
21520   return current_file;
21521 }
21522
21523
21524 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21525    followed by a null byte.  */
21526 static char *
21527 copy_string (const char *buf, int len)
21528 {
21529   char *s = (char *) xmalloc (len + 1);
21530
21531   memcpy (s, buf, len);
21532   s[len] = '\0';
21533   return s;
21534 }
21535
21536
21537 static const char *
21538 consume_improper_spaces (const char *p, const char *body)
21539 {
21540   if (*p == ' ')
21541     {
21542       complaint (&symfile_complaints,
21543                  _("macro definition contains spaces "
21544                    "in formal argument list:\n`%s'"),
21545                  body);
21546
21547       while (*p == ' ')
21548         p++;
21549     }
21550
21551   return p;
21552 }
21553
21554
21555 static void
21556 parse_macro_definition (struct macro_source_file *file, int line,
21557                         const char *body)
21558 {
21559   const char *p;
21560
21561   /* The body string takes one of two forms.  For object-like macro
21562      definitions, it should be:
21563
21564         <macro name> " " <definition>
21565
21566      For function-like macro definitions, it should be:
21567
21568         <macro name> "() " <definition>
21569      or
21570         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21571
21572      Spaces may appear only where explicitly indicated, and in the
21573      <definition>.
21574
21575      The Dwarf 2 spec says that an object-like macro's name is always
21576      followed by a space, but versions of GCC around March 2002 omit
21577      the space when the macro's definition is the empty string.
21578
21579      The Dwarf 2 spec says that there should be no spaces between the
21580      formal arguments in a function-like macro's formal argument list,
21581      but versions of GCC around March 2002 include spaces after the
21582      commas.  */
21583
21584
21585   /* Find the extent of the macro name.  The macro name is terminated
21586      by either a space or null character (for an object-like macro) or
21587      an opening paren (for a function-like macro).  */
21588   for (p = body; *p; p++)
21589     if (*p == ' ' || *p == '(')
21590       break;
21591
21592   if (*p == ' ' || *p == '\0')
21593     {
21594       /* It's an object-like macro.  */
21595       int name_len = p - body;
21596       char *name = copy_string (body, name_len);
21597       const char *replacement;
21598
21599       if (*p == ' ')
21600         replacement = body + name_len + 1;
21601       else
21602         {
21603           dwarf2_macro_malformed_definition_complaint (body);
21604           replacement = body + name_len;
21605         }
21606
21607       macro_define_object (file, line, name, replacement);
21608
21609       xfree (name);
21610     }
21611   else if (*p == '(')
21612     {
21613       /* It's a function-like macro.  */
21614       char *name = copy_string (body, p - body);
21615       int argc = 0;
21616       int argv_size = 1;
21617       char **argv = XNEWVEC (char *, argv_size);
21618
21619       p++;
21620
21621       p = consume_improper_spaces (p, body);
21622
21623       /* Parse the formal argument list.  */
21624       while (*p && *p != ')')
21625         {
21626           /* Find the extent of the current argument name.  */
21627           const char *arg_start = p;
21628
21629           while (*p && *p != ',' && *p != ')' && *p != ' ')
21630             p++;
21631
21632           if (! *p || p == arg_start)
21633             dwarf2_macro_malformed_definition_complaint (body);
21634           else
21635             {
21636               /* Make sure argv has room for the new argument.  */
21637               if (argc >= argv_size)
21638                 {
21639                   argv_size *= 2;
21640                   argv = XRESIZEVEC (char *, argv, argv_size);
21641                 }
21642
21643               argv[argc++] = copy_string (arg_start, p - arg_start);
21644             }
21645
21646           p = consume_improper_spaces (p, body);
21647
21648           /* Consume the comma, if present.  */
21649           if (*p == ',')
21650             {
21651               p++;
21652
21653               p = consume_improper_spaces (p, body);
21654             }
21655         }
21656
21657       if (*p == ')')
21658         {
21659           p++;
21660
21661           if (*p == ' ')
21662             /* Perfectly formed definition, no complaints.  */
21663             macro_define_function (file, line, name,
21664                                    argc, (const char **) argv,
21665                                    p + 1);
21666           else if (*p == '\0')
21667             {
21668               /* Complain, but do define it.  */
21669               dwarf2_macro_malformed_definition_complaint (body);
21670               macro_define_function (file, line, name,
21671                                      argc, (const char **) argv,
21672                                      p);
21673             }
21674           else
21675             /* Just complain.  */
21676             dwarf2_macro_malformed_definition_complaint (body);
21677         }
21678       else
21679         /* Just complain.  */
21680         dwarf2_macro_malformed_definition_complaint (body);
21681
21682       xfree (name);
21683       {
21684         int i;
21685
21686         for (i = 0; i < argc; i++)
21687           xfree (argv[i]);
21688       }
21689       xfree (argv);
21690     }
21691   else
21692     dwarf2_macro_malformed_definition_complaint (body);
21693 }
21694
21695 /* Skip some bytes from BYTES according to the form given in FORM.
21696    Returns the new pointer.  */
21697
21698 static const gdb_byte *
21699 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21700                  enum dwarf_form form,
21701                  unsigned int offset_size,
21702                  struct dwarf2_section_info *section)
21703 {
21704   unsigned int bytes_read;
21705
21706   switch (form)
21707     {
21708     case DW_FORM_data1:
21709     case DW_FORM_flag:
21710       ++bytes;
21711       break;
21712
21713     case DW_FORM_data2:
21714       bytes += 2;
21715       break;
21716
21717     case DW_FORM_data4:
21718       bytes += 4;
21719       break;
21720
21721     case DW_FORM_data8:
21722       bytes += 8;
21723       break;
21724
21725     case DW_FORM_data16:
21726       bytes += 16;
21727       break;
21728
21729     case DW_FORM_string:
21730       read_direct_string (abfd, bytes, &bytes_read);
21731       bytes += bytes_read;
21732       break;
21733
21734     case DW_FORM_sec_offset:
21735     case DW_FORM_strp:
21736     case DW_FORM_GNU_strp_alt:
21737       bytes += offset_size;
21738       break;
21739
21740     case DW_FORM_block:
21741       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21742       bytes += bytes_read;
21743       break;
21744
21745     case DW_FORM_block1:
21746       bytes += 1 + read_1_byte (abfd, bytes);
21747       break;
21748     case DW_FORM_block2:
21749       bytes += 2 + read_2_bytes (abfd, bytes);
21750       break;
21751     case DW_FORM_block4:
21752       bytes += 4 + read_4_bytes (abfd, bytes);
21753       break;
21754
21755     case DW_FORM_sdata:
21756     case DW_FORM_udata:
21757     case DW_FORM_GNU_addr_index:
21758     case DW_FORM_GNU_str_index:
21759       bytes = gdb_skip_leb128 (bytes, buffer_end);
21760       if (bytes == NULL)
21761         {
21762           dwarf2_section_buffer_overflow_complaint (section);
21763           return NULL;
21764         }
21765       break;
21766
21767     default:
21768       {
21769       complain:
21770         complaint (&symfile_complaints,
21771                    _("invalid form 0x%x in `%s'"),
21772                    form, get_section_name (section));
21773         return NULL;
21774       }
21775     }
21776
21777   return bytes;
21778 }
21779
21780 /* A helper for dwarf_decode_macros that handles skipping an unknown
21781    opcode.  Returns an updated pointer to the macro data buffer; or,
21782    on error, issues a complaint and returns NULL.  */
21783
21784 static const gdb_byte *
21785 skip_unknown_opcode (unsigned int opcode,
21786                      const gdb_byte **opcode_definitions,
21787                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21788                      bfd *abfd,
21789                      unsigned int offset_size,
21790                      struct dwarf2_section_info *section)
21791 {
21792   unsigned int bytes_read, i;
21793   unsigned long arg;
21794   const gdb_byte *defn;
21795
21796   if (opcode_definitions[opcode] == NULL)
21797     {
21798       complaint (&symfile_complaints,
21799                  _("unrecognized DW_MACFINO opcode 0x%x"),
21800                  opcode);
21801       return NULL;
21802     }
21803
21804   defn = opcode_definitions[opcode];
21805   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21806   defn += bytes_read;
21807
21808   for (i = 0; i < arg; ++i)
21809     {
21810       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21811                                  (enum dwarf_form) defn[i], offset_size,
21812                                  section);
21813       if (mac_ptr == NULL)
21814         {
21815           /* skip_form_bytes already issued the complaint.  */
21816           return NULL;
21817         }
21818     }
21819
21820   return mac_ptr;
21821 }
21822
21823 /* A helper function which parses the header of a macro section.
21824    If the macro section is the extended (for now called "GNU") type,
21825    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21826    the header, or issues a complaint and returns NULL on error.  */
21827
21828 static const gdb_byte *
21829 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21830                           bfd *abfd,
21831                           const gdb_byte *mac_ptr,
21832                           unsigned int *offset_size,
21833                           int section_is_gnu)
21834 {
21835   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21836
21837   if (section_is_gnu)
21838     {
21839       unsigned int version, flags;
21840
21841       version = read_2_bytes (abfd, mac_ptr);
21842       if (version != 4 && version != 5)
21843         {
21844           complaint (&symfile_complaints,
21845                      _("unrecognized version `%d' in .debug_macro section"),
21846                      version);
21847           return NULL;
21848         }
21849       mac_ptr += 2;
21850
21851       flags = read_1_byte (abfd, mac_ptr);
21852       ++mac_ptr;
21853       *offset_size = (flags & 1) ? 8 : 4;
21854
21855       if ((flags & 2) != 0)
21856         /* We don't need the line table offset.  */
21857         mac_ptr += *offset_size;
21858
21859       /* Vendor opcode descriptions.  */
21860       if ((flags & 4) != 0)
21861         {
21862           unsigned int i, count;
21863
21864           count = read_1_byte (abfd, mac_ptr);
21865           ++mac_ptr;
21866           for (i = 0; i < count; ++i)
21867             {
21868               unsigned int opcode, bytes_read;
21869               unsigned long arg;
21870
21871               opcode = read_1_byte (abfd, mac_ptr);
21872               ++mac_ptr;
21873               opcode_definitions[opcode] = mac_ptr;
21874               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21875               mac_ptr += bytes_read;
21876               mac_ptr += arg;
21877             }
21878         }
21879     }
21880
21881   return mac_ptr;
21882 }
21883
21884 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21885    including DW_MACRO_import.  */
21886
21887 static void
21888 dwarf_decode_macro_bytes (bfd *abfd,
21889                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21890                           struct macro_source_file *current_file,
21891                           struct line_header *lh,
21892                           struct dwarf2_section_info *section,
21893                           int section_is_gnu, int section_is_dwz,
21894                           unsigned int offset_size,
21895                           htab_t include_hash)
21896 {
21897   struct objfile *objfile = dwarf2_per_objfile->objfile;
21898   enum dwarf_macro_record_type macinfo_type;
21899   int at_commandline;
21900   const gdb_byte *opcode_definitions[256];
21901
21902   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21903                                       &offset_size, section_is_gnu);
21904   if (mac_ptr == NULL)
21905     {
21906       /* We already issued a complaint.  */
21907       return;
21908     }
21909
21910   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
21911      GDB is still reading the definitions from command line.  First
21912      DW_MACINFO_start_file will need to be ignored as it was already executed
21913      to create CURRENT_FILE for the main source holding also the command line
21914      definitions.  On first met DW_MACINFO_start_file this flag is reset to
21915      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
21916
21917   at_commandline = 1;
21918
21919   do
21920     {
21921       /* Do we at least have room for a macinfo type byte?  */
21922       if (mac_ptr >= mac_end)
21923         {
21924           dwarf2_section_buffer_overflow_complaint (section);
21925           break;
21926         }
21927
21928       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
21929       mac_ptr++;
21930
21931       /* Note that we rely on the fact that the corresponding GNU and
21932          DWARF constants are the same.  */
21933       switch (macinfo_type)
21934         {
21935           /* A zero macinfo type indicates the end of the macro
21936              information.  */
21937         case 0:
21938           break;
21939
21940         case DW_MACRO_define:
21941         case DW_MACRO_undef:
21942         case DW_MACRO_define_strp:
21943         case DW_MACRO_undef_strp:
21944         case DW_MACRO_define_sup:
21945         case DW_MACRO_undef_sup:
21946           {
21947             unsigned int bytes_read;
21948             int line;
21949             const char *body;
21950             int is_define;
21951
21952             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21953             mac_ptr += bytes_read;
21954
21955             if (macinfo_type == DW_MACRO_define
21956                 || macinfo_type == DW_MACRO_undef)
21957               {
21958                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
21959                 mac_ptr += bytes_read;
21960               }
21961             else
21962               {
21963                 LONGEST str_offset;
21964
21965                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
21966                 mac_ptr += offset_size;
21967
21968                 if (macinfo_type == DW_MACRO_define_sup
21969                     || macinfo_type == DW_MACRO_undef_sup
21970                     || section_is_dwz)
21971                   {
21972                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
21973
21974                     body = read_indirect_string_from_dwz (dwz, str_offset);
21975                   }
21976                 else
21977                   body = read_indirect_string_at_offset (abfd, str_offset);
21978               }
21979
21980             is_define = (macinfo_type == DW_MACRO_define
21981                          || macinfo_type == DW_MACRO_define_strp
21982                          || macinfo_type == DW_MACRO_define_sup);
21983             if (! current_file)
21984               {
21985                 /* DWARF violation as no main source is present.  */
21986                 complaint (&symfile_complaints,
21987                            _("debug info with no main source gives macro %s "
21988                              "on line %d: %s"),
21989                            is_define ? _("definition") : _("undefinition"),
21990                            line, body);
21991                 break;
21992               }
21993             if ((line == 0 && !at_commandline)
21994                 || (line != 0 && at_commandline))
21995               complaint (&symfile_complaints,
21996                          _("debug info gives %s macro %s with %s line %d: %s"),
21997                          at_commandline ? _("command-line") : _("in-file"),
21998                          is_define ? _("definition") : _("undefinition"),
21999                          line == 0 ? _("zero") : _("non-zero"), line, body);
22000
22001             if (is_define)
22002               parse_macro_definition (current_file, line, body);
22003             else
22004               {
22005                 gdb_assert (macinfo_type == DW_MACRO_undef
22006                             || macinfo_type == DW_MACRO_undef_strp
22007                             || macinfo_type == DW_MACRO_undef_sup);
22008                 macro_undef (current_file, line, body);
22009               }
22010           }
22011           break;
22012
22013         case DW_MACRO_start_file:
22014           {
22015             unsigned int bytes_read;
22016             int line, file;
22017
22018             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22019             mac_ptr += bytes_read;
22020             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22021             mac_ptr += bytes_read;
22022
22023             if ((line == 0 && !at_commandline)
22024                 || (line != 0 && at_commandline))
22025               complaint (&symfile_complaints,
22026                          _("debug info gives source %d included "
22027                            "from %s at %s line %d"),
22028                          file, at_commandline ? _("command-line") : _("file"),
22029                          line == 0 ? _("zero") : _("non-zero"), line);
22030
22031             if (at_commandline)
22032               {
22033                 /* This DW_MACRO_start_file was executed in the
22034                    pass one.  */
22035                 at_commandline = 0;
22036               }
22037             else
22038               current_file = macro_start_file (file, line, current_file, lh);
22039           }
22040           break;
22041
22042         case DW_MACRO_end_file:
22043           if (! current_file)
22044             complaint (&symfile_complaints,
22045                        _("macro debug info has an unmatched "
22046                          "`close_file' directive"));
22047           else
22048             {
22049               current_file = current_file->included_by;
22050               if (! current_file)
22051                 {
22052                   enum dwarf_macro_record_type next_type;
22053
22054                   /* GCC circa March 2002 doesn't produce the zero
22055                      type byte marking the end of the compilation
22056                      unit.  Complain if it's not there, but exit no
22057                      matter what.  */
22058
22059                   /* Do we at least have room for a macinfo type byte?  */
22060                   if (mac_ptr >= mac_end)
22061                     {
22062                       dwarf2_section_buffer_overflow_complaint (section);
22063                       return;
22064                     }
22065
22066                   /* We don't increment mac_ptr here, so this is just
22067                      a look-ahead.  */
22068                   next_type
22069                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22070                                                                   mac_ptr);
22071                   if (next_type != 0)
22072                     complaint (&symfile_complaints,
22073                                _("no terminating 0-type entry for "
22074                                  "macros in `.debug_macinfo' section"));
22075
22076                   return;
22077                 }
22078             }
22079           break;
22080
22081         case DW_MACRO_import:
22082         case DW_MACRO_import_sup:
22083           {
22084             LONGEST offset;
22085             void **slot;
22086             bfd *include_bfd = abfd;
22087             struct dwarf2_section_info *include_section = section;
22088             const gdb_byte *include_mac_end = mac_end;
22089             int is_dwz = section_is_dwz;
22090             const gdb_byte *new_mac_ptr;
22091
22092             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22093             mac_ptr += offset_size;
22094
22095             if (macinfo_type == DW_MACRO_import_sup)
22096               {
22097                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22098
22099                 dwarf2_read_section (objfile, &dwz->macro);
22100
22101                 include_section = &dwz->macro;
22102                 include_bfd = get_section_bfd_owner (include_section);
22103                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22104                 is_dwz = 1;
22105               }
22106
22107             new_mac_ptr = include_section->buffer + offset;
22108             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22109
22110             if (*slot != NULL)
22111               {
22112                 /* This has actually happened; see
22113                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22114                 complaint (&symfile_complaints,
22115                            _("recursive DW_MACRO_import in "
22116                              ".debug_macro section"));
22117               }
22118             else
22119               {
22120                 *slot = (void *) new_mac_ptr;
22121
22122                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22123                                           include_mac_end, current_file, lh,
22124                                           section, section_is_gnu, is_dwz,
22125                                           offset_size, include_hash);
22126
22127                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22128               }
22129           }
22130           break;
22131
22132         case DW_MACINFO_vendor_ext:
22133           if (!section_is_gnu)
22134             {
22135               unsigned int bytes_read;
22136
22137               /* This reads the constant, but since we don't recognize
22138                  any vendor extensions, we ignore it.  */
22139               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22140               mac_ptr += bytes_read;
22141               read_direct_string (abfd, mac_ptr, &bytes_read);
22142               mac_ptr += bytes_read;
22143
22144               /* We don't recognize any vendor extensions.  */
22145               break;
22146             }
22147           /* FALLTHROUGH */
22148
22149         default:
22150           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22151                                          mac_ptr, mac_end, abfd, offset_size,
22152                                          section);
22153           if (mac_ptr == NULL)
22154             return;
22155           break;
22156         }
22157     } while (macinfo_type != 0);
22158 }
22159
22160 static void
22161 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22162                      int section_is_gnu)
22163 {
22164   struct objfile *objfile = dwarf2_per_objfile->objfile;
22165   struct line_header *lh = cu->line_header;
22166   bfd *abfd;
22167   const gdb_byte *mac_ptr, *mac_end;
22168   struct macro_source_file *current_file = 0;
22169   enum dwarf_macro_record_type macinfo_type;
22170   unsigned int offset_size = cu->header.offset_size;
22171   const gdb_byte *opcode_definitions[256];
22172   struct cleanup *cleanup;
22173   void **slot;
22174   struct dwarf2_section_info *section;
22175   const char *section_name;
22176
22177   if (cu->dwo_unit != NULL)
22178     {
22179       if (section_is_gnu)
22180         {
22181           section = &cu->dwo_unit->dwo_file->sections.macro;
22182           section_name = ".debug_macro.dwo";
22183         }
22184       else
22185         {
22186           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22187           section_name = ".debug_macinfo.dwo";
22188         }
22189     }
22190   else
22191     {
22192       if (section_is_gnu)
22193         {
22194           section = &dwarf2_per_objfile->macro;
22195           section_name = ".debug_macro";
22196         }
22197       else
22198         {
22199           section = &dwarf2_per_objfile->macinfo;
22200           section_name = ".debug_macinfo";
22201         }
22202     }
22203
22204   dwarf2_read_section (objfile, section);
22205   if (section->buffer == NULL)
22206     {
22207       complaint (&symfile_complaints, _("missing %s section"), section_name);
22208       return;
22209     }
22210   abfd = get_section_bfd_owner (section);
22211
22212   /* First pass: Find the name of the base filename.
22213      This filename is needed in order to process all macros whose definition
22214      (or undefinition) comes from the command line.  These macros are defined
22215      before the first DW_MACINFO_start_file entry, and yet still need to be
22216      associated to the base file.
22217
22218      To determine the base file name, we scan the macro definitions until we
22219      reach the first DW_MACINFO_start_file entry.  We then initialize
22220      CURRENT_FILE accordingly so that any macro definition found before the
22221      first DW_MACINFO_start_file can still be associated to the base file.  */
22222
22223   mac_ptr = section->buffer + offset;
22224   mac_end = section->buffer + section->size;
22225
22226   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22227                                       &offset_size, section_is_gnu);
22228   if (mac_ptr == NULL)
22229     {
22230       /* We already issued a complaint.  */
22231       return;
22232     }
22233
22234   do
22235     {
22236       /* Do we at least have room for a macinfo type byte?  */
22237       if (mac_ptr >= mac_end)
22238         {
22239           /* Complaint is printed during the second pass as GDB will probably
22240              stop the first pass earlier upon finding
22241              DW_MACINFO_start_file.  */
22242           break;
22243         }
22244
22245       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22246       mac_ptr++;
22247
22248       /* Note that we rely on the fact that the corresponding GNU and
22249          DWARF constants are the same.  */
22250       switch (macinfo_type)
22251         {
22252           /* A zero macinfo type indicates the end of the macro
22253              information.  */
22254         case 0:
22255           break;
22256
22257         case DW_MACRO_define:
22258         case DW_MACRO_undef:
22259           /* Only skip the data by MAC_PTR.  */
22260           {
22261             unsigned int bytes_read;
22262
22263             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22264             mac_ptr += bytes_read;
22265             read_direct_string (abfd, mac_ptr, &bytes_read);
22266             mac_ptr += bytes_read;
22267           }
22268           break;
22269
22270         case DW_MACRO_start_file:
22271           {
22272             unsigned int bytes_read;
22273             int line, file;
22274
22275             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22276             mac_ptr += bytes_read;
22277             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22278             mac_ptr += bytes_read;
22279
22280             current_file = macro_start_file (file, line, current_file, lh);
22281           }
22282           break;
22283
22284         case DW_MACRO_end_file:
22285           /* No data to skip by MAC_PTR.  */
22286           break;
22287
22288         case DW_MACRO_define_strp:
22289         case DW_MACRO_undef_strp:
22290         case DW_MACRO_define_sup:
22291         case DW_MACRO_undef_sup:
22292           {
22293             unsigned int bytes_read;
22294
22295             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22296             mac_ptr += bytes_read;
22297             mac_ptr += offset_size;
22298           }
22299           break;
22300
22301         case DW_MACRO_import:
22302         case DW_MACRO_import_sup:
22303           /* Note that, according to the spec, a transparent include
22304              chain cannot call DW_MACRO_start_file.  So, we can just
22305              skip this opcode.  */
22306           mac_ptr += offset_size;
22307           break;
22308
22309         case DW_MACINFO_vendor_ext:
22310           /* Only skip the data by MAC_PTR.  */
22311           if (!section_is_gnu)
22312             {
22313               unsigned int bytes_read;
22314
22315               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22316               mac_ptr += bytes_read;
22317               read_direct_string (abfd, mac_ptr, &bytes_read);
22318               mac_ptr += bytes_read;
22319             }
22320           /* FALLTHROUGH */
22321
22322         default:
22323           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22324                                          mac_ptr, mac_end, abfd, offset_size,
22325                                          section);
22326           if (mac_ptr == NULL)
22327             return;
22328           break;
22329         }
22330     } while (macinfo_type != 0 && current_file == NULL);
22331
22332   /* Second pass: Process all entries.
22333
22334      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22335      command-line macro definitions/undefinitions.  This flag is unset when we
22336      reach the first DW_MACINFO_start_file entry.  */
22337
22338   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22339                                            htab_eq_pointer,
22340                                            NULL, xcalloc, xfree));
22341   mac_ptr = section->buffer + offset;
22342   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22343   *slot = (void *) mac_ptr;
22344   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22345                             current_file, lh, section,
22346                             section_is_gnu, 0, offset_size,
22347                             include_hash.get ());
22348 }
22349
22350 /* Check if the attribute's form is a DW_FORM_block*
22351    if so return true else false.  */
22352
22353 static int
22354 attr_form_is_block (const struct attribute *attr)
22355 {
22356   return (attr == NULL ? 0 :
22357       attr->form == DW_FORM_block1
22358       || attr->form == DW_FORM_block2
22359       || attr->form == DW_FORM_block4
22360       || attr->form == DW_FORM_block
22361       || attr->form == DW_FORM_exprloc);
22362 }
22363
22364 /* Return non-zero if ATTR's value is a section offset --- classes
22365    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22366    You may use DW_UNSND (attr) to retrieve such offsets.
22367
22368    Section 7.5.4, "Attribute Encodings", explains that no attribute
22369    may have a value that belongs to more than one of these classes; it
22370    would be ambiguous if we did, because we use the same forms for all
22371    of them.  */
22372
22373 static int
22374 attr_form_is_section_offset (const struct attribute *attr)
22375 {
22376   return (attr->form == DW_FORM_data4
22377           || attr->form == DW_FORM_data8
22378           || attr->form == DW_FORM_sec_offset);
22379 }
22380
22381 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22382    zero otherwise.  When this function returns true, you can apply
22383    dwarf2_get_attr_constant_value to it.
22384
22385    However, note that for some attributes you must check
22386    attr_form_is_section_offset before using this test.  DW_FORM_data4
22387    and DW_FORM_data8 are members of both the constant class, and of
22388    the classes that contain offsets into other debug sections
22389    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22390    that, if an attribute's can be either a constant or one of the
22391    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22392    taken as section offsets, not constants.
22393
22394    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22395    cannot handle that.  */
22396
22397 static int
22398 attr_form_is_constant (const struct attribute *attr)
22399 {
22400   switch (attr->form)
22401     {
22402     case DW_FORM_sdata:
22403     case DW_FORM_udata:
22404     case DW_FORM_data1:
22405     case DW_FORM_data2:
22406     case DW_FORM_data4:
22407     case DW_FORM_data8:
22408       return 1;
22409     default:
22410       return 0;
22411     }
22412 }
22413
22414
22415 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22416    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22417
22418 static int
22419 attr_form_is_ref (const struct attribute *attr)
22420 {
22421   switch (attr->form)
22422     {
22423     case DW_FORM_ref_addr:
22424     case DW_FORM_ref1:
22425     case DW_FORM_ref2:
22426     case DW_FORM_ref4:
22427     case DW_FORM_ref8:
22428     case DW_FORM_ref_udata:
22429     case DW_FORM_GNU_ref_alt:
22430       return 1;
22431     default:
22432       return 0;
22433     }
22434 }
22435
22436 /* Return the .debug_loc section to use for CU.
22437    For DWO files use .debug_loc.dwo.  */
22438
22439 static struct dwarf2_section_info *
22440 cu_debug_loc_section (struct dwarf2_cu *cu)
22441 {
22442   if (cu->dwo_unit)
22443     {
22444       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22445       
22446       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22447     }
22448   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22449                                   : &dwarf2_per_objfile->loc);
22450 }
22451
22452 /* A helper function that fills in a dwarf2_loclist_baton.  */
22453
22454 static void
22455 fill_in_loclist_baton (struct dwarf2_cu *cu,
22456                        struct dwarf2_loclist_baton *baton,
22457                        const struct attribute *attr)
22458 {
22459   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22460
22461   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22462
22463   baton->per_cu = cu->per_cu;
22464   gdb_assert (baton->per_cu);
22465   /* We don't know how long the location list is, but make sure we
22466      don't run off the edge of the section.  */
22467   baton->size = section->size - DW_UNSND (attr);
22468   baton->data = section->buffer + DW_UNSND (attr);
22469   baton->base_address = cu->base_address;
22470   baton->from_dwo = cu->dwo_unit != NULL;
22471 }
22472
22473 static void
22474 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22475                              struct dwarf2_cu *cu, int is_block)
22476 {
22477   struct objfile *objfile = dwarf2_per_objfile->objfile;
22478   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22479
22480   if (attr_form_is_section_offset (attr)
22481       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22482          the section.  If so, fall through to the complaint in the
22483          other branch.  */
22484       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22485     {
22486       struct dwarf2_loclist_baton *baton;
22487
22488       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22489
22490       fill_in_loclist_baton (cu, baton, attr);
22491
22492       if (cu->base_known == 0)
22493         complaint (&symfile_complaints,
22494                    _("Location list used without "
22495                      "specifying the CU base address."));
22496
22497       SYMBOL_ACLASS_INDEX (sym) = (is_block
22498                                    ? dwarf2_loclist_block_index
22499                                    : dwarf2_loclist_index);
22500       SYMBOL_LOCATION_BATON (sym) = baton;
22501     }
22502   else
22503     {
22504       struct dwarf2_locexpr_baton *baton;
22505
22506       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22507       baton->per_cu = cu->per_cu;
22508       gdb_assert (baton->per_cu);
22509
22510       if (attr_form_is_block (attr))
22511         {
22512           /* Note that we're just copying the block's data pointer
22513              here, not the actual data.  We're still pointing into the
22514              info_buffer for SYM's objfile; right now we never release
22515              that buffer, but when we do clean up properly this may
22516              need to change.  */
22517           baton->size = DW_BLOCK (attr)->size;
22518           baton->data = DW_BLOCK (attr)->data;
22519         }
22520       else
22521         {
22522           dwarf2_invalid_attrib_class_complaint ("location description",
22523                                                  SYMBOL_NATURAL_NAME (sym));
22524           baton->size = 0;
22525         }
22526
22527       SYMBOL_ACLASS_INDEX (sym) = (is_block
22528                                    ? dwarf2_locexpr_block_index
22529                                    : dwarf2_locexpr_index);
22530       SYMBOL_LOCATION_BATON (sym) = baton;
22531     }
22532 }
22533
22534 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22535    came from a separate debuginfo file, then the master objfile is
22536    returned.  */
22537
22538 struct objfile *
22539 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22540 {
22541   struct objfile *objfile = per_cu->objfile;
22542
22543   /* Return the master objfile, so that we can report and look up the
22544      correct file containing this variable.  */
22545   if (objfile->separate_debug_objfile_backlink)
22546     objfile = objfile->separate_debug_objfile_backlink;
22547
22548   return objfile;
22549 }
22550
22551 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22552    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22553    CU_HEADERP first.  */
22554
22555 static const struct comp_unit_head *
22556 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22557                        struct dwarf2_per_cu_data *per_cu)
22558 {
22559   const gdb_byte *info_ptr;
22560
22561   if (per_cu->cu)
22562     return &per_cu->cu->header;
22563
22564   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22565
22566   memset (cu_headerp, 0, sizeof (*cu_headerp));
22567   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22568                        rcuh_kind::COMPILE);
22569
22570   return cu_headerp;
22571 }
22572
22573 /* Return the address size given in the compilation unit header for CU.  */
22574
22575 int
22576 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22577 {
22578   struct comp_unit_head cu_header_local;
22579   const struct comp_unit_head *cu_headerp;
22580
22581   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22582
22583   return cu_headerp->addr_size;
22584 }
22585
22586 /* Return the offset size given in the compilation unit header for CU.  */
22587
22588 int
22589 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22590 {
22591   struct comp_unit_head cu_header_local;
22592   const struct comp_unit_head *cu_headerp;
22593
22594   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22595
22596   return cu_headerp->offset_size;
22597 }
22598
22599 /* See its dwarf2loc.h declaration.  */
22600
22601 int
22602 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22603 {
22604   struct comp_unit_head cu_header_local;
22605   const struct comp_unit_head *cu_headerp;
22606
22607   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22608
22609   if (cu_headerp->version == 2)
22610     return cu_headerp->addr_size;
22611   else
22612     return cu_headerp->offset_size;
22613 }
22614
22615 /* Return the text offset of the CU.  The returned offset comes from
22616    this CU's objfile.  If this objfile came from a separate debuginfo
22617    file, then the offset may be different from the corresponding
22618    offset in the parent objfile.  */
22619
22620 CORE_ADDR
22621 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22622 {
22623   struct objfile *objfile = per_cu->objfile;
22624
22625   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22626 }
22627
22628 /* Return DWARF version number of PER_CU.  */
22629
22630 short
22631 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22632 {
22633   return per_cu->dwarf_version;
22634 }
22635
22636 /* Locate the .debug_info compilation unit from CU's objfile which contains
22637    the DIE at OFFSET.  Raises an error on failure.  */
22638
22639 static struct dwarf2_per_cu_data *
22640 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22641                                   unsigned int offset_in_dwz,
22642                                   struct objfile *objfile)
22643 {
22644   struct dwarf2_per_cu_data *this_cu;
22645   int low, high;
22646   const sect_offset *cu_off;
22647
22648   low = 0;
22649   high = dwarf2_per_objfile->n_comp_units - 1;
22650   while (high > low)
22651     {
22652       struct dwarf2_per_cu_data *mid_cu;
22653       int mid = low + (high - low) / 2;
22654
22655       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22656       cu_off = &mid_cu->sect_off;
22657       if (mid_cu->is_dwz > offset_in_dwz
22658           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22659         high = mid;
22660       else
22661         low = mid + 1;
22662     }
22663   gdb_assert (low == high);
22664   this_cu = dwarf2_per_objfile->all_comp_units[low];
22665   cu_off = &this_cu->sect_off;
22666   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22667     {
22668       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22669         error (_("Dwarf Error: could not find partial DIE containing "
22670                "offset 0x%x [in module %s]"),
22671                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22672
22673       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22674                   <= sect_off);
22675       return dwarf2_per_objfile->all_comp_units[low-1];
22676     }
22677   else
22678     {
22679       this_cu = dwarf2_per_objfile->all_comp_units[low];
22680       if (low == dwarf2_per_objfile->n_comp_units - 1
22681           && sect_off >= this_cu->sect_off + this_cu->length)
22682         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22683       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22684       return this_cu;
22685     }
22686 }
22687
22688 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22689
22690 static void
22691 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22692 {
22693   memset (cu, 0, sizeof (*cu));
22694   per_cu->cu = cu;
22695   cu->per_cu = per_cu;
22696   cu->objfile = per_cu->objfile;
22697   obstack_init (&cu->comp_unit_obstack);
22698 }
22699
22700 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22701
22702 static void
22703 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22704                        enum language pretend_language)
22705 {
22706   struct attribute *attr;
22707
22708   /* Set the language we're debugging.  */
22709   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22710   if (attr)
22711     set_cu_language (DW_UNSND (attr), cu);
22712   else
22713     {
22714       cu->language = pretend_language;
22715       cu->language_defn = language_def (cu->language);
22716     }
22717
22718   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22719 }
22720
22721 /* Release one cached compilation unit, CU.  We unlink it from the tree
22722    of compilation units, but we don't remove it from the read_in_chain;
22723    the caller is responsible for that.
22724    NOTE: DATA is a void * because this function is also used as a
22725    cleanup routine.  */
22726
22727 static void
22728 free_heap_comp_unit (void *data)
22729 {
22730   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22731
22732   gdb_assert (cu->per_cu != NULL);
22733   cu->per_cu->cu = NULL;
22734   cu->per_cu = NULL;
22735
22736   obstack_free (&cu->comp_unit_obstack, NULL);
22737
22738   xfree (cu);
22739 }
22740
22741 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22742    when we're finished with it.  We can't free the pointer itself, but be
22743    sure to unlink it from the cache.  Also release any associated storage.  */
22744
22745 static void
22746 free_stack_comp_unit (void *data)
22747 {
22748   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22749
22750   gdb_assert (cu->per_cu != NULL);
22751   cu->per_cu->cu = NULL;
22752   cu->per_cu = NULL;
22753
22754   obstack_free (&cu->comp_unit_obstack, NULL);
22755   cu->partial_dies = NULL;
22756 }
22757
22758 /* Free all cached compilation units.  */
22759
22760 static void
22761 free_cached_comp_units (void *data)
22762 {
22763   struct dwarf2_per_cu_data *per_cu, **last_chain;
22764
22765   per_cu = dwarf2_per_objfile->read_in_chain;
22766   last_chain = &dwarf2_per_objfile->read_in_chain;
22767   while (per_cu != NULL)
22768     {
22769       struct dwarf2_per_cu_data *next_cu;
22770
22771       next_cu = per_cu->cu->read_in_chain;
22772
22773       free_heap_comp_unit (per_cu->cu);
22774       *last_chain = next_cu;
22775
22776       per_cu = next_cu;
22777     }
22778 }
22779
22780 /* Increase the age counter on each cached compilation unit, and free
22781    any that are too old.  */
22782
22783 static void
22784 age_cached_comp_units (void)
22785 {
22786   struct dwarf2_per_cu_data *per_cu, **last_chain;
22787
22788   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22789   per_cu = dwarf2_per_objfile->read_in_chain;
22790   while (per_cu != NULL)
22791     {
22792       per_cu->cu->last_used ++;
22793       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22794         dwarf2_mark (per_cu->cu);
22795       per_cu = per_cu->cu->read_in_chain;
22796     }
22797
22798   per_cu = dwarf2_per_objfile->read_in_chain;
22799   last_chain = &dwarf2_per_objfile->read_in_chain;
22800   while (per_cu != NULL)
22801     {
22802       struct dwarf2_per_cu_data *next_cu;
22803
22804       next_cu = per_cu->cu->read_in_chain;
22805
22806       if (!per_cu->cu->mark)
22807         {
22808           free_heap_comp_unit (per_cu->cu);
22809           *last_chain = next_cu;
22810         }
22811       else
22812         last_chain = &per_cu->cu->read_in_chain;
22813
22814       per_cu = next_cu;
22815     }
22816 }
22817
22818 /* Remove a single compilation unit from the cache.  */
22819
22820 static void
22821 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22822 {
22823   struct dwarf2_per_cu_data *per_cu, **last_chain;
22824
22825   per_cu = dwarf2_per_objfile->read_in_chain;
22826   last_chain = &dwarf2_per_objfile->read_in_chain;
22827   while (per_cu != NULL)
22828     {
22829       struct dwarf2_per_cu_data *next_cu;
22830
22831       next_cu = per_cu->cu->read_in_chain;
22832
22833       if (per_cu == target_per_cu)
22834         {
22835           free_heap_comp_unit (per_cu->cu);
22836           per_cu->cu = NULL;
22837           *last_chain = next_cu;
22838           break;
22839         }
22840       else
22841         last_chain = &per_cu->cu->read_in_chain;
22842
22843       per_cu = next_cu;
22844     }
22845 }
22846
22847 /* Release all extra memory associated with OBJFILE.  */
22848
22849 void
22850 dwarf2_free_objfile (struct objfile *objfile)
22851 {
22852   dwarf2_per_objfile
22853     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22854                                                   dwarf2_objfile_data_key);
22855
22856   if (dwarf2_per_objfile == NULL)
22857     return;
22858
22859   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
22860   free_cached_comp_units (NULL);
22861
22862   if (dwarf2_per_objfile->quick_file_names_table)
22863     htab_delete (dwarf2_per_objfile->quick_file_names_table);
22864
22865   if (dwarf2_per_objfile->line_header_hash)
22866     htab_delete (dwarf2_per_objfile->line_header_hash);
22867
22868   /* Everything else should be on the objfile obstack.  */
22869 }
22870
22871 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22872    We store these in a hash table separate from the DIEs, and preserve them
22873    when the DIEs are flushed out of cache.
22874
22875    The CU "per_cu" pointer is needed because offset alone is not enough to
22876    uniquely identify the type.  A file may have multiple .debug_types sections,
22877    or the type may come from a DWO file.  Furthermore, while it's more logical
22878    to use per_cu->section+offset, with Fission the section with the data is in
22879    the DWO file but we don't know that section at the point we need it.
22880    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22881    because we can enter the lookup routine, get_die_type_at_offset, from
22882    outside this file, and thus won't necessarily have PER_CU->cu.
22883    Fortunately, PER_CU is stable for the life of the objfile.  */
22884
22885 struct dwarf2_per_cu_offset_and_type
22886 {
22887   const struct dwarf2_per_cu_data *per_cu;
22888   sect_offset sect_off;
22889   struct type *type;
22890 };
22891
22892 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22893
22894 static hashval_t
22895 per_cu_offset_and_type_hash (const void *item)
22896 {
22897   const struct dwarf2_per_cu_offset_and_type *ofs
22898     = (const struct dwarf2_per_cu_offset_and_type *) item;
22899
22900   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
22901 }
22902
22903 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22904
22905 static int
22906 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22907 {
22908   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22909     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22910   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22911     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22912
22913   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22914           && ofs_lhs->sect_off == ofs_rhs->sect_off);
22915 }
22916
22917 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
22918    table if necessary.  For convenience, return TYPE.
22919
22920    The DIEs reading must have careful ordering to:
22921     * Not cause infite loops trying to read in DIEs as a prerequisite for
22922       reading current DIE.
22923     * Not trying to dereference contents of still incompletely read in types
22924       while reading in other DIEs.
22925     * Enable referencing still incompletely read in types just by a pointer to
22926       the type without accessing its fields.
22927
22928    Therefore caller should follow these rules:
22929      * Try to fetch any prerequisite types we may need to build this DIE type
22930        before building the type and calling set_die_type.
22931      * After building type call set_die_type for current DIE as soon as
22932        possible before fetching more types to complete the current type.
22933      * Make the type as complete as possible before fetching more types.  */
22934
22935 static struct type *
22936 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
22937 {
22938   struct dwarf2_per_cu_offset_and_type **slot, ofs;
22939   struct objfile *objfile = cu->objfile;
22940   struct attribute *attr;
22941   struct dynamic_prop prop;
22942
22943   /* For Ada types, make sure that the gnat-specific data is always
22944      initialized (if not already set).  There are a few types where
22945      we should not be doing so, because the type-specific area is
22946      already used to hold some other piece of info (eg: TYPE_CODE_FLT
22947      where the type-specific area is used to store the floatformat).
22948      But this is not a problem, because the gnat-specific information
22949      is actually not needed for these types.  */
22950   if (need_gnat_info (cu)
22951       && TYPE_CODE (type) != TYPE_CODE_FUNC
22952       && TYPE_CODE (type) != TYPE_CODE_FLT
22953       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
22954       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
22955       && TYPE_CODE (type) != TYPE_CODE_METHOD
22956       && !HAVE_GNAT_AUX_INFO (type))
22957     INIT_GNAT_SPECIFIC (type);
22958
22959   /* Read DW_AT_allocated and set in type.  */
22960   attr = dwarf2_attr (die, DW_AT_allocated, cu);
22961   if (attr_form_is_block (attr))
22962     {
22963       if (attr_to_dynamic_prop (attr, die, cu, &prop))
22964         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
22965     }
22966   else if (attr != NULL)
22967     {
22968       complaint (&symfile_complaints,
22969                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
22970                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
22971                  to_underlying (die->sect_off));
22972     }
22973
22974   /* Read DW_AT_associated and set in type.  */
22975   attr = dwarf2_attr (die, DW_AT_associated, cu);
22976   if (attr_form_is_block (attr))
22977     {
22978       if (attr_to_dynamic_prop (attr, die, cu, &prop))
22979         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
22980     }
22981   else if (attr != NULL)
22982     {
22983       complaint (&symfile_complaints,
22984                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
22985                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
22986                  to_underlying (die->sect_off));
22987     }
22988
22989   /* Read DW_AT_data_location and set in type.  */
22990   attr = dwarf2_attr (die, DW_AT_data_location, cu);
22991   if (attr_to_dynamic_prop (attr, die, cu, &prop))
22992     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
22993
22994   if (dwarf2_per_objfile->die_type_hash == NULL)
22995     {
22996       dwarf2_per_objfile->die_type_hash =
22997         htab_create_alloc_ex (127,
22998                               per_cu_offset_and_type_hash,
22999                               per_cu_offset_and_type_eq,
23000                               NULL,
23001                               &objfile->objfile_obstack,
23002                               hashtab_obstack_allocate,
23003                               dummy_obstack_deallocate);
23004     }
23005
23006   ofs.per_cu = cu->per_cu;
23007   ofs.sect_off = die->sect_off;
23008   ofs.type = type;
23009   slot = (struct dwarf2_per_cu_offset_and_type **)
23010     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23011   if (*slot)
23012     complaint (&symfile_complaints,
23013                _("A problem internal to GDB: DIE 0x%x has type already set"),
23014                to_underlying (die->sect_off));
23015   *slot = XOBNEW (&objfile->objfile_obstack,
23016                   struct dwarf2_per_cu_offset_and_type);
23017   **slot = ofs;
23018   return type;
23019 }
23020
23021 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23022    or return NULL if the die does not have a saved type.  */
23023
23024 static struct type *
23025 get_die_type_at_offset (sect_offset sect_off,
23026                         struct dwarf2_per_cu_data *per_cu)
23027 {
23028   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23029
23030   if (dwarf2_per_objfile->die_type_hash == NULL)
23031     return NULL;
23032
23033   ofs.per_cu = per_cu;
23034   ofs.sect_off = sect_off;
23035   slot = ((struct dwarf2_per_cu_offset_and_type *)
23036           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23037   if (slot)
23038     return slot->type;
23039   else
23040     return NULL;
23041 }
23042
23043 /* Look up the type for DIE in CU in die_type_hash,
23044    or return NULL if DIE does not have a saved type.  */
23045
23046 static struct type *
23047 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23048 {
23049   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23050 }
23051
23052 /* Add a dependence relationship from CU to REF_PER_CU.  */
23053
23054 static void
23055 dwarf2_add_dependence (struct dwarf2_cu *cu,
23056                        struct dwarf2_per_cu_data *ref_per_cu)
23057 {
23058   void **slot;
23059
23060   if (cu->dependencies == NULL)
23061     cu->dependencies
23062       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23063                               NULL, &cu->comp_unit_obstack,
23064                               hashtab_obstack_allocate,
23065                               dummy_obstack_deallocate);
23066
23067   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23068   if (*slot == NULL)
23069     *slot = ref_per_cu;
23070 }
23071
23072 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23073    Set the mark field in every compilation unit in the
23074    cache that we must keep because we are keeping CU.  */
23075
23076 static int
23077 dwarf2_mark_helper (void **slot, void *data)
23078 {
23079   struct dwarf2_per_cu_data *per_cu;
23080
23081   per_cu = (struct dwarf2_per_cu_data *) *slot;
23082
23083   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23084      reading of the chain.  As such dependencies remain valid it is not much
23085      useful to track and undo them during QUIT cleanups.  */
23086   if (per_cu->cu == NULL)
23087     return 1;
23088
23089   if (per_cu->cu->mark)
23090     return 1;
23091   per_cu->cu->mark = 1;
23092
23093   if (per_cu->cu->dependencies != NULL)
23094     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23095
23096   return 1;
23097 }
23098
23099 /* Set the mark field in CU and in every other compilation unit in the
23100    cache that we must keep because we are keeping CU.  */
23101
23102 static void
23103 dwarf2_mark (struct dwarf2_cu *cu)
23104 {
23105   if (cu->mark)
23106     return;
23107   cu->mark = 1;
23108   if (cu->dependencies != NULL)
23109     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23110 }
23111
23112 static void
23113 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23114 {
23115   while (per_cu)
23116     {
23117       per_cu->cu->mark = 0;
23118       per_cu = per_cu->cu->read_in_chain;
23119     }
23120 }
23121
23122 /* Trivial hash function for partial_die_info: the hash value of a DIE
23123    is its offset in .debug_info for this objfile.  */
23124
23125 static hashval_t
23126 partial_die_hash (const void *item)
23127 {
23128   const struct partial_die_info *part_die
23129     = (const struct partial_die_info *) item;
23130
23131   return to_underlying (part_die->sect_off);
23132 }
23133
23134 /* Trivial comparison function for partial_die_info structures: two DIEs
23135    are equal if they have the same offset.  */
23136
23137 static int
23138 partial_die_eq (const void *item_lhs, const void *item_rhs)
23139 {
23140   const struct partial_die_info *part_die_lhs
23141     = (const struct partial_die_info *) item_lhs;
23142   const struct partial_die_info *part_die_rhs
23143     = (const struct partial_die_info *) item_rhs;
23144
23145   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23146 }
23147
23148 static struct cmd_list_element *set_dwarf_cmdlist;
23149 static struct cmd_list_element *show_dwarf_cmdlist;
23150
23151 static void
23152 set_dwarf_cmd (char *args, int from_tty)
23153 {
23154   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23155              gdb_stdout);
23156 }
23157
23158 static void
23159 show_dwarf_cmd (char *args, int from_tty)
23160 {
23161   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23162 }
23163
23164 /* Free data associated with OBJFILE, if necessary.  */
23165
23166 static void
23167 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23168 {
23169   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23170   int ix;
23171
23172   /* Make sure we don't accidentally use dwarf2_per_objfile while
23173      cleaning up.  */
23174   dwarf2_per_objfile = NULL;
23175
23176   for (ix = 0; ix < data->n_comp_units; ++ix)
23177    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23178
23179   for (ix = 0; ix < data->n_type_units; ++ix)
23180     VEC_free (dwarf2_per_cu_ptr,
23181               data->all_type_units[ix]->per_cu.imported_symtabs);
23182   xfree (data->all_type_units);
23183
23184   VEC_free (dwarf2_section_info_def, data->types);
23185
23186   if (data->dwo_files)
23187     free_dwo_files (data->dwo_files, objfile);
23188   if (data->dwp_file)
23189     gdb_bfd_unref (data->dwp_file->dbfd);
23190
23191   if (data->dwz_file && data->dwz_file->dwz_bfd)
23192     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23193 }
23194
23195 \f
23196 /* The "save gdb-index" command.  */
23197
23198 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
23199    error checking.  */
23200
23201 static void
23202 file_write (FILE *file, const void *data, size_t size)
23203 {
23204   if (fwrite (data, 1, size, file) != size)
23205     error (_("couldn't data write to file"));
23206 }
23207
23208 /* Write the contents of VEC to FILE, with error checking.  */
23209
23210 template<class Elem>
23211 static void
23212 file_write (FILE *file, const std::vector<Elem> &vec)
23213 {
23214   file_write (file, vec.data (), vec.size() * sizeof (vec[0]));
23215 }
23216
23217 /* In-memory buffer to prepare data to be written later to a file.  */
23218 class data_buf
23219 {
23220 public:
23221   /* Add SIZE bytes at the end of the buffer.  Returns a pointer to
23222      the start of the new block.  */
23223   gdb_byte *append_space (size_t size)
23224   {
23225     m_vec.resize (m_vec.size () + size);
23226     return &*m_vec.end () - size;
23227   }
23228
23229   /* Copy DATA to the end of the buffer.  */
23230   template<typename T>
23231   void append_data (const T &data)
23232   {
23233     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23234                reinterpret_cast<const gdb_byte *> (&data + 1),
23235                append_space (sizeof (data)));
23236   }
23237
23238   /* Copy CSTR (a null-terminated string) to the end of the buffer.
23239      The terminating null is appended too.  */
23240   void append_cstr0 (const char *cstr)
23241   {
23242     const size_t size = strlen (cstr) + 1;
23243     std::copy (cstr, cstr + size, append_space (size));
23244   }
23245
23246   /* Return the size of the buffer.  */
23247   size_t size () const
23248   {
23249     return m_vec.size ();
23250   }
23251
23252   /* Write the buffer to FILE.  */
23253   void file_write (FILE *file) const
23254   {
23255     ::file_write (file, m_vec);
23256   }
23257
23258 private:
23259   std::vector<gdb_byte> m_vec;
23260 };
23261
23262 /* An entry in the symbol table.  */
23263 struct symtab_index_entry
23264 {
23265   /* The name of the symbol.  */
23266   const char *name;
23267   /* The offset of the name in the constant pool.  */
23268   offset_type index_offset;
23269   /* A sorted vector of the indices of all the CUs that hold an object
23270      of this name.  */
23271   std::vector<offset_type> cu_indices;
23272 };
23273
23274 /* The symbol table.  This is a power-of-2-sized hash table.  */
23275 struct mapped_symtab
23276 {
23277   mapped_symtab ()
23278   {
23279     data.resize (1024);
23280   }
23281
23282   offset_type n_elements = 0;
23283   std::vector<std::unique_ptr<symtab_index_entry>> data;
23284 };
23285
23286 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23287    the slot.
23288    
23289    Function is used only during write_hash_table so no index format backward
23290    compatibility is needed.  */
23291
23292 static std::unique_ptr<symtab_index_entry> &
23293 find_slot (struct mapped_symtab *symtab, const char *name)
23294 {
23295   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23296
23297   index = hash & (symtab->data.size () - 1);
23298   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23299
23300   for (;;)
23301     {
23302       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
23303         return symtab->data[index];
23304       index = (index + step) & (symtab->data.size () - 1);
23305     }
23306 }
23307
23308 /* Expand SYMTAB's hash table.  */
23309
23310 static void
23311 hash_expand (struct mapped_symtab *symtab)
23312 {
23313   auto old_entries = std::move (symtab->data);
23314
23315   symtab->data.clear ();
23316   symtab->data.resize (old_entries.size () * 2);
23317
23318   for (auto &it : old_entries)
23319     if (it != NULL)
23320       {
23321         auto &ref = find_slot (symtab, it->name);
23322         ref = std::move (it);
23323       }
23324 }
23325
23326 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23327    CU_INDEX is the index of the CU in which the symbol appears.
23328    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23329
23330 static void
23331 add_index_entry (struct mapped_symtab *symtab, const char *name,
23332                  int is_static, gdb_index_symbol_kind kind,
23333                  offset_type cu_index)
23334 {
23335   offset_type cu_index_and_attrs;
23336
23337   ++symtab->n_elements;
23338   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23339     hash_expand (symtab);
23340
23341   std::unique_ptr<symtab_index_entry> &slot = find_slot (symtab, name);
23342   if (slot == NULL)
23343     {
23344       slot.reset (new symtab_index_entry ());
23345       slot->name = name;
23346       /* index_offset is set later.  */
23347     }
23348
23349   cu_index_and_attrs = 0;
23350   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23351   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23352   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23353
23354   /* We don't want to record an index value twice as we want to avoid the
23355      duplication.
23356      We process all global symbols and then all static symbols
23357      (which would allow us to avoid the duplication by only having to check
23358      the last entry pushed), but a symbol could have multiple kinds in one CU.
23359      To keep things simple we don't worry about the duplication here and
23360      sort and uniqufy the list after we've processed all symbols.  */
23361   slot->cu_indices.push_back (cu_index_and_attrs);
23362 }
23363
23364 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23365
23366 static void
23367 uniquify_cu_indices (struct mapped_symtab *symtab)
23368 {
23369   for (const auto &entry : symtab->data)
23370     {
23371       if (entry && !entry->cu_indices.empty ())
23372         {
23373           unsigned int next_to_insert, next_to_check;
23374           offset_type last_value;
23375
23376           std::sort (entry->cu_indices.begin (), entry->cu_indices.end ());
23377
23378           last_value = entry->cu_indices[0];
23379           next_to_insert = 1;
23380           for (next_to_check = 1;
23381                next_to_check < entry->cu_indices.size ();
23382                ++next_to_check)
23383             if (entry->cu_indices[next_to_check] != last_value)
23384               {
23385                 last_value = entry->cu_indices[next_to_check];
23386                 entry->cu_indices[next_to_insert] = last_value;
23387                 ++next_to_insert;
23388               }
23389           entry->cu_indices.resize (next_to_insert);
23390         }
23391     }
23392 }
23393
23394 /* A form of 'const char *' suitable for container keys.  Only the
23395    pointer is stored.  The strings themselves are compared, not the
23396    pointers.  */
23397 class c_str_view
23398 {
23399 public:
23400   c_str_view (const char *cstr)
23401     : m_cstr (cstr)
23402   {}
23403
23404   bool operator== (const c_str_view &other) const
23405   {
23406     return strcmp (m_cstr, other.m_cstr) == 0;
23407   }
23408
23409 private:
23410   friend class c_str_view_hasher;
23411   const char *const m_cstr;
23412 };
23413
23414 /* A std::unordered_map::hasher for c_str_view that uses the right
23415    hash function for strings in a mapped index.  */
23416 class c_str_view_hasher
23417 {
23418 public:
23419   size_t operator () (const c_str_view &x) const
23420   {
23421     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23422   }
23423 };
23424
23425 /* A std::unordered_map::hasher for std::vector<>.  */
23426 template<typename T>
23427 class vector_hasher
23428 {
23429 public:
23430   size_t operator () (const std::vector<T> &key) const
23431   {
23432     return iterative_hash (key.data (),
23433                            sizeof (key.front ()) * key.size (), 0);
23434   }
23435 };
23436
23437 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23438    constant pool entries going into the data buffer CPOOL.  */
23439
23440 static void
23441 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23442 {
23443   {
23444     /* Elements are sorted vectors of the indices of all the CUs that
23445        hold an object of this name.  */
23446     std::unordered_map<std::vector<offset_type>, offset_type,
23447                        vector_hasher<offset_type>>
23448       symbol_hash_table;
23449
23450     /* We add all the index vectors to the constant pool first, to
23451        ensure alignment is ok.  */
23452     for (const std::unique_ptr<symtab_index_entry> &it : symtab->data)
23453       {
23454         if (it == NULL)
23455           continue;
23456         gdb_assert (it->index_offset == 0);
23457         const auto insertpair
23458           = symbol_hash_table.emplace (it->cu_indices, cpool.size ());
23459         it->index_offset = insertpair.first->second;
23460         if (!insertpair.second)
23461           continue;
23462         cpool.append_data (MAYBE_SWAP (it->cu_indices.size ()));
23463         for (const auto iter : it->cu_indices)
23464           cpool.append_data (MAYBE_SWAP (iter));
23465       }
23466   }
23467
23468   /* Now write out the hash table.  */
23469   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23470   for (const auto &it : symtab->data)
23471     {
23472       offset_type str_off, vec_off;
23473
23474       if (it != NULL)
23475         {
23476           const auto insertpair = str_table.emplace (it->name, cpool.size ());
23477           if (insertpair.second)
23478             cpool.append_cstr0 (it->name);
23479           str_off = insertpair.first->second;
23480           vec_off = it->index_offset;
23481         }
23482       else
23483         {
23484           /* While 0 is a valid constant pool index, it is not valid
23485              to have 0 for both offsets.  */
23486           str_off = 0;
23487           vec_off = 0;
23488         }
23489
23490       output.append_data (MAYBE_SWAP (str_off));
23491       output.append_data (MAYBE_SWAP (vec_off));
23492     }
23493 }
23494
23495 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23496
23497 /* Helper struct for building the address table.  */
23498 struct addrmap_index_data
23499 {
23500   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23501     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23502   {}
23503
23504   struct objfile *objfile;
23505   data_buf &addr_vec;
23506   psym_index_map &cu_index_htab;
23507
23508   /* Non-zero if the previous_* fields are valid.
23509      We can't write an entry until we see the next entry (since it is only then
23510      that we know the end of the entry).  */
23511   int previous_valid;
23512   /* Index of the CU in the table of all CUs in the index file.  */
23513   unsigned int previous_cu_index;
23514   /* Start address of the CU.  */
23515   CORE_ADDR previous_cu_start;
23516 };
23517
23518 /* Write an address entry to ADDR_VEC.  */
23519
23520 static void
23521 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23522                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23523 {
23524   CORE_ADDR baseaddr;
23525
23526   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23527
23528   store_unsigned_integer (addr_vec.append_space (8), 8, BFD_ENDIAN_LITTLE,
23529                           start - baseaddr);
23530   store_unsigned_integer (addr_vec.append_space (8), 8, BFD_ENDIAN_LITTLE,
23531                           end - baseaddr);
23532   addr_vec.append_data (MAYBE_SWAP (cu_index));
23533 }
23534
23535 /* Worker function for traversing an addrmap to build the address table.  */
23536
23537 static int
23538 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23539 {
23540   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23541   struct partial_symtab *pst = (struct partial_symtab *) obj;
23542
23543   if (data->previous_valid)
23544     add_address_entry (data->objfile, data->addr_vec,
23545                        data->previous_cu_start, start_addr,
23546                        data->previous_cu_index);
23547
23548   data->previous_cu_start = start_addr;
23549   if (pst != NULL)
23550     {
23551       const auto it = data->cu_index_htab.find (pst);
23552       gdb_assert (it != data->cu_index_htab.cend ());
23553       data->previous_cu_index = it->second;
23554       data->previous_valid = 1;
23555     }
23556   else
23557     data->previous_valid = 0;
23558
23559   return 0;
23560 }
23561
23562 /* Write OBJFILE's address map to ADDR_VEC.
23563    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23564    in the index file.  */
23565
23566 static void
23567 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23568                    psym_index_map &cu_index_htab)
23569 {
23570   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23571
23572   /* When writing the address table, we have to cope with the fact that
23573      the addrmap iterator only provides the start of a region; we have to
23574      wait until the next invocation to get the start of the next region.  */
23575
23576   addrmap_index_data.objfile = objfile;
23577   addrmap_index_data.previous_valid = 0;
23578
23579   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23580                    &addrmap_index_data);
23581
23582   /* It's highly unlikely the last entry (end address = 0xff...ff)
23583      is valid, but we should still handle it.
23584      The end address is recorded as the start of the next region, but that
23585      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23586      anyway.  */
23587   if (addrmap_index_data.previous_valid)
23588     add_address_entry (objfile, addr_vec,
23589                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23590                        addrmap_index_data.previous_cu_index);
23591 }
23592
23593 /* Return the symbol kind of PSYM.  */
23594
23595 static gdb_index_symbol_kind
23596 symbol_kind (struct partial_symbol *psym)
23597 {
23598   domain_enum domain = PSYMBOL_DOMAIN (psym);
23599   enum address_class aclass = PSYMBOL_CLASS (psym);
23600
23601   switch (domain)
23602     {
23603     case VAR_DOMAIN:
23604       switch (aclass)
23605         {
23606         case LOC_BLOCK:
23607           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23608         case LOC_TYPEDEF:
23609           return GDB_INDEX_SYMBOL_KIND_TYPE;
23610         case LOC_COMPUTED:
23611         case LOC_CONST_BYTES:
23612         case LOC_OPTIMIZED_OUT:
23613         case LOC_STATIC:
23614           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23615         case LOC_CONST:
23616           /* Note: It's currently impossible to recognize psyms as enum values
23617              short of reading the type info.  For now punt.  */
23618           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23619         default:
23620           /* There are other LOC_FOO values that one might want to classify
23621              as variables, but dwarf2read.c doesn't currently use them.  */
23622           return GDB_INDEX_SYMBOL_KIND_OTHER;
23623         }
23624     case STRUCT_DOMAIN:
23625       return GDB_INDEX_SYMBOL_KIND_TYPE;
23626     default:
23627       return GDB_INDEX_SYMBOL_KIND_OTHER;
23628     }
23629 }
23630
23631 /* Add a list of partial symbols to SYMTAB.  */
23632
23633 static void
23634 write_psymbols (struct mapped_symtab *symtab,
23635                 std::unordered_set<partial_symbol *> &psyms_seen,
23636                 struct partial_symbol **psymp,
23637                 int count,
23638                 offset_type cu_index,
23639                 int is_static)
23640 {
23641   for (; count-- > 0; ++psymp)
23642     {
23643       struct partial_symbol *psym = *psymp;
23644
23645       if (SYMBOL_LANGUAGE (psym) == language_ada)
23646         error (_("Ada is not currently supported by the index"));
23647
23648       /* Only add a given psymbol once.  */
23649       if (psyms_seen.insert (psym).second)
23650         {
23651           gdb_index_symbol_kind kind = symbol_kind (psym);
23652
23653           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23654                            is_static, kind, cu_index);
23655         }
23656     }
23657 }
23658
23659 /* A helper struct used when iterating over debug_types.  */
23660 struct signatured_type_index_data
23661 {
23662   signatured_type_index_data (data_buf &types_list_,
23663                               std::unordered_set<partial_symbol *> &psyms_seen_)
23664     : types_list (types_list_), psyms_seen (psyms_seen_)
23665   {}
23666
23667   struct objfile *objfile;
23668   struct mapped_symtab *symtab;
23669   data_buf &types_list;
23670   std::unordered_set<partial_symbol *> &psyms_seen;
23671   int cu_index;
23672 };
23673
23674 /* A helper function that writes a single signatured_type to an
23675    obstack.  */
23676
23677 static int
23678 write_one_signatured_type (void **slot, void *d)
23679 {
23680   struct signatured_type_index_data *info
23681     = (struct signatured_type_index_data *) d;
23682   struct signatured_type *entry = (struct signatured_type *) *slot;
23683   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23684
23685   write_psymbols (info->symtab,
23686                   info->psyms_seen,
23687                   info->objfile->global_psymbols.list
23688                   + psymtab->globals_offset,
23689                   psymtab->n_global_syms, info->cu_index,
23690                   0);
23691   write_psymbols (info->symtab,
23692                   info->psyms_seen,
23693                   info->objfile->static_psymbols.list
23694                   + psymtab->statics_offset,
23695                   psymtab->n_static_syms, info->cu_index,
23696                   1);
23697
23698   store_unsigned_integer (info->types_list.append_space (8), 8,
23699                           BFD_ENDIAN_LITTLE,
23700                           to_underlying (entry->per_cu.sect_off));
23701   store_unsigned_integer (info->types_list.append_space (8), 8,
23702                           BFD_ENDIAN_LITTLE,
23703                           to_underlying (entry->type_offset_in_tu));
23704   store_unsigned_integer (info->types_list.append_space (8), 8,
23705                           BFD_ENDIAN_LITTLE, entry->signature);
23706
23707   ++info->cu_index;
23708
23709   return 1;
23710 }
23711
23712 /* Recurse into all "included" dependencies and write their symbols as
23713    if they appeared in this psymtab.  */
23714
23715 static void
23716 recursively_write_psymbols (struct objfile *objfile,
23717                             struct partial_symtab *psymtab,
23718                             struct mapped_symtab *symtab,
23719                             std::unordered_set<partial_symbol *> &psyms_seen,
23720                             offset_type cu_index)
23721 {
23722   int i;
23723
23724   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23725     if (psymtab->dependencies[i]->user != NULL)
23726       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23727                                   symtab, psyms_seen, cu_index);
23728
23729   write_psymbols (symtab,
23730                   psyms_seen,
23731                   objfile->global_psymbols.list + psymtab->globals_offset,
23732                   psymtab->n_global_syms, cu_index,
23733                   0);
23734   write_psymbols (symtab,
23735                   psyms_seen,
23736                   objfile->static_psymbols.list + psymtab->statics_offset,
23737                   psymtab->n_static_syms, cu_index,
23738                   1);
23739 }
23740
23741 /* Closes FILE on scope exit.  */
23742 struct file_closer
23743 {
23744   explicit file_closer (FILE *file)
23745     : m_file (file)
23746   {}
23747
23748   ~file_closer ()
23749   { fclose (m_file); }
23750
23751 private:
23752   FILE *m_file;
23753 };
23754
23755 /* Create an index file for OBJFILE in the directory DIR.  */
23756
23757 static void
23758 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23759 {
23760   if (dwarf2_per_objfile->using_index)
23761     error (_("Cannot use an index to create the index"));
23762
23763   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23764     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23765
23766   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23767     return;
23768
23769   struct stat st;
23770   if (stat (objfile_name (objfile), &st) < 0)
23771     perror_with_name (objfile_name (objfile));
23772
23773   std::string filename (std::string (dir) + SLASH_STRING
23774                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23775
23776   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb");
23777   if (!out_file)
23778     error (_("Can't open `%s' for writing"), filename.c_str ());
23779
23780   file_closer close_out_file (out_file);
23781   gdb::unlinker unlink_file (filename.c_str ());
23782
23783   mapped_symtab symtab;
23784   data_buf cu_list;
23785   std::unordered_set<partial_symbol *> psyms_seen;
23786
23787   /* While we're scanning CU's create a table that maps a psymtab pointer
23788      (which is what addrmap records) to its index (which is what is recorded
23789      in the index file).  This will later be needed to write the address
23790      table.  */
23791   psym_index_map cu_index_htab;
23792   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23793
23794   /* The CU list is already sorted, so we don't need to do additional
23795      work here.  Also, the debug_types entries do not appear in
23796      all_comp_units, but only in their own hash table.  */
23797   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23798     {
23799       struct dwarf2_per_cu_data *per_cu
23800         = dwarf2_per_objfile->all_comp_units[i];
23801       struct partial_symtab *psymtab = per_cu->v.psymtab;
23802
23803       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23804          It may be referenced from a local scope but in such case it does not
23805          need to be present in .gdb_index.  */
23806       if (psymtab == NULL)
23807         continue;
23808
23809       if (psymtab->user == NULL)
23810         recursively_write_psymbols (objfile, psymtab, &symtab,
23811                                     psyms_seen, i);
23812
23813       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23814       gdb_assert (insertpair.second);
23815
23816       store_unsigned_integer (cu_list.append_space (8), 8,
23817                               BFD_ENDIAN_LITTLE,
23818                               to_underlying (per_cu->sect_off));
23819       store_unsigned_integer (cu_list.append_space (8), 8,
23820                               BFD_ENDIAN_LITTLE, per_cu->length);
23821     }
23822
23823   /* Dump the address map.  */
23824   data_buf addr_vec;
23825   write_address_map (objfile, addr_vec, cu_index_htab);
23826
23827   /* Write out the .debug_type entries, if any.  */
23828   data_buf types_cu_list;
23829   if (dwarf2_per_objfile->signatured_types)
23830     {
23831       signatured_type_index_data sig_data (types_cu_list,
23832                                            psyms_seen);
23833
23834       sig_data.objfile = objfile;
23835       sig_data.symtab = &symtab;
23836       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23837       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23838                               write_one_signatured_type, &sig_data);
23839     }
23840
23841   /* Now that we've processed all symbols we can shrink their cu_indices
23842      lists.  */
23843   uniquify_cu_indices (&symtab);
23844
23845   data_buf symtab_vec, constant_pool;
23846   write_hash_table (&symtab, symtab_vec, constant_pool);
23847
23848   data_buf contents;
23849   const offset_type size_of_contents = 6 * sizeof (offset_type);
23850   offset_type total_len = size_of_contents;
23851
23852   /* The version number.  */
23853   contents.append_data (MAYBE_SWAP (8));
23854
23855   /* The offset of the CU list from the start of the file.  */
23856   contents.append_data (MAYBE_SWAP (total_len));
23857   total_len += cu_list.size ();
23858
23859   /* The offset of the types CU list from the start of the file.  */
23860   contents.append_data (MAYBE_SWAP (total_len));
23861   total_len += types_cu_list.size ();
23862
23863   /* The offset of the address table from the start of the file.  */
23864   contents.append_data (MAYBE_SWAP (total_len));
23865   total_len += addr_vec.size ();
23866
23867   /* The offset of the symbol table from the start of the file.  */
23868   contents.append_data (MAYBE_SWAP (total_len));
23869   total_len += symtab_vec.size ();
23870
23871   /* The offset of the constant pool from the start of the file.  */
23872   contents.append_data (MAYBE_SWAP (total_len));
23873   total_len += constant_pool.size ();
23874
23875   gdb_assert (contents.size () == size_of_contents);
23876
23877   contents.file_write (out_file);
23878   cu_list.file_write (out_file);
23879   types_cu_list.file_write (out_file);
23880   addr_vec.file_write (out_file);
23881   symtab_vec.file_write (out_file);
23882   constant_pool.file_write (out_file);
23883
23884   /* We want to keep the file.  */
23885   unlink_file.keep ();
23886 }
23887
23888 /* Implementation of the `save gdb-index' command.
23889    
23890    Note that the file format used by this command is documented in the
23891    GDB manual.  Any changes here must be documented there.  */
23892
23893 static void
23894 save_gdb_index_command (char *arg, int from_tty)
23895 {
23896   struct objfile *objfile;
23897
23898   if (!arg || !*arg)
23899     error (_("usage: save gdb-index DIRECTORY"));
23900
23901   ALL_OBJFILES (objfile)
23902   {
23903     struct stat st;
23904
23905     /* If the objfile does not correspond to an actual file, skip it.  */
23906     if (stat (objfile_name (objfile), &st) < 0)
23907       continue;
23908
23909     dwarf2_per_objfile
23910       = (struct dwarf2_per_objfile *) objfile_data (objfile,
23911                                                     dwarf2_objfile_data_key);
23912     if (dwarf2_per_objfile)
23913       {
23914
23915         TRY
23916           {
23917             write_psymtabs_to_index (objfile, arg);
23918           }
23919         CATCH (except, RETURN_MASK_ERROR)
23920           {
23921             exception_fprintf (gdb_stderr, except,
23922                                _("Error while writing index for `%s': "),
23923                                objfile_name (objfile));
23924           }
23925         END_CATCH
23926       }
23927   }
23928 }
23929
23930 \f
23931
23932 int dwarf_always_disassemble;
23933
23934 static void
23935 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
23936                                struct cmd_list_element *c, const char *value)
23937 {
23938   fprintf_filtered (file,
23939                     _("Whether to always disassemble "
23940                       "DWARF expressions is %s.\n"),
23941                     value);
23942 }
23943
23944 static void
23945 show_check_physname (struct ui_file *file, int from_tty,
23946                      struct cmd_list_element *c, const char *value)
23947 {
23948   fprintf_filtered (file,
23949                     _("Whether to check \"physname\" is %s.\n"),
23950                     value);
23951 }
23952
23953 void _initialize_dwarf2_read (void);
23954
23955 void
23956 _initialize_dwarf2_read (void)
23957 {
23958   struct cmd_list_element *c;
23959
23960   dwarf2_objfile_data_key
23961     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
23962
23963   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
23964 Set DWARF specific variables.\n\
23965 Configure DWARF variables such as the cache size"),
23966                   &set_dwarf_cmdlist, "maintenance set dwarf ",
23967                   0/*allow-unknown*/, &maintenance_set_cmdlist);
23968
23969   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
23970 Show DWARF specific variables\n\
23971 Show DWARF variables such as the cache size"),
23972                   &show_dwarf_cmdlist, "maintenance show dwarf ",
23973                   0/*allow-unknown*/, &maintenance_show_cmdlist);
23974
23975   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
23976                             &dwarf_max_cache_age, _("\
23977 Set the upper bound on the age of cached DWARF compilation units."), _("\
23978 Show the upper bound on the age of cached DWARF compilation units."), _("\
23979 A higher limit means that cached compilation units will be stored\n\
23980 in memory longer, and more total memory will be used.  Zero disables\n\
23981 caching, which can slow down startup."),
23982                             NULL,
23983                             show_dwarf_max_cache_age,
23984                             &set_dwarf_cmdlist,
23985                             &show_dwarf_cmdlist);
23986
23987   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
23988                            &dwarf_always_disassemble, _("\
23989 Set whether `info address' always disassembles DWARF expressions."), _("\
23990 Show whether `info address' always disassembles DWARF expressions."), _("\
23991 When enabled, DWARF expressions are always printed in an assembly-like\n\
23992 syntax.  When disabled, expressions will be printed in a more\n\
23993 conversational style, when possible."),
23994                            NULL,
23995                            show_dwarf_always_disassemble,
23996                            &set_dwarf_cmdlist,
23997                            &show_dwarf_cmdlist);
23998
23999   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24000 Set debugging of the DWARF reader."), _("\
24001 Show debugging of the DWARF reader."), _("\
24002 When enabled (non-zero), debugging messages are printed during DWARF\n\
24003 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24004 information.  A value greater than 1 provides more verbose information."),
24005                             NULL,
24006                             NULL,
24007                             &setdebuglist, &showdebuglist);
24008
24009   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24010 Set debugging of the DWARF DIE reader."), _("\
24011 Show debugging of the DWARF DIE reader."), _("\
24012 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24013 The value is the maximum depth to print."),
24014                              NULL,
24015                              NULL,
24016                              &setdebuglist, &showdebuglist);
24017
24018   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24019 Set debugging of the dwarf line reader."), _("\
24020 Show debugging of the dwarf line reader."), _("\
24021 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24022 A value of 1 (one) provides basic information.\n\
24023 A value greater than 1 provides more verbose information."),
24024                              NULL,
24025                              NULL,
24026                              &setdebuglist, &showdebuglist);
24027
24028   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24029 Set cross-checking of \"physname\" code against demangler."), _("\
24030 Show cross-checking of \"physname\" code against demangler."), _("\
24031 When enabled, GDB's internal \"physname\" code is checked against\n\
24032 the demangler."),
24033                            NULL, show_check_physname,
24034                            &setdebuglist, &showdebuglist);
24035
24036   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24037                            no_class, &use_deprecated_index_sections, _("\
24038 Set whether to use deprecated gdb_index sections."), _("\
24039 Show whether to use deprecated gdb_index sections."), _("\
24040 When enabled, deprecated .gdb_index sections are used anyway.\n\
24041 Normally they are ignored either because of a missing feature or\n\
24042 performance issue.\n\
24043 Warning: This option must be enabled before gdb reads the file."),
24044                            NULL,
24045                            NULL,
24046                            &setlist, &showlist);
24047
24048   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24049                _("\
24050 Save a gdb-index file.\n\
24051 Usage: save gdb-index DIRECTORY"),
24052                &save_cmdlist);
24053   set_cmd_completer (c, filename_completer);
24054
24055   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24056                                                         &dwarf2_locexpr_funcs);
24057   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24058                                                         &dwarf2_loclist_funcs);
24059
24060   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24061                                         &dwarf2_block_frame_base_locexpr_funcs);
24062   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24063                                         &dwarf2_block_frame_base_loclist_funcs);
24064 }