Move fixup_partial_die to partial_die_info::fixup
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 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 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 /* When == 1, print basic high level tracing messages.
91    When > 1, be more verbose.
92    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
93 static unsigned int dwarf_read_debug = 0;
94
95 /* When non-zero, dump DIEs after they are read in.  */
96 static unsigned int dwarf_die_debug = 0;
97
98 /* When non-zero, dump line number entries as they are read in.  */
99 static unsigned int dwarf_line_debug = 0;
100
101 /* When non-zero, cross-check physname against demangler.  */
102 static int check_physname = 0;
103
104 /* When non-zero, do not reject deprecated .gdb_index sections.  */
105 static int use_deprecated_index_sections = 0;
106
107 static const struct objfile_data *dwarf2_objfile_data_key;
108
109 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
110
111 static int dwarf2_locexpr_index;
112 static int dwarf2_loclist_index;
113 static int dwarf2_locexpr_block_index;
114 static int dwarf2_loclist_block_index;
115
116 /* A descriptor for dwarf sections.
117
118    S.ASECTION, SIZE are typically initialized when the objfile is first
119    scanned.  BUFFER, READIN are filled in later when the section is read.
120    If the section contained compressed data then SIZE is updated to record
121    the uncompressed size of the section.
122
123    DWP file format V2 introduces a wrinkle that is easiest to handle by
124    creating the concept of virtual sections contained within a real section.
125    In DWP V2 the sections of the input DWO files are concatenated together
126    into one section, but section offsets are kept relative to the original
127    input section.
128    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
129    the real section this "virtual" section is contained in, and BUFFER,SIZE
130    describe the virtual section.  */
131
132 struct dwarf2_section_info
133 {
134   union
135   {
136     /* If this is a real section, the bfd section.  */
137     asection *section;
138     /* If this is a virtual section, pointer to the containing ("real")
139        section.  */
140     struct dwarf2_section_info *containing_section;
141   } s;
142   /* Pointer to section data, only valid if readin.  */
143   const gdb_byte *buffer;
144   /* The size of the section, real or virtual.  */
145   bfd_size_type size;
146   /* If this is a virtual section, the offset in the real section.
147      Only valid if is_virtual.  */
148   bfd_size_type virtual_offset;
149   /* True if we have tried to read this section.  */
150   char readin;
151   /* True if this is a virtual section, False otherwise.
152      This specifies which of s.section and s.containing_section to use.  */
153   char is_virtual;
154 };
155
156 typedef struct dwarf2_section_info dwarf2_section_info_def;
157 DEF_VEC_O (dwarf2_section_info_def);
158
159 /* All offsets in the index are of this type.  It must be
160    architecture-independent.  */
161 typedef uint32_t offset_type;
162
163 DEF_VEC_I (offset_type);
164
165 /* Ensure only legit values are used.  */
166 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
167   do { \
168     gdb_assert ((unsigned int) (value) <= 1); \
169     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
170   } while (0)
171
172 /* Ensure only legit values are used.  */
173 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
174   do { \
175     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
176                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
177     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
178   } while (0)
179
180 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
181 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
182   do { \
183     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
184     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
185   } while (0)
186
187 #if WORDS_BIGENDIAN
188
189 /* Convert VALUE between big- and little-endian.  */
190
191 static offset_type
192 byte_swap (offset_type value)
193 {
194   offset_type result;
195
196   result = (value & 0xff) << 24;
197   result |= (value & 0xff00) << 8;
198   result |= (value & 0xff0000) >> 8;
199   result |= (value & 0xff000000) >> 24;
200   return result;
201 }
202
203 #define MAYBE_SWAP(V)  byte_swap (V)
204
205 #else
206 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
207 #endif /* WORDS_BIGENDIAN */
208
209 /* An index into a (C++) symbol name component in a symbol name as
210    recorded in the mapped_index's symbol table.  For each C++ symbol
211    in the symbol table, we record one entry for the start of each
212    component in the symbol in a table of name components, and then
213    sort the table, in order to be able to binary search symbol names,
214    ignoring leading namespaces, both completion and regular look up.
215    For example, for symbol "A::B::C", we'll have an entry that points
216    to "A::B::C", another that points to "B::C", and another for "C".
217    Note that function symbols in GDB index have no parameter
218    information, just the function/method names.  You can convert a
219    name_component to a "const char *" using the
220    'mapped_index::symbol_name_at(offset_type)' method.  */
221
222 struct name_component
223 {
224   /* Offset in the symbol name where the component starts.  Stored as
225      a (32-bit) offset instead of a pointer to save memory and improve
226      locality on 64-bit architectures.  */
227   offset_type name_offset;
228
229   /* The symbol's index in the symbol and constant pool tables of a
230      mapped_index.  */
231   offset_type idx;
232 };
233
234 /* Base class containing bits shared by both .gdb_index and
235    .debug_name indexes.  */
236
237 struct mapped_index_base
238 {
239   /* The name_component table (a sorted vector).  See name_component's
240      description above.  */
241   std::vector<name_component> name_components;
242
243   /* How NAME_COMPONENTS is sorted.  */
244   enum case_sensitivity name_components_casing;
245
246   /* Return the number of names in the symbol table.  */
247   virtual size_t symbol_name_count () const = 0;
248
249   /* Get the name of the symbol at IDX in the symbol table.  */
250   virtual const char *symbol_name_at (offset_type idx) const = 0;
251
252   /* Return whether the name at IDX in the symbol table should be
253      ignored.  */
254   virtual bool symbol_name_slot_invalid (offset_type idx) const
255   {
256     return false;
257   }
258
259   /* Build the symbol name component sorted vector, if we haven't
260      yet.  */
261   void build_name_components ();
262
263   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
264      possible matches for LN_NO_PARAMS in the name component
265      vector.  */
266   std::pair<std::vector<name_component>::const_iterator,
267             std::vector<name_component>::const_iterator>
268     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
269
270   /* Prevent deleting/destroying via a base class pointer.  */
271 protected:
272   ~mapped_index_base() = default;
273 };
274
275 /* A description of the mapped index.  The file format is described in
276    a comment by the code that writes the index.  */
277 struct mapped_index final : public mapped_index_base
278 {
279   /* A slot/bucket in the symbol table hash.  */
280   struct symbol_table_slot
281   {
282     const offset_type name;
283     const offset_type vec;
284   };
285
286   /* Index data format version.  */
287   int version;
288
289   /* The total length of the buffer.  */
290   off_t total_size;
291
292   /* The address table data.  */
293   gdb::array_view<const gdb_byte> address_table;
294
295   /* The symbol table, implemented as a hash table.  */
296   gdb::array_view<symbol_table_slot> symbol_table;
297
298   /* A pointer to the constant pool.  */
299   const char *constant_pool;
300
301   bool symbol_name_slot_invalid (offset_type idx) const override
302   {
303     const auto &bucket = this->symbol_table[idx];
304     return bucket.name == 0 && bucket.vec;
305   }
306
307   /* Convenience method to get at the name of the symbol at IDX in the
308      symbol table.  */
309   const char *symbol_name_at (offset_type idx) const override
310   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
311
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size (); }
314 };
315
316 /* A description of the mapped .debug_names.
317    Uninitialized map has CU_COUNT 0.  */
318 struct mapped_debug_names final : public mapped_index_base
319 {
320   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
321   : dwarf2_per_objfile (dwarf2_per_objfile_)
322   {}
323
324   struct dwarf2_per_objfile *dwarf2_per_objfile;
325   bfd_endian dwarf5_byte_order;
326   bool dwarf5_is_dwarf64;
327   bool augmentation_is_gdb;
328   uint8_t offset_size;
329   uint32_t cu_count = 0;
330   uint32_t tu_count, bucket_count, name_count;
331   const gdb_byte *cu_table_reordered, *tu_table_reordered;
332   const uint32_t *bucket_table_reordered, *hash_table_reordered;
333   const gdb_byte *name_table_string_offs_reordered;
334   const gdb_byte *name_table_entry_offs_reordered;
335   const gdb_byte *entry_pool;
336
337   struct index_val
338   {
339     ULONGEST dwarf_tag;
340     struct attr
341     {
342       /* Attribute name DW_IDX_*.  */
343       ULONGEST dw_idx;
344
345       /* Attribute form DW_FORM_*.  */
346       ULONGEST form;
347
348       /* Value if FORM is DW_FORM_implicit_const.  */
349       LONGEST implicit_const;
350     };
351     std::vector<attr> attr_vec;
352   };
353
354   std::unordered_map<ULONGEST, index_val> abbrev_map;
355
356   const char *namei_to_name (uint32_t namei) const;
357
358   /* Implementation of the mapped_index_base virtual interface, for
359      the name_components cache.  */
360
361   const char *symbol_name_at (offset_type idx) const override
362   { return namei_to_name (idx); }
363
364   size_t symbol_name_count () const override
365   { return this->name_count; }
366 };
367
368 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
369 DEF_VEC_P (dwarf2_per_cu_ptr);
370
371 struct tu_stats
372 {
373   int nr_uniq_abbrev_tables;
374   int nr_symtabs;
375   int nr_symtab_sharers;
376   int nr_stmt_less_type_units;
377   int nr_all_type_units_reallocs;
378 };
379
380 /* Collection of data recorded per objfile.
381    This hangs off of dwarf2_objfile_data_key.  */
382
383 struct dwarf2_per_objfile : public allocate_on_obstack
384 {
385   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
386      dwarf2 section names, or is NULL if the standard ELF names are
387      used.  */
388   dwarf2_per_objfile (struct objfile *objfile,
389                       const dwarf2_debug_sections *names);
390
391   ~dwarf2_per_objfile ();
392
393   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
394
395   /* Free all cached compilation units.  */
396   void free_cached_comp_units ();
397 private:
398   /* This function is mapped across the sections and remembers the
399      offset and size of each of the debugging sections we are
400      interested in.  */
401   void locate_sections (bfd *abfd, asection *sectp,
402                         const dwarf2_debug_sections &names);
403
404 public:
405   dwarf2_section_info info {};
406   dwarf2_section_info abbrev {};
407   dwarf2_section_info line {};
408   dwarf2_section_info loc {};
409   dwarf2_section_info loclists {};
410   dwarf2_section_info macinfo {};
411   dwarf2_section_info macro {};
412   dwarf2_section_info str {};
413   dwarf2_section_info line_str {};
414   dwarf2_section_info ranges {};
415   dwarf2_section_info rnglists {};
416   dwarf2_section_info addr {};
417   dwarf2_section_info frame {};
418   dwarf2_section_info eh_frame {};
419   dwarf2_section_info gdb_index {};
420   dwarf2_section_info debug_names {};
421   dwarf2_section_info debug_aranges {};
422
423   VEC (dwarf2_section_info_def) *types = NULL;
424
425   /* Back link.  */
426   struct objfile *objfile = NULL;
427
428   /* Table of all the compilation units.  This is used to locate
429      the target compilation unit of a particular reference.  */
430   struct dwarf2_per_cu_data **all_comp_units = NULL;
431
432   /* The number of compilation units in ALL_COMP_UNITS.  */
433   int n_comp_units = 0;
434
435   /* The number of .debug_types-related CUs.  */
436   int n_type_units = 0;
437
438   /* The number of elements allocated in all_type_units.
439      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
440   int n_allocated_type_units = 0;
441
442   /* The .debug_types-related CUs (TUs).
443      This is stored in malloc space because we may realloc it.  */
444   struct signatured_type **all_type_units = NULL;
445
446   /* Table of struct type_unit_group objects.
447      The hash key is the DW_AT_stmt_list value.  */
448   htab_t type_unit_groups {};
449
450   /* A table mapping .debug_types signatures to its signatured_type entry.
451      This is NULL if the .debug_types section hasn't been read in yet.  */
452   htab_t signatured_types {};
453
454   /* Type unit statistics, to see how well the scaling improvements
455      are doing.  */
456   struct tu_stats tu_stats {};
457
458   /* A chain of compilation units that are currently read in, so that
459      they can be freed later.  */
460   dwarf2_per_cu_data *read_in_chain = NULL;
461
462   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
463      This is NULL if the table hasn't been allocated yet.  */
464   htab_t dwo_files {};
465
466   /* True if we've checked for whether there is a DWP file.  */
467   bool dwp_checked = false;
468
469   /* The DWP file if there is one, or NULL.  */
470   struct dwp_file *dwp_file = NULL;
471
472   /* The shared '.dwz' file, if one exists.  This is used when the
473      original data was compressed using 'dwz -m'.  */
474   struct dwz_file *dwz_file = NULL;
475
476   /* A flag indicating whether this objfile has a section loaded at a
477      VMA of 0.  */
478   bool has_section_at_zero = false;
479
480   /* True if we are using the mapped index,
481      or we are faking it for OBJF_READNOW's sake.  */
482   bool using_index = false;
483
484   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
485   mapped_index *index_table = NULL;
486
487   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
488   std::unique_ptr<mapped_debug_names> debug_names_table;
489
490   /* When using index_table, this keeps track of all quick_file_names entries.
491      TUs typically share line table entries with a CU, so we maintain a
492      separate table of all line table entries to support the sharing.
493      Note that while there can be way more TUs than CUs, we've already
494      sorted all the TUs into "type unit groups", grouped by their
495      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
496      CU and its associated TU group if there is one.  */
497   htab_t quick_file_names_table {};
498
499   /* Set during partial symbol reading, to prevent queueing of full
500      symbols.  */
501   bool reading_partial_symbols = false;
502
503   /* Table mapping type DIEs to their struct type *.
504      This is NULL if not allocated yet.
505      The mapping is done via (CU/TU + DIE offset) -> type.  */
506   htab_t die_type_hash {};
507
508   /* The CUs we recently read.  */
509   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
510
511   /* Table containing line_header indexed by offset and offset_in_dwz.  */
512   htab_t line_header_hash {};
513
514   /* Table containing all filenames.  This is an optional because the
515      table is lazily constructed on first access.  */
516   gdb::optional<filename_seen_cache> filenames_cache;
517 };
518
519 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
520
521 struct dwarf2_per_objfile *
522 get_dwarf2_per_objfile (struct objfile *objfile)
523 {
524   return ((struct dwarf2_per_objfile *)
525           objfile_data (objfile, dwarf2_objfile_data_key));
526 }
527
528 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
529
530 void
531 set_dwarf2_per_objfile (struct objfile *objfile,
532                         struct dwarf2_per_objfile *dwarf2_per_objfile)
533 {
534   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
535   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
536 }
537
538 /* Default names of the debugging sections.  */
539
540 /* Note that if the debugging section has been compressed, it might
541    have a name like .zdebug_info.  */
542
543 static const struct dwarf2_debug_sections dwarf2_elf_names =
544 {
545   { ".debug_info", ".zdebug_info" },
546   { ".debug_abbrev", ".zdebug_abbrev" },
547   { ".debug_line", ".zdebug_line" },
548   { ".debug_loc", ".zdebug_loc" },
549   { ".debug_loclists", ".zdebug_loclists" },
550   { ".debug_macinfo", ".zdebug_macinfo" },
551   { ".debug_macro", ".zdebug_macro" },
552   { ".debug_str", ".zdebug_str" },
553   { ".debug_line_str", ".zdebug_line_str" },
554   { ".debug_ranges", ".zdebug_ranges" },
555   { ".debug_rnglists", ".zdebug_rnglists" },
556   { ".debug_types", ".zdebug_types" },
557   { ".debug_addr", ".zdebug_addr" },
558   { ".debug_frame", ".zdebug_frame" },
559   { ".eh_frame", NULL },
560   { ".gdb_index", ".zgdb_index" },
561   { ".debug_names", ".zdebug_names" },
562   { ".debug_aranges", ".zdebug_aranges" },
563   23
564 };
565
566 /* List of DWO/DWP sections.  */
567
568 static const struct dwop_section_names
569 {
570   struct dwarf2_section_names abbrev_dwo;
571   struct dwarf2_section_names info_dwo;
572   struct dwarf2_section_names line_dwo;
573   struct dwarf2_section_names loc_dwo;
574   struct dwarf2_section_names loclists_dwo;
575   struct dwarf2_section_names macinfo_dwo;
576   struct dwarf2_section_names macro_dwo;
577   struct dwarf2_section_names str_dwo;
578   struct dwarf2_section_names str_offsets_dwo;
579   struct dwarf2_section_names types_dwo;
580   struct dwarf2_section_names cu_index;
581   struct dwarf2_section_names tu_index;
582 }
583 dwop_section_names =
584 {
585   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
586   { ".debug_info.dwo", ".zdebug_info.dwo" },
587   { ".debug_line.dwo", ".zdebug_line.dwo" },
588   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
589   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
590   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
591   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
592   { ".debug_str.dwo", ".zdebug_str.dwo" },
593   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
594   { ".debug_types.dwo", ".zdebug_types.dwo" },
595   { ".debug_cu_index", ".zdebug_cu_index" },
596   { ".debug_tu_index", ".zdebug_tu_index" },
597 };
598
599 /* local data types */
600
601 /* The data in a compilation unit header, after target2host
602    translation, looks like this.  */
603 struct comp_unit_head
604 {
605   unsigned int length;
606   short version;
607   unsigned char addr_size;
608   unsigned char signed_addr_p;
609   sect_offset abbrev_sect_off;
610
611   /* Size of file offsets; either 4 or 8.  */
612   unsigned int offset_size;
613
614   /* Size of the length field; either 4 or 12.  */
615   unsigned int initial_length_size;
616
617   enum dwarf_unit_type unit_type;
618
619   /* Offset to the first byte of this compilation unit header in the
620      .debug_info section, for resolving relative reference dies.  */
621   sect_offset sect_off;
622
623   /* Offset to first die in this cu from the start of the cu.
624      This will be the first byte following the compilation unit header.  */
625   cu_offset first_die_cu_offset;
626
627   /* 64-bit signature of this type unit - it is valid only for
628      UNIT_TYPE DW_UT_type.  */
629   ULONGEST signature;
630
631   /* For types, offset in the type's DIE of the type defined by this TU.  */
632   cu_offset type_cu_offset_in_tu;
633 };
634
635 /* Type used for delaying computation of method physnames.
636    See comments for compute_delayed_physnames.  */
637 struct delayed_method_info
638 {
639   /* The type to which the method is attached, i.e., its parent class.  */
640   struct type *type;
641
642   /* The index of the method in the type's function fieldlists.  */
643   int fnfield_index;
644
645   /* The index of the method in the fieldlist.  */
646   int index;
647
648   /* The name of the DIE.  */
649   const char *name;
650
651   /*  The DIE associated with this method.  */
652   struct die_info *die;
653 };
654
655 /* Internal state when decoding a particular compilation unit.  */
656 struct dwarf2_cu
657 {
658   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
659   ~dwarf2_cu ();
660
661   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
662
663   /* The header of the compilation unit.  */
664   struct comp_unit_head header {};
665
666   /* Base address of this compilation unit.  */
667   CORE_ADDR base_address = 0;
668
669   /* Non-zero if base_address has been set.  */
670   int base_known = 0;
671
672   /* The language we are debugging.  */
673   enum language language = language_unknown;
674   const struct language_defn *language_defn = nullptr;
675
676   const char *producer = nullptr;
677
678   /* The generic symbol table building routines have separate lists for
679      file scope symbols and all all other scopes (local scopes).  So
680      we need to select the right one to pass to add_symbol_to_list().
681      We do it by keeping a pointer to the correct list in list_in_scope.
682
683      FIXME: The original dwarf code just treated the file scope as the
684      first local scope, and all other local scopes as nested local
685      scopes, and worked fine.  Check to see if we really need to
686      distinguish these in buildsym.c.  */
687   struct pending **list_in_scope = nullptr;
688
689   /* Hash table holding all the loaded partial DIEs
690      with partial_die->offset.SECT_OFF as hash.  */
691   htab_t partial_dies = nullptr;
692
693   /* Storage for things with the same lifetime as this read-in compilation
694      unit, including partial DIEs.  */
695   auto_obstack comp_unit_obstack;
696
697   /* When multiple dwarf2_cu structures are living in memory, this field
698      chains them all together, so that they can be released efficiently.
699      We will probably also want a generation counter so that most-recently-used
700      compilation units are cached...  */
701   struct dwarf2_per_cu_data *read_in_chain = nullptr;
702
703   /* Backlink to our per_cu entry.  */
704   struct dwarf2_per_cu_data *per_cu;
705
706   /* How many compilation units ago was this CU last referenced?  */
707   int last_used = 0;
708
709   /* A hash table of DIE cu_offset for following references with
710      die_info->offset.sect_off as hash.  */
711   htab_t die_hash = nullptr;
712
713   /* Full DIEs if read in.  */
714   struct die_info *dies = nullptr;
715
716   /* A set of pointers to dwarf2_per_cu_data objects for compilation
717      units referenced by this one.  Only set during full symbol processing;
718      partial symbol tables do not have dependencies.  */
719   htab_t dependencies = nullptr;
720
721   /* Header data from the line table, during full symbol processing.  */
722   struct line_header *line_header = nullptr;
723   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
724      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
725      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
726      to the line header as long as this DIE is being processed.  See
727      process_die_scope.  */
728   die_info *line_header_die_owner = nullptr;
729
730   /* A list of methods which need to have physnames computed
731      after all type information has been read.  */
732   std::vector<delayed_method_info> method_list;
733
734   /* To be copied to symtab->call_site_htab.  */
735   htab_t call_site_htab = nullptr;
736
737   /* Non-NULL if this CU came from a DWO file.
738      There is an invariant here that is important to remember:
739      Except for attributes copied from the top level DIE in the "main"
740      (or "stub") file in preparation for reading the DWO file
741      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
742      Either there isn't a DWO file (in which case this is NULL and the point
743      is moot), or there is and either we're not going to read it (in which
744      case this is NULL) or there is and we are reading it (in which case this
745      is non-NULL).  */
746   struct dwo_unit *dwo_unit = nullptr;
747
748   /* The DW_AT_addr_base attribute if present, zero otherwise
749      (zero is a valid value though).
750      Note this value comes from the Fission stub CU/TU's DIE.  */
751   ULONGEST addr_base = 0;
752
753   /* The DW_AT_ranges_base attribute if present, zero otherwise
754      (zero is a valid value though).
755      Note this value comes from the Fission stub CU/TU's DIE.
756      Also note that the value is zero in the non-DWO case so this value can
757      be used without needing to know whether DWO files are in use or not.
758      N.B. This does not apply to DW_AT_ranges appearing in
759      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
760      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
761      DW_AT_ranges_base *would* have to be applied, and we'd have to care
762      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
763   ULONGEST ranges_base = 0;
764
765   /* Mark used when releasing cached dies.  */
766   unsigned int mark : 1;
767
768   /* This CU references .debug_loc.  See the symtab->locations_valid field.
769      This test is imperfect as there may exist optimized debug code not using
770      any location list and still facing inlining issues if handled as
771      unoptimized code.  For a future better test see GCC PR other/32998.  */
772   unsigned int has_loclist : 1;
773
774   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
775      if all the producer_is_* fields are valid.  This information is cached
776      because profiling CU expansion showed excessive time spent in
777      producer_is_gxx_lt_4_6.  */
778   unsigned int checked_producer : 1;
779   unsigned int producer_is_gxx_lt_4_6 : 1;
780   unsigned int producer_is_gcc_lt_4_3 : 1;
781   unsigned int producer_is_icc_lt_14 : 1;
782
783   /* When set, the file that we're processing is known to have
784      debugging info for C++ namespaces.  GCC 3.3.x did not produce
785      this information, but later versions do.  */
786
787   unsigned int processing_has_namespace_info : 1;
788
789   struct partial_die_info *find_partial_die (sect_offset sect_off);
790 };
791
792 /* Persistent data held for a compilation unit, even when not
793    processing it.  We put a pointer to this structure in the
794    read_symtab_private field of the psymtab.  */
795
796 struct dwarf2_per_cu_data
797 {
798   /* The start offset and length of this compilation unit.
799      NOTE: Unlike comp_unit_head.length, this length includes
800      initial_length_size.
801      If the DIE refers to a DWO file, this is always of the original die,
802      not the DWO file.  */
803   sect_offset sect_off;
804   unsigned int length;
805
806   /* DWARF standard version this data has been read from (such as 4 or 5).  */
807   short dwarf_version;
808
809   /* Flag indicating this compilation unit will be read in before
810      any of the current compilation units are processed.  */
811   unsigned int queued : 1;
812
813   /* This flag will be set when reading partial DIEs if we need to load
814      absolutely all DIEs for this compilation unit, instead of just the ones
815      we think are interesting.  It gets set if we look for a DIE in the
816      hash table and don't find it.  */
817   unsigned int load_all_dies : 1;
818
819   /* Non-zero if this CU is from .debug_types.
820      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
821      this is non-zero.  */
822   unsigned int is_debug_types : 1;
823
824   /* Non-zero if this CU is from the .dwz file.  */
825   unsigned int is_dwz : 1;
826
827   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
828      This flag is only valid if is_debug_types is true.
829      We can't read a CU directly from a DWO file: There are required
830      attributes in the stub.  */
831   unsigned int reading_dwo_directly : 1;
832
833   /* Non-zero if the TU has been read.
834      This is used to assist the "Stay in DWO Optimization" for Fission:
835      When reading a DWO, it's faster to read TUs from the DWO instead of
836      fetching them from random other DWOs (due to comdat folding).
837      If the TU has already been read, the optimization is unnecessary
838      (and unwise - we don't want to change where gdb thinks the TU lives
839      "midflight").
840      This flag is only valid if is_debug_types is true.  */
841   unsigned int tu_read : 1;
842
843   /* The section this CU/TU lives in.
844      If the DIE refers to a DWO file, this is always the original die,
845      not the DWO file.  */
846   struct dwarf2_section_info *section;
847
848   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
849      of the CU cache it gets reset to NULL again.  This is left as NULL for
850      dummy CUs (a CU header, but nothing else).  */
851   struct dwarf2_cu *cu;
852
853   /* The corresponding dwarf2_per_objfile.  */
854   struct dwarf2_per_objfile *dwarf2_per_objfile;
855
856   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
857      is active.  Otherwise, the 'psymtab' field is active.  */
858   union
859   {
860     /* The partial symbol table associated with this compilation unit,
861        or NULL for unread partial units.  */
862     struct partial_symtab *psymtab;
863
864     /* Data needed by the "quick" functions.  */
865     struct dwarf2_per_cu_quick_data *quick;
866   } v;
867
868   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
869      while reading psymtabs, used to compute the psymtab dependencies,
870      and then cleared.  Then it is filled in again while reading full
871      symbols, and only deleted when the objfile is destroyed.
872
873      This is also used to work around a difference between the way gold
874      generates .gdb_index version <=7 and the way gdb does.  Arguably this
875      is a gold bug.  For symbols coming from TUs, gold records in the index
876      the CU that includes the TU instead of the TU itself.  This breaks
877      dw2_lookup_symbol: It assumes that if the index says symbol X lives
878      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
879      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
880      we need to look in TU Z to find X.  Fortunately, this is akin to
881      DW_TAG_imported_unit, so we just use the same mechanism: For
882      .gdb_index version <=7 this also records the TUs that the CU referred
883      to.  Concurrently with this change gdb was modified to emit version 8
884      indices so we only pay a price for gold generated indices.
885      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
886   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
887 };
888
889 /* Entry in the signatured_types hash table.  */
890
891 struct signatured_type
892 {
893   /* The "per_cu" object of this type.
894      This struct is used iff per_cu.is_debug_types.
895      N.B.: This is the first member so that it's easy to convert pointers
896      between them.  */
897   struct dwarf2_per_cu_data per_cu;
898
899   /* The type's signature.  */
900   ULONGEST signature;
901
902   /* Offset in the TU of the type's DIE, as read from the TU header.
903      If this TU is a DWO stub and the definition lives in a DWO file
904      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
905   cu_offset type_offset_in_tu;
906
907   /* Offset in the section of the type's DIE.
908      If the definition lives in a DWO file, this is the offset in the
909      .debug_types.dwo section.
910      The value is zero until the actual value is known.
911      Zero is otherwise not a valid section offset.  */
912   sect_offset type_offset_in_section;
913
914   /* Type units are grouped by their DW_AT_stmt_list entry so that they
915      can share them.  This points to the containing symtab.  */
916   struct type_unit_group *type_unit_group;
917
918   /* The type.
919      The first time we encounter this type we fully read it in and install it
920      in the symbol tables.  Subsequent times we only need the type.  */
921   struct type *type;
922
923   /* Containing DWO unit.
924      This field is valid iff per_cu.reading_dwo_directly.  */
925   struct dwo_unit *dwo_unit;
926 };
927
928 typedef struct signatured_type *sig_type_ptr;
929 DEF_VEC_P (sig_type_ptr);
930
931 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
932    This includes type_unit_group and quick_file_names.  */
933
934 struct stmt_list_hash
935 {
936   /* The DWO unit this table is from or NULL if there is none.  */
937   struct dwo_unit *dwo_unit;
938
939   /* Offset in .debug_line or .debug_line.dwo.  */
940   sect_offset line_sect_off;
941 };
942
943 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
944    an object of this type.  */
945
946 struct type_unit_group
947 {
948   /* dwarf2read.c's main "handle" on a TU symtab.
949      To simplify things we create an artificial CU that "includes" all the
950      type units using this stmt_list so that the rest of the code still has
951      a "per_cu" handle on the symtab.
952      This PER_CU is recognized by having no section.  */
953 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
954   struct dwarf2_per_cu_data per_cu;
955
956   /* The TUs that share this DW_AT_stmt_list entry.
957      This is added to while parsing type units to build partial symtabs,
958      and is deleted afterwards and not used again.  */
959   VEC (sig_type_ptr) *tus;
960
961   /* The compunit symtab.
962      Type units in a group needn't all be defined in the same source file,
963      so we create an essentially anonymous symtab as the compunit symtab.  */
964   struct compunit_symtab *compunit_symtab;
965
966   /* The data used to construct the hash key.  */
967   struct stmt_list_hash hash;
968
969   /* The number of symtabs from the line header.
970      The value here must match line_header.num_file_names.  */
971   unsigned int num_symtabs;
972
973   /* The symbol tables for this TU (obtained from the files listed in
974      DW_AT_stmt_list).
975      WARNING: The order of entries here must match the order of entries
976      in the line header.  After the first TU using this type_unit_group, the
977      line header for the subsequent TUs is recreated from this.  This is done
978      because we need to use the same symtabs for each TU using the same
979      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
980      there's no guarantee the line header doesn't have duplicate entries.  */
981   struct symtab **symtabs;
982 };
983
984 /* These sections are what may appear in a (real or virtual) DWO file.  */
985
986 struct dwo_sections
987 {
988   struct dwarf2_section_info abbrev;
989   struct dwarf2_section_info line;
990   struct dwarf2_section_info loc;
991   struct dwarf2_section_info loclists;
992   struct dwarf2_section_info macinfo;
993   struct dwarf2_section_info macro;
994   struct dwarf2_section_info str;
995   struct dwarf2_section_info str_offsets;
996   /* In the case of a virtual DWO file, these two are unused.  */
997   struct dwarf2_section_info info;
998   VEC (dwarf2_section_info_def) *types;
999 };
1000
1001 /* CUs/TUs in DWP/DWO files.  */
1002
1003 struct dwo_unit
1004 {
1005   /* Backlink to the containing struct dwo_file.  */
1006   struct dwo_file *dwo_file;
1007
1008   /* The "id" that distinguishes this CU/TU.
1009      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1010      Since signatures came first, we stick with it for consistency.  */
1011   ULONGEST signature;
1012
1013   /* The section this CU/TU lives in, in the DWO file.  */
1014   struct dwarf2_section_info *section;
1015
1016   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1017   sect_offset sect_off;
1018   unsigned int length;
1019
1020   /* For types, offset in the type's DIE of the type defined by this TU.  */
1021   cu_offset type_offset_in_tu;
1022 };
1023
1024 /* include/dwarf2.h defines the DWP section codes.
1025    It defines a max value but it doesn't define a min value, which we
1026    use for error checking, so provide one.  */
1027
1028 enum dwp_v2_section_ids
1029 {
1030   DW_SECT_MIN = 1
1031 };
1032
1033 /* Data for one DWO file.
1034
1035    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1036    appears in a DWP file).  DWP files don't really have DWO files per se -
1037    comdat folding of types "loses" the DWO file they came from, and from
1038    a high level view DWP files appear to contain a mass of random types.
1039    However, to maintain consistency with the non-DWP case we pretend DWP
1040    files contain virtual DWO files, and we assign each TU with one virtual
1041    DWO file (generally based on the line and abbrev section offsets -
1042    a heuristic that seems to work in practice).  */
1043
1044 struct dwo_file
1045 {
1046   /* The DW_AT_GNU_dwo_name attribute.
1047      For virtual DWO files the name is constructed from the section offsets
1048      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1049      from related CU+TUs.  */
1050   const char *dwo_name;
1051
1052   /* The DW_AT_comp_dir attribute.  */
1053   const char *comp_dir;
1054
1055   /* The bfd, when the file is open.  Otherwise this is NULL.
1056      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1057   bfd *dbfd;
1058
1059   /* The sections that make up this DWO file.
1060      Remember that for virtual DWO files in DWP V2, these are virtual
1061      sections (for lack of a better name).  */
1062   struct dwo_sections sections;
1063
1064   /* The CUs in the file.
1065      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1066      an extension to handle LLVM's Link Time Optimization output (where
1067      multiple source files may be compiled into a single object/dwo pair). */
1068   htab_t cus;
1069
1070   /* Table of TUs in the file.
1071      Each element is a struct dwo_unit.  */
1072   htab_t tus;
1073 };
1074
1075 /* These sections are what may appear in a DWP file.  */
1076
1077 struct dwp_sections
1078 {
1079   /* These are used by both DWP version 1 and 2.  */
1080   struct dwarf2_section_info str;
1081   struct dwarf2_section_info cu_index;
1082   struct dwarf2_section_info tu_index;
1083
1084   /* These are only used by DWP version 2 files.
1085      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1086      sections are referenced by section number, and are not recorded here.
1087      In DWP version 2 there is at most one copy of all these sections, each
1088      section being (effectively) comprised of the concatenation of all of the
1089      individual sections that exist in the version 1 format.
1090      To keep the code simple we treat each of these concatenated pieces as a
1091      section itself (a virtual section?).  */
1092   struct dwarf2_section_info abbrev;
1093   struct dwarf2_section_info info;
1094   struct dwarf2_section_info line;
1095   struct dwarf2_section_info loc;
1096   struct dwarf2_section_info macinfo;
1097   struct dwarf2_section_info macro;
1098   struct dwarf2_section_info str_offsets;
1099   struct dwarf2_section_info types;
1100 };
1101
1102 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1103    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1104
1105 struct virtual_v1_dwo_sections
1106 {
1107   struct dwarf2_section_info abbrev;
1108   struct dwarf2_section_info line;
1109   struct dwarf2_section_info loc;
1110   struct dwarf2_section_info macinfo;
1111   struct dwarf2_section_info macro;
1112   struct dwarf2_section_info str_offsets;
1113   /* Each DWP hash table entry records one CU or one TU.
1114      That is recorded here, and copied to dwo_unit.section.  */
1115   struct dwarf2_section_info info_or_types;
1116 };
1117
1118 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1119    In version 2, the sections of the DWO files are concatenated together
1120    and stored in one section of that name.  Thus each ELF section contains
1121    several "virtual" sections.  */
1122
1123 struct virtual_v2_dwo_sections
1124 {
1125   bfd_size_type abbrev_offset;
1126   bfd_size_type abbrev_size;
1127
1128   bfd_size_type line_offset;
1129   bfd_size_type line_size;
1130
1131   bfd_size_type loc_offset;
1132   bfd_size_type loc_size;
1133
1134   bfd_size_type macinfo_offset;
1135   bfd_size_type macinfo_size;
1136
1137   bfd_size_type macro_offset;
1138   bfd_size_type macro_size;
1139
1140   bfd_size_type str_offsets_offset;
1141   bfd_size_type str_offsets_size;
1142
1143   /* Each DWP hash table entry records one CU or one TU.
1144      That is recorded here, and copied to dwo_unit.section.  */
1145   bfd_size_type info_or_types_offset;
1146   bfd_size_type info_or_types_size;
1147 };
1148
1149 /* Contents of DWP hash tables.  */
1150
1151 struct dwp_hash_table
1152 {
1153   uint32_t version, nr_columns;
1154   uint32_t nr_units, nr_slots;
1155   const gdb_byte *hash_table, *unit_table;
1156   union
1157   {
1158     struct
1159     {
1160       const gdb_byte *indices;
1161     } v1;
1162     struct
1163     {
1164       /* This is indexed by column number and gives the id of the section
1165          in that column.  */
1166 #define MAX_NR_V2_DWO_SECTIONS \
1167   (1 /* .debug_info or .debug_types */ \
1168    + 1 /* .debug_abbrev */ \
1169    + 1 /* .debug_line */ \
1170    + 1 /* .debug_loc */ \
1171    + 1 /* .debug_str_offsets */ \
1172    + 1 /* .debug_macro or .debug_macinfo */)
1173       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1174       const gdb_byte *offsets;
1175       const gdb_byte *sizes;
1176     } v2;
1177   } section_pool;
1178 };
1179
1180 /* Data for one DWP file.  */
1181
1182 struct dwp_file
1183 {
1184   /* Name of the file.  */
1185   const char *name;
1186
1187   /* File format version.  */
1188   int version;
1189
1190   /* The bfd.  */
1191   bfd *dbfd;
1192
1193   /* Section info for this file.  */
1194   struct dwp_sections sections;
1195
1196   /* Table of CUs in the file.  */
1197   const struct dwp_hash_table *cus;
1198
1199   /* Table of TUs in the file.  */
1200   const struct dwp_hash_table *tus;
1201
1202   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1203   htab_t loaded_cus;
1204   htab_t loaded_tus;
1205
1206   /* Table to map ELF section numbers to their sections.
1207      This is only needed for the DWP V1 file format.  */
1208   unsigned int num_sections;
1209   asection **elf_sections;
1210 };
1211
1212 /* This represents a '.dwz' file.  */
1213
1214 struct dwz_file
1215 {
1216   /* A dwz file can only contain a few sections.  */
1217   struct dwarf2_section_info abbrev;
1218   struct dwarf2_section_info info;
1219   struct dwarf2_section_info str;
1220   struct dwarf2_section_info line;
1221   struct dwarf2_section_info macro;
1222   struct dwarf2_section_info gdb_index;
1223   struct dwarf2_section_info debug_names;
1224
1225   /* The dwz's BFD.  */
1226   bfd *dwz_bfd;
1227 };
1228
1229 /* Struct used to pass misc. parameters to read_die_and_children, et
1230    al.  which are used for both .debug_info and .debug_types dies.
1231    All parameters here are unchanging for the life of the call.  This
1232    struct exists to abstract away the constant parameters of die reading.  */
1233
1234 struct die_reader_specs
1235 {
1236   /* The bfd of die_section.  */
1237   bfd* abfd;
1238
1239   /* The CU of the DIE we are parsing.  */
1240   struct dwarf2_cu *cu;
1241
1242   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1243   struct dwo_file *dwo_file;
1244
1245   /* The section the die comes from.
1246      This is either .debug_info or .debug_types, or the .dwo variants.  */
1247   struct dwarf2_section_info *die_section;
1248
1249   /* die_section->buffer.  */
1250   const gdb_byte *buffer;
1251
1252   /* The end of the buffer.  */
1253   const gdb_byte *buffer_end;
1254
1255   /* The value of the DW_AT_comp_dir attribute.  */
1256   const char *comp_dir;
1257
1258   /* The abbreviation table to use when reading the DIEs.  */
1259   struct abbrev_table *abbrev_table;
1260 };
1261
1262 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1263 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1264                                       const gdb_byte *info_ptr,
1265                                       struct die_info *comp_unit_die,
1266                                       int has_children,
1267                                       void *data);
1268
1269 /* A 1-based directory index.  This is a strong typedef to prevent
1270    accidentally using a directory index as a 0-based index into an
1271    array/vector.  */
1272 enum class dir_index : unsigned int {};
1273
1274 /* Likewise, a 1-based file name index.  */
1275 enum class file_name_index : unsigned int {};
1276
1277 struct file_entry
1278 {
1279   file_entry () = default;
1280
1281   file_entry (const char *name_, dir_index d_index_,
1282               unsigned int mod_time_, unsigned int length_)
1283     : name (name_),
1284       d_index (d_index_),
1285       mod_time (mod_time_),
1286       length (length_)
1287   {}
1288
1289   /* Return the include directory at D_INDEX stored in LH.  Returns
1290      NULL if D_INDEX is out of bounds.  */
1291   const char *include_dir (const line_header *lh) const;
1292
1293   /* The file name.  Note this is an observing pointer.  The memory is
1294      owned by debug_line_buffer.  */
1295   const char *name {};
1296
1297   /* The directory index (1-based).  */
1298   dir_index d_index {};
1299
1300   unsigned int mod_time {};
1301
1302   unsigned int length {};
1303
1304   /* True if referenced by the Line Number Program.  */
1305   bool included_p {};
1306
1307   /* The associated symbol table, if any.  */
1308   struct symtab *symtab {};
1309 };
1310
1311 /* The line number information for a compilation unit (found in the
1312    .debug_line section) begins with a "statement program header",
1313    which contains the following information.  */
1314 struct line_header
1315 {
1316   line_header ()
1317     : offset_in_dwz {}
1318   {}
1319
1320   /* Add an entry to the include directory table.  */
1321   void add_include_dir (const char *include_dir);
1322
1323   /* Add an entry to the file name table.  */
1324   void add_file_name (const char *name, dir_index d_index,
1325                       unsigned int mod_time, unsigned int length);
1326
1327   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1328      is out of bounds.  */
1329   const char *include_dir_at (dir_index index) const
1330   {
1331     /* Convert directory index number (1-based) to vector index
1332        (0-based).  */
1333     size_t vec_index = to_underlying (index) - 1;
1334
1335     if (vec_index >= include_dirs.size ())
1336       return NULL;
1337     return include_dirs[vec_index];
1338   }
1339
1340   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1341      is out of bounds.  */
1342   file_entry *file_name_at (file_name_index index)
1343   {
1344     /* Convert file name index number (1-based) to vector index
1345        (0-based).  */
1346     size_t vec_index = to_underlying (index) - 1;
1347
1348     if (vec_index >= file_names.size ())
1349       return NULL;
1350     return &file_names[vec_index];
1351   }
1352
1353   /* Const version of the above.  */
1354   const file_entry *file_name_at (unsigned int index) const
1355   {
1356     if (index >= file_names.size ())
1357       return NULL;
1358     return &file_names[index];
1359   }
1360
1361   /* Offset of line number information in .debug_line section.  */
1362   sect_offset sect_off {};
1363
1364   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1365   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1366
1367   unsigned int total_length {};
1368   unsigned short version {};
1369   unsigned int header_length {};
1370   unsigned char minimum_instruction_length {};
1371   unsigned char maximum_ops_per_instruction {};
1372   unsigned char default_is_stmt {};
1373   int line_base {};
1374   unsigned char line_range {};
1375   unsigned char opcode_base {};
1376
1377   /* standard_opcode_lengths[i] is the number of operands for the
1378      standard opcode whose value is i.  This means that
1379      standard_opcode_lengths[0] is unused, and the last meaningful
1380      element is standard_opcode_lengths[opcode_base - 1].  */
1381   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1382
1383   /* The include_directories table.  Note these are observing
1384      pointers.  The memory is owned by debug_line_buffer.  */
1385   std::vector<const char *> include_dirs;
1386
1387   /* The file_names table.  */
1388   std::vector<file_entry> file_names;
1389
1390   /* The start and end of the statement program following this
1391      header.  These point into dwarf2_per_objfile->line_buffer.  */
1392   const gdb_byte *statement_program_start {}, *statement_program_end {};
1393 };
1394
1395 typedef std::unique_ptr<line_header> line_header_up;
1396
1397 const char *
1398 file_entry::include_dir (const line_header *lh) const
1399 {
1400   return lh->include_dir_at (d_index);
1401 }
1402
1403 /* When we construct a partial symbol table entry we only
1404    need this much information.  */
1405 struct partial_die_info : public allocate_on_obstack
1406   {
1407     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1408
1409     /* Disable assign but still keep copy ctor, which is needed
1410        load_partial_dies.   */
1411     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1412
1413     /* Adjust the partial die before generating a symbol for it.  This
1414        function may set the is_external flag or change the DIE's
1415        name.  */
1416     void fixup (struct dwarf2_cu *cu);
1417
1418     /* Offset of this DIE.  */
1419     const sect_offset sect_off;
1420
1421     /* DWARF-2 tag for this DIE.  */
1422     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1423
1424     /* Assorted flags describing the data found in this DIE.  */
1425     const unsigned int has_children : 1;
1426
1427     unsigned int is_external : 1;
1428     unsigned int is_declaration : 1;
1429     unsigned int has_type : 1;
1430     unsigned int has_specification : 1;
1431     unsigned int has_pc_info : 1;
1432     unsigned int may_be_inlined : 1;
1433
1434     /* This DIE has been marked DW_AT_main_subprogram.  */
1435     unsigned int main_subprogram : 1;
1436
1437     /* Flag set if the SCOPE field of this structure has been
1438        computed.  */
1439     unsigned int scope_set : 1;
1440
1441     /* Flag set if the DIE has a byte_size attribute.  */
1442     unsigned int has_byte_size : 1;
1443
1444     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1445     unsigned int has_const_value : 1;
1446
1447     /* Flag set if any of the DIE's children are template arguments.  */
1448     unsigned int has_template_arguments : 1;
1449
1450     /* Flag set if fixup has been called on this die.  */
1451     unsigned int fixup_called : 1;
1452
1453     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1454     unsigned int is_dwz : 1;
1455
1456     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1457     unsigned int spec_is_dwz : 1;
1458
1459     /* The name of this DIE.  Normally the value of DW_AT_name, but
1460        sometimes a default name for unnamed DIEs.  */
1461     const char *name = nullptr;
1462
1463     /* The linkage name, if present.  */
1464     const char *linkage_name = nullptr;
1465
1466     /* The scope to prepend to our children.  This is generally
1467        allocated on the comp_unit_obstack, so will disappear
1468        when this compilation unit leaves the cache.  */
1469     const char *scope = nullptr;
1470
1471     /* Some data associated with the partial DIE.  The tag determines
1472        which field is live.  */
1473     union
1474     {
1475       /* The location description associated with this DIE, if any.  */
1476       struct dwarf_block *locdesc;
1477       /* The offset of an import, for DW_TAG_imported_unit.  */
1478       sect_offset sect_off;
1479     } d {};
1480
1481     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1482     CORE_ADDR lowpc = 0;
1483     CORE_ADDR highpc = 0;
1484
1485     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1486        DW_AT_sibling, if any.  */
1487     /* NOTE: This member isn't strictly necessary, read_partial_die could
1488        return DW_AT_sibling values to its caller load_partial_dies.  */
1489     const gdb_byte *sibling = nullptr;
1490
1491     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1492        DW_AT_specification (or DW_AT_abstract_origin or
1493        DW_AT_extension).  */
1494     sect_offset spec_offset {};
1495
1496     /* Pointers to this DIE's parent, first child, and next sibling,
1497        if any.  */
1498     struct partial_die_info *die_parent = nullptr;
1499     struct partial_die_info *die_child = nullptr;
1500     struct partial_die_info *die_sibling = nullptr;
1501
1502     friend struct partial_die_info *
1503     dwarf2_cu::find_partial_die (sect_offset sect_off);
1504
1505   private:
1506     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1507     partial_die_info (sect_offset sect_off)
1508       : partial_die_info (sect_off, DW_TAG_padding, 0)
1509     {
1510     }
1511
1512     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1513                       int has_children_)
1514       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1515     {
1516       is_external = 0;
1517       is_declaration = 0;
1518       has_type = 0;
1519       has_specification = 0;
1520       has_pc_info = 0;
1521       may_be_inlined = 0;
1522       main_subprogram = 0;
1523       scope_set = 0;
1524       has_byte_size = 0;
1525       has_const_value = 0;
1526       has_template_arguments = 0;
1527       fixup_called = 0;
1528       is_dwz = 0;
1529       spec_is_dwz = 0;
1530     }
1531   };
1532
1533 /* This data structure holds the information of an abbrev.  */
1534 struct abbrev_info
1535   {
1536     unsigned int number;        /* number identifying abbrev */
1537     enum dwarf_tag tag;         /* dwarf tag */
1538     unsigned short has_children;                /* boolean */
1539     unsigned short num_attrs;   /* number of attributes */
1540     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1541     struct abbrev_info *next;   /* next in chain */
1542   };
1543
1544 struct attr_abbrev
1545   {
1546     ENUM_BITFIELD(dwarf_attribute) name : 16;
1547     ENUM_BITFIELD(dwarf_form) form : 16;
1548
1549     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1550     LONGEST implicit_const;
1551   };
1552
1553 /* Size of abbrev_table.abbrev_hash_table.  */
1554 #define ABBREV_HASH_SIZE 121
1555
1556 /* Top level data structure to contain an abbreviation table.  */
1557
1558 struct abbrev_table
1559 {
1560   explicit abbrev_table (sect_offset off)
1561     : sect_off (off)
1562   {
1563     m_abbrevs =
1564       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1565     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1566   }
1567
1568   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1569
1570   /* Allocate space for a struct abbrev_info object in
1571      ABBREV_TABLE.  */
1572   struct abbrev_info *alloc_abbrev ();
1573
1574   /* Add an abbreviation to the table.  */
1575   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1576
1577   /* Look up an abbrev in the table.
1578      Returns NULL if the abbrev is not found.  */
1579
1580   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1581
1582
1583   /* Where the abbrev table came from.
1584      This is used as a sanity check when the table is used.  */
1585   const sect_offset sect_off;
1586
1587   /* Storage for the abbrev table.  */
1588   auto_obstack abbrev_obstack;
1589
1590 private:
1591
1592   /* Hash table of abbrevs.
1593      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1594      It could be statically allocated, but the previous code didn't so we
1595      don't either.  */
1596   struct abbrev_info **m_abbrevs;
1597 };
1598
1599 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1600
1601 /* Attributes have a name and a value.  */
1602 struct attribute
1603   {
1604     ENUM_BITFIELD(dwarf_attribute) name : 16;
1605     ENUM_BITFIELD(dwarf_form) form : 15;
1606
1607     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1608        field should be in u.str (existing only for DW_STRING) but it is kept
1609        here for better struct attribute alignment.  */
1610     unsigned int string_is_canonical : 1;
1611
1612     union
1613       {
1614         const char *str;
1615         struct dwarf_block *blk;
1616         ULONGEST unsnd;
1617         LONGEST snd;
1618         CORE_ADDR addr;
1619         ULONGEST signature;
1620       }
1621     u;
1622   };
1623
1624 /* This data structure holds a complete die structure.  */
1625 struct die_info
1626   {
1627     /* DWARF-2 tag for this DIE.  */
1628     ENUM_BITFIELD(dwarf_tag) tag : 16;
1629
1630     /* Number of attributes */
1631     unsigned char num_attrs;
1632
1633     /* True if we're presently building the full type name for the
1634        type derived from this DIE.  */
1635     unsigned char building_fullname : 1;
1636
1637     /* True if this die is in process.  PR 16581.  */
1638     unsigned char in_process : 1;
1639
1640     /* Abbrev number */
1641     unsigned int abbrev;
1642
1643     /* Offset in .debug_info or .debug_types section.  */
1644     sect_offset sect_off;
1645
1646     /* The dies in a compilation unit form an n-ary tree.  PARENT
1647        points to this die's parent; CHILD points to the first child of
1648        this node; and all the children of a given node are chained
1649        together via their SIBLING fields.  */
1650     struct die_info *child;     /* Its first child, if any.  */
1651     struct die_info *sibling;   /* Its next sibling, if any.  */
1652     struct die_info *parent;    /* Its parent, if any.  */
1653
1654     /* An array of attributes, with NUM_ATTRS elements.  There may be
1655        zero, but it's not common and zero-sized arrays are not
1656        sufficiently portable C.  */
1657     struct attribute attrs[1];
1658   };
1659
1660 /* Get at parts of an attribute structure.  */
1661
1662 #define DW_STRING(attr)    ((attr)->u.str)
1663 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1664 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1665 #define DW_BLOCK(attr)     ((attr)->u.blk)
1666 #define DW_SND(attr)       ((attr)->u.snd)
1667 #define DW_ADDR(attr)      ((attr)->u.addr)
1668 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1669
1670 /* Blocks are a bunch of untyped bytes.  */
1671 struct dwarf_block
1672   {
1673     size_t size;
1674
1675     /* Valid only if SIZE is not zero.  */
1676     const gdb_byte *data;
1677   };
1678
1679 #ifndef ATTR_ALLOC_CHUNK
1680 #define ATTR_ALLOC_CHUNK 4
1681 #endif
1682
1683 /* Allocate fields for structs, unions and enums in this size.  */
1684 #ifndef DW_FIELD_ALLOC_CHUNK
1685 #define DW_FIELD_ALLOC_CHUNK 4
1686 #endif
1687
1688 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1689    but this would require a corresponding change in unpack_field_as_long
1690    and friends.  */
1691 static int bits_per_byte = 8;
1692
1693 struct nextfield
1694 {
1695   struct nextfield *next;
1696   int accessibility;
1697   int virtuality;
1698   struct field field;
1699 };
1700
1701 struct nextfnfield
1702 {
1703   struct nextfnfield *next;
1704   struct fn_field fnfield;
1705 };
1706
1707 struct fnfieldlist
1708 {
1709   const char *name;
1710   int length;
1711   struct nextfnfield *head;
1712 };
1713
1714 struct decl_field_list
1715 {
1716   struct decl_field field;
1717   struct decl_field_list *next;
1718 };
1719
1720 /* The routines that read and process dies for a C struct or C++ class
1721    pass lists of data member fields and lists of member function fields
1722    in an instance of a field_info structure, as defined below.  */
1723 struct field_info
1724   {
1725     /* List of data member and baseclasses fields.  */
1726     struct nextfield *fields, *baseclasses;
1727
1728     /* Number of fields (including baseclasses).  */
1729     int nfields;
1730
1731     /* Number of baseclasses.  */
1732     int nbaseclasses;
1733
1734     /* Set if the accesibility of one of the fields is not public.  */
1735     int non_public_fields;
1736
1737     /* Member function fieldlist array, contains name of possibly overloaded
1738        member function, number of overloaded member functions and a pointer
1739        to the head of the member function field chain.  */
1740     struct fnfieldlist *fnfieldlists;
1741
1742     /* Number of entries in the fnfieldlists array.  */
1743     int nfnfields;
1744
1745     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1746        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1747     struct decl_field_list *typedef_field_list;
1748     unsigned typedef_field_list_count;
1749
1750     /* Nested types defined by this class and the number of elements in this
1751        list.  */
1752     struct decl_field_list *nested_types_list;
1753     unsigned nested_types_list_count;
1754   };
1755
1756 /* One item on the queue of compilation units to read in full symbols
1757    for.  */
1758 struct dwarf2_queue_item
1759 {
1760   struct dwarf2_per_cu_data *per_cu;
1761   enum language pretend_language;
1762   struct dwarf2_queue_item *next;
1763 };
1764
1765 /* The current queue.  */
1766 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1767
1768 /* Loaded secondary compilation units are kept in memory until they
1769    have not been referenced for the processing of this many
1770    compilation units.  Set this to zero to disable caching.  Cache
1771    sizes of up to at least twenty will improve startup time for
1772    typical inter-CU-reference binaries, at an obvious memory cost.  */
1773 static int dwarf_max_cache_age = 5;
1774 static void
1775 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1776                           struct cmd_list_element *c, const char *value)
1777 {
1778   fprintf_filtered (file, _("The upper bound on the age of cached "
1779                             "DWARF compilation units is %s.\n"),
1780                     value);
1781 }
1782 \f
1783 /* local function prototypes */
1784
1785 static const char *get_section_name (const struct dwarf2_section_info *);
1786
1787 static const char *get_section_file_name (const struct dwarf2_section_info *);
1788
1789 static void dwarf2_find_base_address (struct die_info *die,
1790                                       struct dwarf2_cu *cu);
1791
1792 static struct partial_symtab *create_partial_symtab
1793   (struct dwarf2_per_cu_data *per_cu, const char *name);
1794
1795 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1796                                         const gdb_byte *info_ptr,
1797                                         struct die_info *type_unit_die,
1798                                         int has_children, void *data);
1799
1800 static void dwarf2_build_psymtabs_hard
1801   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1802
1803 static void scan_partial_symbols (struct partial_die_info *,
1804                                   CORE_ADDR *, CORE_ADDR *,
1805                                   int, struct dwarf2_cu *);
1806
1807 static void add_partial_symbol (struct partial_die_info *,
1808                                 struct dwarf2_cu *);
1809
1810 static void add_partial_namespace (struct partial_die_info *pdi,
1811                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1812                                    int set_addrmap, struct dwarf2_cu *cu);
1813
1814 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1815                                 CORE_ADDR *highpc, int set_addrmap,
1816                                 struct dwarf2_cu *cu);
1817
1818 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1819                                      struct dwarf2_cu *cu);
1820
1821 static void add_partial_subprogram (struct partial_die_info *pdi,
1822                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1823                                     int need_pc, struct dwarf2_cu *cu);
1824
1825 static void dwarf2_read_symtab (struct partial_symtab *,
1826                                 struct objfile *);
1827
1828 static void psymtab_to_symtab_1 (struct partial_symtab *);
1829
1830 static abbrev_table_up abbrev_table_read_table
1831   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1832    sect_offset);
1833
1834 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1835
1836 static struct partial_die_info *load_partial_dies
1837   (const struct die_reader_specs *, const gdb_byte *, int);
1838
1839 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1840                                          struct partial_die_info *,
1841                                          const struct abbrev_info &,
1842                                          const gdb_byte *);
1843
1844 static struct partial_die_info *find_partial_die (sect_offset, int,
1845                                                   struct dwarf2_cu *);
1846
1847 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1848                                        struct attribute *, struct attr_abbrev *,
1849                                        const gdb_byte *);
1850
1851 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1852
1853 static int read_1_signed_byte (bfd *, const gdb_byte *);
1854
1855 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1856
1857 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1858
1859 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1860
1861 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1862                                unsigned int *);
1863
1864 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1865
1866 static LONGEST read_checked_initial_length_and_offset
1867   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1868    unsigned int *, unsigned int *);
1869
1870 static LONGEST read_offset (bfd *, const gdb_byte *,
1871                             const struct comp_unit_head *,
1872                             unsigned int *);
1873
1874 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1875
1876 static sect_offset read_abbrev_offset
1877   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1878    struct dwarf2_section_info *, sect_offset);
1879
1880 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1881
1882 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1883
1884 static const char *read_indirect_string
1885   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1886    const struct comp_unit_head *, unsigned int *);
1887
1888 static const char *read_indirect_line_string
1889   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1890    const struct comp_unit_head *, unsigned int *);
1891
1892 static const char *read_indirect_string_at_offset
1893   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1894    LONGEST str_offset);
1895
1896 static const char *read_indirect_string_from_dwz
1897   (struct objfile *objfile, struct dwz_file *, LONGEST);
1898
1899 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1900
1901 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1902                                               const gdb_byte *,
1903                                               unsigned int *);
1904
1905 static const char *read_str_index (const struct die_reader_specs *reader,
1906                                    ULONGEST str_index);
1907
1908 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1909
1910 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1911                                       struct dwarf2_cu *);
1912
1913 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1914                                                 unsigned int);
1915
1916 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1917                                        struct dwarf2_cu *cu);
1918
1919 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1920                                struct dwarf2_cu *cu);
1921
1922 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1923
1924 static struct die_info *die_specification (struct die_info *die,
1925                                            struct dwarf2_cu **);
1926
1927 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1928                                                 struct dwarf2_cu *cu);
1929
1930 static void dwarf_decode_lines (struct line_header *, const char *,
1931                                 struct dwarf2_cu *, struct partial_symtab *,
1932                                 CORE_ADDR, int decode_mapping);
1933
1934 static void dwarf2_start_subfile (const char *, const char *);
1935
1936 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1937                                                     const char *, const char *,
1938                                                     CORE_ADDR);
1939
1940 static struct symbol *new_symbol (struct die_info *, struct type *,
1941                                   struct dwarf2_cu *, struct symbol * = NULL);
1942
1943 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1944                                 struct dwarf2_cu *);
1945
1946 static void dwarf2_const_value_attr (const struct attribute *attr,
1947                                      struct type *type,
1948                                      const char *name,
1949                                      struct obstack *obstack,
1950                                      struct dwarf2_cu *cu, LONGEST *value,
1951                                      const gdb_byte **bytes,
1952                                      struct dwarf2_locexpr_baton **baton);
1953
1954 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1955
1956 static int need_gnat_info (struct dwarf2_cu *);
1957
1958 static struct type *die_descriptive_type (struct die_info *,
1959                                           struct dwarf2_cu *);
1960
1961 static void set_descriptive_type (struct type *, struct die_info *,
1962                                   struct dwarf2_cu *);
1963
1964 static struct type *die_containing_type (struct die_info *,
1965                                          struct dwarf2_cu *);
1966
1967 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1968                                      struct dwarf2_cu *);
1969
1970 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1971
1972 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1973
1974 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1975
1976 static char *typename_concat (struct obstack *obs, const char *prefix,
1977                               const char *suffix, int physname,
1978                               struct dwarf2_cu *cu);
1979
1980 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1981
1982 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1983
1984 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1985
1986 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1987
1988 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1989
1990 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1991
1992 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1993                                struct dwarf2_cu *, struct partial_symtab *);
1994
1995 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1996    values.  Keep the items ordered with increasing constraints compliance.  */
1997 enum pc_bounds_kind
1998 {
1999   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
2000   PC_BOUNDS_NOT_PRESENT,
2001
2002   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
2003      were present but they do not form a valid range of PC addresses.  */
2004   PC_BOUNDS_INVALID,
2005
2006   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
2007   PC_BOUNDS_RANGES,
2008
2009   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
2010   PC_BOUNDS_HIGH_LOW,
2011 };
2012
2013 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
2014                                                  CORE_ADDR *, CORE_ADDR *,
2015                                                  struct dwarf2_cu *,
2016                                                  struct partial_symtab *);
2017
2018 static void get_scope_pc_bounds (struct die_info *,
2019                                  CORE_ADDR *, CORE_ADDR *,
2020                                  struct dwarf2_cu *);
2021
2022 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
2023                                         CORE_ADDR, struct dwarf2_cu *);
2024
2025 static void dwarf2_add_field (struct field_info *, struct die_info *,
2026                               struct dwarf2_cu *);
2027
2028 static void dwarf2_attach_fields_to_type (struct field_info *,
2029                                           struct type *, struct dwarf2_cu *);
2030
2031 static void dwarf2_add_member_fn (struct field_info *,
2032                                   struct die_info *, struct type *,
2033                                   struct dwarf2_cu *);
2034
2035 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
2036                                              struct type *,
2037                                              struct dwarf2_cu *);
2038
2039 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
2040
2041 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2042
2043 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2044
2045 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2046
2047 static struct using_direct **using_directives (enum language);
2048
2049 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2050
2051 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2052
2053 static struct type *read_module_type (struct die_info *die,
2054                                       struct dwarf2_cu *cu);
2055
2056 static const char *namespace_name (struct die_info *die,
2057                                    int *is_anonymous, struct dwarf2_cu *);
2058
2059 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2060
2061 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2062
2063 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2064                                                        struct dwarf2_cu *);
2065
2066 static struct die_info *read_die_and_siblings_1
2067   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2068    struct die_info *);
2069
2070 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2071                                                const gdb_byte *info_ptr,
2072                                                const gdb_byte **new_info_ptr,
2073                                                struct die_info *parent);
2074
2075 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2076                                         struct die_info **, const gdb_byte *,
2077                                         int *, int);
2078
2079 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2080                                       struct die_info **, const gdb_byte *,
2081                                       int *);
2082
2083 static void process_die (struct die_info *, struct dwarf2_cu *);
2084
2085 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2086                                              struct obstack *);
2087
2088 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2089
2090 static const char *dwarf2_full_name (const char *name,
2091                                      struct die_info *die,
2092                                      struct dwarf2_cu *cu);
2093
2094 static const char *dwarf2_physname (const char *name, struct die_info *die,
2095                                     struct dwarf2_cu *cu);
2096
2097 static struct die_info *dwarf2_extension (struct die_info *die,
2098                                           struct dwarf2_cu **);
2099
2100 static const char *dwarf_tag_name (unsigned int);
2101
2102 static const char *dwarf_attr_name (unsigned int);
2103
2104 static const char *dwarf_form_name (unsigned int);
2105
2106 static const char *dwarf_bool_name (unsigned int);
2107
2108 static const char *dwarf_type_encoding_name (unsigned int);
2109
2110 static struct die_info *sibling_die (struct die_info *);
2111
2112 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2113
2114 static void dump_die_for_error (struct die_info *);
2115
2116 static void dump_die_1 (struct ui_file *, int level, int max_level,
2117                         struct die_info *);
2118
2119 /*static*/ void dump_die (struct die_info *, int max_level);
2120
2121 static void store_in_ref_table (struct die_info *,
2122                                 struct dwarf2_cu *);
2123
2124 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2125
2126 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2127
2128 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2129                                                const struct attribute *,
2130                                                struct dwarf2_cu **);
2131
2132 static struct die_info *follow_die_ref (struct die_info *,
2133                                         const struct attribute *,
2134                                         struct dwarf2_cu **);
2135
2136 static struct die_info *follow_die_sig (struct die_info *,
2137                                         const struct attribute *,
2138                                         struct dwarf2_cu **);
2139
2140 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2141                                          struct dwarf2_cu *);
2142
2143 static struct type *get_DW_AT_signature_type (struct die_info *,
2144                                               const struct attribute *,
2145                                               struct dwarf2_cu *);
2146
2147 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2148
2149 static void read_signatured_type (struct signatured_type *);
2150
2151 static int attr_to_dynamic_prop (const struct attribute *attr,
2152                                  struct die_info *die, struct dwarf2_cu *cu,
2153                                  struct dynamic_prop *prop);
2154
2155 /* memory allocation interface */
2156
2157 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2158
2159 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2160
2161 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2162
2163 static int attr_form_is_block (const struct attribute *);
2164
2165 static int attr_form_is_section_offset (const struct attribute *);
2166
2167 static int attr_form_is_constant (const struct attribute *);
2168
2169 static int attr_form_is_ref (const struct attribute *);
2170
2171 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2172                                    struct dwarf2_loclist_baton *baton,
2173                                    const struct attribute *attr);
2174
2175 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2176                                          struct symbol *sym,
2177                                          struct dwarf2_cu *cu,
2178                                          int is_block);
2179
2180 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2181                                      const gdb_byte *info_ptr,
2182                                      struct abbrev_info *abbrev);
2183
2184 static hashval_t partial_die_hash (const void *item);
2185
2186 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2187
2188 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2189   (sect_offset sect_off, unsigned int offset_in_dwz,
2190    struct dwarf2_per_objfile *dwarf2_per_objfile);
2191
2192 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2193                                    struct die_info *comp_unit_die,
2194                                    enum language pretend_language);
2195
2196 static void free_cached_comp_units (void *);
2197
2198 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2199
2200 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2201
2202 static struct type *set_die_type (struct die_info *, struct type *,
2203                                   struct dwarf2_cu *);
2204
2205 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2206
2207 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2208
2209 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2210                                  enum language);
2211
2212 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2213                                     enum language);
2214
2215 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2216                                     enum language);
2217
2218 static void dwarf2_add_dependence (struct dwarf2_cu *,
2219                                    struct dwarf2_per_cu_data *);
2220
2221 static void dwarf2_mark (struct dwarf2_cu *);
2222
2223 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2224
2225 static struct type *get_die_type_at_offset (sect_offset,
2226                                             struct dwarf2_per_cu_data *);
2227
2228 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2229
2230 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2231                              enum language pretend_language);
2232
2233 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2234
2235 /* Class, the destructor of which frees all allocated queue entries.  This
2236    will only have work to do if an error was thrown while processing the
2237    dwarf.  If no error was thrown then the queue entries should have all
2238    been processed, and freed, as we went along.  */
2239
2240 class dwarf2_queue_guard
2241 {
2242 public:
2243   dwarf2_queue_guard () = default;
2244
2245   /* Free any entries remaining on the queue.  There should only be
2246      entries left if we hit an error while processing the dwarf.  */
2247   ~dwarf2_queue_guard ()
2248   {
2249     struct dwarf2_queue_item *item, *last;
2250
2251     item = dwarf2_queue;
2252     while (item)
2253       {
2254         /* Anything still marked queued is likely to be in an
2255            inconsistent state, so discard it.  */
2256         if (item->per_cu->queued)
2257           {
2258             if (item->per_cu->cu != NULL)
2259               free_one_cached_comp_unit (item->per_cu);
2260             item->per_cu->queued = 0;
2261           }
2262
2263         last = item;
2264         item = item->next;
2265         xfree (last);
2266       }
2267
2268     dwarf2_queue = dwarf2_queue_tail = NULL;
2269   }
2270 };
2271
2272 /* The return type of find_file_and_directory.  Note, the enclosed
2273    string pointers are only valid while this object is valid.  */
2274
2275 struct file_and_directory
2276 {
2277   /* The filename.  This is never NULL.  */
2278   const char *name;
2279
2280   /* The compilation directory.  NULL if not known.  If we needed to
2281      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2282      points directly to the DW_AT_comp_dir string attribute owned by
2283      the obstack that owns the DIE.  */
2284   const char *comp_dir;
2285
2286   /* If we needed to build a new string for comp_dir, this is what
2287      owns the storage.  */
2288   std::string comp_dir_storage;
2289 };
2290
2291 static file_and_directory find_file_and_directory (struct die_info *die,
2292                                                    struct dwarf2_cu *cu);
2293
2294 static char *file_full_name (int file, struct line_header *lh,
2295                              const char *comp_dir);
2296
2297 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2298 enum class rcuh_kind { COMPILE, TYPE };
2299
2300 static const gdb_byte *read_and_check_comp_unit_head
2301   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2302    struct comp_unit_head *header,
2303    struct dwarf2_section_info *section,
2304    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2305    rcuh_kind section_kind);
2306
2307 static void init_cutu_and_read_dies
2308   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2309    int use_existing_cu, int keep,
2310    die_reader_func_ftype *die_reader_func, void *data);
2311
2312 static void init_cutu_and_read_dies_simple
2313   (struct dwarf2_per_cu_data *this_cu,
2314    die_reader_func_ftype *die_reader_func, void *data);
2315
2316 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2317
2318 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2319
2320 static struct dwo_unit *lookup_dwo_unit_in_dwp
2321   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2322    struct dwp_file *dwp_file, const char *comp_dir,
2323    ULONGEST signature, int is_debug_types);
2324
2325 static struct dwp_file *get_dwp_file
2326   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2327
2328 static struct dwo_unit *lookup_dwo_comp_unit
2329   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2330
2331 static struct dwo_unit *lookup_dwo_type_unit
2332   (struct signatured_type *, const char *, const char *);
2333
2334 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2335
2336 static void free_dwo_file_cleanup (void *);
2337
2338 struct free_dwo_file_cleanup_data
2339 {
2340   struct dwo_file *dwo_file;
2341   struct dwarf2_per_objfile *dwarf2_per_objfile;
2342 };
2343
2344 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2345
2346 static void check_producer (struct dwarf2_cu *cu);
2347
2348 static void free_line_header_voidp (void *arg);
2349 \f
2350 /* Various complaints about symbol reading that don't abort the process.  */
2351
2352 static void
2353 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2354 {
2355   complaint (&symfile_complaints,
2356              _("statement list doesn't fit in .debug_line section"));
2357 }
2358
2359 static void
2360 dwarf2_debug_line_missing_file_complaint (void)
2361 {
2362   complaint (&symfile_complaints,
2363              _(".debug_line section has line data without a file"));
2364 }
2365
2366 static void
2367 dwarf2_debug_line_missing_end_sequence_complaint (void)
2368 {
2369   complaint (&symfile_complaints,
2370              _(".debug_line section has line "
2371                "program sequence without an end"));
2372 }
2373
2374 static void
2375 dwarf2_complex_location_expr_complaint (void)
2376 {
2377   complaint (&symfile_complaints, _("location expression too complex"));
2378 }
2379
2380 static void
2381 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2382                                               int arg3)
2383 {
2384   complaint (&symfile_complaints,
2385              _("const value length mismatch for '%s', got %d, expected %d"),
2386              arg1, arg2, arg3);
2387 }
2388
2389 static void
2390 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2391 {
2392   complaint (&symfile_complaints,
2393              _("debug info runs off end of %s section"
2394                " [in module %s]"),
2395              get_section_name (section),
2396              get_section_file_name (section));
2397 }
2398
2399 static void
2400 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2401 {
2402   complaint (&symfile_complaints,
2403              _("macro debug info contains a "
2404                "malformed macro definition:\n`%s'"),
2405              arg1);
2406 }
2407
2408 static void
2409 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2410 {
2411   complaint (&symfile_complaints,
2412              _("invalid attribute class or form for '%s' in '%s'"),
2413              arg1, arg2);
2414 }
2415
2416 /* Hash function for line_header_hash.  */
2417
2418 static hashval_t
2419 line_header_hash (const struct line_header *ofs)
2420 {
2421   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2422 }
2423
2424 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2425
2426 static hashval_t
2427 line_header_hash_voidp (const void *item)
2428 {
2429   const struct line_header *ofs = (const struct line_header *) item;
2430
2431   return line_header_hash (ofs);
2432 }
2433
2434 /* Equality function for line_header_hash.  */
2435
2436 static int
2437 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2438 {
2439   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2440   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2441
2442   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2443           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2444 }
2445
2446 \f
2447
2448 /* Read the given attribute value as an address, taking the attribute's
2449    form into account.  */
2450
2451 static CORE_ADDR
2452 attr_value_as_address (struct attribute *attr)
2453 {
2454   CORE_ADDR addr;
2455
2456   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2457     {
2458       /* Aside from a few clearly defined exceptions, attributes that
2459          contain an address must always be in DW_FORM_addr form.
2460          Unfortunately, some compilers happen to be violating this
2461          requirement by encoding addresses using other forms, such
2462          as DW_FORM_data4 for example.  For those broken compilers,
2463          we try to do our best, without any guarantee of success,
2464          to interpret the address correctly.  It would also be nice
2465          to generate a complaint, but that would require us to maintain
2466          a list of legitimate cases where a non-address form is allowed,
2467          as well as update callers to pass in at least the CU's DWARF
2468          version.  This is more overhead than what we're willing to
2469          expand for a pretty rare case.  */
2470       addr = DW_UNSND (attr);
2471     }
2472   else
2473     addr = DW_ADDR (attr);
2474
2475   return addr;
2476 }
2477
2478 /* The suffix for an index file.  */
2479 #define INDEX4_SUFFIX ".gdb-index"
2480 #define INDEX5_SUFFIX ".debug_names"
2481 #define DEBUG_STR_SUFFIX ".debug_str"
2482
2483 /* See declaration.  */
2484
2485 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2486                                         const dwarf2_debug_sections *names)
2487   : objfile (objfile_)
2488 {
2489   if (names == NULL)
2490     names = &dwarf2_elf_names;
2491
2492   bfd *obfd = objfile->obfd;
2493
2494   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2495     locate_sections (obfd, sec, *names);
2496 }
2497
2498 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2499
2500 dwarf2_per_objfile::~dwarf2_per_objfile ()
2501 {
2502   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2503   free_cached_comp_units ();
2504
2505   if (quick_file_names_table)
2506     htab_delete (quick_file_names_table);
2507
2508   if (line_header_hash)
2509     htab_delete (line_header_hash);
2510
2511   for (int ix = 0; ix < n_comp_units; ++ix)
2512    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2513
2514   for (int ix = 0; ix < n_type_units; ++ix)
2515     VEC_free (dwarf2_per_cu_ptr,
2516               all_type_units[ix]->per_cu.imported_symtabs);
2517   xfree (all_type_units);
2518
2519   VEC_free (dwarf2_section_info_def, types);
2520
2521   if (dwo_files != NULL)
2522     free_dwo_files (dwo_files, objfile);
2523   if (dwp_file != NULL)
2524     gdb_bfd_unref (dwp_file->dbfd);
2525
2526   if (dwz_file != NULL && dwz_file->dwz_bfd)
2527     gdb_bfd_unref (dwz_file->dwz_bfd);
2528
2529   if (index_table != NULL)
2530     index_table->~mapped_index ();
2531
2532   /* Everything else should be on the objfile obstack.  */
2533 }
2534
2535 /* See declaration.  */
2536
2537 void
2538 dwarf2_per_objfile::free_cached_comp_units ()
2539 {
2540   dwarf2_per_cu_data *per_cu = read_in_chain;
2541   dwarf2_per_cu_data **last_chain = &read_in_chain;
2542   while (per_cu != NULL)
2543     {
2544       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2545
2546       delete per_cu->cu;
2547       *last_chain = next_cu;
2548       per_cu = next_cu;
2549     }
2550 }
2551
2552 /* Try to locate the sections we need for DWARF 2 debugging
2553    information and return true if we have enough to do something.
2554    NAMES points to the dwarf2 section names, or is NULL if the standard
2555    ELF names are used.  */
2556
2557 int
2558 dwarf2_has_info (struct objfile *objfile,
2559                  const struct dwarf2_debug_sections *names)
2560 {
2561   if (objfile->flags & OBJF_READNEVER)
2562     return 0;
2563
2564   struct dwarf2_per_objfile *dwarf2_per_objfile
2565     = get_dwarf2_per_objfile (objfile);
2566
2567   if (dwarf2_per_objfile == NULL)
2568     {
2569       /* Initialize per-objfile state.  */
2570       dwarf2_per_objfile
2571         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2572                                                                      names);
2573       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2574     }
2575   return (!dwarf2_per_objfile->info.is_virtual
2576           && dwarf2_per_objfile->info.s.section != NULL
2577           && !dwarf2_per_objfile->abbrev.is_virtual
2578           && dwarf2_per_objfile->abbrev.s.section != NULL);
2579 }
2580
2581 /* Return the containing section of virtual section SECTION.  */
2582
2583 static struct dwarf2_section_info *
2584 get_containing_section (const struct dwarf2_section_info *section)
2585 {
2586   gdb_assert (section->is_virtual);
2587   return section->s.containing_section;
2588 }
2589
2590 /* Return the bfd owner of SECTION.  */
2591
2592 static struct bfd *
2593 get_section_bfd_owner (const struct dwarf2_section_info *section)
2594 {
2595   if (section->is_virtual)
2596     {
2597       section = get_containing_section (section);
2598       gdb_assert (!section->is_virtual);
2599     }
2600   return section->s.section->owner;
2601 }
2602
2603 /* Return the bfd section of SECTION.
2604    Returns NULL if the section is not present.  */
2605
2606 static asection *
2607 get_section_bfd_section (const struct dwarf2_section_info *section)
2608 {
2609   if (section->is_virtual)
2610     {
2611       section = get_containing_section (section);
2612       gdb_assert (!section->is_virtual);
2613     }
2614   return section->s.section;
2615 }
2616
2617 /* Return the name of SECTION.  */
2618
2619 static const char *
2620 get_section_name (const struct dwarf2_section_info *section)
2621 {
2622   asection *sectp = get_section_bfd_section (section);
2623
2624   gdb_assert (sectp != NULL);
2625   return bfd_section_name (get_section_bfd_owner (section), sectp);
2626 }
2627
2628 /* Return the name of the file SECTION is in.  */
2629
2630 static const char *
2631 get_section_file_name (const struct dwarf2_section_info *section)
2632 {
2633   bfd *abfd = get_section_bfd_owner (section);
2634
2635   return bfd_get_filename (abfd);
2636 }
2637
2638 /* Return the id of SECTION.
2639    Returns 0 if SECTION doesn't exist.  */
2640
2641 static int
2642 get_section_id (const struct dwarf2_section_info *section)
2643 {
2644   asection *sectp = get_section_bfd_section (section);
2645
2646   if (sectp == NULL)
2647     return 0;
2648   return sectp->id;
2649 }
2650
2651 /* Return the flags of SECTION.
2652    SECTION (or containing section if this is a virtual section) must exist.  */
2653
2654 static int
2655 get_section_flags (const struct dwarf2_section_info *section)
2656 {
2657   asection *sectp = get_section_bfd_section (section);
2658
2659   gdb_assert (sectp != NULL);
2660   return bfd_get_section_flags (sectp->owner, sectp);
2661 }
2662
2663 /* When loading sections, we look either for uncompressed section or for
2664    compressed section names.  */
2665
2666 static int
2667 section_is_p (const char *section_name,
2668               const struct dwarf2_section_names *names)
2669 {
2670   if (names->normal != NULL
2671       && strcmp (section_name, names->normal) == 0)
2672     return 1;
2673   if (names->compressed != NULL
2674       && strcmp (section_name, names->compressed) == 0)
2675     return 1;
2676   return 0;
2677 }
2678
2679 /* See declaration.  */
2680
2681 void
2682 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2683                                      const dwarf2_debug_sections &names)
2684 {
2685   flagword aflag = bfd_get_section_flags (abfd, sectp);
2686
2687   if ((aflag & SEC_HAS_CONTENTS) == 0)
2688     {
2689     }
2690   else if (section_is_p (sectp->name, &names.info))
2691     {
2692       this->info.s.section = sectp;
2693       this->info.size = bfd_get_section_size (sectp);
2694     }
2695   else if (section_is_p (sectp->name, &names.abbrev))
2696     {
2697       this->abbrev.s.section = sectp;
2698       this->abbrev.size = bfd_get_section_size (sectp);
2699     }
2700   else if (section_is_p (sectp->name, &names.line))
2701     {
2702       this->line.s.section = sectp;
2703       this->line.size = bfd_get_section_size (sectp);
2704     }
2705   else if (section_is_p (sectp->name, &names.loc))
2706     {
2707       this->loc.s.section = sectp;
2708       this->loc.size = bfd_get_section_size (sectp);
2709     }
2710   else if (section_is_p (sectp->name, &names.loclists))
2711     {
2712       this->loclists.s.section = sectp;
2713       this->loclists.size = bfd_get_section_size (sectp);
2714     }
2715   else if (section_is_p (sectp->name, &names.macinfo))
2716     {
2717       this->macinfo.s.section = sectp;
2718       this->macinfo.size = bfd_get_section_size (sectp);
2719     }
2720   else if (section_is_p (sectp->name, &names.macro))
2721     {
2722       this->macro.s.section = sectp;
2723       this->macro.size = bfd_get_section_size (sectp);
2724     }
2725   else if (section_is_p (sectp->name, &names.str))
2726     {
2727       this->str.s.section = sectp;
2728       this->str.size = bfd_get_section_size (sectp);
2729     }
2730   else if (section_is_p (sectp->name, &names.line_str))
2731     {
2732       this->line_str.s.section = sectp;
2733       this->line_str.size = bfd_get_section_size (sectp);
2734     }
2735   else if (section_is_p (sectp->name, &names.addr))
2736     {
2737       this->addr.s.section = sectp;
2738       this->addr.size = bfd_get_section_size (sectp);
2739     }
2740   else if (section_is_p (sectp->name, &names.frame))
2741     {
2742       this->frame.s.section = sectp;
2743       this->frame.size = bfd_get_section_size (sectp);
2744     }
2745   else if (section_is_p (sectp->name, &names.eh_frame))
2746     {
2747       this->eh_frame.s.section = sectp;
2748       this->eh_frame.size = bfd_get_section_size (sectp);
2749     }
2750   else if (section_is_p (sectp->name, &names.ranges))
2751     {
2752       this->ranges.s.section = sectp;
2753       this->ranges.size = bfd_get_section_size (sectp);
2754     }
2755   else if (section_is_p (sectp->name, &names.rnglists))
2756     {
2757       this->rnglists.s.section = sectp;
2758       this->rnglists.size = bfd_get_section_size (sectp);
2759     }
2760   else if (section_is_p (sectp->name, &names.types))
2761     {
2762       struct dwarf2_section_info type_section;
2763
2764       memset (&type_section, 0, sizeof (type_section));
2765       type_section.s.section = sectp;
2766       type_section.size = bfd_get_section_size (sectp);
2767
2768       VEC_safe_push (dwarf2_section_info_def, this->types,
2769                      &type_section);
2770     }
2771   else if (section_is_p (sectp->name, &names.gdb_index))
2772     {
2773       this->gdb_index.s.section = sectp;
2774       this->gdb_index.size = bfd_get_section_size (sectp);
2775     }
2776   else if (section_is_p (sectp->name, &names.debug_names))
2777     {
2778       this->debug_names.s.section = sectp;
2779       this->debug_names.size = bfd_get_section_size (sectp);
2780     }
2781   else if (section_is_p (sectp->name, &names.debug_aranges))
2782     {
2783       this->debug_aranges.s.section = sectp;
2784       this->debug_aranges.size = bfd_get_section_size (sectp);
2785     }
2786
2787   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2788       && bfd_section_vma (abfd, sectp) == 0)
2789     this->has_section_at_zero = true;
2790 }
2791
2792 /* A helper function that decides whether a section is empty,
2793    or not present.  */
2794
2795 static int
2796 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2797 {
2798   if (section->is_virtual)
2799     return section->size == 0;
2800   return section->s.section == NULL || section->size == 0;
2801 }
2802
2803 /* Read the contents of the section INFO.
2804    OBJFILE is the main object file, but not necessarily the file where
2805    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2806    of the DWO file.
2807    If the section is compressed, uncompress it before returning.  */
2808
2809 static void
2810 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2811 {
2812   asection *sectp;
2813   bfd *abfd;
2814   gdb_byte *buf, *retbuf;
2815
2816   if (info->readin)
2817     return;
2818   info->buffer = NULL;
2819   info->readin = 1;
2820
2821   if (dwarf2_section_empty_p (info))
2822     return;
2823
2824   sectp = get_section_bfd_section (info);
2825
2826   /* If this is a virtual section we need to read in the real one first.  */
2827   if (info->is_virtual)
2828     {
2829       struct dwarf2_section_info *containing_section =
2830         get_containing_section (info);
2831
2832       gdb_assert (sectp != NULL);
2833       if ((sectp->flags & SEC_RELOC) != 0)
2834         {
2835           error (_("Dwarf Error: DWP format V2 with relocations is not"
2836                    " supported in section %s [in module %s]"),
2837                  get_section_name (info), get_section_file_name (info));
2838         }
2839       dwarf2_read_section (objfile, containing_section);
2840       /* Other code should have already caught virtual sections that don't
2841          fit.  */
2842       gdb_assert (info->virtual_offset + info->size
2843                   <= containing_section->size);
2844       /* If the real section is empty or there was a problem reading the
2845          section we shouldn't get here.  */
2846       gdb_assert (containing_section->buffer != NULL);
2847       info->buffer = containing_section->buffer + info->virtual_offset;
2848       return;
2849     }
2850
2851   /* If the section has relocations, we must read it ourselves.
2852      Otherwise we attach it to the BFD.  */
2853   if ((sectp->flags & SEC_RELOC) == 0)
2854     {
2855       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2856       return;
2857     }
2858
2859   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2860   info->buffer = buf;
2861
2862   /* When debugging .o files, we may need to apply relocations; see
2863      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2864      We never compress sections in .o files, so we only need to
2865      try this when the section is not compressed.  */
2866   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2867   if (retbuf != NULL)
2868     {
2869       info->buffer = retbuf;
2870       return;
2871     }
2872
2873   abfd = get_section_bfd_owner (info);
2874   gdb_assert (abfd != NULL);
2875
2876   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2877       || bfd_bread (buf, info->size, abfd) != info->size)
2878     {
2879       error (_("Dwarf Error: Can't read DWARF data"
2880                " in section %s [in module %s]"),
2881              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2882     }
2883 }
2884
2885 /* A helper function that returns the size of a section in a safe way.
2886    If you are positive that the section has been read before using the
2887    size, then it is safe to refer to the dwarf2_section_info object's
2888    "size" field directly.  In other cases, you must call this
2889    function, because for compressed sections the size field is not set
2890    correctly until the section has been read.  */
2891
2892 static bfd_size_type
2893 dwarf2_section_size (struct objfile *objfile,
2894                      struct dwarf2_section_info *info)
2895 {
2896   if (!info->readin)
2897     dwarf2_read_section (objfile, info);
2898   return info->size;
2899 }
2900
2901 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2902    SECTION_NAME.  */
2903
2904 void
2905 dwarf2_get_section_info (struct objfile *objfile,
2906                          enum dwarf2_section_enum sect,
2907                          asection **sectp, const gdb_byte **bufp,
2908                          bfd_size_type *sizep)
2909 {
2910   struct dwarf2_per_objfile *data
2911     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2912                                                   dwarf2_objfile_data_key);
2913   struct dwarf2_section_info *info;
2914
2915   /* We may see an objfile without any DWARF, in which case we just
2916      return nothing.  */
2917   if (data == NULL)
2918     {
2919       *sectp = NULL;
2920       *bufp = NULL;
2921       *sizep = 0;
2922       return;
2923     }
2924   switch (sect)
2925     {
2926     case DWARF2_DEBUG_FRAME:
2927       info = &data->frame;
2928       break;
2929     case DWARF2_EH_FRAME:
2930       info = &data->eh_frame;
2931       break;
2932     default:
2933       gdb_assert_not_reached ("unexpected section");
2934     }
2935
2936   dwarf2_read_section (objfile, info);
2937
2938   *sectp = get_section_bfd_section (info);
2939   *bufp = info->buffer;
2940   *sizep = info->size;
2941 }
2942
2943 /* A helper function to find the sections for a .dwz file.  */
2944
2945 static void
2946 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2947 {
2948   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2949
2950   /* Note that we only support the standard ELF names, because .dwz
2951      is ELF-only (at the time of writing).  */
2952   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2953     {
2954       dwz_file->abbrev.s.section = sectp;
2955       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2956     }
2957   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2958     {
2959       dwz_file->info.s.section = sectp;
2960       dwz_file->info.size = bfd_get_section_size (sectp);
2961     }
2962   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2963     {
2964       dwz_file->str.s.section = sectp;
2965       dwz_file->str.size = bfd_get_section_size (sectp);
2966     }
2967   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2968     {
2969       dwz_file->line.s.section = sectp;
2970       dwz_file->line.size = bfd_get_section_size (sectp);
2971     }
2972   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2973     {
2974       dwz_file->macro.s.section = sectp;
2975       dwz_file->macro.size = bfd_get_section_size (sectp);
2976     }
2977   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2978     {
2979       dwz_file->gdb_index.s.section = sectp;
2980       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2981     }
2982   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2983     {
2984       dwz_file->debug_names.s.section = sectp;
2985       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2986     }
2987 }
2988
2989 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2990    there is no .gnu_debugaltlink section in the file.  Error if there
2991    is such a section but the file cannot be found.  */
2992
2993 static struct dwz_file *
2994 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2995 {
2996   const char *filename;
2997   struct dwz_file *result;
2998   bfd_size_type buildid_len_arg;
2999   size_t buildid_len;
3000   bfd_byte *buildid;
3001
3002   if (dwarf2_per_objfile->dwz_file != NULL)
3003     return dwarf2_per_objfile->dwz_file;
3004
3005   bfd_set_error (bfd_error_no_error);
3006   gdb::unique_xmalloc_ptr<char> data
3007     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
3008                                   &buildid_len_arg, &buildid));
3009   if (data == NULL)
3010     {
3011       if (bfd_get_error () == bfd_error_no_error)
3012         return NULL;
3013       error (_("could not read '.gnu_debugaltlink' section: %s"),
3014              bfd_errmsg (bfd_get_error ()));
3015     }
3016
3017   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
3018
3019   buildid_len = (size_t) buildid_len_arg;
3020
3021   filename = data.get ();
3022
3023   std::string abs_storage;
3024   if (!IS_ABSOLUTE_PATH (filename))
3025     {
3026       gdb::unique_xmalloc_ptr<char> abs
3027         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
3028
3029       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
3030       filename = abs_storage.c_str ();
3031     }
3032
3033   /* First try the file name given in the section.  If that doesn't
3034      work, try to use the build-id instead.  */
3035   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
3036   if (dwz_bfd != NULL)
3037     {
3038       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
3039         dwz_bfd.release ();
3040     }
3041
3042   if (dwz_bfd == NULL)
3043     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
3044
3045   if (dwz_bfd == NULL)
3046     error (_("could not find '.gnu_debugaltlink' file for %s"),
3047            objfile_name (dwarf2_per_objfile->objfile));
3048
3049   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
3050                            struct dwz_file);
3051   result->dwz_bfd = dwz_bfd.release ();
3052
3053   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
3054
3055   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
3056   dwarf2_per_objfile->dwz_file = result;
3057   return result;
3058 }
3059 \f
3060 /* DWARF quick_symbols_functions support.  */
3061
3062 /* TUs can share .debug_line entries, and there can be a lot more TUs than
3063    unique line tables, so we maintain a separate table of all .debug_line
3064    derived entries to support the sharing.
3065    All the quick functions need is the list of file names.  We discard the
3066    line_header when we're done and don't need to record it here.  */
3067 struct quick_file_names
3068 {
3069   /* The data used to construct the hash key.  */
3070   struct stmt_list_hash hash;
3071
3072   /* The number of entries in file_names, real_names.  */
3073   unsigned int num_file_names;
3074
3075   /* The file names from the line table, after being run through
3076      file_full_name.  */
3077   const char **file_names;
3078
3079   /* The file names from the line table after being run through
3080      gdb_realpath.  These are computed lazily.  */
3081   const char **real_names;
3082 };
3083
3084 /* When using the index (and thus not using psymtabs), each CU has an
3085    object of this type.  This is used to hold information needed by
3086    the various "quick" methods.  */
3087 struct dwarf2_per_cu_quick_data
3088 {
3089   /* The file table.  This can be NULL if there was no file table
3090      or it's currently not read in.
3091      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3092   struct quick_file_names *file_names;
3093
3094   /* The corresponding symbol table.  This is NULL if symbols for this
3095      CU have not yet been read.  */
3096   struct compunit_symtab *compunit_symtab;
3097
3098   /* A temporary mark bit used when iterating over all CUs in
3099      expand_symtabs_matching.  */
3100   unsigned int mark : 1;
3101
3102   /* True if we've tried to read the file table and found there isn't one.
3103      There will be no point in trying to read it again next time.  */
3104   unsigned int no_file_data : 1;
3105 };
3106
3107 /* Utility hash function for a stmt_list_hash.  */
3108
3109 static hashval_t
3110 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3111 {
3112   hashval_t v = 0;
3113
3114   if (stmt_list_hash->dwo_unit != NULL)
3115     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3116   v += to_underlying (stmt_list_hash->line_sect_off);
3117   return v;
3118 }
3119
3120 /* Utility equality function for a stmt_list_hash.  */
3121
3122 static int
3123 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3124                     const struct stmt_list_hash *rhs)
3125 {
3126   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3127     return 0;
3128   if (lhs->dwo_unit != NULL
3129       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3130     return 0;
3131
3132   return lhs->line_sect_off == rhs->line_sect_off;
3133 }
3134
3135 /* Hash function for a quick_file_names.  */
3136
3137 static hashval_t
3138 hash_file_name_entry (const void *e)
3139 {
3140   const struct quick_file_names *file_data
3141     = (const struct quick_file_names *) e;
3142
3143   return hash_stmt_list_entry (&file_data->hash);
3144 }
3145
3146 /* Equality function for a quick_file_names.  */
3147
3148 static int
3149 eq_file_name_entry (const void *a, const void *b)
3150 {
3151   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3152   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3153
3154   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3155 }
3156
3157 /* Delete function for a quick_file_names.  */
3158
3159 static void
3160 delete_file_name_entry (void *e)
3161 {
3162   struct quick_file_names *file_data = (struct quick_file_names *) e;
3163   int i;
3164
3165   for (i = 0; i < file_data->num_file_names; ++i)
3166     {
3167       xfree ((void*) file_data->file_names[i]);
3168       if (file_data->real_names)
3169         xfree ((void*) file_data->real_names[i]);
3170     }
3171
3172   /* The space for the struct itself lives on objfile_obstack,
3173      so we don't free it here.  */
3174 }
3175
3176 /* Create a quick_file_names hash table.  */
3177
3178 static htab_t
3179 create_quick_file_names_table (unsigned int nr_initial_entries)
3180 {
3181   return htab_create_alloc (nr_initial_entries,
3182                             hash_file_name_entry, eq_file_name_entry,
3183                             delete_file_name_entry, xcalloc, xfree);
3184 }
3185
3186 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3187    have to be created afterwards.  You should call age_cached_comp_units after
3188    processing PER_CU->CU.  dw2_setup must have been already called.  */
3189
3190 static void
3191 load_cu (struct dwarf2_per_cu_data *per_cu)
3192 {
3193   if (per_cu->is_debug_types)
3194     load_full_type_unit (per_cu);
3195   else
3196     load_full_comp_unit (per_cu, language_minimal);
3197
3198   if (per_cu->cu == NULL)
3199     return;  /* Dummy CU.  */
3200
3201   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3202 }
3203
3204 /* Read in the symbols for PER_CU.  */
3205
3206 static void
3207 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3208 {
3209   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3210
3211   /* Skip type_unit_groups, reading the type units they contain
3212      is handled elsewhere.  */
3213   if (IS_TYPE_UNIT_GROUP (per_cu))
3214     return;
3215
3216   /* The destructor of dwarf2_queue_guard frees any entries left on
3217      the queue.  After this point we're guaranteed to leave this function
3218      with the dwarf queue empty.  */
3219   dwarf2_queue_guard q_guard;
3220
3221   if (dwarf2_per_objfile->using_index
3222       ? per_cu->v.quick->compunit_symtab == NULL
3223       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3224     {
3225       queue_comp_unit (per_cu, language_minimal);
3226       load_cu (per_cu);
3227
3228       /* If we just loaded a CU from a DWO, and we're working with an index
3229          that may badly handle TUs, load all the TUs in that DWO as well.
3230          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3231       if (!per_cu->is_debug_types
3232           && per_cu->cu != NULL
3233           && per_cu->cu->dwo_unit != NULL
3234           && dwarf2_per_objfile->index_table != NULL
3235           && dwarf2_per_objfile->index_table->version <= 7
3236           /* DWP files aren't supported yet.  */
3237           && get_dwp_file (dwarf2_per_objfile) == NULL)
3238         queue_and_load_all_dwo_tus (per_cu);
3239     }
3240
3241   process_queue (dwarf2_per_objfile);
3242
3243   /* Age the cache, releasing compilation units that have not
3244      been used recently.  */
3245   age_cached_comp_units (dwarf2_per_objfile);
3246 }
3247
3248 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3249    the objfile from which this CU came.  Returns the resulting symbol
3250    table.  */
3251
3252 static struct compunit_symtab *
3253 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3254 {
3255   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3256
3257   gdb_assert (dwarf2_per_objfile->using_index);
3258   if (!per_cu->v.quick->compunit_symtab)
3259     {
3260       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3261                                               dwarf2_per_objfile);
3262       scoped_restore decrementer = increment_reading_symtab ();
3263       dw2_do_instantiate_symtab (per_cu);
3264       process_cu_includes (dwarf2_per_objfile);
3265       do_cleanups (back_to);
3266     }
3267
3268   return per_cu->v.quick->compunit_symtab;
3269 }
3270
3271 /* Return the CU/TU given its index.
3272
3273    This is intended for loops like:
3274
3275    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3276                     + dwarf2_per_objfile->n_type_units); ++i)
3277      {
3278        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3279
3280        ...;
3281      }
3282 */
3283
3284 static struct dwarf2_per_cu_data *
3285 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3286               int index)
3287 {
3288   if (index >= dwarf2_per_objfile->n_comp_units)
3289     {
3290       index -= dwarf2_per_objfile->n_comp_units;
3291       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3292       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3293     }
3294
3295   return dwarf2_per_objfile->all_comp_units[index];
3296 }
3297
3298 /* Return the CU given its index.
3299    This differs from dw2_get_cutu in that it's for when you know INDEX
3300    refers to a CU.  */
3301
3302 static struct dwarf2_per_cu_data *
3303 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3304 {
3305   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3306
3307   return dwarf2_per_objfile->all_comp_units[index];
3308 }
3309
3310 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3311    objfile_obstack, and constructed with the specified field
3312    values.  */
3313
3314 static dwarf2_per_cu_data *
3315 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3316                           struct dwarf2_section_info *section,
3317                           int is_dwz,
3318                           sect_offset sect_off, ULONGEST length)
3319 {
3320   struct objfile *objfile = dwarf2_per_objfile->objfile;
3321   dwarf2_per_cu_data *the_cu
3322     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3323                      struct dwarf2_per_cu_data);
3324   the_cu->sect_off = sect_off;
3325   the_cu->length = length;
3326   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3327   the_cu->section = section;
3328   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3329                                    struct dwarf2_per_cu_quick_data);
3330   the_cu->is_dwz = is_dwz;
3331   return the_cu;
3332 }
3333
3334 /* A helper for create_cus_from_index that handles a given list of
3335    CUs.  */
3336
3337 static void
3338 create_cus_from_index_list (struct objfile *objfile,
3339                             const gdb_byte *cu_list, offset_type n_elements,
3340                             struct dwarf2_section_info *section,
3341                             int is_dwz,
3342                             int base_offset)
3343 {
3344   offset_type i;
3345   struct dwarf2_per_objfile *dwarf2_per_objfile
3346     = get_dwarf2_per_objfile (objfile);
3347
3348   for (i = 0; i < n_elements; i += 2)
3349     {
3350       gdb_static_assert (sizeof (ULONGEST) >= 8);
3351
3352       sect_offset sect_off
3353         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3354       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3355       cu_list += 2 * 8;
3356
3357       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3358         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3359                                      sect_off, length);
3360     }
3361 }
3362
3363 /* Read the CU list from the mapped index, and use it to create all
3364    the CU objects for this objfile.  */
3365
3366 static void
3367 create_cus_from_index (struct objfile *objfile,
3368                        const gdb_byte *cu_list, offset_type cu_list_elements,
3369                        const gdb_byte *dwz_list, offset_type dwz_elements)
3370 {
3371   struct dwz_file *dwz;
3372   struct dwarf2_per_objfile *dwarf2_per_objfile
3373     = get_dwarf2_per_objfile (objfile);
3374
3375   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3376   dwarf2_per_objfile->all_comp_units =
3377     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3378                dwarf2_per_objfile->n_comp_units);
3379
3380   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3381                               &dwarf2_per_objfile->info, 0, 0);
3382
3383   if (dwz_elements == 0)
3384     return;
3385
3386   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3387   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3388                               cu_list_elements / 2);
3389 }
3390
3391 /* Create the signatured type hash table from the index.  */
3392
3393 static void
3394 create_signatured_type_table_from_index (struct objfile *objfile,
3395                                          struct dwarf2_section_info *section,
3396                                          const gdb_byte *bytes,
3397                                          offset_type elements)
3398 {
3399   offset_type i;
3400   htab_t sig_types_hash;
3401   struct dwarf2_per_objfile *dwarf2_per_objfile
3402     = get_dwarf2_per_objfile (objfile);
3403
3404   dwarf2_per_objfile->n_type_units
3405     = dwarf2_per_objfile->n_allocated_type_units
3406     = elements / 3;
3407   dwarf2_per_objfile->all_type_units =
3408     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3409
3410   sig_types_hash = allocate_signatured_type_table (objfile);
3411
3412   for (i = 0; i < elements; i += 3)
3413     {
3414       struct signatured_type *sig_type;
3415       ULONGEST signature;
3416       void **slot;
3417       cu_offset type_offset_in_tu;
3418
3419       gdb_static_assert (sizeof (ULONGEST) >= 8);
3420       sect_offset sect_off
3421         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3422       type_offset_in_tu
3423         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3424                                                 BFD_ENDIAN_LITTLE);
3425       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3426       bytes += 3 * 8;
3427
3428       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3429                                  struct signatured_type);
3430       sig_type->signature = signature;
3431       sig_type->type_offset_in_tu = type_offset_in_tu;
3432       sig_type->per_cu.is_debug_types = 1;
3433       sig_type->per_cu.section = section;
3434       sig_type->per_cu.sect_off = sect_off;
3435       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3436       sig_type->per_cu.v.quick
3437         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3438                           struct dwarf2_per_cu_quick_data);
3439
3440       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3441       *slot = sig_type;
3442
3443       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3444     }
3445
3446   dwarf2_per_objfile->signatured_types = sig_types_hash;
3447 }
3448
3449 /* Create the signatured type hash table from .debug_names.  */
3450
3451 static void
3452 create_signatured_type_table_from_debug_names
3453   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3454    const mapped_debug_names &map,
3455    struct dwarf2_section_info *section,
3456    struct dwarf2_section_info *abbrev_section)
3457 {
3458   struct objfile *objfile = dwarf2_per_objfile->objfile;
3459
3460   dwarf2_read_section (objfile, section);
3461   dwarf2_read_section (objfile, abbrev_section);
3462
3463   dwarf2_per_objfile->n_type_units
3464     = dwarf2_per_objfile->n_allocated_type_units
3465     = map.tu_count;
3466   dwarf2_per_objfile->all_type_units
3467     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3468
3469   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3470
3471   for (uint32_t i = 0; i < map.tu_count; ++i)
3472     {
3473       struct signatured_type *sig_type;
3474       ULONGEST signature;
3475       void **slot;
3476       cu_offset type_offset_in_tu;
3477
3478       sect_offset sect_off
3479         = (sect_offset) (extract_unsigned_integer
3480                          (map.tu_table_reordered + i * map.offset_size,
3481                           map.offset_size,
3482                           map.dwarf5_byte_order));
3483
3484       comp_unit_head cu_header;
3485       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3486                                      abbrev_section,
3487                                      section->buffer + to_underlying (sect_off),
3488                                      rcuh_kind::TYPE);
3489
3490       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3491                                  struct signatured_type);
3492       sig_type->signature = cu_header.signature;
3493       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3494       sig_type->per_cu.is_debug_types = 1;
3495       sig_type->per_cu.section = section;
3496       sig_type->per_cu.sect_off = sect_off;
3497       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3498       sig_type->per_cu.v.quick
3499         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3500                           struct dwarf2_per_cu_quick_data);
3501
3502       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3503       *slot = sig_type;
3504
3505       dwarf2_per_objfile->all_type_units[i] = sig_type;
3506     }
3507
3508   dwarf2_per_objfile->signatured_types = sig_types_hash;
3509 }
3510
3511 /* Read the address map data from the mapped index, and use it to
3512    populate the objfile's psymtabs_addrmap.  */
3513
3514 static void
3515 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3516                            struct mapped_index *index)
3517 {
3518   struct objfile *objfile = dwarf2_per_objfile->objfile;
3519   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3520   const gdb_byte *iter, *end;
3521   struct addrmap *mutable_map;
3522   CORE_ADDR baseaddr;
3523
3524   auto_obstack temp_obstack;
3525
3526   mutable_map = addrmap_create_mutable (&temp_obstack);
3527
3528   iter = index->address_table.data ();
3529   end = iter + index->address_table.size ();
3530
3531   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3532
3533   while (iter < end)
3534     {
3535       ULONGEST hi, lo, cu_index;
3536       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3537       iter += 8;
3538       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3539       iter += 8;
3540       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3541       iter += 4;
3542
3543       if (lo > hi)
3544         {
3545           complaint (&symfile_complaints,
3546                      _(".gdb_index address table has invalid range (%s - %s)"),
3547                      hex_string (lo), hex_string (hi));
3548           continue;
3549         }
3550
3551       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3552         {
3553           complaint (&symfile_complaints,
3554                      _(".gdb_index address table has invalid CU number %u"),
3555                      (unsigned) cu_index);
3556           continue;
3557         }
3558
3559       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3560       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3561       addrmap_set_empty (mutable_map, lo, hi - 1,
3562                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3563     }
3564
3565   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3566                                                     &objfile->objfile_obstack);
3567 }
3568
3569 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3570    populate the objfile's psymtabs_addrmap.  */
3571
3572 static void
3573 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3574                              struct dwarf2_section_info *section)
3575 {
3576   struct objfile *objfile = dwarf2_per_objfile->objfile;
3577   bfd *abfd = objfile->obfd;
3578   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3579   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3580                                        SECT_OFF_TEXT (objfile));
3581
3582   auto_obstack temp_obstack;
3583   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3584
3585   std::unordered_map<sect_offset,
3586                      dwarf2_per_cu_data *,
3587                      gdb::hash_enum<sect_offset>>
3588     debug_info_offset_to_per_cu;
3589   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3590     {
3591       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3592       const auto insertpair
3593         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3594       if (!insertpair.second)
3595         {
3596           warning (_("Section .debug_aranges in %s has duplicate "
3597                      "debug_info_offset %s, ignoring .debug_aranges."),
3598                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3599           return;
3600         }
3601     }
3602
3603   dwarf2_read_section (objfile, section);
3604
3605   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3606
3607   const gdb_byte *addr = section->buffer;
3608
3609   while (addr < section->buffer + section->size)
3610     {
3611       const gdb_byte *const entry_addr = addr;
3612       unsigned int bytes_read;
3613
3614       const LONGEST entry_length = read_initial_length (abfd, addr,
3615                                                         &bytes_read);
3616       addr += bytes_read;
3617
3618       const gdb_byte *const entry_end = addr + entry_length;
3619       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3620       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3621       if (addr + entry_length > section->buffer + section->size)
3622         {
3623           warning (_("Section .debug_aranges in %s entry at offset %zu "
3624                      "length %s exceeds section length %s, "
3625                      "ignoring .debug_aranges."),
3626                    objfile_name (objfile), entry_addr - section->buffer,
3627                    plongest (bytes_read + entry_length),
3628                    pulongest (section->size));
3629           return;
3630         }
3631
3632       /* The version number.  */
3633       const uint16_t version = read_2_bytes (abfd, addr);
3634       addr += 2;
3635       if (version != 2)
3636         {
3637           warning (_("Section .debug_aranges in %s entry at offset %zu "
3638                      "has unsupported version %d, ignoring .debug_aranges."),
3639                    objfile_name (objfile), entry_addr - section->buffer,
3640                    version);
3641           return;
3642         }
3643
3644       const uint64_t debug_info_offset
3645         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3646       addr += offset_size;
3647       const auto per_cu_it
3648         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3649       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3650         {
3651           warning (_("Section .debug_aranges in %s entry at offset %zu "
3652                      "debug_info_offset %s does not exists, "
3653                      "ignoring .debug_aranges."),
3654                    objfile_name (objfile), entry_addr - section->buffer,
3655                    pulongest (debug_info_offset));
3656           return;
3657         }
3658       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3659
3660       const uint8_t address_size = *addr++;
3661       if (address_size < 1 || address_size > 8)
3662         {
3663           warning (_("Section .debug_aranges in %s entry at offset %zu "
3664                      "address_size %u is invalid, ignoring .debug_aranges."),
3665                    objfile_name (objfile), entry_addr - section->buffer,
3666                    address_size);
3667           return;
3668         }
3669
3670       const uint8_t segment_selector_size = *addr++;
3671       if (segment_selector_size != 0)
3672         {
3673           warning (_("Section .debug_aranges in %s entry at offset %zu "
3674                      "segment_selector_size %u is not supported, "
3675                      "ignoring .debug_aranges."),
3676                    objfile_name (objfile), entry_addr - section->buffer,
3677                    segment_selector_size);
3678           return;
3679         }
3680
3681       /* Must pad to an alignment boundary that is twice the address
3682          size.  It is undocumented by the DWARF standard but GCC does
3683          use it.  */
3684       for (size_t padding = ((-(addr - section->buffer))
3685                              & (2 * address_size - 1));
3686            padding > 0; padding--)
3687         if (*addr++ != 0)
3688           {
3689             warning (_("Section .debug_aranges in %s entry at offset %zu "
3690                        "padding is not zero, ignoring .debug_aranges."),
3691                      objfile_name (objfile), entry_addr - section->buffer);
3692             return;
3693           }
3694
3695       for (;;)
3696         {
3697           if (addr + 2 * address_size > entry_end)
3698             {
3699               warning (_("Section .debug_aranges in %s entry at offset %zu "
3700                          "address list is not properly terminated, "
3701                          "ignoring .debug_aranges."),
3702                        objfile_name (objfile), entry_addr - section->buffer);
3703               return;
3704             }
3705           ULONGEST start = extract_unsigned_integer (addr, address_size,
3706                                                      dwarf5_byte_order);
3707           addr += address_size;
3708           ULONGEST length = extract_unsigned_integer (addr, address_size,
3709                                                       dwarf5_byte_order);
3710           addr += address_size;
3711           if (start == 0 && length == 0)
3712             break;
3713           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3714             {
3715               /* Symbol was eliminated due to a COMDAT group.  */
3716               continue;
3717             }
3718           ULONGEST end = start + length;
3719           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3720           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3721           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3722         }
3723     }
3724
3725   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3726                                                     &objfile->objfile_obstack);
3727 }
3728
3729 /* The hash function for strings in the mapped index.  This is the same as
3730    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3731    implementation.  This is necessary because the hash function is tied to the
3732    format of the mapped index file.  The hash values do not have to match with
3733    SYMBOL_HASH_NEXT.
3734    
3735    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3736
3737 static hashval_t
3738 mapped_index_string_hash (int index_version, const void *p)
3739 {
3740   const unsigned char *str = (const unsigned char *) p;
3741   hashval_t r = 0;
3742   unsigned char c;
3743
3744   while ((c = *str++) != 0)
3745     {
3746       if (index_version >= 5)
3747         c = tolower (c);
3748       r = r * 67 + c - 113;
3749     }
3750
3751   return r;
3752 }
3753
3754 /* Find a slot in the mapped index INDEX for the object named NAME.
3755    If NAME is found, set *VEC_OUT to point to the CU vector in the
3756    constant pool and return true.  If NAME cannot be found, return
3757    false.  */
3758
3759 static bool
3760 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3761                           offset_type **vec_out)
3762 {
3763   offset_type hash;
3764   offset_type slot, step;
3765   int (*cmp) (const char *, const char *);
3766
3767   gdb::unique_xmalloc_ptr<char> without_params;
3768   if (current_language->la_language == language_cplus
3769       || current_language->la_language == language_fortran
3770       || current_language->la_language == language_d)
3771     {
3772       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3773          not contain any.  */
3774
3775       if (strchr (name, '(') != NULL)
3776         {
3777           without_params = cp_remove_params (name);
3778
3779           if (without_params != NULL)
3780             name = without_params.get ();
3781         }
3782     }
3783
3784   /* Index version 4 did not support case insensitive searches.  But the
3785      indices for case insensitive languages are built in lowercase, therefore
3786      simulate our NAME being searched is also lowercased.  */
3787   hash = mapped_index_string_hash ((index->version == 4
3788                                     && case_sensitivity == case_sensitive_off
3789                                     ? 5 : index->version),
3790                                    name);
3791
3792   slot = hash & (index->symbol_table.size () - 1);
3793   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3794   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3795
3796   for (;;)
3797     {
3798       const char *str;
3799
3800       const auto &bucket = index->symbol_table[slot];
3801       if (bucket.name == 0 && bucket.vec == 0)
3802         return false;
3803
3804       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3805       if (!cmp (name, str))
3806         {
3807           *vec_out = (offset_type *) (index->constant_pool
3808                                       + MAYBE_SWAP (bucket.vec));
3809           return true;
3810         }
3811
3812       slot = (slot + step) & (index->symbol_table.size () - 1);
3813     }
3814 }
3815
3816 /* A helper function that reads the .gdb_index from SECTION and fills
3817    in MAP.  FILENAME is the name of the file containing the section;
3818    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3819    ok to use deprecated sections.
3820
3821    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3822    out parameters that are filled in with information about the CU and
3823    TU lists in the section.
3824
3825    Returns 1 if all went well, 0 otherwise.  */
3826
3827 static int
3828 read_index_from_section (struct objfile *objfile,
3829                          const char *filename,
3830                          int deprecated_ok,
3831                          struct dwarf2_section_info *section,
3832                          struct mapped_index *map,
3833                          const gdb_byte **cu_list,
3834                          offset_type *cu_list_elements,
3835                          const gdb_byte **types_list,
3836                          offset_type *types_list_elements)
3837 {
3838   const gdb_byte *addr;
3839   offset_type version;
3840   offset_type *metadata;
3841   int i;
3842
3843   if (dwarf2_section_empty_p (section))
3844     return 0;
3845
3846   /* Older elfutils strip versions could keep the section in the main
3847      executable while splitting it for the separate debug info file.  */
3848   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3849     return 0;
3850
3851   dwarf2_read_section (objfile, section);
3852
3853   addr = section->buffer;
3854   /* Version check.  */
3855   version = MAYBE_SWAP (*(offset_type *) addr);
3856   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3857      causes the index to behave very poorly for certain requests.  Version 3
3858      contained incomplete addrmap.  So, it seems better to just ignore such
3859      indices.  */
3860   if (version < 4)
3861     {
3862       static int warning_printed = 0;
3863       if (!warning_printed)
3864         {
3865           warning (_("Skipping obsolete .gdb_index section in %s."),
3866                    filename);
3867           warning_printed = 1;
3868         }
3869       return 0;
3870     }
3871   /* Index version 4 uses a different hash function than index version
3872      5 and later.
3873
3874      Versions earlier than 6 did not emit psymbols for inlined
3875      functions.  Using these files will cause GDB not to be able to
3876      set breakpoints on inlined functions by name, so we ignore these
3877      indices unless the user has done
3878      "set use-deprecated-index-sections on".  */
3879   if (version < 6 && !deprecated_ok)
3880     {
3881       static int warning_printed = 0;
3882       if (!warning_printed)
3883         {
3884           warning (_("\
3885 Skipping deprecated .gdb_index section in %s.\n\
3886 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3887 to use the section anyway."),
3888                    filename);
3889           warning_printed = 1;
3890         }
3891       return 0;
3892     }
3893   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3894      of the TU (for symbols coming from TUs),
3895      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3896      Plus gold-generated indices can have duplicate entries for global symbols,
3897      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3898      These are just performance bugs, and we can't distinguish gdb-generated
3899      indices from gold-generated ones, so issue no warning here.  */
3900
3901   /* Indexes with higher version than the one supported by GDB may be no
3902      longer backward compatible.  */
3903   if (version > 8)
3904     return 0;
3905
3906   map->version = version;
3907   map->total_size = section->size;
3908
3909   metadata = (offset_type *) (addr + sizeof (offset_type));
3910
3911   i = 0;
3912   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3913   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3914                        / 8);
3915   ++i;
3916
3917   *types_list = addr + MAYBE_SWAP (metadata[i]);
3918   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3919                            - MAYBE_SWAP (metadata[i]))
3920                           / 8);
3921   ++i;
3922
3923   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3924   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3925   map->address_table
3926     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3927   ++i;
3928
3929   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3930   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3931   map->symbol_table
3932     = gdb::array_view<mapped_index::symbol_table_slot>
3933        ((mapped_index::symbol_table_slot *) symbol_table,
3934         (mapped_index::symbol_table_slot *) symbol_table_end);
3935
3936   ++i;
3937   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3938
3939   return 1;
3940 }
3941
3942 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3943    elements of all the CUs and return 1.  Otherwise, return 0.  */
3944
3945 static int
3946 dwarf2_read_index (struct objfile *objfile)
3947 {
3948   struct mapped_index local_map, *map;
3949   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3950   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3951   struct dwz_file *dwz;
3952   struct dwarf2_per_objfile *dwarf2_per_objfile
3953     = get_dwarf2_per_objfile (objfile);
3954
3955   if (!read_index_from_section (objfile, objfile_name (objfile),
3956                                 use_deprecated_index_sections,
3957                                 &dwarf2_per_objfile->gdb_index, &local_map,
3958                                 &cu_list, &cu_list_elements,
3959                                 &types_list, &types_list_elements))
3960     return 0;
3961
3962   /* Don't use the index if it's empty.  */
3963   if (local_map.symbol_table.empty ())
3964     return 0;
3965
3966   /* If there is a .dwz file, read it so we can get its CU list as
3967      well.  */
3968   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3969   if (dwz != NULL)
3970     {
3971       struct mapped_index dwz_map;
3972       const gdb_byte *dwz_types_ignore;
3973       offset_type dwz_types_elements_ignore;
3974
3975       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3976                                     1,
3977                                     &dwz->gdb_index, &dwz_map,
3978                                     &dwz_list, &dwz_list_elements,
3979                                     &dwz_types_ignore,
3980                                     &dwz_types_elements_ignore))
3981         {
3982           warning (_("could not read '.gdb_index' section from %s; skipping"),
3983                    bfd_get_filename (dwz->dwz_bfd));
3984           return 0;
3985         }
3986     }
3987
3988   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3989                          dwz_list_elements);
3990
3991   if (types_list_elements)
3992     {
3993       struct dwarf2_section_info *section;
3994
3995       /* We can only handle a single .debug_types when we have an
3996          index.  */
3997       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3998         return 0;
3999
4000       section = VEC_index (dwarf2_section_info_def,
4001                            dwarf2_per_objfile->types, 0);
4002
4003       create_signatured_type_table_from_index (objfile, section, types_list,
4004                                                types_list_elements);
4005     }
4006
4007   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
4008
4009   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
4010   map = new (map) mapped_index ();
4011   *map = local_map;
4012
4013   dwarf2_per_objfile->index_table = map;
4014   dwarf2_per_objfile->using_index = 1;
4015   dwarf2_per_objfile->quick_file_names_table =
4016     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4017
4018   return 1;
4019 }
4020
4021 /* die_reader_func for dw2_get_file_names.  */
4022
4023 static void
4024 dw2_get_file_names_reader (const struct die_reader_specs *reader,
4025                            const gdb_byte *info_ptr,
4026                            struct die_info *comp_unit_die,
4027                            int has_children,
4028                            void *data)
4029 {
4030   struct dwarf2_cu *cu = reader->cu;
4031   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
4032   struct dwarf2_per_objfile *dwarf2_per_objfile
4033     = cu->per_cu->dwarf2_per_objfile;
4034   struct objfile *objfile = dwarf2_per_objfile->objfile;
4035   struct dwarf2_per_cu_data *lh_cu;
4036   struct attribute *attr;
4037   int i;
4038   void **slot;
4039   struct quick_file_names *qfn;
4040
4041   gdb_assert (! this_cu->is_debug_types);
4042
4043   /* Our callers never want to match partial units -- instead they
4044      will match the enclosing full CU.  */
4045   if (comp_unit_die->tag == DW_TAG_partial_unit)
4046     {
4047       this_cu->v.quick->no_file_data = 1;
4048       return;
4049     }
4050
4051   lh_cu = this_cu;
4052   slot = NULL;
4053
4054   line_header_up lh;
4055   sect_offset line_offset {};
4056
4057   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4058   if (attr)
4059     {
4060       struct quick_file_names find_entry;
4061
4062       line_offset = (sect_offset) DW_UNSND (attr);
4063
4064       /* We may have already read in this line header (TU line header sharing).
4065          If we have we're done.  */
4066       find_entry.hash.dwo_unit = cu->dwo_unit;
4067       find_entry.hash.line_sect_off = line_offset;
4068       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
4069                              &find_entry, INSERT);
4070       if (*slot != NULL)
4071         {
4072           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
4073           return;
4074         }
4075
4076       lh = dwarf_decode_line_header (line_offset, cu);
4077     }
4078   if (lh == NULL)
4079     {
4080       lh_cu->v.quick->no_file_data = 1;
4081       return;
4082     }
4083
4084   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4085   qfn->hash.dwo_unit = cu->dwo_unit;
4086   qfn->hash.line_sect_off = line_offset;
4087   gdb_assert (slot != NULL);
4088   *slot = qfn;
4089
4090   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4091
4092   qfn->num_file_names = lh->file_names.size ();
4093   qfn->file_names =
4094     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4095   for (i = 0; i < lh->file_names.size (); ++i)
4096     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4097   qfn->real_names = NULL;
4098
4099   lh_cu->v.quick->file_names = qfn;
4100 }
4101
4102 /* A helper for the "quick" functions which attempts to read the line
4103    table for THIS_CU.  */
4104
4105 static struct quick_file_names *
4106 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4107 {
4108   /* This should never be called for TUs.  */
4109   gdb_assert (! this_cu->is_debug_types);
4110   /* Nor type unit groups.  */
4111   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4112
4113   if (this_cu->v.quick->file_names != NULL)
4114     return this_cu->v.quick->file_names;
4115   /* If we know there is no line data, no point in looking again.  */
4116   if (this_cu->v.quick->no_file_data)
4117     return NULL;
4118
4119   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4120
4121   if (this_cu->v.quick->no_file_data)
4122     return NULL;
4123   return this_cu->v.quick->file_names;
4124 }
4125
4126 /* A helper for the "quick" functions which computes and caches the
4127    real path for a given file name from the line table.  */
4128
4129 static const char *
4130 dw2_get_real_path (struct objfile *objfile,
4131                    struct quick_file_names *qfn, int index)
4132 {
4133   if (qfn->real_names == NULL)
4134     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4135                                       qfn->num_file_names, const char *);
4136
4137   if (qfn->real_names[index] == NULL)
4138     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4139
4140   return qfn->real_names[index];
4141 }
4142
4143 static struct symtab *
4144 dw2_find_last_source_symtab (struct objfile *objfile)
4145 {
4146   struct dwarf2_per_objfile *dwarf2_per_objfile
4147     = get_dwarf2_per_objfile (objfile);
4148   int index = dwarf2_per_objfile->n_comp_units - 1;
4149   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4150   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4151
4152   if (cust == NULL)
4153     return NULL;
4154
4155   return compunit_primary_filetab (cust);
4156 }
4157
4158 /* Traversal function for dw2_forget_cached_source_info.  */
4159
4160 static int
4161 dw2_free_cached_file_names (void **slot, void *info)
4162 {
4163   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4164
4165   if (file_data->real_names)
4166     {
4167       int i;
4168
4169       for (i = 0; i < file_data->num_file_names; ++i)
4170         {
4171           xfree ((void*) file_data->real_names[i]);
4172           file_data->real_names[i] = NULL;
4173         }
4174     }
4175
4176   return 1;
4177 }
4178
4179 static void
4180 dw2_forget_cached_source_info (struct objfile *objfile)
4181 {
4182   struct dwarf2_per_objfile *dwarf2_per_objfile
4183     = get_dwarf2_per_objfile (objfile);
4184
4185   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4186                           dw2_free_cached_file_names, NULL);
4187 }
4188
4189 /* Helper function for dw2_map_symtabs_matching_filename that expands
4190    the symtabs and calls the iterator.  */
4191
4192 static int
4193 dw2_map_expand_apply (struct objfile *objfile,
4194                       struct dwarf2_per_cu_data *per_cu,
4195                       const char *name, const char *real_path,
4196                       gdb::function_view<bool (symtab *)> callback)
4197 {
4198   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4199
4200   /* Don't visit already-expanded CUs.  */
4201   if (per_cu->v.quick->compunit_symtab)
4202     return 0;
4203
4204   /* This may expand more than one symtab, and we want to iterate over
4205      all of them.  */
4206   dw2_instantiate_symtab (per_cu);
4207
4208   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4209                                     last_made, callback);
4210 }
4211
4212 /* Implementation of the map_symtabs_matching_filename method.  */
4213
4214 static bool
4215 dw2_map_symtabs_matching_filename
4216   (struct objfile *objfile, const char *name, const char *real_path,
4217    gdb::function_view<bool (symtab *)> callback)
4218 {
4219   int i;
4220   const char *name_basename = lbasename (name);
4221   struct dwarf2_per_objfile *dwarf2_per_objfile
4222     = get_dwarf2_per_objfile (objfile);
4223
4224   /* The rule is CUs specify all the files, including those used by
4225      any TU, so there's no need to scan TUs here.  */
4226
4227   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4228     {
4229       int j;
4230       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4231       struct quick_file_names *file_data;
4232
4233       /* We only need to look at symtabs not already expanded.  */
4234       if (per_cu->v.quick->compunit_symtab)
4235         continue;
4236
4237       file_data = dw2_get_file_names (per_cu);
4238       if (file_data == NULL)
4239         continue;
4240
4241       for (j = 0; j < file_data->num_file_names; ++j)
4242         {
4243           const char *this_name = file_data->file_names[j];
4244           const char *this_real_name;
4245
4246           if (compare_filenames_for_search (this_name, name))
4247             {
4248               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4249                                         callback))
4250                 return true;
4251               continue;
4252             }
4253
4254           /* Before we invoke realpath, which can get expensive when many
4255              files are involved, do a quick comparison of the basenames.  */
4256           if (! basenames_may_differ
4257               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4258             continue;
4259
4260           this_real_name = dw2_get_real_path (objfile, file_data, j);
4261           if (compare_filenames_for_search (this_real_name, name))
4262             {
4263               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4264                                         callback))
4265                 return true;
4266               continue;
4267             }
4268
4269           if (real_path != NULL)
4270             {
4271               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4272               gdb_assert (IS_ABSOLUTE_PATH (name));
4273               if (this_real_name != NULL
4274                   && FILENAME_CMP (real_path, this_real_name) == 0)
4275                 {
4276                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4277                                             callback))
4278                     return true;
4279                   continue;
4280                 }
4281             }
4282         }
4283     }
4284
4285   return false;
4286 }
4287
4288 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4289
4290 struct dw2_symtab_iterator
4291 {
4292   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4293   struct dwarf2_per_objfile *dwarf2_per_objfile;
4294   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4295   int want_specific_block;
4296   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4297      Unused if !WANT_SPECIFIC_BLOCK.  */
4298   int block_index;
4299   /* The kind of symbol we're looking for.  */
4300   domain_enum domain;
4301   /* The list of CUs from the index entry of the symbol,
4302      or NULL if not found.  */
4303   offset_type *vec;
4304   /* The next element in VEC to look at.  */
4305   int next;
4306   /* The number of elements in VEC, or zero if there is no match.  */
4307   int length;
4308   /* Have we seen a global version of the symbol?
4309      If so we can ignore all further global instances.
4310      This is to work around gold/15646, inefficient gold-generated
4311      indices.  */
4312   int global_seen;
4313 };
4314
4315 /* Initialize the index symtab iterator ITER.
4316    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4317    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4318
4319 static void
4320 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4321                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4322                       int want_specific_block,
4323                       int block_index,
4324                       domain_enum domain,
4325                       const char *name)
4326 {
4327   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4328   iter->want_specific_block = want_specific_block;
4329   iter->block_index = block_index;
4330   iter->domain = domain;
4331   iter->next = 0;
4332   iter->global_seen = 0;
4333
4334   mapped_index *index = dwarf2_per_objfile->index_table;
4335
4336   /* index is NULL if OBJF_READNOW.  */
4337   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4338     iter->length = MAYBE_SWAP (*iter->vec);
4339   else
4340     {
4341       iter->vec = NULL;
4342       iter->length = 0;
4343     }
4344 }
4345
4346 /* Return the next matching CU or NULL if there are no more.  */
4347
4348 static struct dwarf2_per_cu_data *
4349 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4350 {
4351   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4352
4353   for ( ; iter->next < iter->length; ++iter->next)
4354     {
4355       offset_type cu_index_and_attrs =
4356         MAYBE_SWAP (iter->vec[iter->next + 1]);
4357       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4358       struct dwarf2_per_cu_data *per_cu;
4359       int want_static = iter->block_index != GLOBAL_BLOCK;
4360       /* This value is only valid for index versions >= 7.  */
4361       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4362       gdb_index_symbol_kind symbol_kind =
4363         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4364       /* Only check the symbol attributes if they're present.
4365          Indices prior to version 7 don't record them,
4366          and indices >= 7 may elide them for certain symbols
4367          (gold does this).  */
4368       int attrs_valid =
4369         (dwarf2_per_objfile->index_table->version >= 7
4370          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4371
4372       /* Don't crash on bad data.  */
4373       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4374                        + dwarf2_per_objfile->n_type_units))
4375         {
4376           complaint (&symfile_complaints,
4377                      _(".gdb_index entry has bad CU index"
4378                        " [in module %s]"),
4379                      objfile_name (dwarf2_per_objfile->objfile));
4380           continue;
4381         }
4382
4383       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4384
4385       /* Skip if already read in.  */
4386       if (per_cu->v.quick->compunit_symtab)
4387         continue;
4388
4389       /* Check static vs global.  */
4390       if (attrs_valid)
4391         {
4392           if (iter->want_specific_block
4393               && want_static != is_static)
4394             continue;
4395           /* Work around gold/15646.  */
4396           if (!is_static && iter->global_seen)
4397             continue;
4398           if (!is_static)
4399             iter->global_seen = 1;
4400         }
4401
4402       /* Only check the symbol's kind if it has one.  */
4403       if (attrs_valid)
4404         {
4405           switch (iter->domain)
4406             {
4407             case VAR_DOMAIN:
4408               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4409                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4410                   /* Some types are also in VAR_DOMAIN.  */
4411                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4412                 continue;
4413               break;
4414             case STRUCT_DOMAIN:
4415               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4416                 continue;
4417               break;
4418             case LABEL_DOMAIN:
4419               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4420                 continue;
4421               break;
4422             default:
4423               break;
4424             }
4425         }
4426
4427       ++iter->next;
4428       return per_cu;
4429     }
4430
4431   return NULL;
4432 }
4433
4434 static struct compunit_symtab *
4435 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4436                    const char *name, domain_enum domain)
4437 {
4438   struct compunit_symtab *stab_best = NULL;
4439   struct dwarf2_per_objfile *dwarf2_per_objfile
4440     = get_dwarf2_per_objfile (objfile);
4441
4442   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4443
4444   struct dw2_symtab_iterator iter;
4445   struct dwarf2_per_cu_data *per_cu;
4446
4447   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4448
4449   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4450     {
4451       struct symbol *sym, *with_opaque = NULL;
4452       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4453       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4454       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4455
4456       sym = block_find_symbol (block, name, domain,
4457                                block_find_non_opaque_type_preferred,
4458                                &with_opaque);
4459
4460       /* Some caution must be observed with overloaded functions
4461          and methods, since the index will not contain any overload
4462          information (but NAME might contain it).  */
4463
4464       if (sym != NULL
4465           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4466         return stab;
4467       if (with_opaque != NULL
4468           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4469         stab_best = stab;
4470
4471       /* Keep looking through other CUs.  */
4472     }
4473
4474   return stab_best;
4475 }
4476
4477 static void
4478 dw2_print_stats (struct objfile *objfile)
4479 {
4480   struct dwarf2_per_objfile *dwarf2_per_objfile
4481     = get_dwarf2_per_objfile (objfile);
4482   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4483   int count = 0;
4484
4485   for (int i = 0; i < total; ++i)
4486     {
4487       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4488
4489       if (!per_cu->v.quick->compunit_symtab)
4490         ++count;
4491     }
4492   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4493   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4494 }
4495
4496 /* This dumps minimal information about the index.
4497    It is called via "mt print objfiles".
4498    One use is to verify .gdb_index has been loaded by the
4499    gdb.dwarf2/gdb-index.exp testcase.  */
4500
4501 static void
4502 dw2_dump (struct objfile *objfile)
4503 {
4504   struct dwarf2_per_objfile *dwarf2_per_objfile
4505     = get_dwarf2_per_objfile (objfile);
4506
4507   gdb_assert (dwarf2_per_objfile->using_index);
4508   printf_filtered (".gdb_index:");
4509   if (dwarf2_per_objfile->index_table != NULL)
4510     {
4511       printf_filtered (" version %d\n",
4512                        dwarf2_per_objfile->index_table->version);
4513     }
4514   else
4515     printf_filtered (" faked for \"readnow\"\n");
4516   printf_filtered ("\n");
4517 }
4518
4519 static void
4520 dw2_relocate (struct objfile *objfile,
4521               const struct section_offsets *new_offsets,
4522               const struct section_offsets *delta)
4523 {
4524   /* There's nothing to relocate here.  */
4525 }
4526
4527 static void
4528 dw2_expand_symtabs_for_function (struct objfile *objfile,
4529                                  const char *func_name)
4530 {
4531   struct dwarf2_per_objfile *dwarf2_per_objfile
4532     = get_dwarf2_per_objfile (objfile);
4533
4534   struct dw2_symtab_iterator iter;
4535   struct dwarf2_per_cu_data *per_cu;
4536
4537   /* Note: It doesn't matter what we pass for block_index here.  */
4538   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4539                         func_name);
4540
4541   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4542     dw2_instantiate_symtab (per_cu);
4543
4544 }
4545
4546 static void
4547 dw2_expand_all_symtabs (struct objfile *objfile)
4548 {
4549   struct dwarf2_per_objfile *dwarf2_per_objfile
4550     = get_dwarf2_per_objfile (objfile);
4551   int total_units = (dwarf2_per_objfile->n_comp_units
4552                      + dwarf2_per_objfile->n_type_units);
4553
4554   for (int i = 0; i < total_units; ++i)
4555     {
4556       struct dwarf2_per_cu_data *per_cu
4557         = dw2_get_cutu (dwarf2_per_objfile, i);
4558
4559       dw2_instantiate_symtab (per_cu);
4560     }
4561 }
4562
4563 static void
4564 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4565                                   const char *fullname)
4566 {
4567   struct dwarf2_per_objfile *dwarf2_per_objfile
4568     = get_dwarf2_per_objfile (objfile);
4569
4570   /* We don't need to consider type units here.
4571      This is only called for examining code, e.g. expand_line_sal.
4572      There can be an order of magnitude (or more) more type units
4573      than comp units, and we avoid them if we can.  */
4574
4575   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4576     {
4577       int j;
4578       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4579       struct quick_file_names *file_data;
4580
4581       /* We only need to look at symtabs not already expanded.  */
4582       if (per_cu->v.quick->compunit_symtab)
4583         continue;
4584
4585       file_data = dw2_get_file_names (per_cu);
4586       if (file_data == NULL)
4587         continue;
4588
4589       for (j = 0; j < file_data->num_file_names; ++j)
4590         {
4591           const char *this_fullname = file_data->file_names[j];
4592
4593           if (filename_cmp (this_fullname, fullname) == 0)
4594             {
4595               dw2_instantiate_symtab (per_cu);
4596               break;
4597             }
4598         }
4599     }
4600 }
4601
4602 static void
4603 dw2_map_matching_symbols (struct objfile *objfile,
4604                           const char * name, domain_enum domain,
4605                           int global,
4606                           int (*callback) (struct block *,
4607                                            struct symbol *, void *),
4608                           void *data, symbol_name_match_type match,
4609                           symbol_compare_ftype *ordered_compare)
4610 {
4611   /* Currently unimplemented; used for Ada.  The function can be called if the
4612      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4613      does not look for non-Ada symbols this function should just return.  */
4614 }
4615
4616 /* Symbol name matcher for .gdb_index names.
4617
4618    Symbol names in .gdb_index have a few particularities:
4619
4620    - There's no indication of which is the language of each symbol.
4621
4622      Since each language has its own symbol name matching algorithm,
4623      and we don't know which language is the right one, we must match
4624      each symbol against all languages.  This would be a potential
4625      performance problem if it were not mitigated by the
4626      mapped_index::name_components lookup table, which significantly
4627      reduces the number of times we need to call into this matcher,
4628      making it a non-issue.
4629
4630    - Symbol names in the index have no overload (parameter)
4631      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4632      appear as "foo" in the index, for example.
4633
4634      This means that the lookup names passed to the symbol name
4635      matcher functions must have no parameter information either
4636      because (e.g.) symbol search name "foo" does not match
4637      lookup-name "foo(int)" [while swapping search name for lookup
4638      name would match].
4639 */
4640 class gdb_index_symbol_name_matcher
4641 {
4642 public:
4643   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4644   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4645
4646   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4647      Returns true if any matcher matches.  */
4648   bool matches (const char *symbol_name);
4649
4650 private:
4651   /* A reference to the lookup name we're matching against.  */
4652   const lookup_name_info &m_lookup_name;
4653
4654   /* A vector holding all the different symbol name matchers, for all
4655      languages.  */
4656   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4657 };
4658
4659 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4660   (const lookup_name_info &lookup_name)
4661     : m_lookup_name (lookup_name)
4662 {
4663   /* Prepare the vector of comparison functions upfront, to avoid
4664      doing the same work for each symbol.  Care is taken to avoid
4665      matching with the same matcher more than once if/when multiple
4666      languages use the same matcher function.  */
4667   auto &matchers = m_symbol_name_matcher_funcs;
4668   matchers.reserve (nr_languages);
4669
4670   matchers.push_back (default_symbol_name_matcher);
4671
4672   for (int i = 0; i < nr_languages; i++)
4673     {
4674       const language_defn *lang = language_def ((enum language) i);
4675       symbol_name_matcher_ftype *name_matcher
4676         = get_symbol_name_matcher (lang, m_lookup_name);
4677
4678       /* Don't insert the same comparison routine more than once.
4679          Note that we do this linear walk instead of a seemingly
4680          cheaper sorted insert, or use a std::set or something like
4681          that, because relative order of function addresses is not
4682          stable.  This is not a problem in practice because the number
4683          of supported languages is low, and the cost here is tiny
4684          compared to the number of searches we'll do afterwards using
4685          this object.  */
4686       if (name_matcher != default_symbol_name_matcher
4687           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4688               == matchers.end ()))
4689         matchers.push_back (name_matcher);
4690     }
4691 }
4692
4693 bool
4694 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4695 {
4696   for (auto matches_name : m_symbol_name_matcher_funcs)
4697     if (matches_name (symbol_name, m_lookup_name, NULL))
4698       return true;
4699
4700   return false;
4701 }
4702
4703 /* Starting from a search name, return the string that finds the upper
4704    bound of all strings that start with SEARCH_NAME in a sorted name
4705    list.  Returns the empty string to indicate that the upper bound is
4706    the end of the list.  */
4707
4708 static std::string
4709 make_sort_after_prefix_name (const char *search_name)
4710 {
4711   /* When looking to complete "func", we find the upper bound of all
4712      symbols that start with "func" by looking for where we'd insert
4713      the closest string that would follow "func" in lexicographical
4714      order.  Usually, that's "func"-with-last-character-incremented,
4715      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4716      will be UTF-8 multi-byte sequences, but we can't be certain.
4717      Especially mind the 0xff character, which is a valid character in
4718      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4719      rule out compilers allowing it in identifiers.  Note that
4720      conveniently, strcmp/strcasecmp are specified to compare
4721      characters interpreted as unsigned char.  So what we do is treat
4722      the whole string as a base 256 number composed of a sequence of
4723      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4724      to 0, and carries 1 to the following more-significant position.
4725      If the very first character in SEARCH_NAME ends up incremented
4726      and carries/overflows, then the upper bound is the end of the
4727      list.  The string after the empty string is also the empty
4728      string.
4729
4730      Some examples of this operation:
4731
4732        SEARCH_NAME  => "+1" RESULT
4733
4734        "abc"              => "abd"
4735        "ab\xff"           => "ac"
4736        "\xff" "a" "\xff"  => "\xff" "b"
4737        "\xff"             => ""
4738        "\xff\xff"         => ""
4739        ""                 => ""
4740
4741      Then, with these symbols for example:
4742
4743       func
4744       func1
4745       fund
4746
4747      completing "func" looks for symbols between "func" and
4748      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4749      which finds "func" and "func1", but not "fund".
4750
4751      And with:
4752
4753       funcÿ     (Latin1 'ÿ' [0xff])
4754       funcÿ1
4755       fund
4756
4757      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4758      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4759
4760      And with:
4761
4762       ÿÿ        (Latin1 'ÿ' [0xff])
4763       ÿÿ1
4764
4765      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4766      the end of the list.
4767   */
4768   std::string after = search_name;
4769   while (!after.empty () && (unsigned char) after.back () == 0xff)
4770     after.pop_back ();
4771   if (!after.empty ())
4772     after.back () = (unsigned char) after.back () + 1;
4773   return after;
4774 }
4775
4776 /* See declaration.  */
4777
4778 std::pair<std::vector<name_component>::const_iterator,
4779           std::vector<name_component>::const_iterator>
4780 mapped_index_base::find_name_components_bounds
4781   (const lookup_name_info &lookup_name_without_params) const
4782 {
4783   auto *name_cmp
4784     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4785
4786   const char *cplus
4787     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4788
4789   /* Comparison function object for lower_bound that matches against a
4790      given symbol name.  */
4791   auto lookup_compare_lower = [&] (const name_component &elem,
4792                                    const char *name)
4793     {
4794       const char *elem_qualified = this->symbol_name_at (elem.idx);
4795       const char *elem_name = elem_qualified + elem.name_offset;
4796       return name_cmp (elem_name, name) < 0;
4797     };
4798
4799   /* Comparison function object for upper_bound that matches against a
4800      given symbol name.  */
4801   auto lookup_compare_upper = [&] (const char *name,
4802                                    const name_component &elem)
4803     {
4804       const char *elem_qualified = this->symbol_name_at (elem.idx);
4805       const char *elem_name = elem_qualified + elem.name_offset;
4806       return name_cmp (name, elem_name) < 0;
4807     };
4808
4809   auto begin = this->name_components.begin ();
4810   auto end = this->name_components.end ();
4811
4812   /* Find the lower bound.  */
4813   auto lower = [&] ()
4814     {
4815       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4816         return begin;
4817       else
4818         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4819     } ();
4820
4821   /* Find the upper bound.  */
4822   auto upper = [&] ()
4823     {
4824       if (lookup_name_without_params.completion_mode ())
4825         {
4826           /* In completion mode, we want UPPER to point past all
4827              symbols names that have the same prefix.  I.e., with
4828              these symbols, and completing "func":
4829
4830               function        << lower bound
4831               function1
4832               other_function  << upper bound
4833
4834              We find the upper bound by looking for the insertion
4835              point of "func"-with-last-character-incremented,
4836              i.e. "fund".  */
4837           std::string after = make_sort_after_prefix_name (cplus);
4838           if (after.empty ())
4839             return end;
4840           return std::lower_bound (lower, end, after.c_str (),
4841                                    lookup_compare_lower);
4842         }
4843       else
4844         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4845     } ();
4846
4847   return {lower, upper};
4848 }
4849
4850 /* See declaration.  */
4851
4852 void
4853 mapped_index_base::build_name_components ()
4854 {
4855   if (!this->name_components.empty ())
4856     return;
4857
4858   this->name_components_casing = case_sensitivity;
4859   auto *name_cmp
4860     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4861
4862   /* The code below only knows how to break apart components of C++
4863      symbol names (and other languages that use '::' as
4864      namespace/module separator).  If we add support for wild matching
4865      to some language that uses some other operator (E.g., Ada, Go and
4866      D use '.'), then we'll need to try splitting the symbol name
4867      according to that language too.  Note that Ada does support wild
4868      matching, but doesn't currently support .gdb_index.  */
4869   auto count = this->symbol_name_count ();
4870   for (offset_type idx = 0; idx < count; idx++)
4871     {
4872       if (this->symbol_name_slot_invalid (idx))
4873         continue;
4874
4875       const char *name = this->symbol_name_at (idx);
4876
4877       /* Add each name component to the name component table.  */
4878       unsigned int previous_len = 0;
4879       for (unsigned int current_len = cp_find_first_component (name);
4880            name[current_len] != '\0';
4881            current_len += cp_find_first_component (name + current_len))
4882         {
4883           gdb_assert (name[current_len] == ':');
4884           this->name_components.push_back ({previous_len, idx});
4885           /* Skip the '::'.  */
4886           current_len += 2;
4887           previous_len = current_len;
4888         }
4889       this->name_components.push_back ({previous_len, idx});
4890     }
4891
4892   /* Sort name_components elements by name.  */
4893   auto name_comp_compare = [&] (const name_component &left,
4894                                 const name_component &right)
4895     {
4896       const char *left_qualified = this->symbol_name_at (left.idx);
4897       const char *right_qualified = this->symbol_name_at (right.idx);
4898
4899       const char *left_name = left_qualified + left.name_offset;
4900       const char *right_name = right_qualified + right.name_offset;
4901
4902       return name_cmp (left_name, right_name) < 0;
4903     };
4904
4905   std::sort (this->name_components.begin (),
4906              this->name_components.end (),
4907              name_comp_compare);
4908 }
4909
4910 /* Helper for dw2_expand_symtabs_matching that works with a
4911    mapped_index_base instead of the containing objfile.  This is split
4912    to a separate function in order to be able to unit test the
4913    name_components matching using a mock mapped_index_base.  For each
4914    symbol name that matches, calls MATCH_CALLBACK, passing it the
4915    symbol's index in the mapped_index_base symbol table.  */
4916
4917 static void
4918 dw2_expand_symtabs_matching_symbol
4919   (mapped_index_base &index,
4920    const lookup_name_info &lookup_name_in,
4921    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4922    enum search_domain kind,
4923    gdb::function_view<void (offset_type)> match_callback)
4924 {
4925   lookup_name_info lookup_name_without_params
4926     = lookup_name_in.make_ignore_params ();
4927   gdb_index_symbol_name_matcher lookup_name_matcher
4928     (lookup_name_without_params);
4929
4930   /* Build the symbol name component sorted vector, if we haven't
4931      yet.  */
4932   index.build_name_components ();
4933
4934   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4935
4936   /* Now for each symbol name in range, check to see if we have a name
4937      match, and if so, call the MATCH_CALLBACK callback.  */
4938
4939   /* The same symbol may appear more than once in the range though.
4940      E.g., if we're looking for symbols that complete "w", and we have
4941      a symbol named "w1::w2", we'll find the two name components for
4942      that same symbol in the range.  To be sure we only call the
4943      callback once per symbol, we first collect the symbol name
4944      indexes that matched in a temporary vector and ignore
4945      duplicates.  */
4946   std::vector<offset_type> matches;
4947   matches.reserve (std::distance (bounds.first, bounds.second));
4948
4949   for (; bounds.first != bounds.second; ++bounds.first)
4950     {
4951       const char *qualified = index.symbol_name_at (bounds.first->idx);
4952
4953       if (!lookup_name_matcher.matches (qualified)
4954           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4955         continue;
4956
4957       matches.push_back (bounds.first->idx);
4958     }
4959
4960   std::sort (matches.begin (), matches.end ());
4961
4962   /* Finally call the callback, once per match.  */
4963   ULONGEST prev = -1;
4964   for (offset_type idx : matches)
4965     {
4966       if (prev != idx)
4967         {
4968           match_callback (idx);
4969           prev = idx;
4970         }
4971     }
4972
4973   /* Above we use a type wider than idx's for 'prev', since 0 and
4974      (offset_type)-1 are both possible values.  */
4975   static_assert (sizeof (prev) > sizeof (offset_type), "");
4976 }
4977
4978 #if GDB_SELF_TEST
4979
4980 namespace selftests { namespace dw2_expand_symtabs_matching {
4981
4982 /* A mock .gdb_index/.debug_names-like name index table, enough to
4983    exercise dw2_expand_symtabs_matching_symbol, which works with the
4984    mapped_index_base interface.  Builds an index from the symbol list
4985    passed as parameter to the constructor.  */
4986 class mock_mapped_index : public mapped_index_base
4987 {
4988 public:
4989   mock_mapped_index (gdb::array_view<const char *> symbols)
4990     : m_symbol_table (symbols)
4991   {}
4992
4993   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4994
4995   /* Return the number of names in the symbol table.  */
4996   virtual size_t symbol_name_count () const
4997   {
4998     return m_symbol_table.size ();
4999   }
5000
5001   /* Get the name of the symbol at IDX in the symbol table.  */
5002   virtual const char *symbol_name_at (offset_type idx) const
5003   {
5004     return m_symbol_table[idx];
5005   }
5006
5007 private:
5008   gdb::array_view<const char *> m_symbol_table;
5009 };
5010
5011 /* Convenience function that converts a NULL pointer to a "<null>"
5012    string, to pass to print routines.  */
5013
5014 static const char *
5015 string_or_null (const char *str)
5016 {
5017   return str != NULL ? str : "<null>";
5018 }
5019
5020 /* Check if a lookup_name_info built from
5021    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
5022    index.  EXPECTED_LIST is the list of expected matches, in expected
5023    matching order.  If no match expected, then an empty list is
5024    specified.  Returns true on success.  On failure prints a warning
5025    indicating the file:line that failed, and returns false.  */
5026
5027 static bool
5028 check_match (const char *file, int line,
5029              mock_mapped_index &mock_index,
5030              const char *name, symbol_name_match_type match_type,
5031              bool completion_mode,
5032              std::initializer_list<const char *> expected_list)
5033 {
5034   lookup_name_info lookup_name (name, match_type, completion_mode);
5035
5036   bool matched = true;
5037
5038   auto mismatch = [&] (const char *expected_str,
5039                        const char *got)
5040   {
5041     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
5042                "expected=\"%s\", got=\"%s\"\n"),
5043              file, line,
5044              (match_type == symbol_name_match_type::FULL
5045               ? "FULL" : "WILD"),
5046              name, string_or_null (expected_str), string_or_null (got));
5047     matched = false;
5048   };
5049
5050   auto expected_it = expected_list.begin ();
5051   auto expected_end = expected_list.end ();
5052
5053   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
5054                                       NULL, ALL_DOMAIN,
5055                                       [&] (offset_type idx)
5056   {
5057     const char *matched_name = mock_index.symbol_name_at (idx);
5058     const char *expected_str
5059       = expected_it == expected_end ? NULL : *expected_it++;
5060
5061     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
5062       mismatch (expected_str, matched_name);
5063   });
5064
5065   const char *expected_str
5066   = expected_it == expected_end ? NULL : *expected_it++;
5067   if (expected_str != NULL)
5068     mismatch (expected_str, NULL);
5069
5070   return matched;
5071 }
5072
5073 /* The symbols added to the mock mapped_index for testing (in
5074    canonical form).  */
5075 static const char *test_symbols[] = {
5076   "function",
5077   "std::bar",
5078   "std::zfunction",
5079   "std::zfunction2",
5080   "w1::w2",
5081   "ns::foo<char*>",
5082   "ns::foo<int>",
5083   "ns::foo<long>",
5084   "ns2::tmpl<int>::foo2",
5085   "(anonymous namespace)::A::B::C",
5086
5087   /* These are used to check that the increment-last-char in the
5088      matching algorithm for completion doesn't match "t1_fund" when
5089      completing "t1_func".  */
5090   "t1_func",
5091   "t1_func1",
5092   "t1_fund",
5093   "t1_fund1",
5094
5095   /* A UTF-8 name with multi-byte sequences to make sure that
5096      cp-name-parser understands this as a single identifier ("função"
5097      is "function" in PT).  */
5098   u8"u8função",
5099
5100   /* \377 (0xff) is Latin1 'ÿ'.  */
5101   "yfunc\377",
5102
5103   /* \377 (0xff) is Latin1 'ÿ'.  */
5104   "\377",
5105   "\377\377123",
5106
5107   /* A name with all sorts of complications.  Starts with "z" to make
5108      it easier for the completion tests below.  */
5109 #define Z_SYM_NAME \
5110   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5111     "::tuple<(anonymous namespace)::ui*, " \
5112     "std::default_delete<(anonymous namespace)::ui>, void>"
5113
5114   Z_SYM_NAME
5115 };
5116
5117 /* Returns true if the mapped_index_base::find_name_component_bounds
5118    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5119    in completion mode.  */
5120
5121 static bool
5122 check_find_bounds_finds (mapped_index_base &index,
5123                          const char *search_name,
5124                          gdb::array_view<const char *> expected_syms)
5125 {
5126   lookup_name_info lookup_name (search_name,
5127                                 symbol_name_match_type::FULL, true);
5128
5129   auto bounds = index.find_name_components_bounds (lookup_name);
5130
5131   size_t distance = std::distance (bounds.first, bounds.second);
5132   if (distance != expected_syms.size ())
5133     return false;
5134
5135   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5136     {
5137       auto nc_elem = bounds.first + exp_elem;
5138       const char *qualified = index.symbol_name_at (nc_elem->idx);
5139       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5140         return false;
5141     }
5142
5143   return true;
5144 }
5145
5146 /* Test the lower-level mapped_index::find_name_component_bounds
5147    method.  */
5148
5149 static void
5150 test_mapped_index_find_name_component_bounds ()
5151 {
5152   mock_mapped_index mock_index (test_symbols);
5153
5154   mock_index.build_name_components ();
5155
5156   /* Test the lower-level mapped_index::find_name_component_bounds
5157      method in completion mode.  */
5158   {
5159     static const char *expected_syms[] = {
5160       "t1_func",
5161       "t1_func1",
5162     };
5163
5164     SELF_CHECK (check_find_bounds_finds (mock_index,
5165                                          "t1_func", expected_syms));
5166   }
5167
5168   /* Check that the increment-last-char in the name matching algorithm
5169      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5170   {
5171     static const char *expected_syms1[] = {
5172       "\377",
5173       "\377\377123",
5174     };
5175     SELF_CHECK (check_find_bounds_finds (mock_index,
5176                                          "\377", expected_syms1));
5177
5178     static const char *expected_syms2[] = {
5179       "\377\377123",
5180     };
5181     SELF_CHECK (check_find_bounds_finds (mock_index,
5182                                          "\377\377", expected_syms2));
5183   }
5184 }
5185
5186 /* Test dw2_expand_symtabs_matching_symbol.  */
5187
5188 static void
5189 test_dw2_expand_symtabs_matching_symbol ()
5190 {
5191   mock_mapped_index mock_index (test_symbols);
5192
5193   /* We let all tests run until the end even if some fails, for debug
5194      convenience.  */
5195   bool any_mismatch = false;
5196
5197   /* Create the expected symbols list (an initializer_list).  Needed
5198      because lists have commas, and we need to pass them to CHECK,
5199      which is a macro.  */
5200 #define EXPECT(...) { __VA_ARGS__ }
5201
5202   /* Wrapper for check_match that passes down the current
5203      __FILE__/__LINE__.  */
5204 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5205   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5206                                 mock_index,                             \
5207                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5208                                 EXPECTED_LIST)
5209
5210   /* Identity checks.  */
5211   for (const char *sym : test_symbols)
5212     {
5213       /* Should be able to match all existing symbols.  */
5214       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5215                    EXPECT (sym));
5216
5217       /* Should be able to match all existing symbols with
5218          parameters.  */
5219       std::string with_params = std::string (sym) + "(int)";
5220       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5221                    EXPECT (sym));
5222
5223       /* Should be able to match all existing symbols with
5224          parameters and qualifiers.  */
5225       with_params = std::string (sym) + " ( int ) const";
5226       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5227                    EXPECT (sym));
5228
5229       /* This should really find sym, but cp-name-parser.y doesn't
5230          know about lvalue/rvalue qualifiers yet.  */
5231       with_params = std::string (sym) + " ( int ) &&";
5232       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5233                    {});
5234     }
5235
5236   /* Check that the name matching algorithm for completion doesn't get
5237      confused with Latin1 'ÿ' / 0xff.  */
5238   {
5239     static const char str[] = "\377";
5240     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5241                  EXPECT ("\377", "\377\377123"));
5242   }
5243
5244   /* Check that the increment-last-char in the matching algorithm for
5245      completion doesn't match "t1_fund" when completing "t1_func".  */
5246   {
5247     static const char str[] = "t1_func";
5248     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5249                  EXPECT ("t1_func", "t1_func1"));
5250   }
5251
5252   /* Check that completion mode works at each prefix of the expected
5253      symbol name.  */
5254   {
5255     static const char str[] = "function(int)";
5256     size_t len = strlen (str);
5257     std::string lookup;
5258
5259     for (size_t i = 1; i < len; i++)
5260       {
5261         lookup.assign (str, i);
5262         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5263                      EXPECT ("function"));
5264       }
5265   }
5266
5267   /* While "w" is a prefix of both components, the match function
5268      should still only be called once.  */
5269   {
5270     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5271                  EXPECT ("w1::w2"));
5272     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5273                  EXPECT ("w1::w2"));
5274   }
5275
5276   /* Same, with a "complicated" symbol.  */
5277   {
5278     static const char str[] = Z_SYM_NAME;
5279     size_t len = strlen (str);
5280     std::string lookup;
5281
5282     for (size_t i = 1; i < len; i++)
5283       {
5284         lookup.assign (str, i);
5285         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5286                      EXPECT (Z_SYM_NAME));
5287       }
5288   }
5289
5290   /* In FULL mode, an incomplete symbol doesn't match.  */
5291   {
5292     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5293                  {});
5294   }
5295
5296   /* A complete symbol with parameters matches any overload, since the
5297      index has no overload info.  */
5298   {
5299     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5300                  EXPECT ("std::zfunction", "std::zfunction2"));
5301     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5302                  EXPECT ("std::zfunction", "std::zfunction2"));
5303     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5304                  EXPECT ("std::zfunction", "std::zfunction2"));
5305   }
5306
5307   /* Check that whitespace is ignored appropriately.  A symbol with a
5308      template argument list. */
5309   {
5310     static const char expected[] = "ns::foo<int>";
5311     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5312                  EXPECT (expected));
5313     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5314                  EXPECT (expected));
5315   }
5316
5317   /* Check that whitespace is ignored appropriately.  A symbol with a
5318      template argument list that includes a pointer.  */
5319   {
5320     static const char expected[] = "ns::foo<char*>";
5321     /* Try both completion and non-completion modes.  */
5322     static const bool completion_mode[2] = {false, true};
5323     for (size_t i = 0; i < 2; i++)
5324       {
5325         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5326                      completion_mode[i], EXPECT (expected));
5327         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5328                      completion_mode[i], EXPECT (expected));
5329
5330         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5331                      completion_mode[i], EXPECT (expected));
5332         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5333                      completion_mode[i], EXPECT (expected));
5334       }
5335   }
5336
5337   {
5338     /* Check method qualifiers are ignored.  */
5339     static const char expected[] = "ns::foo<char*>";
5340     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5341                  symbol_name_match_type::FULL, true, EXPECT (expected));
5342     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5343                  symbol_name_match_type::FULL, true, EXPECT (expected));
5344     CHECK_MATCH ("foo < char * >  ( int ) const",
5345                  symbol_name_match_type::WILD, true, EXPECT (expected));
5346     CHECK_MATCH ("foo < char * >  ( int ) &&",
5347                  symbol_name_match_type::WILD, true, EXPECT (expected));
5348   }
5349
5350   /* Test lookup names that don't match anything.  */
5351   {
5352     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5353                  {});
5354
5355     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5356                  {});
5357   }
5358
5359   /* Some wild matching tests, exercising "(anonymous namespace)",
5360      which should not be confused with a parameter list.  */
5361   {
5362     static const char *syms[] = {
5363       "A::B::C",
5364       "B::C",
5365       "C",
5366       "A :: B :: C ( int )",
5367       "B :: C ( int )",
5368       "C ( int )",
5369     };
5370
5371     for (const char *s : syms)
5372       {
5373         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5374                      EXPECT ("(anonymous namespace)::A::B::C"));
5375       }
5376   }
5377
5378   {
5379     static const char expected[] = "ns2::tmpl<int>::foo2";
5380     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5381                  EXPECT (expected));
5382     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5383                  EXPECT (expected));
5384   }
5385
5386   SELF_CHECK (!any_mismatch);
5387
5388 #undef EXPECT
5389 #undef CHECK_MATCH
5390 }
5391
5392 static void
5393 run_test ()
5394 {
5395   test_mapped_index_find_name_component_bounds ();
5396   test_dw2_expand_symtabs_matching_symbol ();
5397 }
5398
5399 }} // namespace selftests::dw2_expand_symtabs_matching
5400
5401 #endif /* GDB_SELF_TEST */
5402
5403 /* If FILE_MATCHER is NULL or if PER_CU has
5404    dwarf2_per_cu_quick_data::MARK set (see
5405    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5406    EXPANSION_NOTIFY on it.  */
5407
5408 static void
5409 dw2_expand_symtabs_matching_one
5410   (struct dwarf2_per_cu_data *per_cu,
5411    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5412    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5413 {
5414   if (file_matcher == NULL || per_cu->v.quick->mark)
5415     {
5416       bool symtab_was_null
5417         = (per_cu->v.quick->compunit_symtab == NULL);
5418
5419       dw2_instantiate_symtab (per_cu);
5420
5421       if (expansion_notify != NULL
5422           && symtab_was_null
5423           && per_cu->v.quick->compunit_symtab != NULL)
5424         expansion_notify (per_cu->v.quick->compunit_symtab);
5425     }
5426 }
5427
5428 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5429    matched, to expand corresponding CUs that were marked.  IDX is the
5430    index of the symbol name that matched.  */
5431
5432 static void
5433 dw2_expand_marked_cus
5434   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5435    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5436    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5437    search_domain kind)
5438 {
5439   offset_type *vec, vec_len, vec_idx;
5440   bool global_seen = false;
5441   mapped_index &index = *dwarf2_per_objfile->index_table;
5442
5443   vec = (offset_type *) (index.constant_pool
5444                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5445   vec_len = MAYBE_SWAP (vec[0]);
5446   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5447     {
5448       struct dwarf2_per_cu_data *per_cu;
5449       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5450       /* This value is only valid for index versions >= 7.  */
5451       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5452       gdb_index_symbol_kind symbol_kind =
5453         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5454       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5455       /* Only check the symbol attributes if they're present.
5456          Indices prior to version 7 don't record them,
5457          and indices >= 7 may elide them for certain symbols
5458          (gold does this).  */
5459       int attrs_valid =
5460         (index.version >= 7
5461          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5462
5463       /* Work around gold/15646.  */
5464       if (attrs_valid)
5465         {
5466           if (!is_static && global_seen)
5467             continue;
5468           if (!is_static)
5469             global_seen = true;
5470         }
5471
5472       /* Only check the symbol's kind if it has one.  */
5473       if (attrs_valid)
5474         {
5475           switch (kind)
5476             {
5477             case VARIABLES_DOMAIN:
5478               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5479                 continue;
5480               break;
5481             case FUNCTIONS_DOMAIN:
5482               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5483                 continue;
5484               break;
5485             case TYPES_DOMAIN:
5486               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5487                 continue;
5488               break;
5489             default:
5490               break;
5491             }
5492         }
5493
5494       /* Don't crash on bad data.  */
5495       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5496                        + dwarf2_per_objfile->n_type_units))
5497         {
5498           complaint (&symfile_complaints,
5499                      _(".gdb_index entry has bad CU index"
5500                        " [in module %s]"),
5501                        objfile_name (dwarf2_per_objfile->objfile));
5502           continue;
5503         }
5504
5505       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5506       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5507                                        expansion_notify);
5508     }
5509 }
5510
5511 /* If FILE_MATCHER is non-NULL, set all the
5512    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5513    that match FILE_MATCHER.  */
5514
5515 static void
5516 dw_expand_symtabs_matching_file_matcher
5517   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5518    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5519 {
5520   if (file_matcher == NULL)
5521     return;
5522
5523   objfile *const objfile = dwarf2_per_objfile->objfile;
5524
5525   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5526                                             htab_eq_pointer,
5527                                             NULL, xcalloc, xfree));
5528   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5529                                                 htab_eq_pointer,
5530                                                 NULL, xcalloc, xfree));
5531
5532   /* The rule is CUs specify all the files, including those used by
5533      any TU, so there's no need to scan TUs here.  */
5534
5535   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5536     {
5537       int j;
5538       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5539       struct quick_file_names *file_data;
5540       void **slot;
5541
5542       QUIT;
5543
5544       per_cu->v.quick->mark = 0;
5545
5546       /* We only need to look at symtabs not already expanded.  */
5547       if (per_cu->v.quick->compunit_symtab)
5548         continue;
5549
5550       file_data = dw2_get_file_names (per_cu);
5551       if (file_data == NULL)
5552         continue;
5553
5554       if (htab_find (visited_not_found.get (), file_data) != NULL)
5555         continue;
5556       else if (htab_find (visited_found.get (), file_data) != NULL)
5557         {
5558           per_cu->v.quick->mark = 1;
5559           continue;
5560         }
5561
5562       for (j = 0; j < file_data->num_file_names; ++j)
5563         {
5564           const char *this_real_name;
5565
5566           if (file_matcher (file_data->file_names[j], false))
5567             {
5568               per_cu->v.quick->mark = 1;
5569               break;
5570             }
5571
5572           /* Before we invoke realpath, which can get expensive when many
5573              files are involved, do a quick comparison of the basenames.  */
5574           if (!basenames_may_differ
5575               && !file_matcher (lbasename (file_data->file_names[j]),
5576                                 true))
5577             continue;
5578
5579           this_real_name = dw2_get_real_path (objfile, file_data, j);
5580           if (file_matcher (this_real_name, false))
5581             {
5582               per_cu->v.quick->mark = 1;
5583               break;
5584             }
5585         }
5586
5587       slot = htab_find_slot (per_cu->v.quick->mark
5588                              ? visited_found.get ()
5589                              : visited_not_found.get (),
5590                              file_data, INSERT);
5591       *slot = file_data;
5592     }
5593 }
5594
5595 static void
5596 dw2_expand_symtabs_matching
5597   (struct objfile *objfile,
5598    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5599    const lookup_name_info &lookup_name,
5600    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5601    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5602    enum search_domain kind)
5603 {
5604   struct dwarf2_per_objfile *dwarf2_per_objfile
5605     = get_dwarf2_per_objfile (objfile);
5606
5607   /* index_table is NULL if OBJF_READNOW.  */
5608   if (!dwarf2_per_objfile->index_table)
5609     return;
5610
5611   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5612
5613   mapped_index &index = *dwarf2_per_objfile->index_table;
5614
5615   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5616                                       symbol_matcher,
5617                                       kind, [&] (offset_type idx)
5618     {
5619       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5620                              expansion_notify, kind);
5621     });
5622 }
5623
5624 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5625    symtab.  */
5626
5627 static struct compunit_symtab *
5628 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5629                                           CORE_ADDR pc)
5630 {
5631   int i;
5632
5633   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5634       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5635     return cust;
5636
5637   if (cust->includes == NULL)
5638     return NULL;
5639
5640   for (i = 0; cust->includes[i]; ++i)
5641     {
5642       struct compunit_symtab *s = cust->includes[i];
5643
5644       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5645       if (s != NULL)
5646         return s;
5647     }
5648
5649   return NULL;
5650 }
5651
5652 static struct compunit_symtab *
5653 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5654                                   struct bound_minimal_symbol msymbol,
5655                                   CORE_ADDR pc,
5656                                   struct obj_section *section,
5657                                   int warn_if_readin)
5658 {
5659   struct dwarf2_per_cu_data *data;
5660   struct compunit_symtab *result;
5661
5662   if (!objfile->psymtabs_addrmap)
5663     return NULL;
5664
5665   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5666                                                      pc);
5667   if (!data)
5668     return NULL;
5669
5670   if (warn_if_readin && data->v.quick->compunit_symtab)
5671     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5672              paddress (get_objfile_arch (objfile), pc));
5673
5674   result
5675     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5676                                                 pc);
5677   gdb_assert (result != NULL);
5678   return result;
5679 }
5680
5681 static void
5682 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5683                           void *data, int need_fullname)
5684 {
5685   struct dwarf2_per_objfile *dwarf2_per_objfile
5686     = get_dwarf2_per_objfile (objfile);
5687
5688   if (!dwarf2_per_objfile->filenames_cache)
5689     {
5690       dwarf2_per_objfile->filenames_cache.emplace ();
5691
5692       htab_up visited (htab_create_alloc (10,
5693                                           htab_hash_pointer, htab_eq_pointer,
5694                                           NULL, xcalloc, xfree));
5695
5696       /* The rule is CUs specify all the files, including those used
5697          by any TU, so there's no need to scan TUs here.  We can
5698          ignore file names coming from already-expanded CUs.  */
5699
5700       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5701         {
5702           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5703
5704           if (per_cu->v.quick->compunit_symtab)
5705             {
5706               void **slot = htab_find_slot (visited.get (),
5707                                             per_cu->v.quick->file_names,
5708                                             INSERT);
5709
5710               *slot = per_cu->v.quick->file_names;
5711             }
5712         }
5713
5714       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5715         {
5716           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5717           struct quick_file_names *file_data;
5718           void **slot;
5719
5720           /* We only need to look at symtabs not already expanded.  */
5721           if (per_cu->v.quick->compunit_symtab)
5722             continue;
5723
5724           file_data = dw2_get_file_names (per_cu);
5725           if (file_data == NULL)
5726             continue;
5727
5728           slot = htab_find_slot (visited.get (), file_data, INSERT);
5729           if (*slot)
5730             {
5731               /* Already visited.  */
5732               continue;
5733             }
5734           *slot = file_data;
5735
5736           for (int j = 0; j < file_data->num_file_names; ++j)
5737             {
5738               const char *filename = file_data->file_names[j];
5739               dwarf2_per_objfile->filenames_cache->seen (filename);
5740             }
5741         }
5742     }
5743
5744   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5745     {
5746       gdb::unique_xmalloc_ptr<char> this_real_name;
5747
5748       if (need_fullname)
5749         this_real_name = gdb_realpath (filename);
5750       (*fun) (filename, this_real_name.get (), data);
5751     });
5752 }
5753
5754 static int
5755 dw2_has_symbols (struct objfile *objfile)
5756 {
5757   return 1;
5758 }
5759
5760 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5761 {
5762   dw2_has_symbols,
5763   dw2_find_last_source_symtab,
5764   dw2_forget_cached_source_info,
5765   dw2_map_symtabs_matching_filename,
5766   dw2_lookup_symbol,
5767   dw2_print_stats,
5768   dw2_dump,
5769   dw2_relocate,
5770   dw2_expand_symtabs_for_function,
5771   dw2_expand_all_symtabs,
5772   dw2_expand_symtabs_with_fullname,
5773   dw2_map_matching_symbols,
5774   dw2_expand_symtabs_matching,
5775   dw2_find_pc_sect_compunit_symtab,
5776   NULL,
5777   dw2_map_symbol_filenames
5778 };
5779
5780 /* DWARF-5 debug_names reader.  */
5781
5782 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5783 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5784
5785 /* A helper function that reads the .debug_names section in SECTION
5786    and fills in MAP.  FILENAME is the name of the file containing the
5787    section; it is used for error reporting.
5788
5789    Returns true if all went well, false otherwise.  */
5790
5791 static bool
5792 read_debug_names_from_section (struct objfile *objfile,
5793                                const char *filename,
5794                                struct dwarf2_section_info *section,
5795                                mapped_debug_names &map)
5796 {
5797   if (dwarf2_section_empty_p (section))
5798     return false;
5799
5800   /* Older elfutils strip versions could keep the section in the main
5801      executable while splitting it for the separate debug info file.  */
5802   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5803     return false;
5804
5805   dwarf2_read_section (objfile, section);
5806
5807   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5808
5809   const gdb_byte *addr = section->buffer;
5810
5811   bfd *const abfd = get_section_bfd_owner (section);
5812
5813   unsigned int bytes_read;
5814   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5815   addr += bytes_read;
5816
5817   map.dwarf5_is_dwarf64 = bytes_read != 4;
5818   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5819   if (bytes_read + length != section->size)
5820     {
5821       /* There may be multiple per-CU indices.  */
5822       warning (_("Section .debug_names in %s length %s does not match "
5823                  "section length %s, ignoring .debug_names."),
5824                filename, plongest (bytes_read + length),
5825                pulongest (section->size));
5826       return false;
5827     }
5828
5829   /* The version number.  */
5830   uint16_t version = read_2_bytes (abfd, addr);
5831   addr += 2;
5832   if (version != 5)
5833     {
5834       warning (_("Section .debug_names in %s has unsupported version %d, "
5835                  "ignoring .debug_names."),
5836                filename, version);
5837       return false;
5838     }
5839
5840   /* Padding.  */
5841   uint16_t padding = read_2_bytes (abfd, addr);
5842   addr += 2;
5843   if (padding != 0)
5844     {
5845       warning (_("Section .debug_names in %s has unsupported padding %d, "
5846                  "ignoring .debug_names."),
5847                filename, padding);
5848       return false;
5849     }
5850
5851   /* comp_unit_count - The number of CUs in the CU list.  */
5852   map.cu_count = read_4_bytes (abfd, addr);
5853   addr += 4;
5854
5855   /* local_type_unit_count - The number of TUs in the local TU
5856      list.  */
5857   map.tu_count = read_4_bytes (abfd, addr);
5858   addr += 4;
5859
5860   /* foreign_type_unit_count - The number of TUs in the foreign TU
5861      list.  */
5862   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5863   addr += 4;
5864   if (foreign_tu_count != 0)
5865     {
5866       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5867                  "ignoring .debug_names."),
5868                filename, static_cast<unsigned long> (foreign_tu_count));
5869       return false;
5870     }
5871
5872   /* bucket_count - The number of hash buckets in the hash lookup
5873      table.  */
5874   map.bucket_count = read_4_bytes (abfd, addr);
5875   addr += 4;
5876
5877   /* name_count - The number of unique names in the index.  */
5878   map.name_count = read_4_bytes (abfd, addr);
5879   addr += 4;
5880
5881   /* abbrev_table_size - The size in bytes of the abbreviations
5882      table.  */
5883   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5884   addr += 4;
5885
5886   /* augmentation_string_size - The size in bytes of the augmentation
5887      string.  This value is rounded up to a multiple of 4.  */
5888   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5889   addr += 4;
5890   map.augmentation_is_gdb = ((augmentation_string_size
5891                               == sizeof (dwarf5_augmentation))
5892                              && memcmp (addr, dwarf5_augmentation,
5893                                         sizeof (dwarf5_augmentation)) == 0);
5894   augmentation_string_size += (-augmentation_string_size) & 3;
5895   addr += augmentation_string_size;
5896
5897   /* List of CUs */
5898   map.cu_table_reordered = addr;
5899   addr += map.cu_count * map.offset_size;
5900
5901   /* List of Local TUs */
5902   map.tu_table_reordered = addr;
5903   addr += map.tu_count * map.offset_size;
5904
5905   /* Hash Lookup Table */
5906   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5907   addr += map.bucket_count * 4;
5908   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5909   addr += map.name_count * 4;
5910
5911   /* Name Table */
5912   map.name_table_string_offs_reordered = addr;
5913   addr += map.name_count * map.offset_size;
5914   map.name_table_entry_offs_reordered = addr;
5915   addr += map.name_count * map.offset_size;
5916
5917   const gdb_byte *abbrev_table_start = addr;
5918   for (;;)
5919     {
5920       unsigned int bytes_read;
5921       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5922       addr += bytes_read;
5923       if (index_num == 0)
5924         break;
5925
5926       const auto insertpair
5927         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5928       if (!insertpair.second)
5929         {
5930           warning (_("Section .debug_names in %s has duplicate index %s, "
5931                      "ignoring .debug_names."),
5932                    filename, pulongest (index_num));
5933           return false;
5934         }
5935       mapped_debug_names::index_val &indexval = insertpair.first->second;
5936       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5937       addr += bytes_read;
5938
5939       for (;;)
5940         {
5941           mapped_debug_names::index_val::attr attr;
5942           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5943           addr += bytes_read;
5944           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5945           addr += bytes_read;
5946           if (attr.form == DW_FORM_implicit_const)
5947             {
5948               attr.implicit_const = read_signed_leb128 (abfd, addr,
5949                                                         &bytes_read);
5950               addr += bytes_read;
5951             }
5952           if (attr.dw_idx == 0 && attr.form == 0)
5953             break;
5954           indexval.attr_vec.push_back (std::move (attr));
5955         }
5956     }
5957   if (addr != abbrev_table_start + abbrev_table_size)
5958     {
5959       warning (_("Section .debug_names in %s has abbreviation_table "
5960                  "of size %zu vs. written as %u, ignoring .debug_names."),
5961                filename, addr - abbrev_table_start, abbrev_table_size);
5962       return false;
5963     }
5964   map.entry_pool = addr;
5965
5966   return true;
5967 }
5968
5969 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5970    list.  */
5971
5972 static void
5973 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5974                                   const mapped_debug_names &map,
5975                                   dwarf2_section_info &section,
5976                                   bool is_dwz, int base_offset)
5977 {
5978   sect_offset sect_off_prev;
5979   for (uint32_t i = 0; i <= map.cu_count; ++i)
5980     {
5981       sect_offset sect_off_next;
5982       if (i < map.cu_count)
5983         {
5984           sect_off_next
5985             = (sect_offset) (extract_unsigned_integer
5986                              (map.cu_table_reordered + i * map.offset_size,
5987                               map.offset_size,
5988                               map.dwarf5_byte_order));
5989         }
5990       else
5991         sect_off_next = (sect_offset) section.size;
5992       if (i >= 1)
5993         {
5994           const ULONGEST length = sect_off_next - sect_off_prev;
5995           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5996             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5997                                          sect_off_prev, length);
5998         }
5999       sect_off_prev = sect_off_next;
6000     }
6001 }
6002
6003 /* Read the CU list from the mapped index, and use it to create all
6004    the CU objects for this dwarf2_per_objfile.  */
6005
6006 static void
6007 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
6008                              const mapped_debug_names &map,
6009                              const mapped_debug_names &dwz_map)
6010 {
6011   struct objfile *objfile = dwarf2_per_objfile->objfile;
6012
6013   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
6014   dwarf2_per_objfile->all_comp_units
6015     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
6016                  dwarf2_per_objfile->n_comp_units);
6017
6018   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
6019                                     dwarf2_per_objfile->info,
6020                                     false /* is_dwz */,
6021                                     0 /* base_offset */);
6022
6023   if (dwz_map.cu_count == 0)
6024     return;
6025
6026   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6027   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
6028                                     true /* is_dwz */,
6029                                     map.cu_count /* base_offset */);
6030 }
6031
6032 /* Read .debug_names.  If everything went ok, initialize the "quick"
6033    elements of all the CUs and return true.  Otherwise, return false.  */
6034
6035 static bool
6036 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
6037 {
6038   mapped_debug_names local_map (dwarf2_per_objfile);
6039   mapped_debug_names dwz_map (dwarf2_per_objfile);
6040   struct objfile *objfile = dwarf2_per_objfile->objfile;
6041
6042   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
6043                                       &dwarf2_per_objfile->debug_names,
6044                                       local_map))
6045     return false;
6046
6047   /* Don't use the index if it's empty.  */
6048   if (local_map.name_count == 0)
6049     return false;
6050
6051   /* If there is a .dwz file, read it so we can get its CU list as
6052      well.  */
6053   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6054   if (dwz != NULL)
6055     {
6056       if (!read_debug_names_from_section (objfile,
6057                                           bfd_get_filename (dwz->dwz_bfd),
6058                                           &dwz->debug_names, dwz_map))
6059         {
6060           warning (_("could not read '.debug_names' section from %s; skipping"),
6061                    bfd_get_filename (dwz->dwz_bfd));
6062           return false;
6063         }
6064     }
6065
6066   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
6067
6068   if (local_map.tu_count != 0)
6069     {
6070       /* We can only handle a single .debug_types when we have an
6071          index.  */
6072       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
6073         return false;
6074
6075       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6076                                                 dwarf2_per_objfile->types, 0);
6077
6078       create_signatured_type_table_from_debug_names
6079         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6080     }
6081
6082   create_addrmap_from_aranges (dwarf2_per_objfile,
6083                                &dwarf2_per_objfile->debug_aranges);
6084
6085   dwarf2_per_objfile->debug_names_table.reset
6086     (new mapped_debug_names (dwarf2_per_objfile));
6087   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6088   dwarf2_per_objfile->using_index = 1;
6089   dwarf2_per_objfile->quick_file_names_table =
6090     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6091
6092   return true;
6093 }
6094
6095 /* Symbol name hashing function as specified by DWARF-5.  */
6096
6097 static uint32_t
6098 dwarf5_djb_hash (const char *str_)
6099 {
6100   const unsigned char *str = (const unsigned char *) str_;
6101
6102   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6103      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6104
6105   uint32_t hash = 5381;
6106   while (int c = *str++)
6107     hash = hash * 33 + tolower (c);
6108   return hash;
6109 }
6110
6111 /* Type used to manage iterating over all CUs looking for a symbol for
6112    .debug_names.  */
6113
6114 class dw2_debug_names_iterator
6115 {
6116 public:
6117   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6118      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6119   dw2_debug_names_iterator (const mapped_debug_names &map,
6120                             bool want_specific_block,
6121                             block_enum block_index, domain_enum domain,
6122                             const char *name)
6123     : m_map (map), m_want_specific_block (want_specific_block),
6124       m_block_index (block_index), m_domain (domain),
6125       m_addr (find_vec_in_debug_names (map, name))
6126   {}
6127
6128   dw2_debug_names_iterator (const mapped_debug_names &map,
6129                             search_domain search, uint32_t namei)
6130     : m_map (map),
6131       m_search (search),
6132       m_addr (find_vec_in_debug_names (map, namei))
6133   {}
6134
6135   /* Return the next matching CU or NULL if there are no more.  */
6136   dwarf2_per_cu_data *next ();
6137
6138 private:
6139   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6140                                                   const char *name);
6141   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6142                                                   uint32_t namei);
6143
6144   /* The internalized form of .debug_names.  */
6145   const mapped_debug_names &m_map;
6146
6147   /* If true, only look for symbols that match BLOCK_INDEX.  */
6148   const bool m_want_specific_block = false;
6149
6150   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6151      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6152      value.  */
6153   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6154
6155   /* The kind of symbol we're looking for.  */
6156   const domain_enum m_domain = UNDEF_DOMAIN;
6157   const search_domain m_search = ALL_DOMAIN;
6158
6159   /* The list of CUs from the index entry of the symbol, or NULL if
6160      not found.  */
6161   const gdb_byte *m_addr;
6162 };
6163
6164 const char *
6165 mapped_debug_names::namei_to_name (uint32_t namei) const
6166 {
6167   const ULONGEST namei_string_offs
6168     = extract_unsigned_integer ((name_table_string_offs_reordered
6169                                  + namei * offset_size),
6170                                 offset_size,
6171                                 dwarf5_byte_order);
6172   return read_indirect_string_at_offset
6173     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6174 }
6175
6176 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6177    found, return pointer to its pool data.  If NAME cannot be found,
6178    return NULL.  */
6179
6180 const gdb_byte *
6181 dw2_debug_names_iterator::find_vec_in_debug_names
6182   (const mapped_debug_names &map, const char *name)
6183 {
6184   int (*cmp) (const char *, const char *);
6185
6186   if (current_language->la_language == language_cplus
6187       || current_language->la_language == language_fortran
6188       || current_language->la_language == language_d)
6189     {
6190       /* NAME is already canonical.  Drop any qualifiers as
6191          .debug_names does not contain any.  */
6192
6193       if (strchr (name, '(') != NULL)
6194         {
6195           gdb::unique_xmalloc_ptr<char> without_params
6196             = cp_remove_params (name);
6197
6198           if (without_params != NULL)
6199             {
6200               name = without_params.get();
6201             }
6202         }
6203     }
6204
6205   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6206
6207   const uint32_t full_hash = dwarf5_djb_hash (name);
6208   uint32_t namei
6209     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6210                                 (map.bucket_table_reordered
6211                                  + (full_hash % map.bucket_count)), 4,
6212                                 map.dwarf5_byte_order);
6213   if (namei == 0)
6214     return NULL;
6215   --namei;
6216   if (namei >= map.name_count)
6217     {
6218       complaint (&symfile_complaints,
6219                  _("Wrong .debug_names with name index %u but name_count=%u "
6220                    "[in module %s]"),
6221                  namei, map.name_count,
6222                  objfile_name (map.dwarf2_per_objfile->objfile));
6223       return NULL;
6224     }
6225
6226   for (;;)
6227     {
6228       const uint32_t namei_full_hash
6229         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6230                                     (map.hash_table_reordered + namei), 4,
6231                                     map.dwarf5_byte_order);
6232       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6233         return NULL;
6234
6235       if (full_hash == namei_full_hash)
6236         {
6237           const char *const namei_string = map.namei_to_name (namei);
6238
6239 #if 0 /* An expensive sanity check.  */
6240           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6241             {
6242               complaint (&symfile_complaints,
6243                          _("Wrong .debug_names hash for string at index %u "
6244                            "[in module %s]"),
6245                          namei, objfile_name (dwarf2_per_objfile->objfile));
6246               return NULL;
6247             }
6248 #endif
6249
6250           if (cmp (namei_string, name) == 0)
6251             {
6252               const ULONGEST namei_entry_offs
6253                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6254                                              + namei * map.offset_size),
6255                                             map.offset_size, map.dwarf5_byte_order);
6256               return map.entry_pool + namei_entry_offs;
6257             }
6258         }
6259
6260       ++namei;
6261       if (namei >= map.name_count)
6262         return NULL;
6263     }
6264 }
6265
6266 const gdb_byte *
6267 dw2_debug_names_iterator::find_vec_in_debug_names
6268   (const mapped_debug_names &map, uint32_t namei)
6269 {
6270   if (namei >= map.name_count)
6271     {
6272       complaint (&symfile_complaints,
6273                  _("Wrong .debug_names with name index %u but name_count=%u "
6274                    "[in module %s]"),
6275                  namei, map.name_count,
6276                  objfile_name (map.dwarf2_per_objfile->objfile));
6277       return NULL;
6278     }
6279
6280   const ULONGEST namei_entry_offs
6281     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6282                                  + namei * map.offset_size),
6283                                 map.offset_size, map.dwarf5_byte_order);
6284   return map.entry_pool + namei_entry_offs;
6285 }
6286
6287 /* See dw2_debug_names_iterator.  */
6288
6289 dwarf2_per_cu_data *
6290 dw2_debug_names_iterator::next ()
6291 {
6292   if (m_addr == NULL)
6293     return NULL;
6294
6295   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6296   struct objfile *objfile = dwarf2_per_objfile->objfile;
6297   bfd *const abfd = objfile->obfd;
6298
6299  again:
6300
6301   unsigned int bytes_read;
6302   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6303   m_addr += bytes_read;
6304   if (abbrev == 0)
6305     return NULL;
6306
6307   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6308   if (indexval_it == m_map.abbrev_map.cend ())
6309     {
6310       complaint (&symfile_complaints,
6311                  _("Wrong .debug_names undefined abbrev code %s "
6312                    "[in module %s]"),
6313                  pulongest (abbrev), objfile_name (objfile));
6314       return NULL;
6315     }
6316   const mapped_debug_names::index_val &indexval = indexval_it->second;
6317   bool have_is_static = false;
6318   bool is_static;
6319   dwarf2_per_cu_data *per_cu = NULL;
6320   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6321     {
6322       ULONGEST ull;
6323       switch (attr.form)
6324         {
6325         case DW_FORM_implicit_const:
6326           ull = attr.implicit_const;
6327           break;
6328         case DW_FORM_flag_present:
6329           ull = 1;
6330           break;
6331         case DW_FORM_udata:
6332           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6333           m_addr += bytes_read;
6334           break;
6335         default:
6336           complaint (&symfile_complaints,
6337                      _("Unsupported .debug_names form %s [in module %s]"),
6338                      dwarf_form_name (attr.form),
6339                      objfile_name (objfile));
6340           return NULL;
6341         }
6342       switch (attr.dw_idx)
6343         {
6344         case DW_IDX_compile_unit:
6345           /* Don't crash on bad data.  */
6346           if (ull >= dwarf2_per_objfile->n_comp_units)
6347             {
6348               complaint (&symfile_complaints,
6349                          _(".debug_names entry has bad CU index %s"
6350                            " [in module %s]"),
6351                          pulongest (ull),
6352                          objfile_name (dwarf2_per_objfile->objfile));
6353               continue;
6354             }
6355           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6356           break;
6357         case DW_IDX_type_unit:
6358           /* Don't crash on bad data.  */
6359           if (ull >= dwarf2_per_objfile->n_type_units)
6360             {
6361               complaint (&symfile_complaints,
6362                          _(".debug_names entry has bad TU index %s"
6363                            " [in module %s]"),
6364                          pulongest (ull),
6365                          objfile_name (dwarf2_per_objfile->objfile));
6366               continue;
6367             }
6368           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6369                                  dwarf2_per_objfile->n_comp_units + ull);
6370           break;
6371         case DW_IDX_GNU_internal:
6372           if (!m_map.augmentation_is_gdb)
6373             break;
6374           have_is_static = true;
6375           is_static = true;
6376           break;
6377         case DW_IDX_GNU_external:
6378           if (!m_map.augmentation_is_gdb)
6379             break;
6380           have_is_static = true;
6381           is_static = false;
6382           break;
6383         }
6384     }
6385
6386   /* Skip if already read in.  */
6387   if (per_cu->v.quick->compunit_symtab)
6388     goto again;
6389
6390   /* Check static vs global.  */
6391   if (have_is_static)
6392     {
6393       const bool want_static = m_block_index != GLOBAL_BLOCK;
6394       if (m_want_specific_block && want_static != is_static)
6395         goto again;
6396     }
6397
6398   /* Match dw2_symtab_iter_next, symbol_kind
6399      and debug_names::psymbol_tag.  */
6400   switch (m_domain)
6401     {
6402     case VAR_DOMAIN:
6403       switch (indexval.dwarf_tag)
6404         {
6405         case DW_TAG_variable:
6406         case DW_TAG_subprogram:
6407         /* Some types are also in VAR_DOMAIN.  */
6408         case DW_TAG_typedef:
6409         case DW_TAG_structure_type:
6410           break;
6411         default:
6412           goto again;
6413         }
6414       break;
6415     case STRUCT_DOMAIN:
6416       switch (indexval.dwarf_tag)
6417         {
6418         case DW_TAG_typedef:
6419         case DW_TAG_structure_type:
6420           break;
6421         default:
6422           goto again;
6423         }
6424       break;
6425     case LABEL_DOMAIN:
6426       switch (indexval.dwarf_tag)
6427         {
6428         case 0:
6429         case DW_TAG_variable:
6430           break;
6431         default:
6432           goto again;
6433         }
6434       break;
6435     default:
6436       break;
6437     }
6438
6439   /* Match dw2_expand_symtabs_matching, symbol_kind and
6440      debug_names::psymbol_tag.  */
6441   switch (m_search)
6442     {
6443     case VARIABLES_DOMAIN:
6444       switch (indexval.dwarf_tag)
6445         {
6446         case DW_TAG_variable:
6447           break;
6448         default:
6449           goto again;
6450         }
6451       break;
6452     case FUNCTIONS_DOMAIN:
6453       switch (indexval.dwarf_tag)
6454         {
6455         case DW_TAG_subprogram:
6456           break;
6457         default:
6458           goto again;
6459         }
6460       break;
6461     case TYPES_DOMAIN:
6462       switch (indexval.dwarf_tag)
6463         {
6464         case DW_TAG_typedef:
6465         case DW_TAG_structure_type:
6466           break;
6467         default:
6468           goto again;
6469         }
6470       break;
6471     default:
6472       break;
6473     }
6474
6475   return per_cu;
6476 }
6477
6478 static struct compunit_symtab *
6479 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6480                                const char *name, domain_enum domain)
6481 {
6482   const block_enum block_index = static_cast<block_enum> (block_index_int);
6483   struct dwarf2_per_objfile *dwarf2_per_objfile
6484     = get_dwarf2_per_objfile (objfile);
6485
6486   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6487   if (!mapp)
6488     {
6489       /* index is NULL if OBJF_READNOW.  */
6490       return NULL;
6491     }
6492   const auto &map = *mapp;
6493
6494   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6495                                  block_index, domain, name);
6496
6497   struct compunit_symtab *stab_best = NULL;
6498   struct dwarf2_per_cu_data *per_cu;
6499   while ((per_cu = iter.next ()) != NULL)
6500     {
6501       struct symbol *sym, *with_opaque = NULL;
6502       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6503       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6504       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6505
6506       sym = block_find_symbol (block, name, domain,
6507                                block_find_non_opaque_type_preferred,
6508                                &with_opaque);
6509
6510       /* Some caution must be observed with overloaded functions and
6511          methods, since the index will not contain any overload
6512          information (but NAME might contain it).  */
6513
6514       if (sym != NULL
6515           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6516         return stab;
6517       if (with_opaque != NULL
6518           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6519         stab_best = stab;
6520
6521       /* Keep looking through other CUs.  */
6522     }
6523
6524   return stab_best;
6525 }
6526
6527 /* This dumps minimal information about .debug_names.  It is called
6528    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6529    uses this to verify that .debug_names has been loaded.  */
6530
6531 static void
6532 dw2_debug_names_dump (struct objfile *objfile)
6533 {
6534   struct dwarf2_per_objfile *dwarf2_per_objfile
6535     = get_dwarf2_per_objfile (objfile);
6536
6537   gdb_assert (dwarf2_per_objfile->using_index);
6538   printf_filtered (".debug_names:");
6539   if (dwarf2_per_objfile->debug_names_table)
6540     printf_filtered (" exists\n");
6541   else
6542     printf_filtered (" faked for \"readnow\"\n");
6543   printf_filtered ("\n");
6544 }
6545
6546 static void
6547 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6548                                              const char *func_name)
6549 {
6550   struct dwarf2_per_objfile *dwarf2_per_objfile
6551     = get_dwarf2_per_objfile (objfile);
6552
6553   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6554   if (dwarf2_per_objfile->debug_names_table)
6555     {
6556       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6557
6558       /* Note: It doesn't matter what we pass for block_index here.  */
6559       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6560                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6561
6562       struct dwarf2_per_cu_data *per_cu;
6563       while ((per_cu = iter.next ()) != NULL)
6564         dw2_instantiate_symtab (per_cu);
6565     }
6566 }
6567
6568 static void
6569 dw2_debug_names_expand_symtabs_matching
6570   (struct objfile *objfile,
6571    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6572    const lookup_name_info &lookup_name,
6573    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6574    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6575    enum search_domain kind)
6576 {
6577   struct dwarf2_per_objfile *dwarf2_per_objfile
6578     = get_dwarf2_per_objfile (objfile);
6579
6580   /* debug_names_table is NULL if OBJF_READNOW.  */
6581   if (!dwarf2_per_objfile->debug_names_table)
6582     return;
6583
6584   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6585
6586   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6587
6588   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6589                                       symbol_matcher,
6590                                       kind, [&] (offset_type namei)
6591     {
6592       /* The name was matched, now expand corresponding CUs that were
6593          marked.  */
6594       dw2_debug_names_iterator iter (map, kind, namei);
6595
6596       struct dwarf2_per_cu_data *per_cu;
6597       while ((per_cu = iter.next ()) != NULL)
6598         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6599                                          expansion_notify);
6600     });
6601 }
6602
6603 const struct quick_symbol_functions dwarf2_debug_names_functions =
6604 {
6605   dw2_has_symbols,
6606   dw2_find_last_source_symtab,
6607   dw2_forget_cached_source_info,
6608   dw2_map_symtabs_matching_filename,
6609   dw2_debug_names_lookup_symbol,
6610   dw2_print_stats,
6611   dw2_debug_names_dump,
6612   dw2_relocate,
6613   dw2_debug_names_expand_symtabs_for_function,
6614   dw2_expand_all_symtabs,
6615   dw2_expand_symtabs_with_fullname,
6616   dw2_map_matching_symbols,
6617   dw2_debug_names_expand_symtabs_matching,
6618   dw2_find_pc_sect_compunit_symtab,
6619   NULL,
6620   dw2_map_symbol_filenames
6621 };
6622
6623 /* See symfile.h.  */
6624
6625 bool
6626 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6627 {
6628   struct dwarf2_per_objfile *dwarf2_per_objfile
6629     = get_dwarf2_per_objfile (objfile);
6630
6631   /* If we're about to read full symbols, don't bother with the
6632      indices.  In this case we also don't care if some other debug
6633      format is making psymtabs, because they are all about to be
6634      expanded anyway.  */
6635   if ((objfile->flags & OBJF_READNOW))
6636     {
6637       int i;
6638
6639       dwarf2_per_objfile->using_index = 1;
6640       create_all_comp_units (dwarf2_per_objfile);
6641       create_all_type_units (dwarf2_per_objfile);
6642       dwarf2_per_objfile->quick_file_names_table =
6643         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6644
6645       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6646                        + dwarf2_per_objfile->n_type_units); ++i)
6647         {
6648           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6649
6650           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6651                                             struct dwarf2_per_cu_quick_data);
6652         }
6653
6654       /* Return 1 so that gdb sees the "quick" functions.  However,
6655          these functions will be no-ops because we will have expanded
6656          all symtabs.  */
6657       *index_kind = dw_index_kind::GDB_INDEX;
6658       return true;
6659     }
6660
6661   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6662     {
6663       *index_kind = dw_index_kind::DEBUG_NAMES;
6664       return true;
6665     }
6666
6667   if (dwarf2_read_index (objfile))
6668     {
6669       *index_kind = dw_index_kind::GDB_INDEX;
6670       return true;
6671     }
6672
6673   return false;
6674 }
6675
6676 \f
6677
6678 /* Build a partial symbol table.  */
6679
6680 void
6681 dwarf2_build_psymtabs (struct objfile *objfile)
6682 {
6683   struct dwarf2_per_objfile *dwarf2_per_objfile
6684     = get_dwarf2_per_objfile (objfile);
6685
6686   if (objfile->global_psymbols.capacity () == 0
6687       && objfile->static_psymbols.capacity () == 0)
6688     init_psymbol_list (objfile, 1024);
6689
6690   TRY
6691     {
6692       /* This isn't really ideal: all the data we allocate on the
6693          objfile's obstack is still uselessly kept around.  However,
6694          freeing it seems unsafe.  */
6695       psymtab_discarder psymtabs (objfile);
6696       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6697       psymtabs.keep ();
6698     }
6699   CATCH (except, RETURN_MASK_ERROR)
6700     {
6701       exception_print (gdb_stderr, except);
6702     }
6703   END_CATCH
6704 }
6705
6706 /* Return the total length of the CU described by HEADER.  */
6707
6708 static unsigned int
6709 get_cu_length (const struct comp_unit_head *header)
6710 {
6711   return header->initial_length_size + header->length;
6712 }
6713
6714 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6715
6716 static inline bool
6717 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6718 {
6719   sect_offset bottom = cu_header->sect_off;
6720   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6721
6722   return sect_off >= bottom && sect_off < top;
6723 }
6724
6725 /* Find the base address of the compilation unit for range lists and
6726    location lists.  It will normally be specified by DW_AT_low_pc.
6727    In DWARF-3 draft 4, the base address could be overridden by
6728    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6729    compilation units with discontinuous ranges.  */
6730
6731 static void
6732 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6733 {
6734   struct attribute *attr;
6735
6736   cu->base_known = 0;
6737   cu->base_address = 0;
6738
6739   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6740   if (attr)
6741     {
6742       cu->base_address = attr_value_as_address (attr);
6743       cu->base_known = 1;
6744     }
6745   else
6746     {
6747       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6748       if (attr)
6749         {
6750           cu->base_address = attr_value_as_address (attr);
6751           cu->base_known = 1;
6752         }
6753     }
6754 }
6755
6756 /* Read in the comp unit header information from the debug_info at info_ptr.
6757    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6758    NOTE: This leaves members offset, first_die_offset to be filled in
6759    by the caller.  */
6760
6761 static const gdb_byte *
6762 read_comp_unit_head (struct comp_unit_head *cu_header,
6763                      const gdb_byte *info_ptr,
6764                      struct dwarf2_section_info *section,
6765                      rcuh_kind section_kind)
6766 {
6767   int signed_addr;
6768   unsigned int bytes_read;
6769   const char *filename = get_section_file_name (section);
6770   bfd *abfd = get_section_bfd_owner (section);
6771
6772   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6773   cu_header->initial_length_size = bytes_read;
6774   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6775   info_ptr += bytes_read;
6776   cu_header->version = read_2_bytes (abfd, info_ptr);
6777   info_ptr += 2;
6778   if (cu_header->version < 5)
6779     switch (section_kind)
6780       {
6781       case rcuh_kind::COMPILE:
6782         cu_header->unit_type = DW_UT_compile;
6783         break;
6784       case rcuh_kind::TYPE:
6785         cu_header->unit_type = DW_UT_type;
6786         break;
6787       default:
6788         internal_error (__FILE__, __LINE__,
6789                         _("read_comp_unit_head: invalid section_kind"));
6790       }
6791   else
6792     {
6793       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6794                                                  (read_1_byte (abfd, info_ptr));
6795       info_ptr += 1;
6796       switch (cu_header->unit_type)
6797         {
6798         case DW_UT_compile:
6799           if (section_kind != rcuh_kind::COMPILE)
6800             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6801                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6802                    filename);
6803           break;
6804         case DW_UT_type:
6805           section_kind = rcuh_kind::TYPE;
6806           break;
6807         default:
6808           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6809                  "(is %d, should be %d or %d) [in module %s]"),
6810                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6811         }
6812
6813       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6814       info_ptr += 1;
6815     }
6816   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6817                                                           cu_header,
6818                                                           &bytes_read);
6819   info_ptr += bytes_read;
6820   if (cu_header->version < 5)
6821     {
6822       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6823       info_ptr += 1;
6824     }
6825   signed_addr = bfd_get_sign_extend_vma (abfd);
6826   if (signed_addr < 0)
6827     internal_error (__FILE__, __LINE__,
6828                     _("read_comp_unit_head: dwarf from non elf file"));
6829   cu_header->signed_addr_p = signed_addr;
6830
6831   if (section_kind == rcuh_kind::TYPE)
6832     {
6833       LONGEST type_offset;
6834
6835       cu_header->signature = read_8_bytes (abfd, info_ptr);
6836       info_ptr += 8;
6837
6838       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6839       info_ptr += bytes_read;
6840       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6841       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6842         error (_("Dwarf Error: Too big type_offset in compilation unit "
6843                "header (is %s) [in module %s]"), plongest (type_offset),
6844                filename);
6845     }
6846
6847   return info_ptr;
6848 }
6849
6850 /* Helper function that returns the proper abbrev section for
6851    THIS_CU.  */
6852
6853 static struct dwarf2_section_info *
6854 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6855 {
6856   struct dwarf2_section_info *abbrev;
6857   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6858
6859   if (this_cu->is_dwz)
6860     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6861   else
6862     abbrev = &dwarf2_per_objfile->abbrev;
6863
6864   return abbrev;
6865 }
6866
6867 /* Subroutine of read_and_check_comp_unit_head and
6868    read_and_check_type_unit_head to simplify them.
6869    Perform various error checking on the header.  */
6870
6871 static void
6872 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6873                             struct comp_unit_head *header,
6874                             struct dwarf2_section_info *section,
6875                             struct dwarf2_section_info *abbrev_section)
6876 {
6877   const char *filename = get_section_file_name (section);
6878
6879   if (header->version < 2 || header->version > 5)
6880     error (_("Dwarf Error: wrong version in compilation unit header "
6881            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6882            filename);
6883
6884   if (to_underlying (header->abbrev_sect_off)
6885       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6886     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6887            "(offset %s + 6) [in module %s]"),
6888            sect_offset_str (header->abbrev_sect_off),
6889            sect_offset_str (header->sect_off),
6890            filename);
6891
6892   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6893      avoid potential 32-bit overflow.  */
6894   if (((ULONGEST) header->sect_off + get_cu_length (header))
6895       > section->size)
6896     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6897            "(offset %s + 0) [in module %s]"),
6898            header->length, sect_offset_str (header->sect_off),
6899            filename);
6900 }
6901
6902 /* Read in a CU/TU header and perform some basic error checking.
6903    The contents of the header are stored in HEADER.
6904    The result is a pointer to the start of the first DIE.  */
6905
6906 static const gdb_byte *
6907 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6908                                struct comp_unit_head *header,
6909                                struct dwarf2_section_info *section,
6910                                struct dwarf2_section_info *abbrev_section,
6911                                const gdb_byte *info_ptr,
6912                                rcuh_kind section_kind)
6913 {
6914   const gdb_byte *beg_of_comp_unit = info_ptr;
6915
6916   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6917
6918   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6919
6920   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6921
6922   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6923                               abbrev_section);
6924
6925   return info_ptr;
6926 }
6927
6928 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6929
6930 static sect_offset
6931 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6932                     struct dwarf2_section_info *section,
6933                     sect_offset sect_off)
6934 {
6935   bfd *abfd = get_section_bfd_owner (section);
6936   const gdb_byte *info_ptr;
6937   unsigned int initial_length_size, offset_size;
6938   uint16_t version;
6939
6940   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6941   info_ptr = section->buffer + to_underlying (sect_off);
6942   read_initial_length (abfd, info_ptr, &initial_length_size);
6943   offset_size = initial_length_size == 4 ? 4 : 8;
6944   info_ptr += initial_length_size;
6945
6946   version = read_2_bytes (abfd, info_ptr);
6947   info_ptr += 2;
6948   if (version >= 5)
6949     {
6950       /* Skip unit type and address size.  */
6951       info_ptr += 2;
6952     }
6953
6954   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6955 }
6956
6957 /* Allocate a new partial symtab for file named NAME and mark this new
6958    partial symtab as being an include of PST.  */
6959
6960 static void
6961 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6962                                struct objfile *objfile)
6963 {
6964   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6965
6966   if (!IS_ABSOLUTE_PATH (subpst->filename))
6967     {
6968       /* It shares objfile->objfile_obstack.  */
6969       subpst->dirname = pst->dirname;
6970     }
6971
6972   subpst->textlow = 0;
6973   subpst->texthigh = 0;
6974
6975   subpst->dependencies
6976     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6977   subpst->dependencies[0] = pst;
6978   subpst->number_of_dependencies = 1;
6979
6980   subpst->globals_offset = 0;
6981   subpst->n_global_syms = 0;
6982   subpst->statics_offset = 0;
6983   subpst->n_static_syms = 0;
6984   subpst->compunit_symtab = NULL;
6985   subpst->read_symtab = pst->read_symtab;
6986   subpst->readin = 0;
6987
6988   /* No private part is necessary for include psymtabs.  This property
6989      can be used to differentiate between such include psymtabs and
6990      the regular ones.  */
6991   subpst->read_symtab_private = NULL;
6992 }
6993
6994 /* Read the Line Number Program data and extract the list of files
6995    included by the source file represented by PST.  Build an include
6996    partial symtab for each of these included files.  */
6997
6998 static void
6999 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
7000                                struct die_info *die,
7001                                struct partial_symtab *pst)
7002 {
7003   line_header_up lh;
7004   struct attribute *attr;
7005
7006   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7007   if (attr)
7008     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
7009   if (lh == NULL)
7010     return;  /* No linetable, so no includes.  */
7011
7012   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
7013   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
7014 }
7015
7016 static hashval_t
7017 hash_signatured_type (const void *item)
7018 {
7019   const struct signatured_type *sig_type
7020     = (const struct signatured_type *) item;
7021
7022   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
7023   return sig_type->signature;
7024 }
7025
7026 static int
7027 eq_signatured_type (const void *item_lhs, const void *item_rhs)
7028 {
7029   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
7030   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
7031
7032   return lhs->signature == rhs->signature;
7033 }
7034
7035 /* Allocate a hash table for signatured types.  */
7036
7037 static htab_t
7038 allocate_signatured_type_table (struct objfile *objfile)
7039 {
7040   return htab_create_alloc_ex (41,
7041                                hash_signatured_type,
7042                                eq_signatured_type,
7043                                NULL,
7044                                &objfile->objfile_obstack,
7045                                hashtab_obstack_allocate,
7046                                dummy_obstack_deallocate);
7047 }
7048
7049 /* A helper function to add a signatured type CU to a table.  */
7050
7051 static int
7052 add_signatured_type_cu_to_table (void **slot, void *datum)
7053 {
7054   struct signatured_type *sigt = (struct signatured_type *) *slot;
7055   struct signatured_type ***datap = (struct signatured_type ***) datum;
7056
7057   **datap = sigt;
7058   ++*datap;
7059
7060   return 1;
7061 }
7062
7063 /* A helper for create_debug_types_hash_table.  Read types from SECTION
7064    and fill them into TYPES_HTAB.  It will process only type units,
7065    therefore DW_UT_type.  */
7066
7067 static void
7068 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7069                               struct dwo_file *dwo_file,
7070                               dwarf2_section_info *section, htab_t &types_htab,
7071                               rcuh_kind section_kind)
7072 {
7073   struct objfile *objfile = dwarf2_per_objfile->objfile;
7074   struct dwarf2_section_info *abbrev_section;
7075   bfd *abfd;
7076   const gdb_byte *info_ptr, *end_ptr;
7077
7078   abbrev_section = (dwo_file != NULL
7079                     ? &dwo_file->sections.abbrev
7080                     : &dwarf2_per_objfile->abbrev);
7081
7082   if (dwarf_read_debug)
7083     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7084                         get_section_name (section),
7085                         get_section_file_name (abbrev_section));
7086
7087   dwarf2_read_section (objfile, section);
7088   info_ptr = section->buffer;
7089
7090   if (info_ptr == NULL)
7091     return;
7092
7093   /* We can't set abfd until now because the section may be empty or
7094      not present, in which case the bfd is unknown.  */
7095   abfd = get_section_bfd_owner (section);
7096
7097   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7098      because we don't need to read any dies: the signature is in the
7099      header.  */
7100
7101   end_ptr = info_ptr + section->size;
7102   while (info_ptr < end_ptr)
7103     {
7104       struct signatured_type *sig_type;
7105       struct dwo_unit *dwo_tu;
7106       void **slot;
7107       const gdb_byte *ptr = info_ptr;
7108       struct comp_unit_head header;
7109       unsigned int length;
7110
7111       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7112
7113       /* Initialize it due to a false compiler warning.  */
7114       header.signature = -1;
7115       header.type_cu_offset_in_tu = (cu_offset) -1;
7116
7117       /* We need to read the type's signature in order to build the hash
7118          table, but we don't need anything else just yet.  */
7119
7120       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7121                                            abbrev_section, ptr, section_kind);
7122
7123       length = get_cu_length (&header);
7124
7125       /* Skip dummy type units.  */
7126       if (ptr >= info_ptr + length
7127           || peek_abbrev_code (abfd, ptr) == 0
7128           || header.unit_type != DW_UT_type)
7129         {
7130           info_ptr += length;
7131           continue;
7132         }
7133
7134       if (types_htab == NULL)
7135         {
7136           if (dwo_file)
7137             types_htab = allocate_dwo_unit_table (objfile);
7138           else
7139             types_htab = allocate_signatured_type_table (objfile);
7140         }
7141
7142       if (dwo_file)
7143         {
7144           sig_type = NULL;
7145           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7146                                    struct dwo_unit);
7147           dwo_tu->dwo_file = dwo_file;
7148           dwo_tu->signature = header.signature;
7149           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7150           dwo_tu->section = section;
7151           dwo_tu->sect_off = sect_off;
7152           dwo_tu->length = length;
7153         }
7154       else
7155         {
7156           /* N.B.: type_offset is not usable if this type uses a DWO file.
7157              The real type_offset is in the DWO file.  */
7158           dwo_tu = NULL;
7159           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7160                                      struct signatured_type);
7161           sig_type->signature = header.signature;
7162           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7163           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7164           sig_type->per_cu.is_debug_types = 1;
7165           sig_type->per_cu.section = section;
7166           sig_type->per_cu.sect_off = sect_off;
7167           sig_type->per_cu.length = length;
7168         }
7169
7170       slot = htab_find_slot (types_htab,
7171                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7172                              INSERT);
7173       gdb_assert (slot != NULL);
7174       if (*slot != NULL)
7175         {
7176           sect_offset dup_sect_off;
7177
7178           if (dwo_file)
7179             {
7180               const struct dwo_unit *dup_tu
7181                 = (const struct dwo_unit *) *slot;
7182
7183               dup_sect_off = dup_tu->sect_off;
7184             }
7185           else
7186             {
7187               const struct signatured_type *dup_tu
7188                 = (const struct signatured_type *) *slot;
7189
7190               dup_sect_off = dup_tu->per_cu.sect_off;
7191             }
7192
7193           complaint (&symfile_complaints,
7194                      _("debug type entry at offset %s is duplicate to"
7195                        " the entry at offset %s, signature %s"),
7196                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
7197                      hex_string (header.signature));
7198         }
7199       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7200
7201       if (dwarf_read_debug > 1)
7202         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
7203                             sect_offset_str (sect_off),
7204                             hex_string (header.signature));
7205
7206       info_ptr += length;
7207     }
7208 }
7209
7210 /* Create the hash table of all entries in the .debug_types
7211    (or .debug_types.dwo) section(s).
7212    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7213    otherwise it is NULL.
7214
7215    The result is a pointer to the hash table or NULL if there are no types.
7216
7217    Note: This function processes DWO files only, not DWP files.  */
7218
7219 static void
7220 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7221                                struct dwo_file *dwo_file,
7222                                VEC (dwarf2_section_info_def) *types,
7223                                htab_t &types_htab)
7224 {
7225   int ix;
7226   struct dwarf2_section_info *section;
7227
7228   if (VEC_empty (dwarf2_section_info_def, types))
7229     return;
7230
7231   for (ix = 0;
7232        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7233        ++ix)
7234     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7235                                   types_htab, rcuh_kind::TYPE);
7236 }
7237
7238 /* Create the hash table of all entries in the .debug_types section,
7239    and initialize all_type_units.
7240    The result is zero if there is an error (e.g. missing .debug_types section),
7241    otherwise non-zero.  */
7242
7243 static int
7244 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7245 {
7246   htab_t types_htab = NULL;
7247   struct signatured_type **iter;
7248
7249   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7250                                 &dwarf2_per_objfile->info, types_htab,
7251                                 rcuh_kind::COMPILE);
7252   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7253                                  dwarf2_per_objfile->types, types_htab);
7254   if (types_htab == NULL)
7255     {
7256       dwarf2_per_objfile->signatured_types = NULL;
7257       return 0;
7258     }
7259
7260   dwarf2_per_objfile->signatured_types = types_htab;
7261
7262   dwarf2_per_objfile->n_type_units
7263     = dwarf2_per_objfile->n_allocated_type_units
7264     = htab_elements (types_htab);
7265   dwarf2_per_objfile->all_type_units =
7266     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7267   iter = &dwarf2_per_objfile->all_type_units[0];
7268   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7269   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7270               == dwarf2_per_objfile->n_type_units);
7271
7272   return 1;
7273 }
7274
7275 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7276    If SLOT is non-NULL, it is the entry to use in the hash table.
7277    Otherwise we find one.  */
7278
7279 static struct signatured_type *
7280 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7281                void **slot)
7282 {
7283   struct objfile *objfile = dwarf2_per_objfile->objfile;
7284   int n_type_units = dwarf2_per_objfile->n_type_units;
7285   struct signatured_type *sig_type;
7286
7287   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7288   ++n_type_units;
7289   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7290     {
7291       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7292         dwarf2_per_objfile->n_allocated_type_units = 1;
7293       dwarf2_per_objfile->n_allocated_type_units *= 2;
7294       dwarf2_per_objfile->all_type_units
7295         = XRESIZEVEC (struct signatured_type *,
7296                       dwarf2_per_objfile->all_type_units,
7297                       dwarf2_per_objfile->n_allocated_type_units);
7298       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7299     }
7300   dwarf2_per_objfile->n_type_units = n_type_units;
7301
7302   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7303                              struct signatured_type);
7304   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7305   sig_type->signature = sig;
7306   sig_type->per_cu.is_debug_types = 1;
7307   if (dwarf2_per_objfile->using_index)
7308     {
7309       sig_type->per_cu.v.quick =
7310         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7311                         struct dwarf2_per_cu_quick_data);
7312     }
7313
7314   if (slot == NULL)
7315     {
7316       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7317                              sig_type, INSERT);
7318     }
7319   gdb_assert (*slot == NULL);
7320   *slot = sig_type;
7321   /* The rest of sig_type must be filled in by the caller.  */
7322   return sig_type;
7323 }
7324
7325 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7326    Fill in SIG_ENTRY with DWO_ENTRY.  */
7327
7328 static void
7329 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7330                                   struct signatured_type *sig_entry,
7331                                   struct dwo_unit *dwo_entry)
7332 {
7333   /* Make sure we're not clobbering something we don't expect to.  */
7334   gdb_assert (! sig_entry->per_cu.queued);
7335   gdb_assert (sig_entry->per_cu.cu == NULL);
7336   if (dwarf2_per_objfile->using_index)
7337     {
7338       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7339       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7340     }
7341   else
7342       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7343   gdb_assert (sig_entry->signature == dwo_entry->signature);
7344   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7345   gdb_assert (sig_entry->type_unit_group == NULL);
7346   gdb_assert (sig_entry->dwo_unit == NULL);
7347
7348   sig_entry->per_cu.section = dwo_entry->section;
7349   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7350   sig_entry->per_cu.length = dwo_entry->length;
7351   sig_entry->per_cu.reading_dwo_directly = 1;
7352   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7353   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7354   sig_entry->dwo_unit = dwo_entry;
7355 }
7356
7357 /* Subroutine of lookup_signatured_type.
7358    If we haven't read the TU yet, create the signatured_type data structure
7359    for a TU to be read in directly from a DWO file, bypassing the stub.
7360    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7361    using .gdb_index, then when reading a CU we want to stay in the DWO file
7362    containing that CU.  Otherwise we could end up reading several other DWO
7363    files (due to comdat folding) to process the transitive closure of all the
7364    mentioned TUs, and that can be slow.  The current DWO file will have every
7365    type signature that it needs.
7366    We only do this for .gdb_index because in the psymtab case we already have
7367    to read all the DWOs to build the type unit groups.  */
7368
7369 static struct signatured_type *
7370 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7371 {
7372   struct dwarf2_per_objfile *dwarf2_per_objfile
7373     = cu->per_cu->dwarf2_per_objfile;
7374   struct objfile *objfile = dwarf2_per_objfile->objfile;
7375   struct dwo_file *dwo_file;
7376   struct dwo_unit find_dwo_entry, *dwo_entry;
7377   struct signatured_type find_sig_entry, *sig_entry;
7378   void **slot;
7379
7380   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7381
7382   /* If TU skeletons have been removed then we may not have read in any
7383      TUs yet.  */
7384   if (dwarf2_per_objfile->signatured_types == NULL)
7385     {
7386       dwarf2_per_objfile->signatured_types
7387         = allocate_signatured_type_table (objfile);
7388     }
7389
7390   /* We only ever need to read in one copy of a signatured type.
7391      Use the global signatured_types array to do our own comdat-folding
7392      of types.  If this is the first time we're reading this TU, and
7393      the TU has an entry in .gdb_index, replace the recorded data from
7394      .gdb_index with this TU.  */
7395
7396   find_sig_entry.signature = sig;
7397   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7398                          &find_sig_entry, INSERT);
7399   sig_entry = (struct signatured_type *) *slot;
7400
7401   /* We can get here with the TU already read, *or* in the process of being
7402      read.  Don't reassign the global entry to point to this DWO if that's
7403      the case.  Also note that if the TU is already being read, it may not
7404      have come from a DWO, the program may be a mix of Fission-compiled
7405      code and non-Fission-compiled code.  */
7406
7407   /* Have we already tried to read this TU?
7408      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7409      needn't exist in the global table yet).  */
7410   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7411     return sig_entry;
7412
7413   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7414      dwo_unit of the TU itself.  */
7415   dwo_file = cu->dwo_unit->dwo_file;
7416
7417   /* Ok, this is the first time we're reading this TU.  */
7418   if (dwo_file->tus == NULL)
7419     return NULL;
7420   find_dwo_entry.signature = sig;
7421   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7422   if (dwo_entry == NULL)
7423     return NULL;
7424
7425   /* If the global table doesn't have an entry for this TU, add one.  */
7426   if (sig_entry == NULL)
7427     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7428
7429   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7430   sig_entry->per_cu.tu_read = 1;
7431   return sig_entry;
7432 }
7433
7434 /* Subroutine of lookup_signatured_type.
7435    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7436    then try the DWP file.  If the TU stub (skeleton) has been removed then
7437    it won't be in .gdb_index.  */
7438
7439 static struct signatured_type *
7440 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7441 {
7442   struct dwarf2_per_objfile *dwarf2_per_objfile
7443     = cu->per_cu->dwarf2_per_objfile;
7444   struct objfile *objfile = dwarf2_per_objfile->objfile;
7445   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7446   struct dwo_unit *dwo_entry;
7447   struct signatured_type find_sig_entry, *sig_entry;
7448   void **slot;
7449
7450   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7451   gdb_assert (dwp_file != NULL);
7452
7453   /* If TU skeletons have been removed then we may not have read in any
7454      TUs yet.  */
7455   if (dwarf2_per_objfile->signatured_types == NULL)
7456     {
7457       dwarf2_per_objfile->signatured_types
7458         = allocate_signatured_type_table (objfile);
7459     }
7460
7461   find_sig_entry.signature = sig;
7462   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7463                          &find_sig_entry, INSERT);
7464   sig_entry = (struct signatured_type *) *slot;
7465
7466   /* Have we already tried to read this TU?
7467      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7468      needn't exist in the global table yet).  */
7469   if (sig_entry != NULL)
7470     return sig_entry;
7471
7472   if (dwp_file->tus == NULL)
7473     return NULL;
7474   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7475                                       sig, 1 /* is_debug_types */);
7476   if (dwo_entry == NULL)
7477     return NULL;
7478
7479   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7480   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7481
7482   return sig_entry;
7483 }
7484
7485 /* Lookup a signature based type for DW_FORM_ref_sig8.
7486    Returns NULL if signature SIG is not present in the table.
7487    It is up to the caller to complain about this.  */
7488
7489 static struct signatured_type *
7490 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7491 {
7492   struct dwarf2_per_objfile *dwarf2_per_objfile
7493     = cu->per_cu->dwarf2_per_objfile;
7494
7495   if (cu->dwo_unit
7496       && dwarf2_per_objfile->using_index)
7497     {
7498       /* We're in a DWO/DWP file, and we're using .gdb_index.
7499          These cases require special processing.  */
7500       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7501         return lookup_dwo_signatured_type (cu, sig);
7502       else
7503         return lookup_dwp_signatured_type (cu, sig);
7504     }
7505   else
7506     {
7507       struct signatured_type find_entry, *entry;
7508
7509       if (dwarf2_per_objfile->signatured_types == NULL)
7510         return NULL;
7511       find_entry.signature = sig;
7512       entry = ((struct signatured_type *)
7513                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7514       return entry;
7515     }
7516 }
7517 \f
7518 /* Low level DIE reading support.  */
7519
7520 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7521
7522 static void
7523 init_cu_die_reader (struct die_reader_specs *reader,
7524                     struct dwarf2_cu *cu,
7525                     struct dwarf2_section_info *section,
7526                     struct dwo_file *dwo_file,
7527                     struct abbrev_table *abbrev_table)
7528 {
7529   gdb_assert (section->readin && section->buffer != NULL);
7530   reader->abfd = get_section_bfd_owner (section);
7531   reader->cu = cu;
7532   reader->dwo_file = dwo_file;
7533   reader->die_section = section;
7534   reader->buffer = section->buffer;
7535   reader->buffer_end = section->buffer + section->size;
7536   reader->comp_dir = NULL;
7537   reader->abbrev_table = abbrev_table;
7538 }
7539
7540 /* Subroutine of init_cutu_and_read_dies to simplify it.
7541    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7542    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7543    already.
7544
7545    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7546    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7547    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7548    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7549    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7550    STUB_COMP_DIR may be non-NULL.
7551    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7552    are filled in with the info of the DIE from the DWO file.
7553    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7554    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7555    kept around for at least as long as *RESULT_READER.
7556
7557    The result is non-zero if a valid (non-dummy) DIE was found.  */
7558
7559 static int
7560 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7561                         struct dwo_unit *dwo_unit,
7562                         struct die_info *stub_comp_unit_die,
7563                         const char *stub_comp_dir,
7564                         struct die_reader_specs *result_reader,
7565                         const gdb_byte **result_info_ptr,
7566                         struct die_info **result_comp_unit_die,
7567                         int *result_has_children,
7568                         abbrev_table_up *result_dwo_abbrev_table)
7569 {
7570   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7571   struct objfile *objfile = dwarf2_per_objfile->objfile;
7572   struct dwarf2_cu *cu = this_cu->cu;
7573   bfd *abfd;
7574   const gdb_byte *begin_info_ptr, *info_ptr;
7575   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7576   int i,num_extra_attrs;
7577   struct dwarf2_section_info *dwo_abbrev_section;
7578   struct attribute *attr;
7579   struct die_info *comp_unit_die;
7580
7581   /* At most one of these may be provided.  */
7582   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7583
7584   /* These attributes aren't processed until later:
7585      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7586      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7587      referenced later.  However, these attributes are found in the stub
7588      which we won't have later.  In order to not impose this complication
7589      on the rest of the code, we read them here and copy them to the
7590      DWO CU/TU die.  */
7591
7592   stmt_list = NULL;
7593   low_pc = NULL;
7594   high_pc = NULL;
7595   ranges = NULL;
7596   comp_dir = NULL;
7597
7598   if (stub_comp_unit_die != NULL)
7599     {
7600       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7601          DWO file.  */
7602       if (! this_cu->is_debug_types)
7603         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7604       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7605       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7606       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7607       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7608
7609       /* There should be a DW_AT_addr_base attribute here (if needed).
7610          We need the value before we can process DW_FORM_GNU_addr_index.  */
7611       cu->addr_base = 0;
7612       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7613       if (attr)
7614         cu->addr_base = DW_UNSND (attr);
7615
7616       /* There should be a DW_AT_ranges_base attribute here (if needed).
7617          We need the value before we can process DW_AT_ranges.  */
7618       cu->ranges_base = 0;
7619       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7620       if (attr)
7621         cu->ranges_base = DW_UNSND (attr);
7622     }
7623   else if (stub_comp_dir != NULL)
7624     {
7625       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7626       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7627       comp_dir->name = DW_AT_comp_dir;
7628       comp_dir->form = DW_FORM_string;
7629       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7630       DW_STRING (comp_dir) = stub_comp_dir;
7631     }
7632
7633   /* Set up for reading the DWO CU/TU.  */
7634   cu->dwo_unit = dwo_unit;
7635   dwarf2_section_info *section = dwo_unit->section;
7636   dwarf2_read_section (objfile, section);
7637   abfd = get_section_bfd_owner (section);
7638   begin_info_ptr = info_ptr = (section->buffer
7639                                + to_underlying (dwo_unit->sect_off));
7640   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7641
7642   if (this_cu->is_debug_types)
7643     {
7644       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7645
7646       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7647                                                 &cu->header, section,
7648                                                 dwo_abbrev_section,
7649                                                 info_ptr, rcuh_kind::TYPE);
7650       /* This is not an assert because it can be caused by bad debug info.  */
7651       if (sig_type->signature != cu->header.signature)
7652         {
7653           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7654                    " TU at offset %s [in module %s]"),
7655                  hex_string (sig_type->signature),
7656                  hex_string (cu->header.signature),
7657                  sect_offset_str (dwo_unit->sect_off),
7658                  bfd_get_filename (abfd));
7659         }
7660       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7661       /* For DWOs coming from DWP files, we don't know the CU length
7662          nor the type's offset in the TU until now.  */
7663       dwo_unit->length = get_cu_length (&cu->header);
7664       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7665
7666       /* Establish the type offset that can be used to lookup the type.
7667          For DWO files, we don't know it until now.  */
7668       sig_type->type_offset_in_section
7669         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7670     }
7671   else
7672     {
7673       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7674                                                 &cu->header, section,
7675                                                 dwo_abbrev_section,
7676                                                 info_ptr, rcuh_kind::COMPILE);
7677       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7678       /* For DWOs coming from DWP files, we don't know the CU length
7679          until now.  */
7680       dwo_unit->length = get_cu_length (&cu->header);
7681     }
7682
7683   *result_dwo_abbrev_table
7684     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7685                                cu->header.abbrev_sect_off);
7686   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7687                       result_dwo_abbrev_table->get ());
7688
7689   /* Read in the die, but leave space to copy over the attributes
7690      from the stub.  This has the benefit of simplifying the rest of
7691      the code - all the work to maintain the illusion of a single
7692      DW_TAG_{compile,type}_unit DIE is done here.  */
7693   num_extra_attrs = ((stmt_list != NULL)
7694                      + (low_pc != NULL)
7695                      + (high_pc != NULL)
7696                      + (ranges != NULL)
7697                      + (comp_dir != NULL));
7698   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7699                               result_has_children, num_extra_attrs);
7700
7701   /* Copy over the attributes from the stub to the DIE we just read in.  */
7702   comp_unit_die = *result_comp_unit_die;
7703   i = comp_unit_die->num_attrs;
7704   if (stmt_list != NULL)
7705     comp_unit_die->attrs[i++] = *stmt_list;
7706   if (low_pc != NULL)
7707     comp_unit_die->attrs[i++] = *low_pc;
7708   if (high_pc != NULL)
7709     comp_unit_die->attrs[i++] = *high_pc;
7710   if (ranges != NULL)
7711     comp_unit_die->attrs[i++] = *ranges;
7712   if (comp_dir != NULL)
7713     comp_unit_die->attrs[i++] = *comp_dir;
7714   comp_unit_die->num_attrs += num_extra_attrs;
7715
7716   if (dwarf_die_debug)
7717     {
7718       fprintf_unfiltered (gdb_stdlog,
7719                           "Read die from %s@0x%x of %s:\n",
7720                           get_section_name (section),
7721                           (unsigned) (begin_info_ptr - section->buffer),
7722                           bfd_get_filename (abfd));
7723       dump_die (comp_unit_die, dwarf_die_debug);
7724     }
7725
7726   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7727      TUs by skipping the stub and going directly to the entry in the DWO file.
7728      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7729      to get it via circuitous means.  Blech.  */
7730   if (comp_dir != NULL)
7731     result_reader->comp_dir = DW_STRING (comp_dir);
7732
7733   /* Skip dummy compilation units.  */
7734   if (info_ptr >= begin_info_ptr + dwo_unit->length
7735       || peek_abbrev_code (abfd, info_ptr) == 0)
7736     return 0;
7737
7738   *result_info_ptr = info_ptr;
7739   return 1;
7740 }
7741
7742 /* Subroutine of init_cutu_and_read_dies to simplify it.
7743    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7744    Returns NULL if the specified DWO unit cannot be found.  */
7745
7746 static struct dwo_unit *
7747 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7748                  struct die_info *comp_unit_die)
7749 {
7750   struct dwarf2_cu *cu = this_cu->cu;
7751   ULONGEST signature;
7752   struct dwo_unit *dwo_unit;
7753   const char *comp_dir, *dwo_name;
7754
7755   gdb_assert (cu != NULL);
7756
7757   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7758   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7759   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7760
7761   if (this_cu->is_debug_types)
7762     {
7763       struct signatured_type *sig_type;
7764
7765       /* Since this_cu is the first member of struct signatured_type,
7766          we can go from a pointer to one to a pointer to the other.  */
7767       sig_type = (struct signatured_type *) this_cu;
7768       signature = sig_type->signature;
7769       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7770     }
7771   else
7772     {
7773       struct attribute *attr;
7774
7775       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7776       if (! attr)
7777         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7778                  " [in module %s]"),
7779                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7780       signature = DW_UNSND (attr);
7781       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7782                                        signature);
7783     }
7784
7785   return dwo_unit;
7786 }
7787
7788 /* Subroutine of init_cutu_and_read_dies to simplify it.
7789    See it for a description of the parameters.
7790    Read a TU directly from a DWO file, bypassing the stub.  */
7791
7792 static void
7793 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7794                            int use_existing_cu, int keep,
7795                            die_reader_func_ftype *die_reader_func,
7796                            void *data)
7797 {
7798   std::unique_ptr<dwarf2_cu> new_cu;
7799   struct signatured_type *sig_type;
7800   struct die_reader_specs reader;
7801   const gdb_byte *info_ptr;
7802   struct die_info *comp_unit_die;
7803   int has_children;
7804   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7805
7806   /* Verify we can do the following downcast, and that we have the
7807      data we need.  */
7808   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7809   sig_type = (struct signatured_type *) this_cu;
7810   gdb_assert (sig_type->dwo_unit != NULL);
7811
7812   if (use_existing_cu && this_cu->cu != NULL)
7813     {
7814       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7815       /* There's no need to do the rereading_dwo_cu handling that
7816          init_cutu_and_read_dies does since we don't read the stub.  */
7817     }
7818   else
7819     {
7820       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7821       gdb_assert (this_cu->cu == NULL);
7822       new_cu.reset (new dwarf2_cu (this_cu));
7823     }
7824
7825   /* A future optimization, if needed, would be to use an existing
7826      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7827      could share abbrev tables.  */
7828
7829   /* The abbreviation table used by READER, this must live at least as long as
7830      READER.  */
7831   abbrev_table_up dwo_abbrev_table;
7832
7833   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7834                               NULL /* stub_comp_unit_die */,
7835                               sig_type->dwo_unit->dwo_file->comp_dir,
7836                               &reader, &info_ptr,
7837                               &comp_unit_die, &has_children,
7838                               &dwo_abbrev_table) == 0)
7839     {
7840       /* Dummy die.  */
7841       return;
7842     }
7843
7844   /* All the "real" work is done here.  */
7845   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7846
7847   /* This duplicates the code in init_cutu_and_read_dies,
7848      but the alternative is making the latter more complex.
7849      This function is only for the special case of using DWO files directly:
7850      no point in overly complicating the general case just to handle this.  */
7851   if (new_cu != NULL && keep)
7852     {
7853       /* Link this CU into read_in_chain.  */
7854       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7855       dwarf2_per_objfile->read_in_chain = this_cu;
7856       /* The chain owns it now.  */
7857       new_cu.release ();
7858     }
7859 }
7860
7861 /* Initialize a CU (or TU) and read its DIEs.
7862    If the CU defers to a DWO file, read the DWO file as well.
7863
7864    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7865    Otherwise the table specified in the comp unit header is read in and used.
7866    This is an optimization for when we already have the abbrev table.
7867
7868    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7869    Otherwise, a new CU is allocated with xmalloc.
7870
7871    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7872    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7873
7874    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7875    linker) then DIE_READER_FUNC will not get called.  */
7876
7877 static void
7878 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7879                          struct abbrev_table *abbrev_table,
7880                          int use_existing_cu, int keep,
7881                          die_reader_func_ftype *die_reader_func,
7882                          void *data)
7883 {
7884   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7885   struct objfile *objfile = dwarf2_per_objfile->objfile;
7886   struct dwarf2_section_info *section = this_cu->section;
7887   bfd *abfd = get_section_bfd_owner (section);
7888   struct dwarf2_cu *cu;
7889   const gdb_byte *begin_info_ptr, *info_ptr;
7890   struct die_reader_specs reader;
7891   struct die_info *comp_unit_die;
7892   int has_children;
7893   struct attribute *attr;
7894   struct signatured_type *sig_type = NULL;
7895   struct dwarf2_section_info *abbrev_section;
7896   /* Non-zero if CU currently points to a DWO file and we need to
7897      reread it.  When this happens we need to reread the skeleton die
7898      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7899   int rereading_dwo_cu = 0;
7900
7901   if (dwarf_die_debug)
7902     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7903                         this_cu->is_debug_types ? "type" : "comp",
7904                         sect_offset_str (this_cu->sect_off));
7905
7906   if (use_existing_cu)
7907     gdb_assert (keep);
7908
7909   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7910      file (instead of going through the stub), short-circuit all of this.  */
7911   if (this_cu->reading_dwo_directly)
7912     {
7913       /* Narrow down the scope of possibilities to have to understand.  */
7914       gdb_assert (this_cu->is_debug_types);
7915       gdb_assert (abbrev_table == NULL);
7916       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7917                                  die_reader_func, data);
7918       return;
7919     }
7920
7921   /* This is cheap if the section is already read in.  */
7922   dwarf2_read_section (objfile, section);
7923
7924   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7925
7926   abbrev_section = get_abbrev_section_for_cu (this_cu);
7927
7928   std::unique_ptr<dwarf2_cu> new_cu;
7929   if (use_existing_cu && this_cu->cu != NULL)
7930     {
7931       cu = this_cu->cu;
7932       /* If this CU is from a DWO file we need to start over, we need to
7933          refetch the attributes from the skeleton CU.
7934          This could be optimized by retrieving those attributes from when we
7935          were here the first time: the previous comp_unit_die was stored in
7936          comp_unit_obstack.  But there's no data yet that we need this
7937          optimization.  */
7938       if (cu->dwo_unit != NULL)
7939         rereading_dwo_cu = 1;
7940     }
7941   else
7942     {
7943       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7944       gdb_assert (this_cu->cu == NULL);
7945       new_cu.reset (new dwarf2_cu (this_cu));
7946       cu = new_cu.get ();
7947     }
7948
7949   /* Get the header.  */
7950   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7951     {
7952       /* We already have the header, there's no need to read it in again.  */
7953       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7954     }
7955   else
7956     {
7957       if (this_cu->is_debug_types)
7958         {
7959           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7960                                                     &cu->header, section,
7961                                                     abbrev_section, info_ptr,
7962                                                     rcuh_kind::TYPE);
7963
7964           /* Since per_cu is the first member of struct signatured_type,
7965              we can go from a pointer to one to a pointer to the other.  */
7966           sig_type = (struct signatured_type *) this_cu;
7967           gdb_assert (sig_type->signature == cu->header.signature);
7968           gdb_assert (sig_type->type_offset_in_tu
7969                       == cu->header.type_cu_offset_in_tu);
7970           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7971
7972           /* LENGTH has not been set yet for type units if we're
7973              using .gdb_index.  */
7974           this_cu->length = get_cu_length (&cu->header);
7975
7976           /* Establish the type offset that can be used to lookup the type.  */
7977           sig_type->type_offset_in_section =
7978             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7979
7980           this_cu->dwarf_version = cu->header.version;
7981         }
7982       else
7983         {
7984           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7985                                                     &cu->header, section,
7986                                                     abbrev_section,
7987                                                     info_ptr,
7988                                                     rcuh_kind::COMPILE);
7989
7990           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7991           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7992           this_cu->dwarf_version = cu->header.version;
7993         }
7994     }
7995
7996   /* Skip dummy compilation units.  */
7997   if (info_ptr >= begin_info_ptr + this_cu->length
7998       || peek_abbrev_code (abfd, info_ptr) == 0)
7999     return;
8000
8001   /* If we don't have them yet, read the abbrevs for this compilation unit.
8002      And if we need to read them now, make sure they're freed when we're
8003      done (own the table through ABBREV_TABLE_HOLDER).  */
8004   abbrev_table_up abbrev_table_holder;
8005   if (abbrev_table != NULL)
8006     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
8007   else
8008     {
8009       abbrev_table_holder
8010         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8011                                    cu->header.abbrev_sect_off);
8012       abbrev_table = abbrev_table_holder.get ();
8013     }
8014
8015   /* Read the top level CU/TU die.  */
8016   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
8017   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8018
8019   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
8020      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
8021      table from the DWO file and pass the ownership over to us.  It will be
8022      referenced from READER, so we must make sure to free it after we're done
8023      with READER.
8024
8025      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
8026      DWO CU, that this test will fail (the attribute will not be present).  */
8027   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
8028   abbrev_table_up dwo_abbrev_table;
8029   if (attr)
8030     {
8031       struct dwo_unit *dwo_unit;
8032       struct die_info *dwo_comp_unit_die;
8033
8034       if (has_children)
8035         {
8036           complaint (&symfile_complaints,
8037                      _("compilation unit with DW_AT_GNU_dwo_name"
8038                        " has children (offset %s) [in module %s]"),
8039                      sect_offset_str (this_cu->sect_off),
8040                      bfd_get_filename (abfd));
8041         }
8042       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
8043       if (dwo_unit != NULL)
8044         {
8045           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
8046                                       comp_unit_die, NULL,
8047                                       &reader, &info_ptr,
8048                                       &dwo_comp_unit_die, &has_children,
8049                                       &dwo_abbrev_table) == 0)
8050             {
8051               /* Dummy die.  */
8052               return;
8053             }
8054           comp_unit_die = dwo_comp_unit_die;
8055         }
8056       else
8057         {
8058           /* Yikes, we couldn't find the rest of the DIE, we only have
8059              the stub.  A complaint has already been logged.  There's
8060              not much more we can do except pass on the stub DIE to
8061              die_reader_func.  We don't want to throw an error on bad
8062              debug info.  */
8063         }
8064     }
8065
8066   /* All of the above is setup for this call.  Yikes.  */
8067   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8068
8069   /* Done, clean up.  */
8070   if (new_cu != NULL && keep)
8071     {
8072       /* Link this CU into read_in_chain.  */
8073       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8074       dwarf2_per_objfile->read_in_chain = this_cu;
8075       /* The chain owns it now.  */
8076       new_cu.release ();
8077     }
8078 }
8079
8080 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8081    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8082    to have already done the lookup to find the DWO file).
8083
8084    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8085    THIS_CU->is_debug_types, but nothing else.
8086
8087    We fill in THIS_CU->length.
8088
8089    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8090    linker) then DIE_READER_FUNC will not get called.
8091
8092    THIS_CU->cu is always freed when done.
8093    This is done in order to not leave THIS_CU->cu in a state where we have
8094    to care whether it refers to the "main" CU or the DWO CU.  */
8095
8096 static void
8097 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8098                                    struct dwo_file *dwo_file,
8099                                    die_reader_func_ftype *die_reader_func,
8100                                    void *data)
8101 {
8102   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8103   struct objfile *objfile = dwarf2_per_objfile->objfile;
8104   struct dwarf2_section_info *section = this_cu->section;
8105   bfd *abfd = get_section_bfd_owner (section);
8106   struct dwarf2_section_info *abbrev_section;
8107   const gdb_byte *begin_info_ptr, *info_ptr;
8108   struct die_reader_specs reader;
8109   struct die_info *comp_unit_die;
8110   int has_children;
8111
8112   if (dwarf_die_debug)
8113     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
8114                         this_cu->is_debug_types ? "type" : "comp",
8115                         sect_offset_str (this_cu->sect_off));
8116
8117   gdb_assert (this_cu->cu == NULL);
8118
8119   abbrev_section = (dwo_file != NULL
8120                     ? &dwo_file->sections.abbrev
8121                     : get_abbrev_section_for_cu (this_cu));
8122
8123   /* This is cheap if the section is already read in.  */
8124   dwarf2_read_section (objfile, section);
8125
8126   struct dwarf2_cu cu (this_cu);
8127
8128   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8129   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8130                                             &cu.header, section,
8131                                             abbrev_section, info_ptr,
8132                                             (this_cu->is_debug_types
8133                                              ? rcuh_kind::TYPE
8134                                              : rcuh_kind::COMPILE));
8135
8136   this_cu->length = get_cu_length (&cu.header);
8137
8138   /* Skip dummy compilation units.  */
8139   if (info_ptr >= begin_info_ptr + this_cu->length
8140       || peek_abbrev_code (abfd, info_ptr) == 0)
8141     return;
8142
8143   abbrev_table_up abbrev_table
8144     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8145                                cu.header.abbrev_sect_off);
8146
8147   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8148   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8149
8150   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8151 }
8152
8153 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8154    does not lookup the specified DWO file.
8155    This cannot be used to read DWO files.
8156
8157    THIS_CU->cu is always freed when done.
8158    This is done in order to not leave THIS_CU->cu in a state where we have
8159    to care whether it refers to the "main" CU or the DWO CU.
8160    We can revisit this if the data shows there's a performance issue.  */
8161
8162 static void
8163 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8164                                 die_reader_func_ftype *die_reader_func,
8165                                 void *data)
8166 {
8167   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8168 }
8169 \f
8170 /* Type Unit Groups.
8171
8172    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8173    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8174    so that all types coming from the same compilation (.o file) are grouped
8175    together.  A future step could be to put the types in the same symtab as
8176    the CU the types ultimately came from.  */
8177
8178 static hashval_t
8179 hash_type_unit_group (const void *item)
8180 {
8181   const struct type_unit_group *tu_group
8182     = (const struct type_unit_group *) item;
8183
8184   return hash_stmt_list_entry (&tu_group->hash);
8185 }
8186
8187 static int
8188 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8189 {
8190   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8191   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8192
8193   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8194 }
8195
8196 /* Allocate a hash table for type unit groups.  */
8197
8198 static htab_t
8199 allocate_type_unit_groups_table (struct objfile *objfile)
8200 {
8201   return htab_create_alloc_ex (3,
8202                                hash_type_unit_group,
8203                                eq_type_unit_group,
8204                                NULL,
8205                                &objfile->objfile_obstack,
8206                                hashtab_obstack_allocate,
8207                                dummy_obstack_deallocate);
8208 }
8209
8210 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8211    partial symtabs.  We combine several TUs per psymtab to not let the size
8212    of any one psymtab grow too big.  */
8213 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8214 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8215
8216 /* Helper routine for get_type_unit_group.
8217    Create the type_unit_group object used to hold one or more TUs.  */
8218
8219 static struct type_unit_group *
8220 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8221 {
8222   struct dwarf2_per_objfile *dwarf2_per_objfile
8223     = cu->per_cu->dwarf2_per_objfile;
8224   struct objfile *objfile = dwarf2_per_objfile->objfile;
8225   struct dwarf2_per_cu_data *per_cu;
8226   struct type_unit_group *tu_group;
8227
8228   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8229                              struct type_unit_group);
8230   per_cu = &tu_group->per_cu;
8231   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8232
8233   if (dwarf2_per_objfile->using_index)
8234     {
8235       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8236                                         struct dwarf2_per_cu_quick_data);
8237     }
8238   else
8239     {
8240       unsigned int line_offset = to_underlying (line_offset_struct);
8241       struct partial_symtab *pst;
8242       char *name;
8243
8244       /* Give the symtab a useful name for debug purposes.  */
8245       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8246         name = xstrprintf ("<type_units_%d>",
8247                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8248       else
8249         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8250
8251       pst = create_partial_symtab (per_cu, name);
8252       pst->anonymous = 1;
8253
8254       xfree (name);
8255     }
8256
8257   tu_group->hash.dwo_unit = cu->dwo_unit;
8258   tu_group->hash.line_sect_off = line_offset_struct;
8259
8260   return tu_group;
8261 }
8262
8263 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8264    STMT_LIST is a DW_AT_stmt_list attribute.  */
8265
8266 static struct type_unit_group *
8267 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8268 {
8269   struct dwarf2_per_objfile *dwarf2_per_objfile
8270     = cu->per_cu->dwarf2_per_objfile;
8271   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8272   struct type_unit_group *tu_group;
8273   void **slot;
8274   unsigned int line_offset;
8275   struct type_unit_group type_unit_group_for_lookup;
8276
8277   if (dwarf2_per_objfile->type_unit_groups == NULL)
8278     {
8279       dwarf2_per_objfile->type_unit_groups =
8280         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8281     }
8282
8283   /* Do we need to create a new group, or can we use an existing one?  */
8284
8285   if (stmt_list)
8286     {
8287       line_offset = DW_UNSND (stmt_list);
8288       ++tu_stats->nr_symtab_sharers;
8289     }
8290   else
8291     {
8292       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8293          We can do various things here like create one group per TU or
8294          spread them over multiple groups to split up the expansion work.
8295          To avoid worst case scenarios (too many groups or too large groups)
8296          we, umm, group them in bunches.  */
8297       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8298                      | (tu_stats->nr_stmt_less_type_units
8299                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8300       ++tu_stats->nr_stmt_less_type_units;
8301     }
8302
8303   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8304   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8305   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8306                          &type_unit_group_for_lookup, INSERT);
8307   if (*slot != NULL)
8308     {
8309       tu_group = (struct type_unit_group *) *slot;
8310       gdb_assert (tu_group != NULL);
8311     }
8312   else
8313     {
8314       sect_offset line_offset_struct = (sect_offset) line_offset;
8315       tu_group = create_type_unit_group (cu, line_offset_struct);
8316       *slot = tu_group;
8317       ++tu_stats->nr_symtabs;
8318     }
8319
8320   return tu_group;
8321 }
8322 \f
8323 /* Partial symbol tables.  */
8324
8325 /* Create a psymtab named NAME and assign it to PER_CU.
8326
8327    The caller must fill in the following details:
8328    dirname, textlow, texthigh.  */
8329
8330 static struct partial_symtab *
8331 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8332 {
8333   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8334   struct partial_symtab *pst;
8335
8336   pst = start_psymtab_common (objfile, name, 0,
8337                               objfile->global_psymbols,
8338                               objfile->static_psymbols);
8339
8340   pst->psymtabs_addrmap_supported = 1;
8341
8342   /* This is the glue that links PST into GDB's symbol API.  */
8343   pst->read_symtab_private = per_cu;
8344   pst->read_symtab = dwarf2_read_symtab;
8345   per_cu->v.psymtab = pst;
8346
8347   return pst;
8348 }
8349
8350 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8351    type.  */
8352
8353 struct process_psymtab_comp_unit_data
8354 {
8355   /* True if we are reading a DW_TAG_partial_unit.  */
8356
8357   int want_partial_unit;
8358
8359   /* The "pretend" language that is used if the CU doesn't declare a
8360      language.  */
8361
8362   enum language pretend_language;
8363 };
8364
8365 /* die_reader_func for process_psymtab_comp_unit.  */
8366
8367 static void
8368 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8369                                   const gdb_byte *info_ptr,
8370                                   struct die_info *comp_unit_die,
8371                                   int has_children,
8372                                   void *data)
8373 {
8374   struct dwarf2_cu *cu = reader->cu;
8375   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8376   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8377   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8378   CORE_ADDR baseaddr;
8379   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8380   struct partial_symtab *pst;
8381   enum pc_bounds_kind cu_bounds_kind;
8382   const char *filename;
8383   struct process_psymtab_comp_unit_data *info
8384     = (struct process_psymtab_comp_unit_data *) data;
8385
8386   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8387     return;
8388
8389   gdb_assert (! per_cu->is_debug_types);
8390
8391   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8392
8393   cu->list_in_scope = &file_symbols;
8394
8395   /* Allocate a new partial symbol table structure.  */
8396   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8397   if (filename == NULL)
8398     filename = "";
8399
8400   pst = create_partial_symtab (per_cu, filename);
8401
8402   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8403   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8404
8405   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8406
8407   dwarf2_find_base_address (comp_unit_die, cu);
8408
8409   /* Possibly set the default values of LOWPC and HIGHPC from
8410      `DW_AT_ranges'.  */
8411   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8412                                          &best_highpc, cu, pst);
8413   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8414     /* Store the contiguous range if it is not empty; it can be empty for
8415        CUs with no code.  */
8416     addrmap_set_empty (objfile->psymtabs_addrmap,
8417                        gdbarch_adjust_dwarf2_addr (gdbarch,
8418                                                    best_lowpc + baseaddr),
8419                        gdbarch_adjust_dwarf2_addr (gdbarch,
8420                                                    best_highpc + baseaddr) - 1,
8421                        pst);
8422
8423   /* Check if comp unit has_children.
8424      If so, read the rest of the partial symbols from this comp unit.
8425      If not, there's no more debug_info for this comp unit.  */
8426   if (has_children)
8427     {
8428       struct partial_die_info *first_die;
8429       CORE_ADDR lowpc, highpc;
8430
8431       lowpc = ((CORE_ADDR) -1);
8432       highpc = ((CORE_ADDR) 0);
8433
8434       first_die = load_partial_dies (reader, info_ptr, 1);
8435
8436       scan_partial_symbols (first_die, &lowpc, &highpc,
8437                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8438
8439       /* If we didn't find a lowpc, set it to highpc to avoid
8440          complaints from `maint check'.  */
8441       if (lowpc == ((CORE_ADDR) -1))
8442         lowpc = highpc;
8443
8444       /* If the compilation unit didn't have an explicit address range,
8445          then use the information extracted from its child dies.  */
8446       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8447         {
8448           best_lowpc = lowpc;
8449           best_highpc = highpc;
8450         }
8451     }
8452   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8453   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8454
8455   end_psymtab_common (objfile, pst);
8456
8457   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8458     {
8459       int i;
8460       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8461       struct dwarf2_per_cu_data *iter;
8462
8463       /* Fill in 'dependencies' here; we fill in 'users' in a
8464          post-pass.  */
8465       pst->number_of_dependencies = len;
8466       pst->dependencies =
8467         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8468       for (i = 0;
8469            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8470                         i, iter);
8471            ++i)
8472         pst->dependencies[i] = iter->v.psymtab;
8473
8474       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8475     }
8476
8477   /* Get the list of files included in the current compilation unit,
8478      and build a psymtab for each of them.  */
8479   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8480
8481   if (dwarf_read_debug)
8482     {
8483       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8484
8485       fprintf_unfiltered (gdb_stdlog,
8486                           "Psymtab for %s unit @%s: %s - %s"
8487                           ", %d global, %d static syms\n",
8488                           per_cu->is_debug_types ? "type" : "comp",
8489                           sect_offset_str (per_cu->sect_off),
8490                           paddress (gdbarch, pst->textlow),
8491                           paddress (gdbarch, pst->texthigh),
8492                           pst->n_global_syms, pst->n_static_syms);
8493     }
8494 }
8495
8496 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8497    Process compilation unit THIS_CU for a psymtab.  */
8498
8499 static void
8500 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8501                            int want_partial_unit,
8502                            enum language pretend_language)
8503 {
8504   /* If this compilation unit was already read in, free the
8505      cached copy in order to read it in again.  This is
8506      necessary because we skipped some symbols when we first
8507      read in the compilation unit (see load_partial_dies).
8508      This problem could be avoided, but the benefit is unclear.  */
8509   if (this_cu->cu != NULL)
8510     free_one_cached_comp_unit (this_cu);
8511
8512   if (this_cu->is_debug_types)
8513     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8514                              NULL);
8515   else
8516     {
8517       process_psymtab_comp_unit_data info;
8518       info.want_partial_unit = want_partial_unit;
8519       info.pretend_language = pretend_language;
8520       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8521                                process_psymtab_comp_unit_reader, &info);
8522     }
8523
8524   /* Age out any secondary CUs.  */
8525   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8526 }
8527
8528 /* Reader function for build_type_psymtabs.  */
8529
8530 static void
8531 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8532                             const gdb_byte *info_ptr,
8533                             struct die_info *type_unit_die,
8534                             int has_children,
8535                             void *data)
8536 {
8537   struct dwarf2_per_objfile *dwarf2_per_objfile
8538     = reader->cu->per_cu->dwarf2_per_objfile;
8539   struct objfile *objfile = dwarf2_per_objfile->objfile;
8540   struct dwarf2_cu *cu = reader->cu;
8541   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8542   struct signatured_type *sig_type;
8543   struct type_unit_group *tu_group;
8544   struct attribute *attr;
8545   struct partial_die_info *first_die;
8546   CORE_ADDR lowpc, highpc;
8547   struct partial_symtab *pst;
8548
8549   gdb_assert (data == NULL);
8550   gdb_assert (per_cu->is_debug_types);
8551   sig_type = (struct signatured_type *) per_cu;
8552
8553   if (! has_children)
8554     return;
8555
8556   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8557   tu_group = get_type_unit_group (cu, attr);
8558
8559   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8560
8561   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8562   cu->list_in_scope = &file_symbols;
8563   pst = create_partial_symtab (per_cu, "");
8564   pst->anonymous = 1;
8565
8566   first_die = load_partial_dies (reader, info_ptr, 1);
8567
8568   lowpc = (CORE_ADDR) -1;
8569   highpc = (CORE_ADDR) 0;
8570   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8571
8572   end_psymtab_common (objfile, pst);
8573 }
8574
8575 /* Struct used to sort TUs by their abbreviation table offset.  */
8576
8577 struct tu_abbrev_offset
8578 {
8579   struct signatured_type *sig_type;
8580   sect_offset abbrev_offset;
8581 };
8582
8583 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8584
8585 static int
8586 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8587 {
8588   const struct tu_abbrev_offset * const *a
8589     = (const struct tu_abbrev_offset * const*) ap;
8590   const struct tu_abbrev_offset * const *b
8591     = (const struct tu_abbrev_offset * const*) bp;
8592   sect_offset aoff = (*a)->abbrev_offset;
8593   sect_offset boff = (*b)->abbrev_offset;
8594
8595   return (aoff > boff) - (aoff < boff);
8596 }
8597
8598 /* Efficiently read all the type units.
8599    This does the bulk of the work for build_type_psymtabs.
8600
8601    The efficiency is because we sort TUs by the abbrev table they use and
8602    only read each abbrev table once.  In one program there are 200K TUs
8603    sharing 8K abbrev tables.
8604
8605    The main purpose of this function is to support building the
8606    dwarf2_per_objfile->type_unit_groups table.
8607    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8608    can collapse the search space by grouping them by stmt_list.
8609    The savings can be significant, in the same program from above the 200K TUs
8610    share 8K stmt_list tables.
8611
8612    FUNC is expected to call get_type_unit_group, which will create the
8613    struct type_unit_group if necessary and add it to
8614    dwarf2_per_objfile->type_unit_groups.  */
8615
8616 static void
8617 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8618 {
8619   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8620   struct cleanup *cleanups;
8621   abbrev_table_up abbrev_table;
8622   sect_offset abbrev_offset;
8623   struct tu_abbrev_offset *sorted_by_abbrev;
8624   int i;
8625
8626   /* It's up to the caller to not call us multiple times.  */
8627   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8628
8629   if (dwarf2_per_objfile->n_type_units == 0)
8630     return;
8631
8632   /* TUs typically share abbrev tables, and there can be way more TUs than
8633      abbrev tables.  Sort by abbrev table to reduce the number of times we
8634      read each abbrev table in.
8635      Alternatives are to punt or to maintain a cache of abbrev tables.
8636      This is simpler and efficient enough for now.
8637
8638      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8639      symtab to use).  Typically TUs with the same abbrev offset have the same
8640      stmt_list value too so in practice this should work well.
8641
8642      The basic algorithm here is:
8643
8644       sort TUs by abbrev table
8645       for each TU with same abbrev table:
8646         read abbrev table if first user
8647         read TU top level DIE
8648           [IWBN if DWO skeletons had DW_AT_stmt_list]
8649         call FUNC  */
8650
8651   if (dwarf_read_debug)
8652     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8653
8654   /* Sort in a separate table to maintain the order of all_type_units
8655      for .gdb_index: TU indices directly index all_type_units.  */
8656   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8657                               dwarf2_per_objfile->n_type_units);
8658   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8659     {
8660       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8661
8662       sorted_by_abbrev[i].sig_type = sig_type;
8663       sorted_by_abbrev[i].abbrev_offset =
8664         read_abbrev_offset (dwarf2_per_objfile,
8665                             sig_type->per_cu.section,
8666                             sig_type->per_cu.sect_off);
8667     }
8668   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8669   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8670          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8671
8672   abbrev_offset = (sect_offset) ~(unsigned) 0;
8673
8674   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8675     {
8676       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8677
8678       /* Switch to the next abbrev table if necessary.  */
8679       if (abbrev_table == NULL
8680           || tu->abbrev_offset != abbrev_offset)
8681         {
8682           abbrev_offset = tu->abbrev_offset;
8683           abbrev_table =
8684             abbrev_table_read_table (dwarf2_per_objfile,
8685                                      &dwarf2_per_objfile->abbrev,
8686                                      abbrev_offset);
8687           ++tu_stats->nr_uniq_abbrev_tables;
8688         }
8689
8690       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8691                                0, 0, build_type_psymtabs_reader, NULL);
8692     }
8693
8694   do_cleanups (cleanups);
8695 }
8696
8697 /* Print collected type unit statistics.  */
8698
8699 static void
8700 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8701 {
8702   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8703
8704   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8705   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8706                       dwarf2_per_objfile->n_type_units);
8707   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8708                       tu_stats->nr_uniq_abbrev_tables);
8709   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8710                       tu_stats->nr_symtabs);
8711   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8712                       tu_stats->nr_symtab_sharers);
8713   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8714                       tu_stats->nr_stmt_less_type_units);
8715   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8716                       tu_stats->nr_all_type_units_reallocs);
8717 }
8718
8719 /* Traversal function for build_type_psymtabs.  */
8720
8721 static int
8722 build_type_psymtab_dependencies (void **slot, void *info)
8723 {
8724   struct dwarf2_per_objfile *dwarf2_per_objfile
8725     = (struct dwarf2_per_objfile *) info;
8726   struct objfile *objfile = dwarf2_per_objfile->objfile;
8727   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8728   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8729   struct partial_symtab *pst = per_cu->v.psymtab;
8730   int len = VEC_length (sig_type_ptr, tu_group->tus);
8731   struct signatured_type *iter;
8732   int i;
8733
8734   gdb_assert (len > 0);
8735   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8736
8737   pst->number_of_dependencies = len;
8738   pst->dependencies =
8739     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8740   for (i = 0;
8741        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8742        ++i)
8743     {
8744       gdb_assert (iter->per_cu.is_debug_types);
8745       pst->dependencies[i] = iter->per_cu.v.psymtab;
8746       iter->type_unit_group = tu_group;
8747     }
8748
8749   VEC_free (sig_type_ptr, tu_group->tus);
8750
8751   return 1;
8752 }
8753
8754 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8755    Build partial symbol tables for the .debug_types comp-units.  */
8756
8757 static void
8758 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8759 {
8760   if (! create_all_type_units (dwarf2_per_objfile))
8761     return;
8762
8763   build_type_psymtabs_1 (dwarf2_per_objfile);
8764 }
8765
8766 /* Traversal function for process_skeletonless_type_unit.
8767    Read a TU in a DWO file and build partial symbols for it.  */
8768
8769 static int
8770 process_skeletonless_type_unit (void **slot, void *info)
8771 {
8772   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8773   struct dwarf2_per_objfile *dwarf2_per_objfile
8774     = (struct dwarf2_per_objfile *) info;
8775   struct signatured_type find_entry, *entry;
8776
8777   /* If this TU doesn't exist in the global table, add it and read it in.  */
8778
8779   if (dwarf2_per_objfile->signatured_types == NULL)
8780     {
8781       dwarf2_per_objfile->signatured_types
8782         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8783     }
8784
8785   find_entry.signature = dwo_unit->signature;
8786   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8787                          INSERT);
8788   /* If we've already seen this type there's nothing to do.  What's happening
8789      is we're doing our own version of comdat-folding here.  */
8790   if (*slot != NULL)
8791     return 1;
8792
8793   /* This does the job that create_all_type_units would have done for
8794      this TU.  */
8795   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8796   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8797   *slot = entry;
8798
8799   /* This does the job that build_type_psymtabs_1 would have done.  */
8800   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8801                            build_type_psymtabs_reader, NULL);
8802
8803   return 1;
8804 }
8805
8806 /* Traversal function for process_skeletonless_type_units.  */
8807
8808 static int
8809 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8810 {
8811   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8812
8813   if (dwo_file->tus != NULL)
8814     {
8815       htab_traverse_noresize (dwo_file->tus,
8816                               process_skeletonless_type_unit, info);
8817     }
8818
8819   return 1;
8820 }
8821
8822 /* Scan all TUs of DWO files, verifying we've processed them.
8823    This is needed in case a TU was emitted without its skeleton.
8824    Note: This can't be done until we know what all the DWO files are.  */
8825
8826 static void
8827 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8828 {
8829   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8830   if (get_dwp_file (dwarf2_per_objfile) == NULL
8831       && dwarf2_per_objfile->dwo_files != NULL)
8832     {
8833       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8834                               process_dwo_file_for_skeletonless_type_units,
8835                               dwarf2_per_objfile);
8836     }
8837 }
8838
8839 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8840
8841 static void
8842 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8843 {
8844   int i;
8845
8846   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8847     {
8848       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8849       struct partial_symtab *pst = per_cu->v.psymtab;
8850       int j;
8851
8852       if (pst == NULL)
8853         continue;
8854
8855       for (j = 0; j < pst->number_of_dependencies; ++j)
8856         {
8857           /* Set the 'user' field only if it is not already set.  */
8858           if (pst->dependencies[j]->user == NULL)
8859             pst->dependencies[j]->user = pst;
8860         }
8861     }
8862 }
8863
8864 /* Build the partial symbol table by doing a quick pass through the
8865    .debug_info and .debug_abbrev sections.  */
8866
8867 static void
8868 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8869 {
8870   struct cleanup *back_to;
8871   int i;
8872   struct objfile *objfile = dwarf2_per_objfile->objfile;
8873
8874   if (dwarf_read_debug)
8875     {
8876       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8877                           objfile_name (objfile));
8878     }
8879
8880   dwarf2_per_objfile->reading_partial_symbols = 1;
8881
8882   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8883
8884   /* Any cached compilation units will be linked by the per-objfile
8885      read_in_chain.  Make sure to free them when we're done.  */
8886   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8887
8888   build_type_psymtabs (dwarf2_per_objfile);
8889
8890   create_all_comp_units (dwarf2_per_objfile);
8891
8892   /* Create a temporary address map on a temporary obstack.  We later
8893      copy this to the final obstack.  */
8894   auto_obstack temp_obstack;
8895
8896   scoped_restore save_psymtabs_addrmap
8897     = make_scoped_restore (&objfile->psymtabs_addrmap,
8898                            addrmap_create_mutable (&temp_obstack));
8899
8900   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8901     {
8902       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8903
8904       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8905     }
8906
8907   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8908   process_skeletonless_type_units (dwarf2_per_objfile);
8909
8910   /* Now that all TUs have been processed we can fill in the dependencies.  */
8911   if (dwarf2_per_objfile->type_unit_groups != NULL)
8912     {
8913       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8914                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8915     }
8916
8917   if (dwarf_read_debug)
8918     print_tu_stats (dwarf2_per_objfile);
8919
8920   set_partial_user (dwarf2_per_objfile);
8921
8922   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8923                                                     &objfile->objfile_obstack);
8924   /* At this point we want to keep the address map.  */
8925   save_psymtabs_addrmap.release ();
8926
8927   do_cleanups (back_to);
8928
8929   if (dwarf_read_debug)
8930     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8931                         objfile_name (objfile));
8932 }
8933
8934 /* die_reader_func for load_partial_comp_unit.  */
8935
8936 static void
8937 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8938                                const gdb_byte *info_ptr,
8939                                struct die_info *comp_unit_die,
8940                                int has_children,
8941                                void *data)
8942 {
8943   struct dwarf2_cu *cu = reader->cu;
8944
8945   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8946
8947   /* Check if comp unit has_children.
8948      If so, read the rest of the partial symbols from this comp unit.
8949      If not, there's no more debug_info for this comp unit.  */
8950   if (has_children)
8951     load_partial_dies (reader, info_ptr, 0);
8952 }
8953
8954 /* Load the partial DIEs for a secondary CU into memory.
8955    This is also used when rereading a primary CU with load_all_dies.  */
8956
8957 static void
8958 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8959 {
8960   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8961                            load_partial_comp_unit_reader, NULL);
8962 }
8963
8964 static void
8965 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8966                               struct dwarf2_section_info *section,
8967                               struct dwarf2_section_info *abbrev_section,
8968                               unsigned int is_dwz,
8969                               int *n_allocated,
8970                               int *n_comp_units,
8971                               struct dwarf2_per_cu_data ***all_comp_units)
8972 {
8973   const gdb_byte *info_ptr;
8974   struct objfile *objfile = dwarf2_per_objfile->objfile;
8975
8976   if (dwarf_read_debug)
8977     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8978                         get_section_name (section),
8979                         get_section_file_name (section));
8980
8981   dwarf2_read_section (objfile, section);
8982
8983   info_ptr = section->buffer;
8984
8985   while (info_ptr < section->buffer + section->size)
8986     {
8987       struct dwarf2_per_cu_data *this_cu;
8988
8989       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8990
8991       comp_unit_head cu_header;
8992       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8993                                      abbrev_section, info_ptr,
8994                                      rcuh_kind::COMPILE);
8995
8996       /* Save the compilation unit for later lookup.  */
8997       if (cu_header.unit_type != DW_UT_type)
8998         {
8999           this_cu = XOBNEW (&objfile->objfile_obstack,
9000                             struct dwarf2_per_cu_data);
9001           memset (this_cu, 0, sizeof (*this_cu));
9002         }
9003       else
9004         {
9005           auto sig_type = XOBNEW (&objfile->objfile_obstack,
9006                                   struct signatured_type);
9007           memset (sig_type, 0, sizeof (*sig_type));
9008           sig_type->signature = cu_header.signature;
9009           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
9010           this_cu = &sig_type->per_cu;
9011         }
9012       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
9013       this_cu->sect_off = sect_off;
9014       this_cu->length = cu_header.length + cu_header.initial_length_size;
9015       this_cu->is_dwz = is_dwz;
9016       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
9017       this_cu->section = section;
9018
9019       if (*n_comp_units == *n_allocated)
9020         {
9021           *n_allocated *= 2;
9022           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
9023                                         *all_comp_units, *n_allocated);
9024         }
9025       (*all_comp_units)[*n_comp_units] = this_cu;
9026       ++*n_comp_units;
9027
9028       info_ptr = info_ptr + this_cu->length;
9029     }
9030 }
9031
9032 /* Create a list of all compilation units in OBJFILE.
9033    This is only done for -readnow and building partial symtabs.  */
9034
9035 static void
9036 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
9037 {
9038   int n_allocated;
9039   int n_comp_units;
9040   struct dwarf2_per_cu_data **all_comp_units;
9041   struct dwz_file *dwz;
9042   struct objfile *objfile = dwarf2_per_objfile->objfile;
9043
9044   n_comp_units = 0;
9045   n_allocated = 10;
9046   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9047
9048   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9049                                 &dwarf2_per_objfile->abbrev, 0,
9050                                 &n_allocated, &n_comp_units, &all_comp_units);
9051
9052   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9053   if (dwz != NULL)
9054     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9055                                   1, &n_allocated, &n_comp_units,
9056                                   &all_comp_units);
9057
9058   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9059                                                   struct dwarf2_per_cu_data *,
9060                                                   n_comp_units);
9061   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9062           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9063   xfree (all_comp_units);
9064   dwarf2_per_objfile->n_comp_units = n_comp_units;
9065 }
9066
9067 /* Process all loaded DIEs for compilation unit CU, starting at
9068    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9069    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9070    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9071    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9072
9073 static void
9074 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9075                       CORE_ADDR *highpc, int set_addrmap,
9076                       struct dwarf2_cu *cu)
9077 {
9078   struct partial_die_info *pdi;
9079
9080   /* Now, march along the PDI's, descending into ones which have
9081      interesting children but skipping the children of the other ones,
9082      until we reach the end of the compilation unit.  */
9083
9084   pdi = first_die;
9085
9086   while (pdi != NULL)
9087     {
9088       pdi->fixup (cu);
9089
9090       /* Anonymous namespaces or modules have no name but have interesting
9091          children, so we need to look at them.  Ditto for anonymous
9092          enums.  */
9093
9094       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9095           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9096           || pdi->tag == DW_TAG_imported_unit
9097           || pdi->tag == DW_TAG_inlined_subroutine)
9098         {
9099           switch (pdi->tag)
9100             {
9101             case DW_TAG_subprogram:
9102             case DW_TAG_inlined_subroutine:
9103               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9104               break;
9105             case DW_TAG_constant:
9106             case DW_TAG_variable:
9107             case DW_TAG_typedef:
9108             case DW_TAG_union_type:
9109               if (!pdi->is_declaration)
9110                 {
9111                   add_partial_symbol (pdi, cu);
9112                 }
9113               break;
9114             case DW_TAG_class_type:
9115             case DW_TAG_interface_type:
9116             case DW_TAG_structure_type:
9117               if (!pdi->is_declaration)
9118                 {
9119                   add_partial_symbol (pdi, cu);
9120                 }
9121               if (cu->language == language_rust && pdi->has_children)
9122                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9123                                       set_addrmap, cu);
9124               break;
9125             case DW_TAG_enumeration_type:
9126               if (!pdi->is_declaration)
9127                 add_partial_enumeration (pdi, cu);
9128               break;
9129             case DW_TAG_base_type:
9130             case DW_TAG_subrange_type:
9131               /* File scope base type definitions are added to the partial
9132                  symbol table.  */
9133               add_partial_symbol (pdi, cu);
9134               break;
9135             case DW_TAG_namespace:
9136               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9137               break;
9138             case DW_TAG_module:
9139               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9140               break;
9141             case DW_TAG_imported_unit:
9142               {
9143                 struct dwarf2_per_cu_data *per_cu;
9144
9145                 /* For now we don't handle imported units in type units.  */
9146                 if (cu->per_cu->is_debug_types)
9147                   {
9148                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9149                              " supported in type units [in module %s]"),
9150                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9151                   }
9152
9153                 per_cu = dwarf2_find_containing_comp_unit
9154                            (pdi->d.sect_off, pdi->is_dwz,
9155                             cu->per_cu->dwarf2_per_objfile);
9156
9157                 /* Go read the partial unit, if needed.  */
9158                 if (per_cu->v.psymtab == NULL)
9159                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9160
9161                 VEC_safe_push (dwarf2_per_cu_ptr,
9162                                cu->per_cu->imported_symtabs, per_cu);
9163               }
9164               break;
9165             case DW_TAG_imported_declaration:
9166               add_partial_symbol (pdi, cu);
9167               break;
9168             default:
9169               break;
9170             }
9171         }
9172
9173       /* If the die has a sibling, skip to the sibling.  */
9174
9175       pdi = pdi->die_sibling;
9176     }
9177 }
9178
9179 /* Functions used to compute the fully scoped name of a partial DIE.
9180
9181    Normally, this is simple.  For C++, the parent DIE's fully scoped
9182    name is concatenated with "::" and the partial DIE's name.
9183    Enumerators are an exception; they use the scope of their parent
9184    enumeration type, i.e. the name of the enumeration type is not
9185    prepended to the enumerator.
9186
9187    There are two complexities.  One is DW_AT_specification; in this
9188    case "parent" means the parent of the target of the specification,
9189    instead of the direct parent of the DIE.  The other is compilers
9190    which do not emit DW_TAG_namespace; in this case we try to guess
9191    the fully qualified name of structure types from their members'
9192    linkage names.  This must be done using the DIE's children rather
9193    than the children of any DW_AT_specification target.  We only need
9194    to do this for structures at the top level, i.e. if the target of
9195    any DW_AT_specification (if any; otherwise the DIE itself) does not
9196    have a parent.  */
9197
9198 /* Compute the scope prefix associated with PDI's parent, in
9199    compilation unit CU.  The result will be allocated on CU's
9200    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9201    field.  NULL is returned if no prefix is necessary.  */
9202 static const char *
9203 partial_die_parent_scope (struct partial_die_info *pdi,
9204                           struct dwarf2_cu *cu)
9205 {
9206   const char *grandparent_scope;
9207   struct partial_die_info *parent, *real_pdi;
9208
9209   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9210      then this means the parent of the specification DIE.  */
9211
9212   real_pdi = pdi;
9213   while (real_pdi->has_specification)
9214     real_pdi = find_partial_die (real_pdi->spec_offset,
9215                                  real_pdi->spec_is_dwz, cu);
9216
9217   parent = real_pdi->die_parent;
9218   if (parent == NULL)
9219     return NULL;
9220
9221   if (parent->scope_set)
9222     return parent->scope;
9223
9224   parent->fixup (cu);
9225
9226   grandparent_scope = partial_die_parent_scope (parent, cu);
9227
9228   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9229      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9230      Work around this problem here.  */
9231   if (cu->language == language_cplus
9232       && parent->tag == DW_TAG_namespace
9233       && strcmp (parent->name, "::") == 0
9234       && grandparent_scope == NULL)
9235     {
9236       parent->scope = NULL;
9237       parent->scope_set = 1;
9238       return NULL;
9239     }
9240
9241   if (pdi->tag == DW_TAG_enumerator)
9242     /* Enumerators should not get the name of the enumeration as a prefix.  */
9243     parent->scope = grandparent_scope;
9244   else if (parent->tag == DW_TAG_namespace
9245       || parent->tag == DW_TAG_module
9246       || parent->tag == DW_TAG_structure_type
9247       || parent->tag == DW_TAG_class_type
9248       || parent->tag == DW_TAG_interface_type
9249       || parent->tag == DW_TAG_union_type
9250       || parent->tag == DW_TAG_enumeration_type)
9251     {
9252       if (grandparent_scope == NULL)
9253         parent->scope = parent->name;
9254       else
9255         parent->scope = typename_concat (&cu->comp_unit_obstack,
9256                                          grandparent_scope,
9257                                          parent->name, 0, cu);
9258     }
9259   else
9260     {
9261       /* FIXME drow/2004-04-01: What should we be doing with
9262          function-local names?  For partial symbols, we should probably be
9263          ignoring them.  */
9264       complaint (&symfile_complaints,
9265                  _("unhandled containing DIE tag %d for DIE at %s"),
9266                  parent->tag, sect_offset_str (pdi->sect_off));
9267       parent->scope = grandparent_scope;
9268     }
9269
9270   parent->scope_set = 1;
9271   return parent->scope;
9272 }
9273
9274 /* Return the fully scoped name associated with PDI, from compilation unit
9275    CU.  The result will be allocated with malloc.  */
9276
9277 static char *
9278 partial_die_full_name (struct partial_die_info *pdi,
9279                        struct dwarf2_cu *cu)
9280 {
9281   const char *parent_scope;
9282
9283   /* If this is a template instantiation, we can not work out the
9284      template arguments from partial DIEs.  So, unfortunately, we have
9285      to go through the full DIEs.  At least any work we do building
9286      types here will be reused if full symbols are loaded later.  */
9287   if (pdi->has_template_arguments)
9288     {
9289       pdi->fixup (cu);
9290
9291       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9292         {
9293           struct die_info *die;
9294           struct attribute attr;
9295           struct dwarf2_cu *ref_cu = cu;
9296
9297           /* DW_FORM_ref_addr is using section offset.  */
9298           attr.name = (enum dwarf_attribute) 0;
9299           attr.form = DW_FORM_ref_addr;
9300           attr.u.unsnd = to_underlying (pdi->sect_off);
9301           die = follow_die_ref (NULL, &attr, &ref_cu);
9302
9303           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9304         }
9305     }
9306
9307   parent_scope = partial_die_parent_scope (pdi, cu);
9308   if (parent_scope == NULL)
9309     return NULL;
9310   else
9311     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9312 }
9313
9314 static void
9315 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9316 {
9317   struct dwarf2_per_objfile *dwarf2_per_objfile
9318     = cu->per_cu->dwarf2_per_objfile;
9319   struct objfile *objfile = dwarf2_per_objfile->objfile;
9320   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9321   CORE_ADDR addr = 0;
9322   const char *actual_name = NULL;
9323   CORE_ADDR baseaddr;
9324   char *built_actual_name;
9325
9326   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9327
9328   built_actual_name = partial_die_full_name (pdi, cu);
9329   if (built_actual_name != NULL)
9330     actual_name = built_actual_name;
9331
9332   if (actual_name == NULL)
9333     actual_name = pdi->name;
9334
9335   switch (pdi->tag)
9336     {
9337     case DW_TAG_inlined_subroutine:
9338     case DW_TAG_subprogram:
9339       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9340       if (pdi->is_external || cu->language == language_ada)
9341         {
9342           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9343              of the global scope.  But in Ada, we want to be able to access
9344              nested procedures globally.  So all Ada subprograms are stored
9345              in the global scope.  */
9346           add_psymbol_to_list (actual_name, strlen (actual_name),
9347                                built_actual_name != NULL,
9348                                VAR_DOMAIN, LOC_BLOCK,
9349                                &objfile->global_psymbols,
9350                                addr, cu->language, objfile);
9351         }
9352       else
9353         {
9354           add_psymbol_to_list (actual_name, strlen (actual_name),
9355                                built_actual_name != NULL,
9356                                VAR_DOMAIN, LOC_BLOCK,
9357                                &objfile->static_psymbols,
9358                                addr, cu->language, objfile);
9359         }
9360
9361       if (pdi->main_subprogram && actual_name != NULL)
9362         set_objfile_main_name (objfile, actual_name, cu->language);
9363       break;
9364     case DW_TAG_constant:
9365       {
9366         std::vector<partial_symbol *> *list;
9367
9368         if (pdi->is_external)
9369           list = &objfile->global_psymbols;
9370         else
9371           list = &objfile->static_psymbols;
9372         add_psymbol_to_list (actual_name, strlen (actual_name),
9373                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9374                              list, 0, cu->language, objfile);
9375       }
9376       break;
9377     case DW_TAG_variable:
9378       if (pdi->d.locdesc)
9379         addr = decode_locdesc (pdi->d.locdesc, cu);
9380
9381       if (pdi->d.locdesc
9382           && addr == 0
9383           && !dwarf2_per_objfile->has_section_at_zero)
9384         {
9385           /* A global or static variable may also have been stripped
9386              out by the linker if unused, in which case its address
9387              will be nullified; do not add such variables into partial
9388              symbol table then.  */
9389         }
9390       else if (pdi->is_external)
9391         {
9392           /* Global Variable.
9393              Don't enter into the minimal symbol tables as there is
9394              a minimal symbol table entry from the ELF symbols already.
9395              Enter into partial symbol table if it has a location
9396              descriptor or a type.
9397              If the location descriptor is missing, new_symbol will create
9398              a LOC_UNRESOLVED symbol, the address of the variable will then
9399              be determined from the minimal symbol table whenever the variable
9400              is referenced.
9401              The address for the partial symbol table entry is not
9402              used by GDB, but it comes in handy for debugging partial symbol
9403              table building.  */
9404
9405           if (pdi->d.locdesc || pdi->has_type)
9406             add_psymbol_to_list (actual_name, strlen (actual_name),
9407                                  built_actual_name != NULL,
9408                                  VAR_DOMAIN, LOC_STATIC,
9409                                  &objfile->global_psymbols,
9410                                  addr + baseaddr,
9411                                  cu->language, objfile);
9412         }
9413       else
9414         {
9415           int has_loc = pdi->d.locdesc != NULL;
9416
9417           /* Static Variable.  Skip symbols whose value we cannot know (those
9418              without location descriptors or constant values).  */
9419           if (!has_loc && !pdi->has_const_value)
9420             {
9421               xfree (built_actual_name);
9422               return;
9423             }
9424
9425           add_psymbol_to_list (actual_name, strlen (actual_name),
9426                                built_actual_name != NULL,
9427                                VAR_DOMAIN, LOC_STATIC,
9428                                &objfile->static_psymbols,
9429                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9430                                cu->language, objfile);
9431         }
9432       break;
9433     case DW_TAG_typedef:
9434     case DW_TAG_base_type:
9435     case DW_TAG_subrange_type:
9436       add_psymbol_to_list (actual_name, strlen (actual_name),
9437                            built_actual_name != NULL,
9438                            VAR_DOMAIN, LOC_TYPEDEF,
9439                            &objfile->static_psymbols,
9440                            0, cu->language, objfile);
9441       break;
9442     case DW_TAG_imported_declaration:
9443     case DW_TAG_namespace:
9444       add_psymbol_to_list (actual_name, strlen (actual_name),
9445                            built_actual_name != NULL,
9446                            VAR_DOMAIN, LOC_TYPEDEF,
9447                            &objfile->global_psymbols,
9448                            0, cu->language, objfile);
9449       break;
9450     case DW_TAG_module:
9451       add_psymbol_to_list (actual_name, strlen (actual_name),
9452                            built_actual_name != NULL,
9453                            MODULE_DOMAIN, LOC_TYPEDEF,
9454                            &objfile->global_psymbols,
9455                            0, cu->language, objfile);
9456       break;
9457     case DW_TAG_class_type:
9458     case DW_TAG_interface_type:
9459     case DW_TAG_structure_type:
9460     case DW_TAG_union_type:
9461     case DW_TAG_enumeration_type:
9462       /* Skip external references.  The DWARF standard says in the section
9463          about "Structure, Union, and Class Type Entries": "An incomplete
9464          structure, union or class type is represented by a structure,
9465          union or class entry that does not have a byte size attribute
9466          and that has a DW_AT_declaration attribute."  */
9467       if (!pdi->has_byte_size && pdi->is_declaration)
9468         {
9469           xfree (built_actual_name);
9470           return;
9471         }
9472
9473       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9474          static vs. global.  */
9475       add_psymbol_to_list (actual_name, strlen (actual_name),
9476                            built_actual_name != NULL,
9477                            STRUCT_DOMAIN, LOC_TYPEDEF,
9478                            cu->language == language_cplus
9479                            ? &objfile->global_psymbols
9480                            : &objfile->static_psymbols,
9481                            0, cu->language, objfile);
9482
9483       break;
9484     case DW_TAG_enumerator:
9485       add_psymbol_to_list (actual_name, strlen (actual_name),
9486                            built_actual_name != NULL,
9487                            VAR_DOMAIN, LOC_CONST,
9488                            cu->language == language_cplus
9489                            ? &objfile->global_psymbols
9490                            : &objfile->static_psymbols,
9491                            0, cu->language, objfile);
9492       break;
9493     default:
9494       break;
9495     }
9496
9497   xfree (built_actual_name);
9498 }
9499
9500 /* Read a partial die corresponding to a namespace; also, add a symbol
9501    corresponding to that namespace to the symbol table.  NAMESPACE is
9502    the name of the enclosing namespace.  */
9503
9504 static void
9505 add_partial_namespace (struct partial_die_info *pdi,
9506                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9507                        int set_addrmap, struct dwarf2_cu *cu)
9508 {
9509   /* Add a symbol for the namespace.  */
9510
9511   add_partial_symbol (pdi, cu);
9512
9513   /* Now scan partial symbols in that namespace.  */
9514
9515   if (pdi->has_children)
9516     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9517 }
9518
9519 /* Read a partial die corresponding to a Fortran module.  */
9520
9521 static void
9522 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9523                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9524 {
9525   /* Add a symbol for the namespace.  */
9526
9527   add_partial_symbol (pdi, cu);
9528
9529   /* Now scan partial symbols in that module.  */
9530
9531   if (pdi->has_children)
9532     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9533 }
9534
9535 /* Read a partial die corresponding to a subprogram or an inlined
9536    subprogram and create a partial symbol for that subprogram.
9537    When the CU language allows it, this routine also defines a partial
9538    symbol for each nested subprogram that this subprogram contains.
9539    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9540    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9541
9542    PDI may also be a lexical block, in which case we simply search
9543    recursively for subprograms defined inside that lexical block.
9544    Again, this is only performed when the CU language allows this
9545    type of definitions.  */
9546
9547 static void
9548 add_partial_subprogram (struct partial_die_info *pdi,
9549                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9550                         int set_addrmap, struct dwarf2_cu *cu)
9551 {
9552   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9553     {
9554       if (pdi->has_pc_info)
9555         {
9556           if (pdi->lowpc < *lowpc)
9557             *lowpc = pdi->lowpc;
9558           if (pdi->highpc > *highpc)
9559             *highpc = pdi->highpc;
9560           if (set_addrmap)
9561             {
9562               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9563               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9564               CORE_ADDR baseaddr;
9565               CORE_ADDR highpc;
9566               CORE_ADDR lowpc;
9567
9568               baseaddr = ANOFFSET (objfile->section_offsets,
9569                                    SECT_OFF_TEXT (objfile));
9570               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9571                                                   pdi->lowpc + baseaddr);
9572               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9573                                                    pdi->highpc + baseaddr);
9574               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9575                                  cu->per_cu->v.psymtab);
9576             }
9577         }
9578
9579       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9580         {
9581           if (!pdi->is_declaration)
9582             /* Ignore subprogram DIEs that do not have a name, they are
9583                illegal.  Do not emit a complaint at this point, we will
9584                do so when we convert this psymtab into a symtab.  */
9585             if (pdi->name)
9586               add_partial_symbol (pdi, cu);
9587         }
9588     }
9589
9590   if (! pdi->has_children)
9591     return;
9592
9593   if (cu->language == language_ada)
9594     {
9595       pdi = pdi->die_child;
9596       while (pdi != NULL)
9597         {
9598           pdi->fixup (cu);
9599           if (pdi->tag == DW_TAG_subprogram
9600               || pdi->tag == DW_TAG_inlined_subroutine
9601               || pdi->tag == DW_TAG_lexical_block)
9602             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9603           pdi = pdi->die_sibling;
9604         }
9605     }
9606 }
9607
9608 /* Read a partial die corresponding to an enumeration type.  */
9609
9610 static void
9611 add_partial_enumeration (struct partial_die_info *enum_pdi,
9612                          struct dwarf2_cu *cu)
9613 {
9614   struct partial_die_info *pdi;
9615
9616   if (enum_pdi->name != NULL)
9617     add_partial_symbol (enum_pdi, cu);
9618
9619   pdi = enum_pdi->die_child;
9620   while (pdi)
9621     {
9622       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9623         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9624       else
9625         add_partial_symbol (pdi, cu);
9626       pdi = pdi->die_sibling;
9627     }
9628 }
9629
9630 /* Return the initial uleb128 in the die at INFO_PTR.  */
9631
9632 static unsigned int
9633 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9634 {
9635   unsigned int bytes_read;
9636
9637   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9638 }
9639
9640 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9641    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9642
9643    Return the corresponding abbrev, or NULL if the number is zero (indicating
9644    an empty DIE).  In either case *BYTES_READ will be set to the length of
9645    the initial number.  */
9646
9647 static struct abbrev_info *
9648 peek_die_abbrev (const die_reader_specs &reader,
9649                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9650 {
9651   dwarf2_cu *cu = reader.cu;
9652   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9653   unsigned int abbrev_number
9654     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9655
9656   if (abbrev_number == 0)
9657     return NULL;
9658
9659   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9660   if (!abbrev)
9661     {
9662       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9663                " at offset %s [in module %s]"),
9664              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9665              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9666     }
9667
9668   return abbrev;
9669 }
9670
9671 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9672    Returns a pointer to the end of a series of DIEs, terminated by an empty
9673    DIE.  Any children of the skipped DIEs will also be skipped.  */
9674
9675 static const gdb_byte *
9676 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9677 {
9678   while (1)
9679     {
9680       unsigned int bytes_read;
9681       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9682
9683       if (abbrev == NULL)
9684         return info_ptr + bytes_read;
9685       else
9686         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9687     }
9688 }
9689
9690 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9691    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9692    abbrev corresponding to that skipped uleb128 should be passed in
9693    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9694    children.  */
9695
9696 static const gdb_byte *
9697 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9698               struct abbrev_info *abbrev)
9699 {
9700   unsigned int bytes_read;
9701   struct attribute attr;
9702   bfd *abfd = reader->abfd;
9703   struct dwarf2_cu *cu = reader->cu;
9704   const gdb_byte *buffer = reader->buffer;
9705   const gdb_byte *buffer_end = reader->buffer_end;
9706   unsigned int form, i;
9707
9708   for (i = 0; i < abbrev->num_attrs; i++)
9709     {
9710       /* The only abbrev we care about is DW_AT_sibling.  */
9711       if (abbrev->attrs[i].name == DW_AT_sibling)
9712         {
9713           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9714           if (attr.form == DW_FORM_ref_addr)
9715             complaint (&symfile_complaints,
9716                        _("ignoring absolute DW_AT_sibling"));
9717           else
9718             {
9719               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9720               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9721
9722               if (sibling_ptr < info_ptr)
9723                 complaint (&symfile_complaints,
9724                            _("DW_AT_sibling points backwards"));
9725               else if (sibling_ptr > reader->buffer_end)
9726                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9727               else
9728                 return sibling_ptr;
9729             }
9730         }
9731
9732       /* If it isn't DW_AT_sibling, skip this attribute.  */
9733       form = abbrev->attrs[i].form;
9734     skip_attribute:
9735       switch (form)
9736         {
9737         case DW_FORM_ref_addr:
9738           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9739              and later it is offset sized.  */
9740           if (cu->header.version == 2)
9741             info_ptr += cu->header.addr_size;
9742           else
9743             info_ptr += cu->header.offset_size;
9744           break;
9745         case DW_FORM_GNU_ref_alt:
9746           info_ptr += cu->header.offset_size;
9747           break;
9748         case DW_FORM_addr:
9749           info_ptr += cu->header.addr_size;
9750           break;
9751         case DW_FORM_data1:
9752         case DW_FORM_ref1:
9753         case DW_FORM_flag:
9754           info_ptr += 1;
9755           break;
9756         case DW_FORM_flag_present:
9757         case DW_FORM_implicit_const:
9758           break;
9759         case DW_FORM_data2:
9760         case DW_FORM_ref2:
9761           info_ptr += 2;
9762           break;
9763         case DW_FORM_data4:
9764         case DW_FORM_ref4:
9765           info_ptr += 4;
9766           break;
9767         case DW_FORM_data8:
9768         case DW_FORM_ref8:
9769         case DW_FORM_ref_sig8:
9770           info_ptr += 8;
9771           break;
9772         case DW_FORM_data16:
9773           info_ptr += 16;
9774           break;
9775         case DW_FORM_string:
9776           read_direct_string (abfd, info_ptr, &bytes_read);
9777           info_ptr += bytes_read;
9778           break;
9779         case DW_FORM_sec_offset:
9780         case DW_FORM_strp:
9781         case DW_FORM_GNU_strp_alt:
9782           info_ptr += cu->header.offset_size;
9783           break;
9784         case DW_FORM_exprloc:
9785         case DW_FORM_block:
9786           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9787           info_ptr += bytes_read;
9788           break;
9789         case DW_FORM_block1:
9790           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9791           break;
9792         case DW_FORM_block2:
9793           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9794           break;
9795         case DW_FORM_block4:
9796           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9797           break;
9798         case DW_FORM_sdata:
9799         case DW_FORM_udata:
9800         case DW_FORM_ref_udata:
9801         case DW_FORM_GNU_addr_index:
9802         case DW_FORM_GNU_str_index:
9803           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9804           break;
9805         case DW_FORM_indirect:
9806           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9807           info_ptr += bytes_read;
9808           /* We need to continue parsing from here, so just go back to
9809              the top.  */
9810           goto skip_attribute;
9811
9812         default:
9813           error (_("Dwarf Error: Cannot handle %s "
9814                    "in DWARF reader [in module %s]"),
9815                  dwarf_form_name (form),
9816                  bfd_get_filename (abfd));
9817         }
9818     }
9819
9820   if (abbrev->has_children)
9821     return skip_children (reader, info_ptr);
9822   else
9823     return info_ptr;
9824 }
9825
9826 /* Locate ORIG_PDI's sibling.
9827    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9828
9829 static const gdb_byte *
9830 locate_pdi_sibling (const struct die_reader_specs *reader,
9831                     struct partial_die_info *orig_pdi,
9832                     const gdb_byte *info_ptr)
9833 {
9834   /* Do we know the sibling already?  */
9835
9836   if (orig_pdi->sibling)
9837     return orig_pdi->sibling;
9838
9839   /* Are there any children to deal with?  */
9840
9841   if (!orig_pdi->has_children)
9842     return info_ptr;
9843
9844   /* Skip the children the long way.  */
9845
9846   return skip_children (reader, info_ptr);
9847 }
9848
9849 /* Expand this partial symbol table into a full symbol table.  SELF is
9850    not NULL.  */
9851
9852 static void
9853 dwarf2_read_symtab (struct partial_symtab *self,
9854                     struct objfile *objfile)
9855 {
9856   struct dwarf2_per_objfile *dwarf2_per_objfile
9857     = get_dwarf2_per_objfile (objfile);
9858
9859   if (self->readin)
9860     {
9861       warning (_("bug: psymtab for %s is already read in."),
9862                self->filename);
9863     }
9864   else
9865     {
9866       if (info_verbose)
9867         {
9868           printf_filtered (_("Reading in symbols for %s..."),
9869                            self->filename);
9870           gdb_flush (gdb_stdout);
9871         }
9872
9873       /* If this psymtab is constructed from a debug-only objfile, the
9874          has_section_at_zero flag will not necessarily be correct.  We
9875          can get the correct value for this flag by looking at the data
9876          associated with the (presumably stripped) associated objfile.  */
9877       if (objfile->separate_debug_objfile_backlink)
9878         {
9879           struct dwarf2_per_objfile *dpo_backlink
9880             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9881
9882           dwarf2_per_objfile->has_section_at_zero
9883             = dpo_backlink->has_section_at_zero;
9884         }
9885
9886       dwarf2_per_objfile->reading_partial_symbols = 0;
9887
9888       psymtab_to_symtab_1 (self);
9889
9890       /* Finish up the debug error message.  */
9891       if (info_verbose)
9892         printf_filtered (_("done.\n"));
9893     }
9894
9895   process_cu_includes (dwarf2_per_objfile);
9896 }
9897 \f
9898 /* Reading in full CUs.  */
9899
9900 /* Add PER_CU to the queue.  */
9901
9902 static void
9903 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9904                  enum language pretend_language)
9905 {
9906   struct dwarf2_queue_item *item;
9907
9908   per_cu->queued = 1;
9909   item = XNEW (struct dwarf2_queue_item);
9910   item->per_cu = per_cu;
9911   item->pretend_language = pretend_language;
9912   item->next = NULL;
9913
9914   if (dwarf2_queue == NULL)
9915     dwarf2_queue = item;
9916   else
9917     dwarf2_queue_tail->next = item;
9918
9919   dwarf2_queue_tail = item;
9920 }
9921
9922 /* If PER_CU is not yet queued, add it to the queue.
9923    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9924    dependency.
9925    The result is non-zero if PER_CU was queued, otherwise the result is zero
9926    meaning either PER_CU is already queued or it is already loaded.
9927
9928    N.B. There is an invariant here that if a CU is queued then it is loaded.
9929    The caller is required to load PER_CU if we return non-zero.  */
9930
9931 static int
9932 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9933                        struct dwarf2_per_cu_data *per_cu,
9934                        enum language pretend_language)
9935 {
9936   /* We may arrive here during partial symbol reading, if we need full
9937      DIEs to process an unusual case (e.g. template arguments).  Do
9938      not queue PER_CU, just tell our caller to load its DIEs.  */
9939   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9940     {
9941       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9942         return 1;
9943       return 0;
9944     }
9945
9946   /* Mark the dependence relation so that we don't flush PER_CU
9947      too early.  */
9948   if (dependent_cu != NULL)
9949     dwarf2_add_dependence (dependent_cu, per_cu);
9950
9951   /* If it's already on the queue, we have nothing to do.  */
9952   if (per_cu->queued)
9953     return 0;
9954
9955   /* If the compilation unit is already loaded, just mark it as
9956      used.  */
9957   if (per_cu->cu != NULL)
9958     {
9959       per_cu->cu->last_used = 0;
9960       return 0;
9961     }
9962
9963   /* Add it to the queue.  */
9964   queue_comp_unit (per_cu, pretend_language);
9965
9966   return 1;
9967 }
9968
9969 /* Process the queue.  */
9970
9971 static void
9972 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9973 {
9974   struct dwarf2_queue_item *item, *next_item;
9975
9976   if (dwarf_read_debug)
9977     {
9978       fprintf_unfiltered (gdb_stdlog,
9979                           "Expanding one or more symtabs of objfile %s ...\n",
9980                           objfile_name (dwarf2_per_objfile->objfile));
9981     }
9982
9983   /* The queue starts out with one item, but following a DIE reference
9984      may load a new CU, adding it to the end of the queue.  */
9985   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9986     {
9987       if ((dwarf2_per_objfile->using_index
9988            ? !item->per_cu->v.quick->compunit_symtab
9989            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9990           /* Skip dummy CUs.  */
9991           && item->per_cu->cu != NULL)
9992         {
9993           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9994           unsigned int debug_print_threshold;
9995           char buf[100];
9996
9997           if (per_cu->is_debug_types)
9998             {
9999               struct signatured_type *sig_type =
10000                 (struct signatured_type *) per_cu;
10001
10002               sprintf (buf, "TU %s at offset %s",
10003                        hex_string (sig_type->signature),
10004                        sect_offset_str (per_cu->sect_off));
10005               /* There can be 100s of TUs.
10006                  Only print them in verbose mode.  */
10007               debug_print_threshold = 2;
10008             }
10009           else
10010             {
10011               sprintf (buf, "CU at offset %s",
10012                        sect_offset_str (per_cu->sect_off));
10013               debug_print_threshold = 1;
10014             }
10015
10016           if (dwarf_read_debug >= debug_print_threshold)
10017             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
10018
10019           if (per_cu->is_debug_types)
10020             process_full_type_unit (per_cu, item->pretend_language);
10021           else
10022             process_full_comp_unit (per_cu, item->pretend_language);
10023
10024           if (dwarf_read_debug >= debug_print_threshold)
10025             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
10026         }
10027
10028       item->per_cu->queued = 0;
10029       next_item = item->next;
10030       xfree (item);
10031     }
10032
10033   dwarf2_queue_tail = NULL;
10034
10035   if (dwarf_read_debug)
10036     {
10037       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
10038                           objfile_name (dwarf2_per_objfile->objfile));
10039     }
10040 }
10041
10042 /* Read in full symbols for PST, and anything it depends on.  */
10043
10044 static void
10045 psymtab_to_symtab_1 (struct partial_symtab *pst)
10046 {
10047   struct dwarf2_per_cu_data *per_cu;
10048   int i;
10049
10050   if (pst->readin)
10051     return;
10052
10053   for (i = 0; i < pst->number_of_dependencies; i++)
10054     if (!pst->dependencies[i]->readin
10055         && pst->dependencies[i]->user == NULL)
10056       {
10057         /* Inform about additional files that need to be read in.  */
10058         if (info_verbose)
10059           {
10060             /* FIXME: i18n: Need to make this a single string.  */
10061             fputs_filtered (" ", gdb_stdout);
10062             wrap_here ("");
10063             fputs_filtered ("and ", gdb_stdout);
10064             wrap_here ("");
10065             printf_filtered ("%s...", pst->dependencies[i]->filename);
10066             wrap_here ("");     /* Flush output.  */
10067             gdb_flush (gdb_stdout);
10068           }
10069         psymtab_to_symtab_1 (pst->dependencies[i]);
10070       }
10071
10072   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10073
10074   if (per_cu == NULL)
10075     {
10076       /* It's an include file, no symbols to read for it.
10077          Everything is in the parent symtab.  */
10078       pst->readin = 1;
10079       return;
10080     }
10081
10082   dw2_do_instantiate_symtab (per_cu);
10083 }
10084
10085 /* Trivial hash function for die_info: the hash value of a DIE
10086    is its offset in .debug_info for this objfile.  */
10087
10088 static hashval_t
10089 die_hash (const void *item)
10090 {
10091   const struct die_info *die = (const struct die_info *) item;
10092
10093   return to_underlying (die->sect_off);
10094 }
10095
10096 /* Trivial comparison function for die_info structures: two DIEs
10097    are equal if they have the same offset.  */
10098
10099 static int
10100 die_eq (const void *item_lhs, const void *item_rhs)
10101 {
10102   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10103   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10104
10105   return die_lhs->sect_off == die_rhs->sect_off;
10106 }
10107
10108 /* die_reader_func for load_full_comp_unit.
10109    This is identical to read_signatured_type_reader,
10110    but is kept separate for now.  */
10111
10112 static void
10113 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10114                             const gdb_byte *info_ptr,
10115                             struct die_info *comp_unit_die,
10116                             int has_children,
10117                             void *data)
10118 {
10119   struct dwarf2_cu *cu = reader->cu;
10120   enum language *language_ptr = (enum language *) data;
10121
10122   gdb_assert (cu->die_hash == NULL);
10123   cu->die_hash =
10124     htab_create_alloc_ex (cu->header.length / 12,
10125                           die_hash,
10126                           die_eq,
10127                           NULL,
10128                           &cu->comp_unit_obstack,
10129                           hashtab_obstack_allocate,
10130                           dummy_obstack_deallocate);
10131
10132   if (has_children)
10133     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10134                                                   &info_ptr, comp_unit_die);
10135   cu->dies = comp_unit_die;
10136   /* comp_unit_die is not stored in die_hash, no need.  */
10137
10138   /* We try not to read any attributes in this function, because not
10139      all CUs needed for references have been loaded yet, and symbol
10140      table processing isn't initialized.  But we have to set the CU language,
10141      or we won't be able to build types correctly.
10142      Similarly, if we do not read the producer, we can not apply
10143      producer-specific interpretation.  */
10144   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10145 }
10146
10147 /* Load the DIEs associated with PER_CU into memory.  */
10148
10149 static void
10150 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10151                      enum language pretend_language)
10152 {
10153   gdb_assert (! this_cu->is_debug_types);
10154
10155   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10156                            load_full_comp_unit_reader, &pretend_language);
10157 }
10158
10159 /* Add a DIE to the delayed physname list.  */
10160
10161 static void
10162 add_to_method_list (struct type *type, int fnfield_index, int index,
10163                     const char *name, struct die_info *die,
10164                     struct dwarf2_cu *cu)
10165 {
10166   struct delayed_method_info mi;
10167   mi.type = type;
10168   mi.fnfield_index = fnfield_index;
10169   mi.index = index;
10170   mi.name = name;
10171   mi.die = die;
10172   cu->method_list.push_back (mi);
10173 }
10174
10175 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10176    "const" / "volatile".  If so, decrements LEN by the length of the
10177    modifier and return true.  Otherwise return false.  */
10178
10179 template<size_t N>
10180 static bool
10181 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10182 {
10183   size_t mod_len = sizeof (mod) - 1;
10184   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10185     {
10186       len -= mod_len;
10187       return true;
10188     }
10189   return false;
10190 }
10191
10192 /* Compute the physnames of any methods on the CU's method list.
10193
10194    The computation of method physnames is delayed in order to avoid the
10195    (bad) condition that one of the method's formal parameters is of an as yet
10196    incomplete type.  */
10197
10198 static void
10199 compute_delayed_physnames (struct dwarf2_cu *cu)
10200 {
10201   /* Only C++ delays computing physnames.  */
10202   if (cu->method_list.empty ())
10203     return;
10204   gdb_assert (cu->language == language_cplus);
10205
10206   for (struct delayed_method_info &mi : cu->method_list)
10207     {
10208       const char *physname;
10209       struct fn_fieldlist *fn_flp
10210         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10211       physname = dwarf2_physname (mi.name, mi.die, cu);
10212       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10213         = physname ? physname : "";
10214
10215       /* Since there's no tag to indicate whether a method is a
10216          const/volatile overload, extract that information out of the
10217          demangled name.  */
10218       if (physname != NULL)
10219         {
10220           size_t len = strlen (physname);
10221
10222           while (1)
10223             {
10224               if (physname[len] == ')') /* shortcut */
10225                 break;
10226               else if (check_modifier (physname, len, " const"))
10227                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10228               else if (check_modifier (physname, len, " volatile"))
10229                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10230               else
10231                 break;
10232             }
10233         }
10234     }
10235
10236   /* The list is no longer needed.  */
10237   cu->method_list.clear ();
10238 }
10239
10240 /* Go objects should be embedded in a DW_TAG_module DIE,
10241    and it's not clear if/how imported objects will appear.
10242    To keep Go support simple until that's worked out,
10243    go back through what we've read and create something usable.
10244    We could do this while processing each DIE, and feels kinda cleaner,
10245    but that way is more invasive.
10246    This is to, for example, allow the user to type "p var" or "b main"
10247    without having to specify the package name, and allow lookups
10248    of module.object to work in contexts that use the expression
10249    parser.  */
10250
10251 static void
10252 fixup_go_packaging (struct dwarf2_cu *cu)
10253 {
10254   char *package_name = NULL;
10255   struct pending *list;
10256   int i;
10257
10258   for (list = global_symbols; list != NULL; list = list->next)
10259     {
10260       for (i = 0; i < list->nsyms; ++i)
10261         {
10262           struct symbol *sym = list->symbol[i];
10263
10264           if (SYMBOL_LANGUAGE (sym) == language_go
10265               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10266             {
10267               char *this_package_name = go_symbol_package_name (sym);
10268
10269               if (this_package_name == NULL)
10270                 continue;
10271               if (package_name == NULL)
10272                 package_name = this_package_name;
10273               else
10274                 {
10275                   struct objfile *objfile
10276                     = cu->per_cu->dwarf2_per_objfile->objfile;
10277                   if (strcmp (package_name, this_package_name) != 0)
10278                     complaint (&symfile_complaints,
10279                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10280                                (symbol_symtab (sym) != NULL
10281                                 ? symtab_to_filename_for_display
10282                                     (symbol_symtab (sym))
10283                                 : objfile_name (objfile)),
10284                                this_package_name, package_name);
10285                   xfree (this_package_name);
10286                 }
10287             }
10288         }
10289     }
10290
10291   if (package_name != NULL)
10292     {
10293       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10294       const char *saved_package_name
10295         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10296                                         package_name,
10297                                         strlen (package_name));
10298       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10299                                      saved_package_name);
10300       struct symbol *sym;
10301
10302       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10303
10304       sym = allocate_symbol (objfile);
10305       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10306       SYMBOL_SET_NAMES (sym, saved_package_name,
10307                         strlen (saved_package_name), 0, objfile);
10308       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10309          e.g., "main" finds the "main" module and not C's main().  */
10310       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10311       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10312       SYMBOL_TYPE (sym) = type;
10313
10314       add_symbol_to_list (sym, &global_symbols);
10315
10316       xfree (package_name);
10317     }
10318 }
10319
10320 /* Return the symtab for PER_CU.  This works properly regardless of
10321    whether we're using the index or psymtabs.  */
10322
10323 static struct compunit_symtab *
10324 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10325 {
10326   return (per_cu->dwarf2_per_objfile->using_index
10327           ? per_cu->v.quick->compunit_symtab
10328           : per_cu->v.psymtab->compunit_symtab);
10329 }
10330
10331 /* A helper function for computing the list of all symbol tables
10332    included by PER_CU.  */
10333
10334 static void
10335 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10336                                 htab_t all_children, htab_t all_type_symtabs,
10337                                 struct dwarf2_per_cu_data *per_cu,
10338                                 struct compunit_symtab *immediate_parent)
10339 {
10340   void **slot;
10341   int ix;
10342   struct compunit_symtab *cust;
10343   struct dwarf2_per_cu_data *iter;
10344
10345   slot = htab_find_slot (all_children, per_cu, INSERT);
10346   if (*slot != NULL)
10347     {
10348       /* This inclusion and its children have been processed.  */
10349       return;
10350     }
10351
10352   *slot = per_cu;
10353   /* Only add a CU if it has a symbol table.  */
10354   cust = get_compunit_symtab (per_cu);
10355   if (cust != NULL)
10356     {
10357       /* If this is a type unit only add its symbol table if we haven't
10358          seen it yet (type unit per_cu's can share symtabs).  */
10359       if (per_cu->is_debug_types)
10360         {
10361           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10362           if (*slot == NULL)
10363             {
10364               *slot = cust;
10365               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10366               if (cust->user == NULL)
10367                 cust->user = immediate_parent;
10368             }
10369         }
10370       else
10371         {
10372           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10373           if (cust->user == NULL)
10374             cust->user = immediate_parent;
10375         }
10376     }
10377
10378   for (ix = 0;
10379        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10380        ++ix)
10381     {
10382       recursively_compute_inclusions (result, all_children,
10383                                       all_type_symtabs, iter, cust);
10384     }
10385 }
10386
10387 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10388    PER_CU.  */
10389
10390 static void
10391 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10392 {
10393   gdb_assert (! per_cu->is_debug_types);
10394
10395   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10396     {
10397       int ix, len;
10398       struct dwarf2_per_cu_data *per_cu_iter;
10399       struct compunit_symtab *compunit_symtab_iter;
10400       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10401       htab_t all_children, all_type_symtabs;
10402       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10403
10404       /* If we don't have a symtab, we can just skip this case.  */
10405       if (cust == NULL)
10406         return;
10407
10408       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10409                                         NULL, xcalloc, xfree);
10410       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10411                                             NULL, xcalloc, xfree);
10412
10413       for (ix = 0;
10414            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10415                         ix, per_cu_iter);
10416            ++ix)
10417         {
10418           recursively_compute_inclusions (&result_symtabs, all_children,
10419                                           all_type_symtabs, per_cu_iter,
10420                                           cust);
10421         }
10422
10423       /* Now we have a transitive closure of all the included symtabs.  */
10424       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10425       cust->includes
10426         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10427                      struct compunit_symtab *, len + 1);
10428       for (ix = 0;
10429            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10430                         compunit_symtab_iter);
10431            ++ix)
10432         cust->includes[ix] = compunit_symtab_iter;
10433       cust->includes[len] = NULL;
10434
10435       VEC_free (compunit_symtab_ptr, result_symtabs);
10436       htab_delete (all_children);
10437       htab_delete (all_type_symtabs);
10438     }
10439 }
10440
10441 /* Compute the 'includes' field for the symtabs of all the CUs we just
10442    read.  */
10443
10444 static void
10445 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10446 {
10447   int ix;
10448   struct dwarf2_per_cu_data *iter;
10449
10450   for (ix = 0;
10451        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10452                     ix, iter);
10453        ++ix)
10454     {
10455       if (! iter->is_debug_types)
10456         compute_compunit_symtab_includes (iter);
10457     }
10458
10459   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10460 }
10461
10462 /* Generate full symbol information for PER_CU, whose DIEs have
10463    already been loaded into memory.  */
10464
10465 static void
10466 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10467                         enum language pretend_language)
10468 {
10469   struct dwarf2_cu *cu = per_cu->cu;
10470   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10471   struct objfile *objfile = dwarf2_per_objfile->objfile;
10472   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10473   CORE_ADDR lowpc, highpc;
10474   struct compunit_symtab *cust;
10475   CORE_ADDR baseaddr;
10476   struct block *static_block;
10477   CORE_ADDR addr;
10478
10479   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10480
10481   buildsym_init ();
10482   scoped_free_pendings free_pending;
10483
10484   /* Clear the list here in case something was left over.  */
10485   cu->method_list.clear ();
10486
10487   cu->list_in_scope = &file_symbols;
10488
10489   cu->language = pretend_language;
10490   cu->language_defn = language_def (cu->language);
10491
10492   /* Do line number decoding in read_file_scope () */
10493   process_die (cu->dies, cu);
10494
10495   /* For now fudge the Go package.  */
10496   if (cu->language == language_go)
10497     fixup_go_packaging (cu);
10498
10499   /* Now that we have processed all the DIEs in the CU, all the types 
10500      should be complete, and it should now be safe to compute all of the
10501      physnames.  */
10502   compute_delayed_physnames (cu);
10503
10504   /* Some compilers don't define a DW_AT_high_pc attribute for the
10505      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10506      it, by scanning the DIE's below the compilation unit.  */
10507   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10508
10509   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10510   static_block = end_symtab_get_static_block (addr, 0, 1);
10511
10512   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10513      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10514      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10515      addrmap to help ensure it has an accurate map of pc values belonging to
10516      this comp unit.  */
10517   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10518
10519   cust = end_symtab_from_static_block (static_block,
10520                                        SECT_OFF_TEXT (objfile), 0);
10521
10522   if (cust != NULL)
10523     {
10524       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10525
10526       /* Set symtab language to language from DW_AT_language.  If the
10527          compilation is from a C file generated by language preprocessors, do
10528          not set the language if it was already deduced by start_subfile.  */
10529       if (!(cu->language == language_c
10530             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10531         COMPUNIT_FILETABS (cust)->language = cu->language;
10532
10533       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10534          produce DW_AT_location with location lists but it can be possibly
10535          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10536          there were bugs in prologue debug info, fixed later in GCC-4.5
10537          by "unwind info for epilogues" patch (which is not directly related).
10538
10539          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10540          needed, it would be wrong due to missing DW_AT_producer there.
10541
10542          Still one can confuse GDB by using non-standard GCC compilation
10543          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10544          */ 
10545       if (cu->has_loclist && gcc_4_minor >= 5)
10546         cust->locations_valid = 1;
10547
10548       if (gcc_4_minor >= 5)
10549         cust->epilogue_unwind_valid = 1;
10550
10551       cust->call_site_htab = cu->call_site_htab;
10552     }
10553
10554   if (dwarf2_per_objfile->using_index)
10555     per_cu->v.quick->compunit_symtab = cust;
10556   else
10557     {
10558       struct partial_symtab *pst = per_cu->v.psymtab;
10559       pst->compunit_symtab = cust;
10560       pst->readin = 1;
10561     }
10562
10563   /* Push it for inclusion processing later.  */
10564   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10565 }
10566
10567 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10568    already been loaded into memory.  */
10569
10570 static void
10571 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10572                         enum language pretend_language)
10573 {
10574   struct dwarf2_cu *cu = per_cu->cu;
10575   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10576   struct objfile *objfile = dwarf2_per_objfile->objfile;
10577   struct compunit_symtab *cust;
10578   struct signatured_type *sig_type;
10579
10580   gdb_assert (per_cu->is_debug_types);
10581   sig_type = (struct signatured_type *) per_cu;
10582
10583   buildsym_init ();
10584   scoped_free_pendings free_pending;
10585
10586   /* Clear the list here in case something was left over.  */
10587   cu->method_list.clear ();
10588
10589   cu->list_in_scope = &file_symbols;
10590
10591   cu->language = pretend_language;
10592   cu->language_defn = language_def (cu->language);
10593
10594   /* The symbol tables are set up in read_type_unit_scope.  */
10595   process_die (cu->dies, cu);
10596
10597   /* For now fudge the Go package.  */
10598   if (cu->language == language_go)
10599     fixup_go_packaging (cu);
10600
10601   /* Now that we have processed all the DIEs in the CU, all the types 
10602      should be complete, and it should now be safe to compute all of the
10603      physnames.  */
10604   compute_delayed_physnames (cu);
10605
10606   /* TUs share symbol tables.
10607      If this is the first TU to use this symtab, complete the construction
10608      of it with end_expandable_symtab.  Otherwise, complete the addition of
10609      this TU's symbols to the existing symtab.  */
10610   if (sig_type->type_unit_group->compunit_symtab == NULL)
10611     {
10612       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10613       sig_type->type_unit_group->compunit_symtab = cust;
10614
10615       if (cust != NULL)
10616         {
10617           /* Set symtab language to language from DW_AT_language.  If the
10618              compilation is from a C file generated by language preprocessors,
10619              do not set the language if it was already deduced by
10620              start_subfile.  */
10621           if (!(cu->language == language_c
10622                 && COMPUNIT_FILETABS (cust)->language != language_c))
10623             COMPUNIT_FILETABS (cust)->language = cu->language;
10624         }
10625     }
10626   else
10627     {
10628       augment_type_symtab ();
10629       cust = sig_type->type_unit_group->compunit_symtab;
10630     }
10631
10632   if (dwarf2_per_objfile->using_index)
10633     per_cu->v.quick->compunit_symtab = cust;
10634   else
10635     {
10636       struct partial_symtab *pst = per_cu->v.psymtab;
10637       pst->compunit_symtab = cust;
10638       pst->readin = 1;
10639     }
10640 }
10641
10642 /* Process an imported unit DIE.  */
10643
10644 static void
10645 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10646 {
10647   struct attribute *attr;
10648
10649   /* For now we don't handle imported units in type units.  */
10650   if (cu->per_cu->is_debug_types)
10651     {
10652       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10653                " supported in type units [in module %s]"),
10654              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10655     }
10656
10657   attr = dwarf2_attr (die, DW_AT_import, cu);
10658   if (attr != NULL)
10659     {
10660       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10661       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10662       dwarf2_per_cu_data *per_cu
10663         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10664                                             cu->per_cu->dwarf2_per_objfile);
10665
10666       /* If necessary, add it to the queue and load its DIEs.  */
10667       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10668         load_full_comp_unit (per_cu, cu->language);
10669
10670       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10671                      per_cu);
10672     }
10673 }
10674
10675 /* RAII object that represents a process_die scope: i.e.,
10676    starts/finishes processing a DIE.  */
10677 class process_die_scope
10678 {
10679 public:
10680   process_die_scope (die_info *die, dwarf2_cu *cu)
10681     : m_die (die), m_cu (cu)
10682   {
10683     /* We should only be processing DIEs not already in process.  */
10684     gdb_assert (!m_die->in_process);
10685     m_die->in_process = true;
10686   }
10687
10688   ~process_die_scope ()
10689   {
10690     m_die->in_process = false;
10691
10692     /* If we're done processing the DIE for the CU that owns the line
10693        header, we don't need the line header anymore.  */
10694     if (m_cu->line_header_die_owner == m_die)
10695       {
10696         delete m_cu->line_header;
10697         m_cu->line_header = NULL;
10698         m_cu->line_header_die_owner = NULL;
10699       }
10700   }
10701
10702 private:
10703   die_info *m_die;
10704   dwarf2_cu *m_cu;
10705 };
10706
10707 /* Process a die and its children.  */
10708
10709 static void
10710 process_die (struct die_info *die, struct dwarf2_cu *cu)
10711 {
10712   process_die_scope scope (die, cu);
10713
10714   switch (die->tag)
10715     {
10716     case DW_TAG_padding:
10717       break;
10718     case DW_TAG_compile_unit:
10719     case DW_TAG_partial_unit:
10720       read_file_scope (die, cu);
10721       break;
10722     case DW_TAG_type_unit:
10723       read_type_unit_scope (die, cu);
10724       break;
10725     case DW_TAG_subprogram:
10726     case DW_TAG_inlined_subroutine:
10727       read_func_scope (die, cu);
10728       break;
10729     case DW_TAG_lexical_block:
10730     case DW_TAG_try_block:
10731     case DW_TAG_catch_block:
10732       read_lexical_block_scope (die, cu);
10733       break;
10734     case DW_TAG_call_site:
10735     case DW_TAG_GNU_call_site:
10736       read_call_site_scope (die, cu);
10737       break;
10738     case DW_TAG_class_type:
10739     case DW_TAG_interface_type:
10740     case DW_TAG_structure_type:
10741     case DW_TAG_union_type:
10742       process_structure_scope (die, cu);
10743       break;
10744     case DW_TAG_enumeration_type:
10745       process_enumeration_scope (die, cu);
10746       break;
10747
10748     /* These dies have a type, but processing them does not create
10749        a symbol or recurse to process the children.  Therefore we can
10750        read them on-demand through read_type_die.  */
10751     case DW_TAG_subroutine_type:
10752     case DW_TAG_set_type:
10753     case DW_TAG_array_type:
10754     case DW_TAG_pointer_type:
10755     case DW_TAG_ptr_to_member_type:
10756     case DW_TAG_reference_type:
10757     case DW_TAG_rvalue_reference_type:
10758     case DW_TAG_string_type:
10759       break;
10760
10761     case DW_TAG_base_type:
10762     case DW_TAG_subrange_type:
10763     case DW_TAG_typedef:
10764       /* Add a typedef symbol for the type definition, if it has a
10765          DW_AT_name.  */
10766       new_symbol (die, read_type_die (die, cu), cu);
10767       break;
10768     case DW_TAG_common_block:
10769       read_common_block (die, cu);
10770       break;
10771     case DW_TAG_common_inclusion:
10772       break;
10773     case DW_TAG_namespace:
10774       cu->processing_has_namespace_info = 1;
10775       read_namespace (die, cu);
10776       break;
10777     case DW_TAG_module:
10778       cu->processing_has_namespace_info = 1;
10779       read_module (die, cu);
10780       break;
10781     case DW_TAG_imported_declaration:
10782       cu->processing_has_namespace_info = 1;
10783       if (read_namespace_alias (die, cu))
10784         break;
10785       /* The declaration is not a global namespace alias: fall through.  */
10786     case DW_TAG_imported_module:
10787       cu->processing_has_namespace_info = 1;
10788       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10789                                  || cu->language != language_fortran))
10790         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10791                    dwarf_tag_name (die->tag));
10792       read_import_statement (die, cu);
10793       break;
10794
10795     case DW_TAG_imported_unit:
10796       process_imported_unit_die (die, cu);
10797       break;
10798
10799     case DW_TAG_variable:
10800       read_variable (die, cu);
10801       break;
10802
10803     default:
10804       new_symbol (die, NULL, cu);
10805       break;
10806     }
10807 }
10808 \f
10809 /* DWARF name computation.  */
10810
10811 /* A helper function for dwarf2_compute_name which determines whether DIE
10812    needs to have the name of the scope prepended to the name listed in the
10813    die.  */
10814
10815 static int
10816 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10817 {
10818   struct attribute *attr;
10819
10820   switch (die->tag)
10821     {
10822     case DW_TAG_namespace:
10823     case DW_TAG_typedef:
10824     case DW_TAG_class_type:
10825     case DW_TAG_interface_type:
10826     case DW_TAG_structure_type:
10827     case DW_TAG_union_type:
10828     case DW_TAG_enumeration_type:
10829     case DW_TAG_enumerator:
10830     case DW_TAG_subprogram:
10831     case DW_TAG_inlined_subroutine:
10832     case DW_TAG_member:
10833     case DW_TAG_imported_declaration:
10834       return 1;
10835
10836     case DW_TAG_variable:
10837     case DW_TAG_constant:
10838       /* We only need to prefix "globally" visible variables.  These include
10839          any variable marked with DW_AT_external or any variable that
10840          lives in a namespace.  [Variables in anonymous namespaces
10841          require prefixing, but they are not DW_AT_external.]  */
10842
10843       if (dwarf2_attr (die, DW_AT_specification, cu))
10844         {
10845           struct dwarf2_cu *spec_cu = cu;
10846
10847           return die_needs_namespace (die_specification (die, &spec_cu),
10848                                       spec_cu);
10849         }
10850
10851       attr = dwarf2_attr (die, DW_AT_external, cu);
10852       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10853           && die->parent->tag != DW_TAG_module)
10854         return 0;
10855       /* A variable in a lexical block of some kind does not need a
10856          namespace, even though in C++ such variables may be external
10857          and have a mangled name.  */
10858       if (die->parent->tag ==  DW_TAG_lexical_block
10859           || die->parent->tag ==  DW_TAG_try_block
10860           || die->parent->tag ==  DW_TAG_catch_block
10861           || die->parent->tag == DW_TAG_subprogram)
10862         return 0;
10863       return 1;
10864
10865     default:
10866       return 0;
10867     }
10868 }
10869
10870 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10871    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10872    defined for the given DIE.  */
10873
10874 static struct attribute *
10875 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10876 {
10877   struct attribute *attr;
10878
10879   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10880   if (attr == NULL)
10881     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10882
10883   return attr;
10884 }
10885
10886 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10887    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10888    defined for the given DIE.  */
10889
10890 static const char *
10891 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10892 {
10893   const char *linkage_name;
10894
10895   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10896   if (linkage_name == NULL)
10897     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10898
10899   return linkage_name;
10900 }
10901
10902 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10903    compute the physname for the object, which include a method's:
10904    - formal parameters (C++),
10905    - receiver type (Go),
10906
10907    The term "physname" is a bit confusing.
10908    For C++, for example, it is the demangled name.
10909    For Go, for example, it's the mangled name.
10910
10911    For Ada, return the DIE's linkage name rather than the fully qualified
10912    name.  PHYSNAME is ignored..
10913
10914    The result is allocated on the objfile_obstack and canonicalized.  */
10915
10916 static const char *
10917 dwarf2_compute_name (const char *name,
10918                      struct die_info *die, struct dwarf2_cu *cu,
10919                      int physname)
10920 {
10921   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10922
10923   if (name == NULL)
10924     name = dwarf2_name (die, cu);
10925
10926   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10927      but otherwise compute it by typename_concat inside GDB.
10928      FIXME: Actually this is not really true, or at least not always true.
10929      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10930      Fortran names because there is no mangling standard.  So new_symbol
10931      will set the demangled name to the result of dwarf2_full_name, and it is
10932      the demangled name that GDB uses if it exists.  */
10933   if (cu->language == language_ada
10934       || (cu->language == language_fortran && physname))
10935     {
10936       /* For Ada unit, we prefer the linkage name over the name, as
10937          the former contains the exported name, which the user expects
10938          to be able to reference.  Ideally, we want the user to be able
10939          to reference this entity using either natural or linkage name,
10940          but we haven't started looking at this enhancement yet.  */
10941       const char *linkage_name = dw2_linkage_name (die, cu);
10942
10943       if (linkage_name != NULL)
10944         return linkage_name;
10945     }
10946
10947   /* These are the only languages we know how to qualify names in.  */
10948   if (name != NULL
10949       && (cu->language == language_cplus
10950           || cu->language == language_fortran || cu->language == language_d
10951           || cu->language == language_rust))
10952     {
10953       if (die_needs_namespace (die, cu))
10954         {
10955           const char *prefix;
10956           const char *canonical_name = NULL;
10957
10958           string_file buf;
10959
10960           prefix = determine_prefix (die, cu);
10961           if (*prefix != '\0')
10962             {
10963               char *prefixed_name = typename_concat (NULL, prefix, name,
10964                                                      physname, cu);
10965
10966               buf.puts (prefixed_name);
10967               xfree (prefixed_name);
10968             }
10969           else
10970             buf.puts (name);
10971
10972           /* Template parameters may be specified in the DIE's DW_AT_name, or
10973              as children with DW_TAG_template_type_param or
10974              DW_TAG_value_type_param.  If the latter, add them to the name
10975              here.  If the name already has template parameters, then
10976              skip this step; some versions of GCC emit both, and
10977              it is more efficient to use the pre-computed name.
10978
10979              Something to keep in mind about this process: it is very
10980              unlikely, or in some cases downright impossible, to produce
10981              something that will match the mangled name of a function.
10982              If the definition of the function has the same debug info,
10983              we should be able to match up with it anyway.  But fallbacks
10984              using the minimal symbol, for instance to find a method
10985              implemented in a stripped copy of libstdc++, will not work.
10986              If we do not have debug info for the definition, we will have to
10987              match them up some other way.
10988
10989              When we do name matching there is a related problem with function
10990              templates; two instantiated function templates are allowed to
10991              differ only by their return types, which we do not add here.  */
10992
10993           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10994             {
10995               struct attribute *attr;
10996               struct die_info *child;
10997               int first = 1;
10998
10999               die->building_fullname = 1;
11000
11001               for (child = die->child; child != NULL; child = child->sibling)
11002                 {
11003                   struct type *type;
11004                   LONGEST value;
11005                   const gdb_byte *bytes;
11006                   struct dwarf2_locexpr_baton *baton;
11007                   struct value *v;
11008
11009                   if (child->tag != DW_TAG_template_type_param
11010                       && child->tag != DW_TAG_template_value_param)
11011                     continue;
11012
11013                   if (first)
11014                     {
11015                       buf.puts ("<");
11016                       first = 0;
11017                     }
11018                   else
11019                     buf.puts (", ");
11020
11021                   attr = dwarf2_attr (child, DW_AT_type, cu);
11022                   if (attr == NULL)
11023                     {
11024                       complaint (&symfile_complaints,
11025                                  _("template parameter missing DW_AT_type"));
11026                       buf.puts ("UNKNOWN_TYPE");
11027                       continue;
11028                     }
11029                   type = die_type (child, cu);
11030
11031                   if (child->tag == DW_TAG_template_type_param)
11032                     {
11033                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11034                       continue;
11035                     }
11036
11037                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11038                   if (attr == NULL)
11039                     {
11040                       complaint (&symfile_complaints,
11041                                  _("template parameter missing "
11042                                    "DW_AT_const_value"));
11043                       buf.puts ("UNKNOWN_VALUE");
11044                       continue;
11045                     }
11046
11047                   dwarf2_const_value_attr (attr, type, name,
11048                                            &cu->comp_unit_obstack, cu,
11049                                            &value, &bytes, &baton);
11050
11051                   if (TYPE_NOSIGN (type))
11052                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11053                        changed, this can use value_print instead.  */
11054                     c_printchar (value, type, &buf);
11055                   else
11056                     {
11057                       struct value_print_options opts;
11058
11059                       if (baton != NULL)
11060                         v = dwarf2_evaluate_loc_desc (type, NULL,
11061                                                       baton->data,
11062                                                       baton->size,
11063                                                       baton->per_cu);
11064                       else if (bytes != NULL)
11065                         {
11066                           v = allocate_value (type);
11067                           memcpy (value_contents_writeable (v), bytes,
11068                                   TYPE_LENGTH (type));
11069                         }
11070                       else
11071                         v = value_from_longest (type, value);
11072
11073                       /* Specify decimal so that we do not depend on
11074                          the radix.  */
11075                       get_formatted_print_options (&opts, 'd');
11076                       opts.raw = 1;
11077                       value_print (v, &buf, &opts);
11078                       release_value (v);
11079                       value_free (v);
11080                     }
11081                 }
11082
11083               die->building_fullname = 0;
11084
11085               if (!first)
11086                 {
11087                   /* Close the argument list, with a space if necessary
11088                      (nested templates).  */
11089                   if (!buf.empty () && buf.string ().back () == '>')
11090                     buf.puts (" >");
11091                   else
11092                     buf.puts (">");
11093                 }
11094             }
11095
11096           /* For C++ methods, append formal parameter type
11097              information, if PHYSNAME.  */
11098
11099           if (physname && die->tag == DW_TAG_subprogram
11100               && cu->language == language_cplus)
11101             {
11102               struct type *type = read_type_die (die, cu);
11103
11104               c_type_print_args (type, &buf, 1, cu->language,
11105                                  &type_print_raw_options);
11106
11107               if (cu->language == language_cplus)
11108                 {
11109                   /* Assume that an artificial first parameter is
11110                      "this", but do not crash if it is not.  RealView
11111                      marks unnamed (and thus unused) parameters as
11112                      artificial; there is no way to differentiate
11113                      the two cases.  */
11114                   if (TYPE_NFIELDS (type) > 0
11115                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11116                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11117                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11118                                                                         0))))
11119                     buf.puts (" const");
11120                 }
11121             }
11122
11123           const std::string &intermediate_name = buf.string ();
11124
11125           if (cu->language == language_cplus)
11126             canonical_name
11127               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11128                                           &objfile->per_bfd->storage_obstack);
11129
11130           /* If we only computed INTERMEDIATE_NAME, or if
11131              INTERMEDIATE_NAME is already canonical, then we need to
11132              copy it to the appropriate obstack.  */
11133           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11134             name = ((const char *)
11135                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11136                                    intermediate_name.c_str (),
11137                                    intermediate_name.length ()));
11138           else
11139             name = canonical_name;
11140         }
11141     }
11142
11143   return name;
11144 }
11145
11146 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11147    If scope qualifiers are appropriate they will be added.  The result
11148    will be allocated on the storage_obstack, or NULL if the DIE does
11149    not have a name.  NAME may either be from a previous call to
11150    dwarf2_name or NULL.
11151
11152    The output string will be canonicalized (if C++).  */
11153
11154 static const char *
11155 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11156 {
11157   return dwarf2_compute_name (name, die, cu, 0);
11158 }
11159
11160 /* Construct a physname for the given DIE in CU.  NAME may either be
11161    from a previous call to dwarf2_name or NULL.  The result will be
11162    allocated on the objfile_objstack or NULL if the DIE does not have a
11163    name.
11164
11165    The output string will be canonicalized (if C++).  */
11166
11167 static const char *
11168 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11169 {
11170   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11171   const char *retval, *mangled = NULL, *canon = NULL;
11172   int need_copy = 1;
11173
11174   /* In this case dwarf2_compute_name is just a shortcut not building anything
11175      on its own.  */
11176   if (!die_needs_namespace (die, cu))
11177     return dwarf2_compute_name (name, die, cu, 1);
11178
11179   mangled = dw2_linkage_name (die, cu);
11180
11181   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11182      See https://github.com/rust-lang/rust/issues/32925.  */
11183   if (cu->language == language_rust && mangled != NULL
11184       && strchr (mangled, '{') != NULL)
11185     mangled = NULL;
11186
11187   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11188      has computed.  */
11189   gdb::unique_xmalloc_ptr<char> demangled;
11190   if (mangled != NULL)
11191     {
11192
11193       if (cu->language == language_go)
11194         {
11195           /* This is a lie, but we already lie to the caller new_symbol.
11196              new_symbol assumes we return the mangled name.
11197              This just undoes that lie until things are cleaned up.  */
11198         }
11199       else
11200         {
11201           /* Use DMGL_RET_DROP for C++ template functions to suppress
11202              their return type.  It is easier for GDB users to search
11203              for such functions as `name(params)' than `long name(params)'.
11204              In such case the minimal symbol names do not match the full
11205              symbol names but for template functions there is never a need
11206              to look up their definition from their declaration so
11207              the only disadvantage remains the minimal symbol variant
11208              `long name(params)' does not have the proper inferior type.  */
11209           demangled.reset (gdb_demangle (mangled,
11210                                          (DMGL_PARAMS | DMGL_ANSI
11211                                           | DMGL_RET_DROP)));
11212         }
11213       if (demangled)
11214         canon = demangled.get ();
11215       else
11216         {
11217           canon = mangled;
11218           need_copy = 0;
11219         }
11220     }
11221
11222   if (canon == NULL || check_physname)
11223     {
11224       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11225
11226       if (canon != NULL && strcmp (physname, canon) != 0)
11227         {
11228           /* It may not mean a bug in GDB.  The compiler could also
11229              compute DW_AT_linkage_name incorrectly.  But in such case
11230              GDB would need to be bug-to-bug compatible.  */
11231
11232           complaint (&symfile_complaints,
11233                      _("Computed physname <%s> does not match demangled <%s> "
11234                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11235                      physname, canon, mangled, sect_offset_str (die->sect_off),
11236                      objfile_name (objfile));
11237
11238           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11239              is available here - over computed PHYSNAME.  It is safer
11240              against both buggy GDB and buggy compilers.  */
11241
11242           retval = canon;
11243         }
11244       else
11245         {
11246           retval = physname;
11247           need_copy = 0;
11248         }
11249     }
11250   else
11251     retval = canon;
11252
11253   if (need_copy)
11254     retval = ((const char *)
11255               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11256                              retval, strlen (retval)));
11257
11258   return retval;
11259 }
11260
11261 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11262    a new symbol for it.
11263
11264    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11265
11266 static int
11267 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11268 {
11269   struct attribute *attr;
11270
11271   /* If the die does not have a name, this is not a namespace
11272      alias.  */
11273   attr = dwarf2_attr (die, DW_AT_name, cu);
11274   if (attr != NULL)
11275     {
11276       int num;
11277       struct die_info *d = die;
11278       struct dwarf2_cu *imported_cu = cu;
11279
11280       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11281          keep inspecting DIEs until we hit the underlying import.  */
11282 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11283       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11284         {
11285           attr = dwarf2_attr (d, DW_AT_import, cu);
11286           if (attr == NULL)
11287             break;
11288
11289           d = follow_die_ref (d, attr, &imported_cu);
11290           if (d->tag != DW_TAG_imported_declaration)
11291             break;
11292         }
11293
11294       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11295         {
11296           complaint (&symfile_complaints,
11297                      _("DIE at %s has too many recursively imported "
11298                        "declarations"), sect_offset_str (d->sect_off));
11299           return 0;
11300         }
11301
11302       if (attr != NULL)
11303         {
11304           struct type *type;
11305           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11306
11307           type = get_die_type_at_offset (sect_off, cu->per_cu);
11308           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11309             {
11310               /* This declaration is a global namespace alias.  Add
11311                  a symbol for it whose type is the aliased namespace.  */
11312               new_symbol (die, type, cu);
11313               return 1;
11314             }
11315         }
11316     }
11317
11318   return 0;
11319 }
11320
11321 /* Return the using directives repository (global or local?) to use in the
11322    current context for LANGUAGE.
11323
11324    For Ada, imported declarations can materialize renamings, which *may* be
11325    global.  However it is impossible (for now?) in DWARF to distinguish
11326    "external" imported declarations and "static" ones.  As all imported
11327    declarations seem to be static in all other languages, make them all CU-wide
11328    global only in Ada.  */
11329
11330 static struct using_direct **
11331 using_directives (enum language language)
11332 {
11333   if (language == language_ada && context_stack_depth == 0)
11334     return &global_using_directives;
11335   else
11336     return &local_using_directives;
11337 }
11338
11339 /* Read the import statement specified by the given die and record it.  */
11340
11341 static void
11342 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11343 {
11344   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11345   struct attribute *import_attr;
11346   struct die_info *imported_die, *child_die;
11347   struct dwarf2_cu *imported_cu;
11348   const char *imported_name;
11349   const char *imported_name_prefix;
11350   const char *canonical_name;
11351   const char *import_alias;
11352   const char *imported_declaration = NULL;
11353   const char *import_prefix;
11354   std::vector<const char *> excludes;
11355
11356   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11357   if (import_attr == NULL)
11358     {
11359       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11360                  dwarf_tag_name (die->tag));
11361       return;
11362     }
11363
11364   imported_cu = cu;
11365   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11366   imported_name = dwarf2_name (imported_die, imported_cu);
11367   if (imported_name == NULL)
11368     {
11369       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11370
11371         The import in the following code:
11372         namespace A
11373           {
11374             typedef int B;
11375           }
11376
11377         int main ()
11378           {
11379             using A::B;
11380             B b;
11381             return b;
11382           }
11383
11384         ...
11385          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11386             <52>   DW_AT_decl_file   : 1
11387             <53>   DW_AT_decl_line   : 6
11388             <54>   DW_AT_import      : <0x75>
11389          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11390             <59>   DW_AT_name        : B
11391             <5b>   DW_AT_decl_file   : 1
11392             <5c>   DW_AT_decl_line   : 2
11393             <5d>   DW_AT_type        : <0x6e>
11394         ...
11395          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11396             <76>   DW_AT_byte_size   : 4
11397             <77>   DW_AT_encoding    : 5        (signed)
11398
11399         imports the wrong die ( 0x75 instead of 0x58 ).
11400         This case will be ignored until the gcc bug is fixed.  */
11401       return;
11402     }
11403
11404   /* Figure out the local name after import.  */
11405   import_alias = dwarf2_name (die, cu);
11406
11407   /* Figure out where the statement is being imported to.  */
11408   import_prefix = determine_prefix (die, cu);
11409
11410   /* Figure out what the scope of the imported die is and prepend it
11411      to the name of the imported die.  */
11412   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11413
11414   if (imported_die->tag != DW_TAG_namespace
11415       && imported_die->tag != DW_TAG_module)
11416     {
11417       imported_declaration = imported_name;
11418       canonical_name = imported_name_prefix;
11419     }
11420   else if (strlen (imported_name_prefix) > 0)
11421     canonical_name = obconcat (&objfile->objfile_obstack,
11422                                imported_name_prefix,
11423                                (cu->language == language_d ? "." : "::"),
11424                                imported_name, (char *) NULL);
11425   else
11426     canonical_name = imported_name;
11427
11428   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11429     for (child_die = die->child; child_die && child_die->tag;
11430          child_die = sibling_die (child_die))
11431       {
11432         /* DWARF-4: A Fortran use statement with a “rename list” may be
11433            represented by an imported module entry with an import attribute
11434            referring to the module and owned entries corresponding to those
11435            entities that are renamed as part of being imported.  */
11436
11437         if (child_die->tag != DW_TAG_imported_declaration)
11438           {
11439             complaint (&symfile_complaints,
11440                        _("child DW_TAG_imported_declaration expected "
11441                          "- DIE at %s [in module %s]"),
11442                        sect_offset_str (child_die->sect_off),
11443                        objfile_name (objfile));
11444             continue;
11445           }
11446
11447         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11448         if (import_attr == NULL)
11449           {
11450             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11451                        dwarf_tag_name (child_die->tag));
11452             continue;
11453           }
11454
11455         imported_cu = cu;
11456         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11457                                               &imported_cu);
11458         imported_name = dwarf2_name (imported_die, imported_cu);
11459         if (imported_name == NULL)
11460           {
11461             complaint (&symfile_complaints,
11462                        _("child DW_TAG_imported_declaration has unknown "
11463                          "imported name - DIE at %s [in module %s]"),
11464                        sect_offset_str (child_die->sect_off),
11465                        objfile_name (objfile));
11466             continue;
11467           }
11468
11469         excludes.push_back (imported_name);
11470
11471         process_die (child_die, cu);
11472       }
11473
11474   add_using_directive (using_directives (cu->language),
11475                        import_prefix,
11476                        canonical_name,
11477                        import_alias,
11478                        imported_declaration,
11479                        excludes,
11480                        0,
11481                        &objfile->objfile_obstack);
11482 }
11483
11484 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11485    types, but gives them a size of zero.  Starting with version 14,
11486    ICC is compatible with GCC.  */
11487
11488 static int
11489 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11490 {
11491   if (!cu->checked_producer)
11492     check_producer (cu);
11493
11494   return cu->producer_is_icc_lt_14;
11495 }
11496
11497 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11498    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11499    this, it was first present in GCC release 4.3.0.  */
11500
11501 static int
11502 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11503 {
11504   if (!cu->checked_producer)
11505     check_producer (cu);
11506
11507   return cu->producer_is_gcc_lt_4_3;
11508 }
11509
11510 static file_and_directory
11511 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11512 {
11513   file_and_directory res;
11514
11515   /* Find the filename.  Do not use dwarf2_name here, since the filename
11516      is not a source language identifier.  */
11517   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11518   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11519
11520   if (res.comp_dir == NULL
11521       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11522       && IS_ABSOLUTE_PATH (res.name))
11523     {
11524       res.comp_dir_storage = ldirname (res.name);
11525       if (!res.comp_dir_storage.empty ())
11526         res.comp_dir = res.comp_dir_storage.c_str ();
11527     }
11528   if (res.comp_dir != NULL)
11529     {
11530       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11531          directory, get rid of it.  */
11532       const char *cp = strchr (res.comp_dir, ':');
11533
11534       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11535         res.comp_dir = cp + 1;
11536     }
11537
11538   if (res.name == NULL)
11539     res.name = "<unknown>";
11540
11541   return res;
11542 }
11543
11544 /* Handle DW_AT_stmt_list for a compilation unit.
11545    DIE is the DW_TAG_compile_unit die for CU.
11546    COMP_DIR is the compilation directory.  LOWPC is passed to
11547    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11548
11549 static void
11550 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11551                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11552 {
11553   struct dwarf2_per_objfile *dwarf2_per_objfile
11554     = cu->per_cu->dwarf2_per_objfile;
11555   struct objfile *objfile = dwarf2_per_objfile->objfile;
11556   struct attribute *attr;
11557   struct line_header line_header_local;
11558   hashval_t line_header_local_hash;
11559   void **slot;
11560   int decode_mapping;
11561
11562   gdb_assert (! cu->per_cu->is_debug_types);
11563
11564   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11565   if (attr == NULL)
11566     return;
11567
11568   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11569
11570   /* The line header hash table is only created if needed (it exists to
11571      prevent redundant reading of the line table for partial_units).
11572      If we're given a partial_unit, we'll need it.  If we're given a
11573      compile_unit, then use the line header hash table if it's already
11574      created, but don't create one just yet.  */
11575
11576   if (dwarf2_per_objfile->line_header_hash == NULL
11577       && die->tag == DW_TAG_partial_unit)
11578     {
11579       dwarf2_per_objfile->line_header_hash
11580         = htab_create_alloc_ex (127, line_header_hash_voidp,
11581                                 line_header_eq_voidp,
11582                                 free_line_header_voidp,
11583                                 &objfile->objfile_obstack,
11584                                 hashtab_obstack_allocate,
11585                                 dummy_obstack_deallocate);
11586     }
11587
11588   line_header_local.sect_off = line_offset;
11589   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11590   line_header_local_hash = line_header_hash (&line_header_local);
11591   if (dwarf2_per_objfile->line_header_hash != NULL)
11592     {
11593       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11594                                        &line_header_local,
11595                                        line_header_local_hash, NO_INSERT);
11596
11597       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11598          is not present in *SLOT (since if there is something in *SLOT then
11599          it will be for a partial_unit).  */
11600       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11601         {
11602           gdb_assert (*slot != NULL);
11603           cu->line_header = (struct line_header *) *slot;
11604           return;
11605         }
11606     }
11607
11608   /* dwarf_decode_line_header does not yet provide sufficient information.
11609      We always have to call also dwarf_decode_lines for it.  */
11610   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11611   if (lh == NULL)
11612     return;
11613
11614   cu->line_header = lh.release ();
11615   cu->line_header_die_owner = die;
11616
11617   if (dwarf2_per_objfile->line_header_hash == NULL)
11618     slot = NULL;
11619   else
11620     {
11621       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11622                                        &line_header_local,
11623                                        line_header_local_hash, INSERT);
11624       gdb_assert (slot != NULL);
11625     }
11626   if (slot != NULL && *slot == NULL)
11627     {
11628       /* This newly decoded line number information unit will be owned
11629          by line_header_hash hash table.  */
11630       *slot = cu->line_header;
11631       cu->line_header_die_owner = NULL;
11632     }
11633   else
11634     {
11635       /* We cannot free any current entry in (*slot) as that struct line_header
11636          may be already used by multiple CUs.  Create only temporary decoded
11637          line_header for this CU - it may happen at most once for each line
11638          number information unit.  And if we're not using line_header_hash
11639          then this is what we want as well.  */
11640       gdb_assert (die->tag != DW_TAG_partial_unit);
11641     }
11642   decode_mapping = (die->tag != DW_TAG_partial_unit);
11643   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11644                       decode_mapping);
11645
11646 }
11647
11648 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11649
11650 static void
11651 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11652 {
11653   struct dwarf2_per_objfile *dwarf2_per_objfile
11654     = cu->per_cu->dwarf2_per_objfile;
11655   struct objfile *objfile = dwarf2_per_objfile->objfile;
11656   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11657   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11658   CORE_ADDR highpc = ((CORE_ADDR) 0);
11659   struct attribute *attr;
11660   struct die_info *child_die;
11661   CORE_ADDR baseaddr;
11662
11663   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11664
11665   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11666
11667   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11668      from finish_block.  */
11669   if (lowpc == ((CORE_ADDR) -1))
11670     lowpc = highpc;
11671   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11672
11673   file_and_directory fnd = find_file_and_directory (die, cu);
11674
11675   prepare_one_comp_unit (cu, die, cu->language);
11676
11677   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11678      standardised yet.  As a workaround for the language detection we fall
11679      back to the DW_AT_producer string.  */
11680   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11681     cu->language = language_opencl;
11682
11683   /* Similar hack for Go.  */
11684   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11685     set_cu_language (DW_LANG_Go, cu);
11686
11687   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11688
11689   /* Decode line number information if present.  We do this before
11690      processing child DIEs, so that the line header table is available
11691      for DW_AT_decl_file.  */
11692   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11693
11694   /* Process all dies in compilation unit.  */
11695   if (die->child != NULL)
11696     {
11697       child_die = die->child;
11698       while (child_die && child_die->tag)
11699         {
11700           process_die (child_die, cu);
11701           child_die = sibling_die (child_die);
11702         }
11703     }
11704
11705   /* Decode macro information, if present.  Dwarf 2 macro information
11706      refers to information in the line number info statement program
11707      header, so we can only read it if we've read the header
11708      successfully.  */
11709   attr = dwarf2_attr (die, DW_AT_macros, cu);
11710   if (attr == NULL)
11711     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11712   if (attr && cu->line_header)
11713     {
11714       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11715         complaint (&symfile_complaints,
11716                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11717
11718       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11719     }
11720   else
11721     {
11722       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11723       if (attr && cu->line_header)
11724         {
11725           unsigned int macro_offset = DW_UNSND (attr);
11726
11727           dwarf_decode_macros (cu, macro_offset, 0);
11728         }
11729     }
11730 }
11731
11732 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11733    Create the set of symtabs used by this TU, or if this TU is sharing
11734    symtabs with another TU and the symtabs have already been created
11735    then restore those symtabs in the line header.
11736    We don't need the pc/line-number mapping for type units.  */
11737
11738 static void
11739 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11740 {
11741   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11742   struct type_unit_group *tu_group;
11743   int first_time;
11744   struct attribute *attr;
11745   unsigned int i;
11746   struct signatured_type *sig_type;
11747
11748   gdb_assert (per_cu->is_debug_types);
11749   sig_type = (struct signatured_type *) per_cu;
11750
11751   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11752
11753   /* If we're using .gdb_index (includes -readnow) then
11754      per_cu->type_unit_group may not have been set up yet.  */
11755   if (sig_type->type_unit_group == NULL)
11756     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11757   tu_group = sig_type->type_unit_group;
11758
11759   /* If we've already processed this stmt_list there's no real need to
11760      do it again, we could fake it and just recreate the part we need
11761      (file name,index -> symtab mapping).  If data shows this optimization
11762      is useful we can do it then.  */
11763   first_time = tu_group->compunit_symtab == NULL;
11764
11765   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11766      debug info.  */
11767   line_header_up lh;
11768   if (attr != NULL)
11769     {
11770       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11771       lh = dwarf_decode_line_header (line_offset, cu);
11772     }
11773   if (lh == NULL)
11774     {
11775       if (first_time)
11776         dwarf2_start_symtab (cu, "", NULL, 0);
11777       else
11778         {
11779           gdb_assert (tu_group->symtabs == NULL);
11780           restart_symtab (tu_group->compunit_symtab, "", 0);
11781         }
11782       return;
11783     }
11784
11785   cu->line_header = lh.release ();
11786   cu->line_header_die_owner = die;
11787
11788   if (first_time)
11789     {
11790       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11791
11792       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11793          still initializing it, and our caller (a few levels up)
11794          process_full_type_unit still needs to know if this is the first
11795          time.  */
11796
11797       tu_group->num_symtabs = cu->line_header->file_names.size ();
11798       tu_group->symtabs = XNEWVEC (struct symtab *,
11799                                    cu->line_header->file_names.size ());
11800
11801       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11802         {
11803           file_entry &fe = cu->line_header->file_names[i];
11804
11805           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11806
11807           if (current_subfile->symtab == NULL)
11808             {
11809               /* NOTE: start_subfile will recognize when it's been
11810                  passed a file it has already seen.  So we can't
11811                  assume there's a simple mapping from
11812                  cu->line_header->file_names to subfiles, plus
11813                  cu->line_header->file_names may contain dups.  */
11814               current_subfile->symtab
11815                 = allocate_symtab (cust, current_subfile->name);
11816             }
11817
11818           fe.symtab = current_subfile->symtab;
11819           tu_group->symtabs[i] = fe.symtab;
11820         }
11821     }
11822   else
11823     {
11824       restart_symtab (tu_group->compunit_symtab, "", 0);
11825
11826       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11827         {
11828           file_entry &fe = cu->line_header->file_names[i];
11829
11830           fe.symtab = tu_group->symtabs[i];
11831         }
11832     }
11833
11834   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11835      so they don't have a "real" (so to speak) symtab anyway.
11836      There is later code that will assign the main symtab to all symbols
11837      that don't have one.  We need to handle the case of a symbol with a
11838      missing symtab (DW_AT_decl_file) anyway.  */
11839 }
11840
11841 /* Process DW_TAG_type_unit.
11842    For TUs we want to skip the first top level sibling if it's not the
11843    actual type being defined by this TU.  In this case the first top
11844    level sibling is there to provide context only.  */
11845
11846 static void
11847 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11848 {
11849   struct die_info *child_die;
11850
11851   prepare_one_comp_unit (cu, die, language_minimal);
11852
11853   /* Initialize (or reinitialize) the machinery for building symtabs.
11854      We do this before processing child DIEs, so that the line header table
11855      is available for DW_AT_decl_file.  */
11856   setup_type_unit_groups (die, cu);
11857
11858   if (die->child != NULL)
11859     {
11860       child_die = die->child;
11861       while (child_die && child_die->tag)
11862         {
11863           process_die (child_die, cu);
11864           child_die = sibling_die (child_die);
11865         }
11866     }
11867 }
11868 \f
11869 /* DWO/DWP files.
11870
11871    http://gcc.gnu.org/wiki/DebugFission
11872    http://gcc.gnu.org/wiki/DebugFissionDWP
11873
11874    To simplify handling of both DWO files ("object" files with the DWARF info)
11875    and DWP files (a file with the DWOs packaged up into one file), we treat
11876    DWP files as having a collection of virtual DWO files.  */
11877
11878 static hashval_t
11879 hash_dwo_file (const void *item)
11880 {
11881   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11882   hashval_t hash;
11883
11884   hash = htab_hash_string (dwo_file->dwo_name);
11885   if (dwo_file->comp_dir != NULL)
11886     hash += htab_hash_string (dwo_file->comp_dir);
11887   return hash;
11888 }
11889
11890 static int
11891 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11892 {
11893   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11894   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11895
11896   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11897     return 0;
11898   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11899     return lhs->comp_dir == rhs->comp_dir;
11900   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11901 }
11902
11903 /* Allocate a hash table for DWO files.  */
11904
11905 static htab_t
11906 allocate_dwo_file_hash_table (struct objfile *objfile)
11907 {
11908   return htab_create_alloc_ex (41,
11909                                hash_dwo_file,
11910                                eq_dwo_file,
11911                                NULL,
11912                                &objfile->objfile_obstack,
11913                                hashtab_obstack_allocate,
11914                                dummy_obstack_deallocate);
11915 }
11916
11917 /* Lookup DWO file DWO_NAME.  */
11918
11919 static void **
11920 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11921                       const char *dwo_name,
11922                       const char *comp_dir)
11923 {
11924   struct dwo_file find_entry;
11925   void **slot;
11926
11927   if (dwarf2_per_objfile->dwo_files == NULL)
11928     dwarf2_per_objfile->dwo_files
11929       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11930
11931   memset (&find_entry, 0, sizeof (find_entry));
11932   find_entry.dwo_name = dwo_name;
11933   find_entry.comp_dir = comp_dir;
11934   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11935
11936   return slot;
11937 }
11938
11939 static hashval_t
11940 hash_dwo_unit (const void *item)
11941 {
11942   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11943
11944   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11945   return dwo_unit->signature;
11946 }
11947
11948 static int
11949 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11950 {
11951   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11952   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11953
11954   /* The signature is assumed to be unique within the DWO file.
11955      So while object file CU dwo_id's always have the value zero,
11956      that's OK, assuming each object file DWO file has only one CU,
11957      and that's the rule for now.  */
11958   return lhs->signature == rhs->signature;
11959 }
11960
11961 /* Allocate a hash table for DWO CUs,TUs.
11962    There is one of these tables for each of CUs,TUs for each DWO file.  */
11963
11964 static htab_t
11965 allocate_dwo_unit_table (struct objfile *objfile)
11966 {
11967   /* Start out with a pretty small number.
11968      Generally DWO files contain only one CU and maybe some TUs.  */
11969   return htab_create_alloc_ex (3,
11970                                hash_dwo_unit,
11971                                eq_dwo_unit,
11972                                NULL,
11973                                &objfile->objfile_obstack,
11974                                hashtab_obstack_allocate,
11975                                dummy_obstack_deallocate);
11976 }
11977
11978 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11979
11980 struct create_dwo_cu_data
11981 {
11982   struct dwo_file *dwo_file;
11983   struct dwo_unit dwo_unit;
11984 };
11985
11986 /* die_reader_func for create_dwo_cu.  */
11987
11988 static void
11989 create_dwo_cu_reader (const struct die_reader_specs *reader,
11990                       const gdb_byte *info_ptr,
11991                       struct die_info *comp_unit_die,
11992                       int has_children,
11993                       void *datap)
11994 {
11995   struct dwarf2_cu *cu = reader->cu;
11996   sect_offset sect_off = cu->per_cu->sect_off;
11997   struct dwarf2_section_info *section = cu->per_cu->section;
11998   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11999   struct dwo_file *dwo_file = data->dwo_file;
12000   struct dwo_unit *dwo_unit = &data->dwo_unit;
12001   struct attribute *attr;
12002
12003   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
12004   if (attr == NULL)
12005     {
12006       complaint (&symfile_complaints,
12007                  _("Dwarf Error: debug entry at offset %s is missing"
12008                    " its dwo_id [in module %s]"),
12009                  sect_offset_str (sect_off), dwo_file->dwo_name);
12010       return;
12011     }
12012
12013   dwo_unit->dwo_file = dwo_file;
12014   dwo_unit->signature = DW_UNSND (attr);
12015   dwo_unit->section = section;
12016   dwo_unit->sect_off = sect_off;
12017   dwo_unit->length = cu->per_cu->length;
12018
12019   if (dwarf_read_debug)
12020     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
12021                         sect_offset_str (sect_off),
12022                         hex_string (dwo_unit->signature));
12023 }
12024
12025 /* Create the dwo_units for the CUs in a DWO_FILE.
12026    Note: This function processes DWO files only, not DWP files.  */
12027
12028 static void
12029 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12030                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12031                        htab_t &cus_htab)
12032 {
12033   struct objfile *objfile = dwarf2_per_objfile->objfile;
12034   const gdb_byte *info_ptr, *end_ptr;
12035
12036   dwarf2_read_section (objfile, &section);
12037   info_ptr = section.buffer;
12038
12039   if (info_ptr == NULL)
12040     return;
12041
12042   if (dwarf_read_debug)
12043     {
12044       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12045                           get_section_name (&section),
12046                           get_section_file_name (&section));
12047     }
12048
12049   end_ptr = info_ptr + section.size;
12050   while (info_ptr < end_ptr)
12051     {
12052       struct dwarf2_per_cu_data per_cu;
12053       struct create_dwo_cu_data create_dwo_cu_data;
12054       struct dwo_unit *dwo_unit;
12055       void **slot;
12056       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12057
12058       memset (&create_dwo_cu_data.dwo_unit, 0,
12059               sizeof (create_dwo_cu_data.dwo_unit));
12060       memset (&per_cu, 0, sizeof (per_cu));
12061       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12062       per_cu.is_debug_types = 0;
12063       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12064       per_cu.section = &section;
12065       create_dwo_cu_data.dwo_file = &dwo_file;
12066
12067       init_cutu_and_read_dies_no_follow (
12068           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12069       info_ptr += per_cu.length;
12070
12071       // If the unit could not be parsed, skip it.
12072       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12073         continue;
12074
12075       if (cus_htab == NULL)
12076         cus_htab = allocate_dwo_unit_table (objfile);
12077
12078       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12079       *dwo_unit = create_dwo_cu_data.dwo_unit;
12080       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12081       gdb_assert (slot != NULL);
12082       if (*slot != NULL)
12083         {
12084           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12085           sect_offset dup_sect_off = dup_cu->sect_off;
12086
12087           complaint (&symfile_complaints,
12088                      _("debug cu entry at offset %s is duplicate to"
12089                        " the entry at offset %s, signature %s"),
12090                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
12091                      hex_string (dwo_unit->signature));
12092         }
12093       *slot = (void *)dwo_unit;
12094     }
12095 }
12096
12097 /* DWP file .debug_{cu,tu}_index section format:
12098    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12099
12100    DWP Version 1:
12101
12102    Both index sections have the same format, and serve to map a 64-bit
12103    signature to a set of section numbers.  Each section begins with a header,
12104    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12105    indexes, and a pool of 32-bit section numbers.  The index sections will be
12106    aligned at 8-byte boundaries in the file.
12107
12108    The index section header consists of:
12109
12110     V, 32 bit version number
12111     -, 32 bits unused
12112     N, 32 bit number of compilation units or type units in the index
12113     M, 32 bit number of slots in the hash table
12114
12115    Numbers are recorded using the byte order of the application binary.
12116
12117    The hash table begins at offset 16 in the section, and consists of an array
12118    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12119    order of the application binary).  Unused slots in the hash table are 0.
12120    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12121
12122    The parallel table begins immediately after the hash table
12123    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12124    array of 32-bit indexes (using the byte order of the application binary),
12125    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12126    table contains a 32-bit index into the pool of section numbers.  For unused
12127    hash table slots, the corresponding entry in the parallel table will be 0.
12128
12129    The pool of section numbers begins immediately following the hash table
12130    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12131    section numbers consists of an array of 32-bit words (using the byte order
12132    of the application binary).  Each item in the array is indexed starting
12133    from 0.  The hash table entry provides the index of the first section
12134    number in the set.  Additional section numbers in the set follow, and the
12135    set is terminated by a 0 entry (section number 0 is not used in ELF).
12136
12137    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12138    section must be the first entry in the set, and the .debug_abbrev.dwo must
12139    be the second entry. Other members of the set may follow in any order.
12140
12141    ---
12142
12143    DWP Version 2:
12144
12145    DWP Version 2 combines all the .debug_info, etc. sections into one,
12146    and the entries in the index tables are now offsets into these sections.
12147    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12148    section.
12149
12150    Index Section Contents:
12151     Header
12152     Hash Table of Signatures   dwp_hash_table.hash_table
12153     Parallel Table of Indices  dwp_hash_table.unit_table
12154     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12155     Table of Section Sizes     dwp_hash_table.v2.sizes
12156
12157    The index section header consists of:
12158
12159     V, 32 bit version number
12160     L, 32 bit number of columns in the table of section offsets
12161     N, 32 bit number of compilation units or type units in the index
12162     M, 32 bit number of slots in the hash table
12163
12164    Numbers are recorded using the byte order of the application binary.
12165
12166    The hash table has the same format as version 1.
12167    The parallel table of indices has the same format as version 1,
12168    except that the entries are origin-1 indices into the table of sections
12169    offsets and the table of section sizes.
12170
12171    The table of offsets begins immediately following the parallel table
12172    (at offset 16 + 12 * M from the beginning of the section).  The table is
12173    a two-dimensional array of 32-bit words (using the byte order of the
12174    application binary), with L columns and N+1 rows, in row-major order.
12175    Each row in the array is indexed starting from 0.  The first row provides
12176    a key to the remaining rows: each column in this row provides an identifier
12177    for a debug section, and the offsets in the same column of subsequent rows
12178    refer to that section.  The section identifiers are:
12179
12180     DW_SECT_INFO         1  .debug_info.dwo
12181     DW_SECT_TYPES        2  .debug_types.dwo
12182     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12183     DW_SECT_LINE         4  .debug_line.dwo
12184     DW_SECT_LOC          5  .debug_loc.dwo
12185     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12186     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12187     DW_SECT_MACRO        8  .debug_macro.dwo
12188
12189    The offsets provided by the CU and TU index sections are the base offsets
12190    for the contributions made by each CU or TU to the corresponding section
12191    in the package file.  Each CU and TU header contains an abbrev_offset
12192    field, used to find the abbreviations table for that CU or TU within the
12193    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12194    be interpreted as relative to the base offset given in the index section.
12195    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12196    should be interpreted as relative to the base offset for .debug_line.dwo,
12197    and offsets into other debug sections obtained from DWARF attributes should
12198    also be interpreted as relative to the corresponding base offset.
12199
12200    The table of sizes begins immediately following the table of offsets.
12201    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12202    with L columns and N rows, in row-major order.  Each row in the array is
12203    indexed starting from 1 (row 0 is shared by the two tables).
12204
12205    ---
12206
12207    Hash table lookup is handled the same in version 1 and 2:
12208
12209    We assume that N and M will not exceed 2^32 - 1.
12210    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12211
12212    Given a 64-bit compilation unit signature or a type signature S, an entry
12213    in the hash table is located as follows:
12214
12215    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12216       the low-order k bits all set to 1.
12217
12218    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12219
12220    3) If the hash table entry at index H matches the signature, use that
12221       entry.  If the hash table entry at index H is unused (all zeroes),
12222       terminate the search: the signature is not present in the table.
12223
12224    4) Let H = (H + H') modulo M. Repeat at Step 3.
12225
12226    Because M > N and H' and M are relatively prime, the search is guaranteed
12227    to stop at an unused slot or find the match.  */
12228
12229 /* Create a hash table to map DWO IDs to their CU/TU entry in
12230    .debug_{info,types}.dwo in DWP_FILE.
12231    Returns NULL if there isn't one.
12232    Note: This function processes DWP files only, not DWO files.  */
12233
12234 static struct dwp_hash_table *
12235 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12236                        struct dwp_file *dwp_file, int is_debug_types)
12237 {
12238   struct objfile *objfile = dwarf2_per_objfile->objfile;
12239   bfd *dbfd = dwp_file->dbfd;
12240   const gdb_byte *index_ptr, *index_end;
12241   struct dwarf2_section_info *index;
12242   uint32_t version, nr_columns, nr_units, nr_slots;
12243   struct dwp_hash_table *htab;
12244
12245   if (is_debug_types)
12246     index = &dwp_file->sections.tu_index;
12247   else
12248     index = &dwp_file->sections.cu_index;
12249
12250   if (dwarf2_section_empty_p (index))
12251     return NULL;
12252   dwarf2_read_section (objfile, index);
12253
12254   index_ptr = index->buffer;
12255   index_end = index_ptr + index->size;
12256
12257   version = read_4_bytes (dbfd, index_ptr);
12258   index_ptr += 4;
12259   if (version == 2)
12260     nr_columns = read_4_bytes (dbfd, index_ptr);
12261   else
12262     nr_columns = 0;
12263   index_ptr += 4;
12264   nr_units = read_4_bytes (dbfd, index_ptr);
12265   index_ptr += 4;
12266   nr_slots = read_4_bytes (dbfd, index_ptr);
12267   index_ptr += 4;
12268
12269   if (version != 1 && version != 2)
12270     {
12271       error (_("Dwarf Error: unsupported DWP file version (%s)"
12272                " [in module %s]"),
12273              pulongest (version), dwp_file->name);
12274     }
12275   if (nr_slots != (nr_slots & -nr_slots))
12276     {
12277       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12278                " is not power of 2 [in module %s]"),
12279              pulongest (nr_slots), dwp_file->name);
12280     }
12281
12282   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12283   htab->version = version;
12284   htab->nr_columns = nr_columns;
12285   htab->nr_units = nr_units;
12286   htab->nr_slots = nr_slots;
12287   htab->hash_table = index_ptr;
12288   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12289
12290   /* Exit early if the table is empty.  */
12291   if (nr_slots == 0 || nr_units == 0
12292       || (version == 2 && nr_columns == 0))
12293     {
12294       /* All must be zero.  */
12295       if (nr_slots != 0 || nr_units != 0
12296           || (version == 2 && nr_columns != 0))
12297         {
12298           complaint (&symfile_complaints,
12299                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12300                        " all zero [in modules %s]"),
12301                      dwp_file->name);
12302         }
12303       return htab;
12304     }
12305
12306   if (version == 1)
12307     {
12308       htab->section_pool.v1.indices =
12309         htab->unit_table + sizeof (uint32_t) * nr_slots;
12310       /* It's harder to decide whether the section is too small in v1.
12311          V1 is deprecated anyway so we punt.  */
12312     }
12313   else
12314     {
12315       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12316       int *ids = htab->section_pool.v2.section_ids;
12317       /* Reverse map for error checking.  */
12318       int ids_seen[DW_SECT_MAX + 1];
12319       int i;
12320
12321       if (nr_columns < 2)
12322         {
12323           error (_("Dwarf Error: bad DWP hash table, too few columns"
12324                    " in section table [in module %s]"),
12325                  dwp_file->name);
12326         }
12327       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12328         {
12329           error (_("Dwarf Error: bad DWP hash table, too many columns"
12330                    " in section table [in module %s]"),
12331                  dwp_file->name);
12332         }
12333       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12334       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12335       for (i = 0; i < nr_columns; ++i)
12336         {
12337           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12338
12339           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12340             {
12341               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12342                        " in section table [in module %s]"),
12343                      id, dwp_file->name);
12344             }
12345           if (ids_seen[id] != -1)
12346             {
12347               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12348                        " id %d in section table [in module %s]"),
12349                      id, dwp_file->name);
12350             }
12351           ids_seen[id] = i;
12352           ids[i] = id;
12353         }
12354       /* Must have exactly one info or types section.  */
12355       if (((ids_seen[DW_SECT_INFO] != -1)
12356            + (ids_seen[DW_SECT_TYPES] != -1))
12357           != 1)
12358         {
12359           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12360                    " DWO info/types section [in module %s]"),
12361                  dwp_file->name);
12362         }
12363       /* Must have an abbrev section.  */
12364       if (ids_seen[DW_SECT_ABBREV] == -1)
12365         {
12366           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12367                    " section [in module %s]"),
12368                  dwp_file->name);
12369         }
12370       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12371       htab->section_pool.v2.sizes =
12372         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12373                                          * nr_units * nr_columns);
12374       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12375                                           * nr_units * nr_columns))
12376           > index_end)
12377         {
12378           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12379                    " [in module %s]"),
12380                  dwp_file->name);
12381         }
12382     }
12383
12384   return htab;
12385 }
12386
12387 /* Update SECTIONS with the data from SECTP.
12388
12389    This function is like the other "locate" section routines that are
12390    passed to bfd_map_over_sections, but in this context the sections to
12391    read comes from the DWP V1 hash table, not the full ELF section table.
12392
12393    The result is non-zero for success, or zero if an error was found.  */
12394
12395 static int
12396 locate_v1_virtual_dwo_sections (asection *sectp,
12397                                 struct virtual_v1_dwo_sections *sections)
12398 {
12399   const struct dwop_section_names *names = &dwop_section_names;
12400
12401   if (section_is_p (sectp->name, &names->abbrev_dwo))
12402     {
12403       /* There can be only one.  */
12404       if (sections->abbrev.s.section != NULL)
12405         return 0;
12406       sections->abbrev.s.section = sectp;
12407       sections->abbrev.size = bfd_get_section_size (sectp);
12408     }
12409   else if (section_is_p (sectp->name, &names->info_dwo)
12410            || section_is_p (sectp->name, &names->types_dwo))
12411     {
12412       /* There can be only one.  */
12413       if (sections->info_or_types.s.section != NULL)
12414         return 0;
12415       sections->info_or_types.s.section = sectp;
12416       sections->info_or_types.size = bfd_get_section_size (sectp);
12417     }
12418   else if (section_is_p (sectp->name, &names->line_dwo))
12419     {
12420       /* There can be only one.  */
12421       if (sections->line.s.section != NULL)
12422         return 0;
12423       sections->line.s.section = sectp;
12424       sections->line.size = bfd_get_section_size (sectp);
12425     }
12426   else if (section_is_p (sectp->name, &names->loc_dwo))
12427     {
12428       /* There can be only one.  */
12429       if (sections->loc.s.section != NULL)
12430         return 0;
12431       sections->loc.s.section = sectp;
12432       sections->loc.size = bfd_get_section_size (sectp);
12433     }
12434   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12435     {
12436       /* There can be only one.  */
12437       if (sections->macinfo.s.section != NULL)
12438         return 0;
12439       sections->macinfo.s.section = sectp;
12440       sections->macinfo.size = bfd_get_section_size (sectp);
12441     }
12442   else if (section_is_p (sectp->name, &names->macro_dwo))
12443     {
12444       /* There can be only one.  */
12445       if (sections->macro.s.section != NULL)
12446         return 0;
12447       sections->macro.s.section = sectp;
12448       sections->macro.size = bfd_get_section_size (sectp);
12449     }
12450   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12451     {
12452       /* There can be only one.  */
12453       if (sections->str_offsets.s.section != NULL)
12454         return 0;
12455       sections->str_offsets.s.section = sectp;
12456       sections->str_offsets.size = bfd_get_section_size (sectp);
12457     }
12458   else
12459     {
12460       /* No other kind of section is valid.  */
12461       return 0;
12462     }
12463
12464   return 1;
12465 }
12466
12467 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12468    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12469    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12470    This is for DWP version 1 files.  */
12471
12472 static struct dwo_unit *
12473 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12474                            struct dwp_file *dwp_file,
12475                            uint32_t unit_index,
12476                            const char *comp_dir,
12477                            ULONGEST signature, int is_debug_types)
12478 {
12479   struct objfile *objfile = dwarf2_per_objfile->objfile;
12480   const struct dwp_hash_table *dwp_htab =
12481     is_debug_types ? dwp_file->tus : dwp_file->cus;
12482   bfd *dbfd = dwp_file->dbfd;
12483   const char *kind = is_debug_types ? "TU" : "CU";
12484   struct dwo_file *dwo_file;
12485   struct dwo_unit *dwo_unit;
12486   struct virtual_v1_dwo_sections sections;
12487   void **dwo_file_slot;
12488   int i;
12489
12490   gdb_assert (dwp_file->version == 1);
12491
12492   if (dwarf_read_debug)
12493     {
12494       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12495                           kind,
12496                           pulongest (unit_index), hex_string (signature),
12497                           dwp_file->name);
12498     }
12499
12500   /* Fetch the sections of this DWO unit.
12501      Put a limit on the number of sections we look for so that bad data
12502      doesn't cause us to loop forever.  */
12503
12504 #define MAX_NR_V1_DWO_SECTIONS \
12505   (1 /* .debug_info or .debug_types */ \
12506    + 1 /* .debug_abbrev */ \
12507    + 1 /* .debug_line */ \
12508    + 1 /* .debug_loc */ \
12509    + 1 /* .debug_str_offsets */ \
12510    + 1 /* .debug_macro or .debug_macinfo */ \
12511    + 1 /* trailing zero */)
12512
12513   memset (&sections, 0, sizeof (sections));
12514
12515   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12516     {
12517       asection *sectp;
12518       uint32_t section_nr =
12519         read_4_bytes (dbfd,
12520                       dwp_htab->section_pool.v1.indices
12521                       + (unit_index + i) * sizeof (uint32_t));
12522
12523       if (section_nr == 0)
12524         break;
12525       if (section_nr >= dwp_file->num_sections)
12526         {
12527           error (_("Dwarf Error: bad DWP hash table, section number too large"
12528                    " [in module %s]"),
12529                  dwp_file->name);
12530         }
12531
12532       sectp = dwp_file->elf_sections[section_nr];
12533       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12534         {
12535           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12536                    " [in module %s]"),
12537                  dwp_file->name);
12538         }
12539     }
12540
12541   if (i < 2
12542       || dwarf2_section_empty_p (&sections.info_or_types)
12543       || dwarf2_section_empty_p (&sections.abbrev))
12544     {
12545       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12546                " [in module %s]"),
12547              dwp_file->name);
12548     }
12549   if (i == MAX_NR_V1_DWO_SECTIONS)
12550     {
12551       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12552                " [in module %s]"),
12553              dwp_file->name);
12554     }
12555
12556   /* It's easier for the rest of the code if we fake a struct dwo_file and
12557      have dwo_unit "live" in that.  At least for now.
12558
12559      The DWP file can be made up of a random collection of CUs and TUs.
12560      However, for each CU + set of TUs that came from the same original DWO
12561      file, we can combine them back into a virtual DWO file to save space
12562      (fewer struct dwo_file objects to allocate).  Remember that for really
12563      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12564
12565   std::string virtual_dwo_name =
12566     string_printf ("virtual-dwo/%d-%d-%d-%d",
12567                    get_section_id (&sections.abbrev),
12568                    get_section_id (&sections.line),
12569                    get_section_id (&sections.loc),
12570                    get_section_id (&sections.str_offsets));
12571   /* Can we use an existing virtual DWO file?  */
12572   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12573                                         virtual_dwo_name.c_str (),
12574                                         comp_dir);
12575   /* Create one if necessary.  */
12576   if (*dwo_file_slot == NULL)
12577     {
12578       if (dwarf_read_debug)
12579         {
12580           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12581                               virtual_dwo_name.c_str ());
12582         }
12583       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12584       dwo_file->dwo_name
12585         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12586                                         virtual_dwo_name.c_str (),
12587                                         virtual_dwo_name.size ());
12588       dwo_file->comp_dir = comp_dir;
12589       dwo_file->sections.abbrev = sections.abbrev;
12590       dwo_file->sections.line = sections.line;
12591       dwo_file->sections.loc = sections.loc;
12592       dwo_file->sections.macinfo = sections.macinfo;
12593       dwo_file->sections.macro = sections.macro;
12594       dwo_file->sections.str_offsets = sections.str_offsets;
12595       /* The "str" section is global to the entire DWP file.  */
12596       dwo_file->sections.str = dwp_file->sections.str;
12597       /* The info or types section is assigned below to dwo_unit,
12598          there's no need to record it in dwo_file.
12599          Also, we can't simply record type sections in dwo_file because
12600          we record a pointer into the vector in dwo_unit.  As we collect more
12601          types we'll grow the vector and eventually have to reallocate space
12602          for it, invalidating all copies of pointers into the previous
12603          contents.  */
12604       *dwo_file_slot = dwo_file;
12605     }
12606   else
12607     {
12608       if (dwarf_read_debug)
12609         {
12610           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12611                               virtual_dwo_name.c_str ());
12612         }
12613       dwo_file = (struct dwo_file *) *dwo_file_slot;
12614     }
12615
12616   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12617   dwo_unit->dwo_file = dwo_file;
12618   dwo_unit->signature = signature;
12619   dwo_unit->section =
12620     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12621   *dwo_unit->section = sections.info_or_types;
12622   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12623
12624   return dwo_unit;
12625 }
12626
12627 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12628    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12629    piece within that section used by a TU/CU, return a virtual section
12630    of just that piece.  */
12631
12632 static struct dwarf2_section_info
12633 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12634                        struct dwarf2_section_info *section,
12635                        bfd_size_type offset, bfd_size_type size)
12636 {
12637   struct dwarf2_section_info result;
12638   asection *sectp;
12639
12640   gdb_assert (section != NULL);
12641   gdb_assert (!section->is_virtual);
12642
12643   memset (&result, 0, sizeof (result));
12644   result.s.containing_section = section;
12645   result.is_virtual = 1;
12646
12647   if (size == 0)
12648     return result;
12649
12650   sectp = get_section_bfd_section (section);
12651
12652   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12653      bounds of the real section.  This is a pretty-rare event, so just
12654      flag an error (easier) instead of a warning and trying to cope.  */
12655   if (sectp == NULL
12656       || offset + size > bfd_get_section_size (sectp))
12657     {
12658       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12659                " in section %s [in module %s]"),
12660              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12661              objfile_name (dwarf2_per_objfile->objfile));
12662     }
12663
12664   result.virtual_offset = offset;
12665   result.size = size;
12666   return result;
12667 }
12668
12669 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12670    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12671    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12672    This is for DWP version 2 files.  */
12673
12674 static struct dwo_unit *
12675 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12676                            struct dwp_file *dwp_file,
12677                            uint32_t unit_index,
12678                            const char *comp_dir,
12679                            ULONGEST signature, int is_debug_types)
12680 {
12681   struct objfile *objfile = dwarf2_per_objfile->objfile;
12682   const struct dwp_hash_table *dwp_htab =
12683     is_debug_types ? dwp_file->tus : dwp_file->cus;
12684   bfd *dbfd = dwp_file->dbfd;
12685   const char *kind = is_debug_types ? "TU" : "CU";
12686   struct dwo_file *dwo_file;
12687   struct dwo_unit *dwo_unit;
12688   struct virtual_v2_dwo_sections sections;
12689   void **dwo_file_slot;
12690   int i;
12691
12692   gdb_assert (dwp_file->version == 2);
12693
12694   if (dwarf_read_debug)
12695     {
12696       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12697                           kind,
12698                           pulongest (unit_index), hex_string (signature),
12699                           dwp_file->name);
12700     }
12701
12702   /* Fetch the section offsets of this DWO unit.  */
12703
12704   memset (&sections, 0, sizeof (sections));
12705
12706   for (i = 0; i < dwp_htab->nr_columns; ++i)
12707     {
12708       uint32_t offset = read_4_bytes (dbfd,
12709                                       dwp_htab->section_pool.v2.offsets
12710                                       + (((unit_index - 1) * dwp_htab->nr_columns
12711                                           + i)
12712                                          * sizeof (uint32_t)));
12713       uint32_t size = read_4_bytes (dbfd,
12714                                     dwp_htab->section_pool.v2.sizes
12715                                     + (((unit_index - 1) * dwp_htab->nr_columns
12716                                         + i)
12717                                        * sizeof (uint32_t)));
12718
12719       switch (dwp_htab->section_pool.v2.section_ids[i])
12720         {
12721         case DW_SECT_INFO:
12722         case DW_SECT_TYPES:
12723           sections.info_or_types_offset = offset;
12724           sections.info_or_types_size = size;
12725           break;
12726         case DW_SECT_ABBREV:
12727           sections.abbrev_offset = offset;
12728           sections.abbrev_size = size;
12729           break;
12730         case DW_SECT_LINE:
12731           sections.line_offset = offset;
12732           sections.line_size = size;
12733           break;
12734         case DW_SECT_LOC:
12735           sections.loc_offset = offset;
12736           sections.loc_size = size;
12737           break;
12738         case DW_SECT_STR_OFFSETS:
12739           sections.str_offsets_offset = offset;
12740           sections.str_offsets_size = size;
12741           break;
12742         case DW_SECT_MACINFO:
12743           sections.macinfo_offset = offset;
12744           sections.macinfo_size = size;
12745           break;
12746         case DW_SECT_MACRO:
12747           sections.macro_offset = offset;
12748           sections.macro_size = size;
12749           break;
12750         }
12751     }
12752
12753   /* It's easier for the rest of the code if we fake a struct dwo_file and
12754      have dwo_unit "live" in that.  At least for now.
12755
12756      The DWP file can be made up of a random collection of CUs and TUs.
12757      However, for each CU + set of TUs that came from the same original DWO
12758      file, we can combine them back into a virtual DWO file to save space
12759      (fewer struct dwo_file objects to allocate).  Remember that for really
12760      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12761
12762   std::string virtual_dwo_name =
12763     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12764                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12765                    (long) (sections.line_size ? sections.line_offset : 0),
12766                    (long) (sections.loc_size ? sections.loc_offset : 0),
12767                    (long) (sections.str_offsets_size
12768                            ? sections.str_offsets_offset : 0));
12769   /* Can we use an existing virtual DWO file?  */
12770   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12771                                         virtual_dwo_name.c_str (),
12772                                         comp_dir);
12773   /* Create one if necessary.  */
12774   if (*dwo_file_slot == NULL)
12775     {
12776       if (dwarf_read_debug)
12777         {
12778           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12779                               virtual_dwo_name.c_str ());
12780         }
12781       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12782       dwo_file->dwo_name
12783         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12784                                         virtual_dwo_name.c_str (),
12785                                         virtual_dwo_name.size ());
12786       dwo_file->comp_dir = comp_dir;
12787       dwo_file->sections.abbrev =
12788         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12789                                sections.abbrev_offset, sections.abbrev_size);
12790       dwo_file->sections.line =
12791         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12792                                sections.line_offset, sections.line_size);
12793       dwo_file->sections.loc =
12794         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12795                                sections.loc_offset, sections.loc_size);
12796       dwo_file->sections.macinfo =
12797         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12798                                sections.macinfo_offset, sections.macinfo_size);
12799       dwo_file->sections.macro =
12800         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12801                                sections.macro_offset, sections.macro_size);
12802       dwo_file->sections.str_offsets =
12803         create_dwp_v2_section (dwarf2_per_objfile,
12804                                &dwp_file->sections.str_offsets,
12805                                sections.str_offsets_offset,
12806                                sections.str_offsets_size);
12807       /* The "str" section is global to the entire DWP file.  */
12808       dwo_file->sections.str = dwp_file->sections.str;
12809       /* The info or types section is assigned below to dwo_unit,
12810          there's no need to record it in dwo_file.
12811          Also, we can't simply record type sections in dwo_file because
12812          we record a pointer into the vector in dwo_unit.  As we collect more
12813          types we'll grow the vector and eventually have to reallocate space
12814          for it, invalidating all copies of pointers into the previous
12815          contents.  */
12816       *dwo_file_slot = dwo_file;
12817     }
12818   else
12819     {
12820       if (dwarf_read_debug)
12821         {
12822           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12823                               virtual_dwo_name.c_str ());
12824         }
12825       dwo_file = (struct dwo_file *) *dwo_file_slot;
12826     }
12827
12828   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12829   dwo_unit->dwo_file = dwo_file;
12830   dwo_unit->signature = signature;
12831   dwo_unit->section =
12832     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12833   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12834                                               is_debug_types
12835                                               ? &dwp_file->sections.types
12836                                               : &dwp_file->sections.info,
12837                                               sections.info_or_types_offset,
12838                                               sections.info_or_types_size);
12839   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12840
12841   return dwo_unit;
12842 }
12843
12844 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12845    Returns NULL if the signature isn't found.  */
12846
12847 static struct dwo_unit *
12848 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12849                         struct dwp_file *dwp_file, const char *comp_dir,
12850                         ULONGEST signature, int is_debug_types)
12851 {
12852   const struct dwp_hash_table *dwp_htab =
12853     is_debug_types ? dwp_file->tus : dwp_file->cus;
12854   bfd *dbfd = dwp_file->dbfd;
12855   uint32_t mask = dwp_htab->nr_slots - 1;
12856   uint32_t hash = signature & mask;
12857   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12858   unsigned int i;
12859   void **slot;
12860   struct dwo_unit find_dwo_cu;
12861
12862   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12863   find_dwo_cu.signature = signature;
12864   slot = htab_find_slot (is_debug_types
12865                          ? dwp_file->loaded_tus
12866                          : dwp_file->loaded_cus,
12867                          &find_dwo_cu, INSERT);
12868
12869   if (*slot != NULL)
12870     return (struct dwo_unit *) *slot;
12871
12872   /* Use a for loop so that we don't loop forever on bad debug info.  */
12873   for (i = 0; i < dwp_htab->nr_slots; ++i)
12874     {
12875       ULONGEST signature_in_table;
12876
12877       signature_in_table =
12878         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12879       if (signature_in_table == signature)
12880         {
12881           uint32_t unit_index =
12882             read_4_bytes (dbfd,
12883                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12884
12885           if (dwp_file->version == 1)
12886             {
12887               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12888                                                  dwp_file, unit_index,
12889                                                  comp_dir, signature,
12890                                                  is_debug_types);
12891             }
12892           else
12893             {
12894               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12895                                                  dwp_file, unit_index,
12896                                                  comp_dir, signature,
12897                                                  is_debug_types);
12898             }
12899           return (struct dwo_unit *) *slot;
12900         }
12901       if (signature_in_table == 0)
12902         return NULL;
12903       hash = (hash + hash2) & mask;
12904     }
12905
12906   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12907            " [in module %s]"),
12908          dwp_file->name);
12909 }
12910
12911 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12912    Open the file specified by FILE_NAME and hand it off to BFD for
12913    preliminary analysis.  Return a newly initialized bfd *, which
12914    includes a canonicalized copy of FILE_NAME.
12915    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12916    SEARCH_CWD is true if the current directory is to be searched.
12917    It will be searched before debug-file-directory.
12918    If successful, the file is added to the bfd include table of the
12919    objfile's bfd (see gdb_bfd_record_inclusion).
12920    If unable to find/open the file, return NULL.
12921    NOTE: This function is derived from symfile_bfd_open.  */
12922
12923 static gdb_bfd_ref_ptr
12924 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12925                     const char *file_name, int is_dwp, int search_cwd)
12926 {
12927   int desc;
12928   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12929      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12930      to debug_file_directory.  */
12931   const char *search_path;
12932   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12933
12934   gdb::unique_xmalloc_ptr<char> search_path_holder;
12935   if (search_cwd)
12936     {
12937       if (*debug_file_directory != '\0')
12938         {
12939           search_path_holder.reset (concat (".", dirname_separator_string,
12940                                             debug_file_directory,
12941                                             (char *) NULL));
12942           search_path = search_path_holder.get ();
12943         }
12944       else
12945         search_path = ".";
12946     }
12947   else
12948     search_path = debug_file_directory;
12949
12950   openp_flags flags = OPF_RETURN_REALPATH;
12951   if (is_dwp)
12952     flags |= OPF_SEARCH_IN_PATH;
12953
12954   gdb::unique_xmalloc_ptr<char> absolute_name;
12955   desc = openp (search_path, flags, file_name,
12956                 O_RDONLY | O_BINARY, &absolute_name);
12957   if (desc < 0)
12958     return NULL;
12959
12960   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12961                                          gnutarget, desc));
12962   if (sym_bfd == NULL)
12963     return NULL;
12964   bfd_set_cacheable (sym_bfd.get (), 1);
12965
12966   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12967     return NULL;
12968
12969   /* Success.  Record the bfd as having been included by the objfile's bfd.
12970      This is important because things like demangled_names_hash lives in the
12971      objfile's per_bfd space and may have references to things like symbol
12972      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12973   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12974
12975   return sym_bfd;
12976 }
12977
12978 /* Try to open DWO file FILE_NAME.
12979    COMP_DIR is the DW_AT_comp_dir attribute.
12980    The result is the bfd handle of the file.
12981    If there is a problem finding or opening the file, return NULL.
12982    Upon success, the canonicalized path of the file is stored in the bfd,
12983    same as symfile_bfd_open.  */
12984
12985 static gdb_bfd_ref_ptr
12986 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12987                const char *file_name, const char *comp_dir)
12988 {
12989   if (IS_ABSOLUTE_PATH (file_name))
12990     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12991                                0 /*is_dwp*/, 0 /*search_cwd*/);
12992
12993   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12994
12995   if (comp_dir != NULL)
12996     {
12997       char *path_to_try = concat (comp_dir, SLASH_STRING,
12998                                   file_name, (char *) NULL);
12999
13000       /* NOTE: If comp_dir is a relative path, this will also try the
13001          search path, which seems useful.  */
13002       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
13003                                                 path_to_try,
13004                                                 0 /*is_dwp*/,
13005                                                 1 /*search_cwd*/));
13006       xfree (path_to_try);
13007       if (abfd != NULL)
13008         return abfd;
13009     }
13010
13011   /* That didn't work, try debug-file-directory, which, despite its name,
13012      is a list of paths.  */
13013
13014   if (*debug_file_directory == '\0')
13015     return NULL;
13016
13017   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13018                              0 /*is_dwp*/, 1 /*search_cwd*/);
13019 }
13020
13021 /* This function is mapped across the sections and remembers the offset and
13022    size of each of the DWO debugging sections we are interested in.  */
13023
13024 static void
13025 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13026 {
13027   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13028   const struct dwop_section_names *names = &dwop_section_names;
13029
13030   if (section_is_p (sectp->name, &names->abbrev_dwo))
13031     {
13032       dwo_sections->abbrev.s.section = sectp;
13033       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13034     }
13035   else if (section_is_p (sectp->name, &names->info_dwo))
13036     {
13037       dwo_sections->info.s.section = sectp;
13038       dwo_sections->info.size = bfd_get_section_size (sectp);
13039     }
13040   else if (section_is_p (sectp->name, &names->line_dwo))
13041     {
13042       dwo_sections->line.s.section = sectp;
13043       dwo_sections->line.size = bfd_get_section_size (sectp);
13044     }
13045   else if (section_is_p (sectp->name, &names->loc_dwo))
13046     {
13047       dwo_sections->loc.s.section = sectp;
13048       dwo_sections->loc.size = bfd_get_section_size (sectp);
13049     }
13050   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13051     {
13052       dwo_sections->macinfo.s.section = sectp;
13053       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13054     }
13055   else if (section_is_p (sectp->name, &names->macro_dwo))
13056     {
13057       dwo_sections->macro.s.section = sectp;
13058       dwo_sections->macro.size = bfd_get_section_size (sectp);
13059     }
13060   else if (section_is_p (sectp->name, &names->str_dwo))
13061     {
13062       dwo_sections->str.s.section = sectp;
13063       dwo_sections->str.size = bfd_get_section_size (sectp);
13064     }
13065   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13066     {
13067       dwo_sections->str_offsets.s.section = sectp;
13068       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13069     }
13070   else if (section_is_p (sectp->name, &names->types_dwo))
13071     {
13072       struct dwarf2_section_info type_section;
13073
13074       memset (&type_section, 0, sizeof (type_section));
13075       type_section.s.section = sectp;
13076       type_section.size = bfd_get_section_size (sectp);
13077       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13078                      &type_section);
13079     }
13080 }
13081
13082 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13083    by PER_CU.  This is for the non-DWP case.
13084    The result is NULL if DWO_NAME can't be found.  */
13085
13086 static struct dwo_file *
13087 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13088                         const char *dwo_name, const char *comp_dir)
13089 {
13090   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13091   struct objfile *objfile = dwarf2_per_objfile->objfile;
13092   struct dwo_file *dwo_file;
13093   struct cleanup *cleanups;
13094
13095   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13096   if (dbfd == NULL)
13097     {
13098       if (dwarf_read_debug)
13099         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13100       return NULL;
13101     }
13102   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13103   dwo_file->dwo_name = dwo_name;
13104   dwo_file->comp_dir = comp_dir;
13105   dwo_file->dbfd = dbfd.release ();
13106
13107   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13108   cleanup_data->dwo_file = dwo_file;
13109   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13110
13111   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13112
13113   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13114                          &dwo_file->sections);
13115
13116   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13117                          dwo_file->cus);
13118
13119   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13120                                  dwo_file->sections.types, dwo_file->tus);
13121
13122   discard_cleanups (cleanups);
13123
13124   if (dwarf_read_debug)
13125     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13126
13127   return dwo_file;
13128 }
13129
13130 /* This function is mapped across the sections and remembers the offset and
13131    size of each of the DWP debugging sections common to version 1 and 2 that
13132    we are interested in.  */
13133
13134 static void
13135 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13136                                    void *dwp_file_ptr)
13137 {
13138   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13139   const struct dwop_section_names *names = &dwop_section_names;
13140   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13141
13142   /* Record the ELF section number for later lookup: this is what the
13143      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13144   gdb_assert (elf_section_nr < dwp_file->num_sections);
13145   dwp_file->elf_sections[elf_section_nr] = sectp;
13146
13147   /* Look for specific sections that we need.  */
13148   if (section_is_p (sectp->name, &names->str_dwo))
13149     {
13150       dwp_file->sections.str.s.section = sectp;
13151       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13152     }
13153   else if (section_is_p (sectp->name, &names->cu_index))
13154     {
13155       dwp_file->sections.cu_index.s.section = sectp;
13156       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13157     }
13158   else if (section_is_p (sectp->name, &names->tu_index))
13159     {
13160       dwp_file->sections.tu_index.s.section = sectp;
13161       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13162     }
13163 }
13164
13165 /* This function is mapped across the sections and remembers the offset and
13166    size of each of the DWP version 2 debugging sections that we are interested
13167    in.  This is split into a separate function because we don't know if we
13168    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13169
13170 static void
13171 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13172 {
13173   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13174   const struct dwop_section_names *names = &dwop_section_names;
13175   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13176
13177   /* Record the ELF section number for later lookup: this is what the
13178      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13179   gdb_assert (elf_section_nr < dwp_file->num_sections);
13180   dwp_file->elf_sections[elf_section_nr] = sectp;
13181
13182   /* Look for specific sections that we need.  */
13183   if (section_is_p (sectp->name, &names->abbrev_dwo))
13184     {
13185       dwp_file->sections.abbrev.s.section = sectp;
13186       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13187     }
13188   else if (section_is_p (sectp->name, &names->info_dwo))
13189     {
13190       dwp_file->sections.info.s.section = sectp;
13191       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13192     }
13193   else if (section_is_p (sectp->name, &names->line_dwo))
13194     {
13195       dwp_file->sections.line.s.section = sectp;
13196       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13197     }
13198   else if (section_is_p (sectp->name, &names->loc_dwo))
13199     {
13200       dwp_file->sections.loc.s.section = sectp;
13201       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13202     }
13203   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13204     {
13205       dwp_file->sections.macinfo.s.section = sectp;
13206       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13207     }
13208   else if (section_is_p (sectp->name, &names->macro_dwo))
13209     {
13210       dwp_file->sections.macro.s.section = sectp;
13211       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13212     }
13213   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13214     {
13215       dwp_file->sections.str_offsets.s.section = sectp;
13216       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13217     }
13218   else if (section_is_p (sectp->name, &names->types_dwo))
13219     {
13220       dwp_file->sections.types.s.section = sectp;
13221       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13222     }
13223 }
13224
13225 /* Hash function for dwp_file loaded CUs/TUs.  */
13226
13227 static hashval_t
13228 hash_dwp_loaded_cutus (const void *item)
13229 {
13230   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13231
13232   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13233   return dwo_unit->signature;
13234 }
13235
13236 /* Equality function for dwp_file loaded CUs/TUs.  */
13237
13238 static int
13239 eq_dwp_loaded_cutus (const void *a, const void *b)
13240 {
13241   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13242   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13243
13244   return dua->signature == dub->signature;
13245 }
13246
13247 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13248
13249 static htab_t
13250 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13251 {
13252   return htab_create_alloc_ex (3,
13253                                hash_dwp_loaded_cutus,
13254                                eq_dwp_loaded_cutus,
13255                                NULL,
13256                                &objfile->objfile_obstack,
13257                                hashtab_obstack_allocate,
13258                                dummy_obstack_deallocate);
13259 }
13260
13261 /* Try to open DWP file FILE_NAME.
13262    The result is the bfd handle of the file.
13263    If there is a problem finding or opening the file, return NULL.
13264    Upon success, the canonicalized path of the file is stored in the bfd,
13265    same as symfile_bfd_open.  */
13266
13267 static gdb_bfd_ref_ptr
13268 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13269                const char *file_name)
13270 {
13271   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13272                                             1 /*is_dwp*/,
13273                                             1 /*search_cwd*/));
13274   if (abfd != NULL)
13275     return abfd;
13276
13277   /* Work around upstream bug 15652.
13278      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13279      [Whether that's a "bug" is debatable, but it is getting in our way.]
13280      We have no real idea where the dwp file is, because gdb's realpath-ing
13281      of the executable's path may have discarded the needed info.
13282      [IWBN if the dwp file name was recorded in the executable, akin to
13283      .gnu_debuglink, but that doesn't exist yet.]
13284      Strip the directory from FILE_NAME and search again.  */
13285   if (*debug_file_directory != '\0')
13286     {
13287       /* Don't implicitly search the current directory here.
13288          If the user wants to search "." to handle this case,
13289          it must be added to debug-file-directory.  */
13290       return try_open_dwop_file (dwarf2_per_objfile,
13291                                  lbasename (file_name), 1 /*is_dwp*/,
13292                                  0 /*search_cwd*/);
13293     }
13294
13295   return NULL;
13296 }
13297
13298 /* Initialize the use of the DWP file for the current objfile.
13299    By convention the name of the DWP file is ${objfile}.dwp.
13300    The result is NULL if it can't be found.  */
13301
13302 static struct dwp_file *
13303 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13304 {
13305   struct objfile *objfile = dwarf2_per_objfile->objfile;
13306   struct dwp_file *dwp_file;
13307
13308   /* Try to find first .dwp for the binary file before any symbolic links
13309      resolving.  */
13310
13311   /* If the objfile is a debug file, find the name of the real binary
13312      file and get the name of dwp file from there.  */
13313   std::string dwp_name;
13314   if (objfile->separate_debug_objfile_backlink != NULL)
13315     {
13316       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13317       const char *backlink_basename = lbasename (backlink->original_name);
13318
13319       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13320     }
13321   else
13322     dwp_name = objfile->original_name;
13323
13324   dwp_name += ".dwp";
13325
13326   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13327   if (dbfd == NULL
13328       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13329     {
13330       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13331       dwp_name = objfile_name (objfile);
13332       dwp_name += ".dwp";
13333       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13334     }
13335
13336   if (dbfd == NULL)
13337     {
13338       if (dwarf_read_debug)
13339         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13340       return NULL;
13341     }
13342   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13343   dwp_file->name = bfd_get_filename (dbfd.get ());
13344   dwp_file->dbfd = dbfd.release ();
13345
13346   /* +1: section 0 is unused */
13347   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13348   dwp_file->elf_sections =
13349     OBSTACK_CALLOC (&objfile->objfile_obstack,
13350                     dwp_file->num_sections, asection *);
13351
13352   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13353                          dwp_file);
13354
13355   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13356
13357   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13358
13359   /* The DWP file version is stored in the hash table.  Oh well.  */
13360   if (dwp_file->cus && dwp_file->tus
13361       && dwp_file->cus->version != dwp_file->tus->version)
13362     {
13363       /* Technically speaking, we should try to limp along, but this is
13364          pretty bizarre.  We use pulongest here because that's the established
13365          portability solution (e.g, we cannot use %u for uint32_t).  */
13366       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13367                " TU version %s [in DWP file %s]"),
13368              pulongest (dwp_file->cus->version),
13369              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13370     }
13371
13372   if (dwp_file->cus)
13373     dwp_file->version = dwp_file->cus->version;
13374   else if (dwp_file->tus)
13375     dwp_file->version = dwp_file->tus->version;
13376   else
13377     dwp_file->version = 2;
13378
13379   if (dwp_file->version == 2)
13380     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13381                            dwp_file);
13382
13383   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13384   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13385
13386   if (dwarf_read_debug)
13387     {
13388       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13389       fprintf_unfiltered (gdb_stdlog,
13390                           "    %s CUs, %s TUs\n",
13391                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13392                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13393     }
13394
13395   return dwp_file;
13396 }
13397
13398 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13399
13400 static struct dwp_file *
13401 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13402 {
13403   if (! dwarf2_per_objfile->dwp_checked)
13404     {
13405       dwarf2_per_objfile->dwp_file
13406         = open_and_init_dwp_file (dwarf2_per_objfile);
13407       dwarf2_per_objfile->dwp_checked = 1;
13408     }
13409   return dwarf2_per_objfile->dwp_file;
13410 }
13411
13412 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13413    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13414    or in the DWP file for the objfile, referenced by THIS_UNIT.
13415    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13416    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13417
13418    This is called, for example, when wanting to read a variable with a
13419    complex location.  Therefore we don't want to do file i/o for every call.
13420    Therefore we don't want to look for a DWO file on every call.
13421    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13422    then we check if we've already seen DWO_NAME, and only THEN do we check
13423    for a DWO file.
13424
13425    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13426    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13427
13428 static struct dwo_unit *
13429 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13430                  const char *dwo_name, const char *comp_dir,
13431                  ULONGEST signature, int is_debug_types)
13432 {
13433   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13434   struct objfile *objfile = dwarf2_per_objfile->objfile;
13435   const char *kind = is_debug_types ? "TU" : "CU";
13436   void **dwo_file_slot;
13437   struct dwo_file *dwo_file;
13438   struct dwp_file *dwp_file;
13439
13440   /* First see if there's a DWP file.
13441      If we have a DWP file but didn't find the DWO inside it, don't
13442      look for the original DWO file.  It makes gdb behave differently
13443      depending on whether one is debugging in the build tree.  */
13444
13445   dwp_file = get_dwp_file (dwarf2_per_objfile);
13446   if (dwp_file != NULL)
13447     {
13448       const struct dwp_hash_table *dwp_htab =
13449         is_debug_types ? dwp_file->tus : dwp_file->cus;
13450
13451       if (dwp_htab != NULL)
13452         {
13453           struct dwo_unit *dwo_cutu =
13454             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13455                                     signature, is_debug_types);
13456
13457           if (dwo_cutu != NULL)
13458             {
13459               if (dwarf_read_debug)
13460                 {
13461                   fprintf_unfiltered (gdb_stdlog,
13462                                       "Virtual DWO %s %s found: @%s\n",
13463                                       kind, hex_string (signature),
13464                                       host_address_to_string (dwo_cutu));
13465                 }
13466               return dwo_cutu;
13467             }
13468         }
13469     }
13470   else
13471     {
13472       /* No DWP file, look for the DWO file.  */
13473
13474       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13475                                             dwo_name, comp_dir);
13476       if (*dwo_file_slot == NULL)
13477         {
13478           /* Read in the file and build a table of the CUs/TUs it contains.  */
13479           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13480         }
13481       /* NOTE: This will be NULL if unable to open the file.  */
13482       dwo_file = (struct dwo_file *) *dwo_file_slot;
13483
13484       if (dwo_file != NULL)
13485         {
13486           struct dwo_unit *dwo_cutu = NULL;
13487
13488           if (is_debug_types && dwo_file->tus)
13489             {
13490               struct dwo_unit find_dwo_cutu;
13491
13492               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13493               find_dwo_cutu.signature = signature;
13494               dwo_cutu
13495                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13496             }
13497           else if (!is_debug_types && dwo_file->cus)
13498             {
13499               struct dwo_unit find_dwo_cutu;
13500
13501               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13502               find_dwo_cutu.signature = signature;
13503               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13504                                                        &find_dwo_cutu);
13505             }
13506
13507           if (dwo_cutu != NULL)
13508             {
13509               if (dwarf_read_debug)
13510                 {
13511                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13512                                       kind, dwo_name, hex_string (signature),
13513                                       host_address_to_string (dwo_cutu));
13514                 }
13515               return dwo_cutu;
13516             }
13517         }
13518     }
13519
13520   /* We didn't find it.  This could mean a dwo_id mismatch, or
13521      someone deleted the DWO/DWP file, or the search path isn't set up
13522      correctly to find the file.  */
13523
13524   if (dwarf_read_debug)
13525     {
13526       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13527                           kind, dwo_name, hex_string (signature));
13528     }
13529
13530   /* This is a warning and not a complaint because it can be caused by
13531      pilot error (e.g., user accidentally deleting the DWO).  */
13532   {
13533     /* Print the name of the DWP file if we looked there, helps the user
13534        better diagnose the problem.  */
13535     std::string dwp_text;
13536
13537     if (dwp_file != NULL)
13538       dwp_text = string_printf (" [in DWP file %s]",
13539                                 lbasename (dwp_file->name));
13540
13541     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13542                " [in module %s]"),
13543              kind, dwo_name, hex_string (signature),
13544              dwp_text.c_str (),
13545              this_unit->is_debug_types ? "TU" : "CU",
13546              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13547   }
13548   return NULL;
13549 }
13550
13551 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13552    See lookup_dwo_cutu_unit for details.  */
13553
13554 static struct dwo_unit *
13555 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13556                       const char *dwo_name, const char *comp_dir,
13557                       ULONGEST signature)
13558 {
13559   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13560 }
13561
13562 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13563    See lookup_dwo_cutu_unit for details.  */
13564
13565 static struct dwo_unit *
13566 lookup_dwo_type_unit (struct signatured_type *this_tu,
13567                       const char *dwo_name, const char *comp_dir)
13568 {
13569   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13570 }
13571
13572 /* Traversal function for queue_and_load_all_dwo_tus.  */
13573
13574 static int
13575 queue_and_load_dwo_tu (void **slot, void *info)
13576 {
13577   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13578   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13579   ULONGEST signature = dwo_unit->signature;
13580   struct signatured_type *sig_type =
13581     lookup_dwo_signatured_type (per_cu->cu, signature);
13582
13583   if (sig_type != NULL)
13584     {
13585       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13586
13587       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13588          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13589          while processing PER_CU.  */
13590       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13591         load_full_type_unit (sig_cu);
13592       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13593     }
13594
13595   return 1;
13596 }
13597
13598 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13599    The DWO may have the only definition of the type, though it may not be
13600    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13601    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13602
13603 static void
13604 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13605 {
13606   struct dwo_unit *dwo_unit;
13607   struct dwo_file *dwo_file;
13608
13609   gdb_assert (!per_cu->is_debug_types);
13610   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13611   gdb_assert (per_cu->cu != NULL);
13612
13613   dwo_unit = per_cu->cu->dwo_unit;
13614   gdb_assert (dwo_unit != NULL);
13615
13616   dwo_file = dwo_unit->dwo_file;
13617   if (dwo_file->tus != NULL)
13618     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13619 }
13620
13621 /* Free all resources associated with DWO_FILE.
13622    Close the DWO file and munmap the sections.
13623    All memory should be on the objfile obstack.  */
13624
13625 static void
13626 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13627 {
13628
13629   /* Note: dbfd is NULL for virtual DWO files.  */
13630   gdb_bfd_unref (dwo_file->dbfd);
13631
13632   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13633 }
13634
13635 /* Wrapper for free_dwo_file for use in cleanups.  */
13636
13637 static void
13638 free_dwo_file_cleanup (void *arg)
13639 {
13640   struct free_dwo_file_cleanup_data *data
13641     = (struct free_dwo_file_cleanup_data *) arg;
13642   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13643
13644   free_dwo_file (data->dwo_file, objfile);
13645
13646   xfree (data);
13647 }
13648
13649 /* Traversal function for free_dwo_files.  */
13650
13651 static int
13652 free_dwo_file_from_slot (void **slot, void *info)
13653 {
13654   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13655   struct objfile *objfile = (struct objfile *) info;
13656
13657   free_dwo_file (dwo_file, objfile);
13658
13659   return 1;
13660 }
13661
13662 /* Free all resources associated with DWO_FILES.  */
13663
13664 static void
13665 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13666 {
13667   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13668 }
13669 \f
13670 /* Read in various DIEs.  */
13671
13672 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13673    Inherit only the children of the DW_AT_abstract_origin DIE not being
13674    already referenced by DW_AT_abstract_origin from the children of the
13675    current DIE.  */
13676
13677 static void
13678 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13679 {
13680   struct die_info *child_die;
13681   sect_offset *offsetp;
13682   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13683   struct die_info *origin_die;
13684   /* Iterator of the ORIGIN_DIE children.  */
13685   struct die_info *origin_child_die;
13686   struct attribute *attr;
13687   struct dwarf2_cu *origin_cu;
13688   struct pending **origin_previous_list_in_scope;
13689
13690   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13691   if (!attr)
13692     return;
13693
13694   /* Note that following die references may follow to a die in a
13695      different cu.  */
13696
13697   origin_cu = cu;
13698   origin_die = follow_die_ref (die, attr, &origin_cu);
13699
13700   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13701      symbols in.  */
13702   origin_previous_list_in_scope = origin_cu->list_in_scope;
13703   origin_cu->list_in_scope = cu->list_in_scope;
13704
13705   if (die->tag != origin_die->tag
13706       && !(die->tag == DW_TAG_inlined_subroutine
13707            && origin_die->tag == DW_TAG_subprogram))
13708     complaint (&symfile_complaints,
13709                _("DIE %s and its abstract origin %s have different tags"),
13710                sect_offset_str (die->sect_off),
13711                sect_offset_str (origin_die->sect_off));
13712
13713   std::vector<sect_offset> offsets;
13714
13715   for (child_die = die->child;
13716        child_die && child_die->tag;
13717        child_die = sibling_die (child_die))
13718     {
13719       struct die_info *child_origin_die;
13720       struct dwarf2_cu *child_origin_cu;
13721
13722       /* We are trying to process concrete instance entries:
13723          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13724          it's not relevant to our analysis here. i.e. detecting DIEs that are
13725          present in the abstract instance but not referenced in the concrete
13726          one.  */
13727       if (child_die->tag == DW_TAG_call_site
13728           || child_die->tag == DW_TAG_GNU_call_site)
13729         continue;
13730
13731       /* For each CHILD_DIE, find the corresponding child of
13732          ORIGIN_DIE.  If there is more than one layer of
13733          DW_AT_abstract_origin, follow them all; there shouldn't be,
13734          but GCC versions at least through 4.4 generate this (GCC PR
13735          40573).  */
13736       child_origin_die = child_die;
13737       child_origin_cu = cu;
13738       while (1)
13739         {
13740           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13741                               child_origin_cu);
13742           if (attr == NULL)
13743             break;
13744           child_origin_die = follow_die_ref (child_origin_die, attr,
13745                                              &child_origin_cu);
13746         }
13747
13748       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13749          counterpart may exist.  */
13750       if (child_origin_die != child_die)
13751         {
13752           if (child_die->tag != child_origin_die->tag
13753               && !(child_die->tag == DW_TAG_inlined_subroutine
13754                    && child_origin_die->tag == DW_TAG_subprogram))
13755             complaint (&symfile_complaints,
13756                        _("Child DIE %s and its abstract origin %s have "
13757                          "different tags"),
13758                        sect_offset_str (child_die->sect_off),
13759                        sect_offset_str (child_origin_die->sect_off));
13760           if (child_origin_die->parent != origin_die)
13761             complaint (&symfile_complaints,
13762                        _("Child DIE %s and its abstract origin %s have "
13763                          "different parents"),
13764                        sect_offset_str (child_die->sect_off),
13765                        sect_offset_str (child_origin_die->sect_off));
13766           else
13767             offsets.push_back (child_origin_die->sect_off);
13768         }
13769     }
13770   std::sort (offsets.begin (), offsets.end ());
13771   sect_offset *offsets_end = offsets.data () + offsets.size ();
13772   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13773     if (offsetp[-1] == *offsetp)
13774       complaint (&symfile_complaints,
13775                  _("Multiple children of DIE %s refer "
13776                    "to DIE %s as their abstract origin"),
13777                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13778
13779   offsetp = offsets.data ();
13780   origin_child_die = origin_die->child;
13781   while (origin_child_die && origin_child_die->tag)
13782     {
13783       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13784       while (offsetp < offsets_end
13785              && *offsetp < origin_child_die->sect_off)
13786         offsetp++;
13787       if (offsetp >= offsets_end
13788           || *offsetp > origin_child_die->sect_off)
13789         {
13790           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13791              Check whether we're already processing ORIGIN_CHILD_DIE.
13792              This can happen with mutually referenced abstract_origins.
13793              PR 16581.  */
13794           if (!origin_child_die->in_process)
13795             process_die (origin_child_die, origin_cu);
13796         }
13797       origin_child_die = sibling_die (origin_child_die);
13798     }
13799   origin_cu->list_in_scope = origin_previous_list_in_scope;
13800 }
13801
13802 static void
13803 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13804 {
13805   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13806   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13807   struct context_stack *newobj;
13808   CORE_ADDR lowpc;
13809   CORE_ADDR highpc;
13810   struct die_info *child_die;
13811   struct attribute *attr, *call_line, *call_file;
13812   const char *name;
13813   CORE_ADDR baseaddr;
13814   struct block *block;
13815   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13816   std::vector<struct symbol *> template_args;
13817   struct template_symbol *templ_func = NULL;
13818
13819   if (inlined_func)
13820     {
13821       /* If we do not have call site information, we can't show the
13822          caller of this inlined function.  That's too confusing, so
13823          only use the scope for local variables.  */
13824       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13825       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13826       if (call_line == NULL || call_file == NULL)
13827         {
13828           read_lexical_block_scope (die, cu);
13829           return;
13830         }
13831     }
13832
13833   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13834
13835   name = dwarf2_name (die, cu);
13836
13837   /* Ignore functions with missing or empty names.  These are actually
13838      illegal according to the DWARF standard.  */
13839   if (name == NULL)
13840     {
13841       complaint (&symfile_complaints,
13842                  _("missing name for subprogram DIE at %s"),
13843                  sect_offset_str (die->sect_off));
13844       return;
13845     }
13846
13847   /* Ignore functions with missing or invalid low and high pc attributes.  */
13848   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13849       <= PC_BOUNDS_INVALID)
13850     {
13851       attr = dwarf2_attr (die, DW_AT_external, cu);
13852       if (!attr || !DW_UNSND (attr))
13853         complaint (&symfile_complaints,
13854                    _("cannot get low and high bounds "
13855                      "for subprogram DIE at %s"),
13856                    sect_offset_str (die->sect_off));
13857       return;
13858     }
13859
13860   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13861   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13862
13863   /* If we have any template arguments, then we must allocate a
13864      different sort of symbol.  */
13865   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13866     {
13867       if (child_die->tag == DW_TAG_template_type_param
13868           || child_die->tag == DW_TAG_template_value_param)
13869         {
13870           templ_func = allocate_template_symbol (objfile);
13871           templ_func->subclass = SYMBOL_TEMPLATE;
13872           break;
13873         }
13874     }
13875
13876   newobj = push_context (0, lowpc);
13877   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13878                              (struct symbol *) templ_func);
13879
13880   /* If there is a location expression for DW_AT_frame_base, record
13881      it.  */
13882   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13883   if (attr)
13884     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13885
13886   /* If there is a location for the static link, record it.  */
13887   newobj->static_link = NULL;
13888   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13889   if (attr)
13890     {
13891       newobj->static_link
13892         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13893       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13894     }
13895
13896   cu->list_in_scope = &local_symbols;
13897
13898   if (die->child != NULL)
13899     {
13900       child_die = die->child;
13901       while (child_die && child_die->tag)
13902         {
13903           if (child_die->tag == DW_TAG_template_type_param
13904               || child_die->tag == DW_TAG_template_value_param)
13905             {
13906               struct symbol *arg = new_symbol (child_die, NULL, cu);
13907
13908               if (arg != NULL)
13909                 template_args.push_back (arg);
13910             }
13911           else
13912             process_die (child_die, cu);
13913           child_die = sibling_die (child_die);
13914         }
13915     }
13916
13917   inherit_abstract_dies (die, cu);
13918
13919   /* If we have a DW_AT_specification, we might need to import using
13920      directives from the context of the specification DIE.  See the
13921      comment in determine_prefix.  */
13922   if (cu->language == language_cplus
13923       && dwarf2_attr (die, DW_AT_specification, cu))
13924     {
13925       struct dwarf2_cu *spec_cu = cu;
13926       struct die_info *spec_die = die_specification (die, &spec_cu);
13927
13928       while (spec_die)
13929         {
13930           child_die = spec_die->child;
13931           while (child_die && child_die->tag)
13932             {
13933               if (child_die->tag == DW_TAG_imported_module)
13934                 process_die (child_die, spec_cu);
13935               child_die = sibling_die (child_die);
13936             }
13937
13938           /* In some cases, GCC generates specification DIEs that
13939              themselves contain DW_AT_specification attributes.  */
13940           spec_die = die_specification (spec_die, &spec_cu);
13941         }
13942     }
13943
13944   newobj = pop_context ();
13945   /* Make a block for the local symbols within.  */
13946   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13947                         newobj->static_link, lowpc, highpc);
13948
13949   /* For C++, set the block's scope.  */
13950   if ((cu->language == language_cplus
13951        || cu->language == language_fortran
13952        || cu->language == language_d
13953        || cu->language == language_rust)
13954       && cu->processing_has_namespace_info)
13955     block_set_scope (block, determine_prefix (die, cu),
13956                      &objfile->objfile_obstack);
13957
13958   /* If we have address ranges, record them.  */
13959   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13960
13961   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13962
13963   /* Attach template arguments to function.  */
13964   if (!template_args.empty ())
13965     {
13966       gdb_assert (templ_func != NULL);
13967
13968       templ_func->n_template_arguments = template_args.size ();
13969       templ_func->template_arguments
13970         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13971                      templ_func->n_template_arguments);
13972       memcpy (templ_func->template_arguments,
13973               template_args.data (),
13974               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13975     }
13976
13977   /* In C++, we can have functions nested inside functions (e.g., when
13978      a function declares a class that has methods).  This means that
13979      when we finish processing a function scope, we may need to go
13980      back to building a containing block's symbol lists.  */
13981   local_symbols = newobj->locals;
13982   local_using_directives = newobj->local_using_directives;
13983
13984   /* If we've finished processing a top-level function, subsequent
13985      symbols go in the file symbol list.  */
13986   if (outermost_context_p ())
13987     cu->list_in_scope = &file_symbols;
13988 }
13989
13990 /* Process all the DIES contained within a lexical block scope.  Start
13991    a new scope, process the dies, and then close the scope.  */
13992
13993 static void
13994 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13995 {
13996   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13997   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13998   struct context_stack *newobj;
13999   CORE_ADDR lowpc, highpc;
14000   struct die_info *child_die;
14001   CORE_ADDR baseaddr;
14002
14003   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14004
14005   /* Ignore blocks with missing or invalid low and high pc attributes.  */
14006   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
14007      as multiple lexical blocks?  Handling children in a sane way would
14008      be nasty.  Might be easier to properly extend generic blocks to
14009      describe ranges.  */
14010   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14011     {
14012     case PC_BOUNDS_NOT_PRESENT:
14013       /* DW_TAG_lexical_block has no attributes, process its children as if
14014          there was no wrapping by that DW_TAG_lexical_block.
14015          GCC does no longer produces such DWARF since GCC r224161.  */
14016       for (child_die = die->child;
14017            child_die != NULL && child_die->tag;
14018            child_die = sibling_die (child_die))
14019         process_die (child_die, cu);
14020       return;
14021     case PC_BOUNDS_INVALID:
14022       return;
14023     }
14024   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14025   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14026
14027   push_context (0, lowpc);
14028   if (die->child != NULL)
14029     {
14030       child_die = die->child;
14031       while (child_die && child_die->tag)
14032         {
14033           process_die (child_die, cu);
14034           child_die = sibling_die (child_die);
14035         }
14036     }
14037   inherit_abstract_dies (die, cu);
14038   newobj = pop_context ();
14039
14040   if (local_symbols != NULL || local_using_directives != NULL)
14041     {
14042       struct block *block
14043         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14044                         newobj->start_addr, highpc);
14045
14046       /* Note that recording ranges after traversing children, as we
14047          do here, means that recording a parent's ranges entails
14048          walking across all its children's ranges as they appear in
14049          the address map, which is quadratic behavior.
14050
14051          It would be nicer to record the parent's ranges before
14052          traversing its children, simply overriding whatever you find
14053          there.  But since we don't even decide whether to create a
14054          block until after we've traversed its children, that's hard
14055          to do.  */
14056       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14057     }
14058   local_symbols = newobj->locals;
14059   local_using_directives = newobj->local_using_directives;
14060 }
14061
14062 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14063
14064 static void
14065 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14066 {
14067   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14068   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14069   CORE_ADDR pc, baseaddr;
14070   struct attribute *attr;
14071   struct call_site *call_site, call_site_local;
14072   void **slot;
14073   int nparams;
14074   struct die_info *child_die;
14075
14076   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14077
14078   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14079   if (attr == NULL)
14080     {
14081       /* This was a pre-DWARF-5 GNU extension alias
14082          for DW_AT_call_return_pc.  */
14083       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14084     }
14085   if (!attr)
14086     {
14087       complaint (&symfile_complaints,
14088                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14089                    "DIE %s [in module %s]"),
14090                  sect_offset_str (die->sect_off), objfile_name (objfile));
14091       return;
14092     }
14093   pc = attr_value_as_address (attr) + baseaddr;
14094   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14095
14096   if (cu->call_site_htab == NULL)
14097     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14098                                                NULL, &objfile->objfile_obstack,
14099                                                hashtab_obstack_allocate, NULL);
14100   call_site_local.pc = pc;
14101   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14102   if (*slot != NULL)
14103     {
14104       complaint (&symfile_complaints,
14105                  _("Duplicate PC %s for DW_TAG_call_site "
14106                    "DIE %s [in module %s]"),
14107                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
14108                  objfile_name (objfile));
14109       return;
14110     }
14111
14112   /* Count parameters at the caller.  */
14113
14114   nparams = 0;
14115   for (child_die = die->child; child_die && child_die->tag;
14116        child_die = sibling_die (child_die))
14117     {
14118       if (child_die->tag != DW_TAG_call_site_parameter
14119           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14120         {
14121           complaint (&symfile_complaints,
14122                      _("Tag %d is not DW_TAG_call_site_parameter in "
14123                        "DW_TAG_call_site child DIE %s [in module %s]"),
14124                      child_die->tag, sect_offset_str (child_die->sect_off),
14125                      objfile_name (objfile));
14126           continue;
14127         }
14128
14129       nparams++;
14130     }
14131
14132   call_site
14133     = ((struct call_site *)
14134        obstack_alloc (&objfile->objfile_obstack,
14135                       sizeof (*call_site)
14136                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14137   *slot = call_site;
14138   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14139   call_site->pc = pc;
14140
14141   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14142       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14143     {
14144       struct die_info *func_die;
14145
14146       /* Skip also over DW_TAG_inlined_subroutine.  */
14147       for (func_die = die->parent;
14148            func_die && func_die->tag != DW_TAG_subprogram
14149            && func_die->tag != DW_TAG_subroutine_type;
14150            func_die = func_die->parent);
14151
14152       /* DW_AT_call_all_calls is a superset
14153          of DW_AT_call_all_tail_calls.  */
14154       if (func_die
14155           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14156           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14157           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14158           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14159         {
14160           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14161              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14162              both the initial caller containing the real return address PC and
14163              the final callee containing the current PC of a chain of tail
14164              calls do not need to have the tail call list complete.  But any
14165              function candidate for a virtual tail call frame searched via
14166              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14167              determined unambiguously.  */
14168         }
14169       else
14170         {
14171           struct type *func_type = NULL;
14172
14173           if (func_die)
14174             func_type = get_die_type (func_die, cu);
14175           if (func_type != NULL)
14176             {
14177               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14178
14179               /* Enlist this call site to the function.  */
14180               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14181               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14182             }
14183           else
14184             complaint (&symfile_complaints,
14185                        _("Cannot find function owning DW_TAG_call_site "
14186                          "DIE %s [in module %s]"),
14187                        sect_offset_str (die->sect_off), objfile_name (objfile));
14188         }
14189     }
14190
14191   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14192   if (attr == NULL)
14193     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14194   if (attr == NULL)
14195     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14196   if (attr == NULL)
14197     {
14198       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14199       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14200     }
14201   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14202   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14203     /* Keep NULL DWARF_BLOCK.  */;
14204   else if (attr_form_is_block (attr))
14205     {
14206       struct dwarf2_locexpr_baton *dlbaton;
14207
14208       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14209       dlbaton->data = DW_BLOCK (attr)->data;
14210       dlbaton->size = DW_BLOCK (attr)->size;
14211       dlbaton->per_cu = cu->per_cu;
14212
14213       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14214     }
14215   else if (attr_form_is_ref (attr))
14216     {
14217       struct dwarf2_cu *target_cu = cu;
14218       struct die_info *target_die;
14219
14220       target_die = follow_die_ref (die, attr, &target_cu);
14221       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14222       if (die_is_declaration (target_die, target_cu))
14223         {
14224           const char *target_physname;
14225
14226           /* Prefer the mangled name; otherwise compute the demangled one.  */
14227           target_physname = dw2_linkage_name (target_die, target_cu);
14228           if (target_physname == NULL)
14229             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14230           if (target_physname == NULL)
14231             complaint (&symfile_complaints,
14232                        _("DW_AT_call_target target DIE has invalid "
14233                          "physname, for referencing DIE %s [in module %s]"),
14234                        sect_offset_str (die->sect_off), objfile_name (objfile));
14235           else
14236             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14237         }
14238       else
14239         {
14240           CORE_ADDR lowpc;
14241
14242           /* DW_AT_entry_pc should be preferred.  */
14243           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14244               <= PC_BOUNDS_INVALID)
14245             complaint (&symfile_complaints,
14246                        _("DW_AT_call_target target DIE has invalid "
14247                          "low pc, for referencing DIE %s [in module %s]"),
14248                        sect_offset_str (die->sect_off), objfile_name (objfile));
14249           else
14250             {
14251               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14252               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14253             }
14254         }
14255     }
14256   else
14257     complaint (&symfile_complaints,
14258                _("DW_TAG_call_site DW_AT_call_target is neither "
14259                  "block nor reference, for DIE %s [in module %s]"),
14260                sect_offset_str (die->sect_off), objfile_name (objfile));
14261
14262   call_site->per_cu = cu->per_cu;
14263
14264   for (child_die = die->child;
14265        child_die && child_die->tag;
14266        child_die = sibling_die (child_die))
14267     {
14268       struct call_site_parameter *parameter;
14269       struct attribute *loc, *origin;
14270
14271       if (child_die->tag != DW_TAG_call_site_parameter
14272           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14273         {
14274           /* Already printed the complaint above.  */
14275           continue;
14276         }
14277
14278       gdb_assert (call_site->parameter_count < nparams);
14279       parameter = &call_site->parameter[call_site->parameter_count];
14280
14281       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14282          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14283          register is contained in DW_AT_call_value.  */
14284
14285       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14286       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14287       if (origin == NULL)
14288         {
14289           /* This was a pre-DWARF-5 GNU extension alias
14290              for DW_AT_call_parameter.  */
14291           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14292         }
14293       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14294         {
14295           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14296
14297           sect_offset sect_off
14298             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14299           if (!offset_in_cu_p (&cu->header, sect_off))
14300             {
14301               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14302                  binding can be done only inside one CU.  Such referenced DIE
14303                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14304               complaint (&symfile_complaints,
14305                          _("DW_AT_call_parameter offset is not in CU for "
14306                            "DW_TAG_call_site child DIE %s [in module %s]"),
14307                          sect_offset_str (child_die->sect_off),
14308                          objfile_name (objfile));
14309               continue;
14310             }
14311           parameter->u.param_cu_off
14312             = (cu_offset) (sect_off - cu->header.sect_off);
14313         }
14314       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14315         {
14316           complaint (&symfile_complaints,
14317                      _("No DW_FORM_block* DW_AT_location for "
14318                        "DW_TAG_call_site child DIE %s [in module %s]"),
14319                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14320           continue;
14321         }
14322       else
14323         {
14324           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14325             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14326           if (parameter->u.dwarf_reg != -1)
14327             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14328           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14329                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14330                                              &parameter->u.fb_offset))
14331             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14332           else
14333             {
14334               complaint (&symfile_complaints,
14335                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14336                            "for DW_FORM_block* DW_AT_location is supported for "
14337                            "DW_TAG_call_site child DIE %s "
14338                            "[in module %s]"),
14339                          sect_offset_str (child_die->sect_off),
14340                          objfile_name (objfile));
14341               continue;
14342             }
14343         }
14344
14345       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14346       if (attr == NULL)
14347         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14348       if (!attr_form_is_block (attr))
14349         {
14350           complaint (&symfile_complaints,
14351                      _("No DW_FORM_block* DW_AT_call_value for "
14352                        "DW_TAG_call_site child DIE %s [in module %s]"),
14353                      sect_offset_str (child_die->sect_off),
14354                      objfile_name (objfile));
14355           continue;
14356         }
14357       parameter->value = DW_BLOCK (attr)->data;
14358       parameter->value_size = DW_BLOCK (attr)->size;
14359
14360       /* Parameters are not pre-cleared by memset above.  */
14361       parameter->data_value = NULL;
14362       parameter->data_value_size = 0;
14363       call_site->parameter_count++;
14364
14365       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14366       if (attr == NULL)
14367         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14368       if (attr)
14369         {
14370           if (!attr_form_is_block (attr))
14371             complaint (&symfile_complaints,
14372                        _("No DW_FORM_block* DW_AT_call_data_value for "
14373                          "DW_TAG_call_site child DIE %s [in module %s]"),
14374                        sect_offset_str (child_die->sect_off),
14375                        objfile_name (objfile));
14376           else
14377             {
14378               parameter->data_value = DW_BLOCK (attr)->data;
14379               parameter->data_value_size = DW_BLOCK (attr)->size;
14380             }
14381         }
14382     }
14383 }
14384
14385 /* Helper function for read_variable.  If DIE represents a virtual
14386    table, then return the type of the concrete object that is
14387    associated with the virtual table.  Otherwise, return NULL.  */
14388
14389 static struct type *
14390 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14391 {
14392   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14393   if (attr == NULL)
14394     return NULL;
14395
14396   /* Find the type DIE.  */
14397   struct die_info *type_die = NULL;
14398   struct dwarf2_cu *type_cu = cu;
14399
14400   if (attr_form_is_ref (attr))
14401     type_die = follow_die_ref (die, attr, &type_cu);
14402   if (type_die == NULL)
14403     return NULL;
14404
14405   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14406     return NULL;
14407   return die_containing_type (type_die, type_cu);
14408 }
14409
14410 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14411
14412 static void
14413 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14414 {
14415   struct rust_vtable_symbol *storage = NULL;
14416
14417   if (cu->language == language_rust)
14418     {
14419       struct type *containing_type = rust_containing_type (die, cu);
14420
14421       if (containing_type != NULL)
14422         {
14423           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14424
14425           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14426                                     struct rust_vtable_symbol);
14427           initialize_objfile_symbol (storage);
14428           storage->concrete_type = containing_type;
14429           storage->subclass = SYMBOL_RUST_VTABLE;
14430         }
14431     }
14432
14433   new_symbol (die, NULL, cu, storage);
14434 }
14435
14436 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14437    reading .debug_rnglists.
14438    Callback's type should be:
14439     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14440    Return true if the attributes are present and valid, otherwise,
14441    return false.  */
14442
14443 template <typename Callback>
14444 static bool
14445 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14446                          Callback &&callback)
14447 {
14448   struct dwarf2_per_objfile *dwarf2_per_objfile
14449     = cu->per_cu->dwarf2_per_objfile;
14450   struct objfile *objfile = dwarf2_per_objfile->objfile;
14451   bfd *obfd = objfile->obfd;
14452   /* Base address selection entry.  */
14453   CORE_ADDR base;
14454   int found_base;
14455   const gdb_byte *buffer;
14456   CORE_ADDR baseaddr;
14457   bool overflow = false;
14458
14459   found_base = cu->base_known;
14460   base = cu->base_address;
14461
14462   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14463   if (offset >= dwarf2_per_objfile->rnglists.size)
14464     {
14465       complaint (&symfile_complaints,
14466                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14467                  offset);
14468       return false;
14469     }
14470   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14471
14472   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14473
14474   while (1)
14475     {
14476       /* Initialize it due to a false compiler warning.  */
14477       CORE_ADDR range_beginning = 0, range_end = 0;
14478       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14479                                  + dwarf2_per_objfile->rnglists.size);
14480       unsigned int bytes_read;
14481
14482       if (buffer == buf_end)
14483         {
14484           overflow = true;
14485           break;
14486         }
14487       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14488       switch (rlet)
14489         {
14490         case DW_RLE_end_of_list:
14491           break;
14492         case DW_RLE_base_address:
14493           if (buffer + cu->header.addr_size > buf_end)
14494             {
14495               overflow = true;
14496               break;
14497             }
14498           base = read_address (obfd, buffer, cu, &bytes_read);
14499           found_base = 1;
14500           buffer += bytes_read;
14501           break;
14502         case DW_RLE_start_length:
14503           if (buffer + cu->header.addr_size > buf_end)
14504             {
14505               overflow = true;
14506               break;
14507             }
14508           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14509           buffer += bytes_read;
14510           range_end = (range_beginning
14511                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14512           buffer += bytes_read;
14513           if (buffer > buf_end)
14514             {
14515               overflow = true;
14516               break;
14517             }
14518           break;
14519         case DW_RLE_offset_pair:
14520           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14521           buffer += bytes_read;
14522           if (buffer > buf_end)
14523             {
14524               overflow = true;
14525               break;
14526             }
14527           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14528           buffer += bytes_read;
14529           if (buffer > buf_end)
14530             {
14531               overflow = true;
14532               break;
14533             }
14534           break;
14535         case DW_RLE_start_end:
14536           if (buffer + 2 * cu->header.addr_size > buf_end)
14537             {
14538               overflow = true;
14539               break;
14540             }
14541           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14542           buffer += bytes_read;
14543           range_end = read_address (obfd, buffer, cu, &bytes_read);
14544           buffer += bytes_read;
14545           break;
14546         default:
14547           complaint (&symfile_complaints,
14548                      _("Invalid .debug_rnglists data (no base address)"));
14549           return false;
14550         }
14551       if (rlet == DW_RLE_end_of_list || overflow)
14552         break;
14553       if (rlet == DW_RLE_base_address)
14554         continue;
14555
14556       if (!found_base)
14557         {
14558           /* We have no valid base address for the ranges
14559              data.  */
14560           complaint (&symfile_complaints,
14561                      _("Invalid .debug_rnglists data (no base address)"));
14562           return false;
14563         }
14564
14565       if (range_beginning > range_end)
14566         {
14567           /* Inverted range entries are invalid.  */
14568           complaint (&symfile_complaints,
14569                      _("Invalid .debug_rnglists data (inverted range)"));
14570           return false;
14571         }
14572
14573       /* Empty range entries have no effect.  */
14574       if (range_beginning == range_end)
14575         continue;
14576
14577       range_beginning += base;
14578       range_end += base;
14579
14580       /* A not-uncommon case of bad debug info.
14581          Don't pollute the addrmap with bad data.  */
14582       if (range_beginning + baseaddr == 0
14583           && !dwarf2_per_objfile->has_section_at_zero)
14584         {
14585           complaint (&symfile_complaints,
14586                      _(".debug_rnglists entry has start address of zero"
14587                        " [in module %s]"), objfile_name (objfile));
14588           continue;
14589         }
14590
14591       callback (range_beginning, range_end);
14592     }
14593
14594   if (overflow)
14595     {
14596       complaint (&symfile_complaints,
14597                  _("Offset %d is not terminated "
14598                    "for DW_AT_ranges attribute"),
14599                  offset);
14600       return false;
14601     }
14602
14603   return true;
14604 }
14605
14606 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14607    Callback's type should be:
14608     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14609    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14610
14611 template <typename Callback>
14612 static int
14613 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14614                        Callback &&callback)
14615 {
14616   struct dwarf2_per_objfile *dwarf2_per_objfile
14617       = cu->per_cu->dwarf2_per_objfile;
14618   struct objfile *objfile = dwarf2_per_objfile->objfile;
14619   struct comp_unit_head *cu_header = &cu->header;
14620   bfd *obfd = objfile->obfd;
14621   unsigned int addr_size = cu_header->addr_size;
14622   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14623   /* Base address selection entry.  */
14624   CORE_ADDR base;
14625   int found_base;
14626   unsigned int dummy;
14627   const gdb_byte *buffer;
14628   CORE_ADDR baseaddr;
14629
14630   if (cu_header->version >= 5)
14631     return dwarf2_rnglists_process (offset, cu, callback);
14632
14633   found_base = cu->base_known;
14634   base = cu->base_address;
14635
14636   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14637   if (offset >= dwarf2_per_objfile->ranges.size)
14638     {
14639       complaint (&symfile_complaints,
14640                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14641                  offset);
14642       return 0;
14643     }
14644   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14645
14646   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14647
14648   while (1)
14649     {
14650       CORE_ADDR range_beginning, range_end;
14651
14652       range_beginning = read_address (obfd, buffer, cu, &dummy);
14653       buffer += addr_size;
14654       range_end = read_address (obfd, buffer, cu, &dummy);
14655       buffer += addr_size;
14656       offset += 2 * addr_size;
14657
14658       /* An end of list marker is a pair of zero addresses.  */
14659       if (range_beginning == 0 && range_end == 0)
14660         /* Found the end of list entry.  */
14661         break;
14662
14663       /* Each base address selection entry is a pair of 2 values.
14664          The first is the largest possible address, the second is
14665          the base address.  Check for a base address here.  */
14666       if ((range_beginning & mask) == mask)
14667         {
14668           /* If we found the largest possible address, then we already
14669              have the base address in range_end.  */
14670           base = range_end;
14671           found_base = 1;
14672           continue;
14673         }
14674
14675       if (!found_base)
14676         {
14677           /* We have no valid base address for the ranges
14678              data.  */
14679           complaint (&symfile_complaints,
14680                      _("Invalid .debug_ranges data (no base address)"));
14681           return 0;
14682         }
14683
14684       if (range_beginning > range_end)
14685         {
14686           /* Inverted range entries are invalid.  */
14687           complaint (&symfile_complaints,
14688                      _("Invalid .debug_ranges data (inverted range)"));
14689           return 0;
14690         }
14691
14692       /* Empty range entries have no effect.  */
14693       if (range_beginning == range_end)
14694         continue;
14695
14696       range_beginning += base;
14697       range_end += base;
14698
14699       /* A not-uncommon case of bad debug info.
14700          Don't pollute the addrmap with bad data.  */
14701       if (range_beginning + baseaddr == 0
14702           && !dwarf2_per_objfile->has_section_at_zero)
14703         {
14704           complaint (&symfile_complaints,
14705                      _(".debug_ranges entry has start address of zero"
14706                        " [in module %s]"), objfile_name (objfile));
14707           continue;
14708         }
14709
14710       callback (range_beginning, range_end);
14711     }
14712
14713   return 1;
14714 }
14715
14716 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14717    Return 1 if the attributes are present and valid, otherwise, return 0.
14718    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14719
14720 static int
14721 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14722                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14723                     struct partial_symtab *ranges_pst)
14724 {
14725   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14726   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14727   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14728                                        SECT_OFF_TEXT (objfile));
14729   int low_set = 0;
14730   CORE_ADDR low = 0;
14731   CORE_ADDR high = 0;
14732   int retval;
14733
14734   retval = dwarf2_ranges_process (offset, cu,
14735     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14736     {
14737       if (ranges_pst != NULL)
14738         {
14739           CORE_ADDR lowpc;
14740           CORE_ADDR highpc;
14741
14742           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14743                                               range_beginning + baseaddr);
14744           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14745                                                range_end + baseaddr);
14746           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14747                              ranges_pst);
14748         }
14749
14750       /* FIXME: This is recording everything as a low-high
14751          segment of consecutive addresses.  We should have a
14752          data structure for discontiguous block ranges
14753          instead.  */
14754       if (! low_set)
14755         {
14756           low = range_beginning;
14757           high = range_end;
14758           low_set = 1;
14759         }
14760       else
14761         {
14762           if (range_beginning < low)
14763             low = range_beginning;
14764           if (range_end > high)
14765             high = range_end;
14766         }
14767     });
14768   if (!retval)
14769     return 0;
14770
14771   if (! low_set)
14772     /* If the first entry is an end-of-list marker, the range
14773        describes an empty scope, i.e. no instructions.  */
14774     return 0;
14775
14776   if (low_return)
14777     *low_return = low;
14778   if (high_return)
14779     *high_return = high;
14780   return 1;
14781 }
14782
14783 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14784    definition for the return value.  *LOWPC and *HIGHPC are set iff
14785    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14786
14787 static enum pc_bounds_kind
14788 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14789                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14790                       struct partial_symtab *pst)
14791 {
14792   struct dwarf2_per_objfile *dwarf2_per_objfile
14793     = cu->per_cu->dwarf2_per_objfile;
14794   struct attribute *attr;
14795   struct attribute *attr_high;
14796   CORE_ADDR low = 0;
14797   CORE_ADDR high = 0;
14798   enum pc_bounds_kind ret;
14799
14800   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14801   if (attr_high)
14802     {
14803       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14804       if (attr)
14805         {
14806           low = attr_value_as_address (attr);
14807           high = attr_value_as_address (attr_high);
14808           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14809             high += low;
14810         }
14811       else
14812         /* Found high w/o low attribute.  */
14813         return PC_BOUNDS_INVALID;
14814
14815       /* Found consecutive range of addresses.  */
14816       ret = PC_BOUNDS_HIGH_LOW;
14817     }
14818   else
14819     {
14820       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14821       if (attr != NULL)
14822         {
14823           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14824              We take advantage of the fact that DW_AT_ranges does not appear
14825              in DW_TAG_compile_unit of DWO files.  */
14826           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14827           unsigned int ranges_offset = (DW_UNSND (attr)
14828                                         + (need_ranges_base
14829                                            ? cu->ranges_base
14830                                            : 0));
14831
14832           /* Value of the DW_AT_ranges attribute is the offset in the
14833              .debug_ranges section.  */
14834           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14835             return PC_BOUNDS_INVALID;
14836           /* Found discontinuous range of addresses.  */
14837           ret = PC_BOUNDS_RANGES;
14838         }
14839       else
14840         return PC_BOUNDS_NOT_PRESENT;
14841     }
14842
14843   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14844   if (high <= low)
14845     return PC_BOUNDS_INVALID;
14846
14847   /* When using the GNU linker, .gnu.linkonce. sections are used to
14848      eliminate duplicate copies of functions and vtables and such.
14849      The linker will arbitrarily choose one and discard the others.
14850      The AT_*_pc values for such functions refer to local labels in
14851      these sections.  If the section from that file was discarded, the
14852      labels are not in the output, so the relocs get a value of 0.
14853      If this is a discarded function, mark the pc bounds as invalid,
14854      so that GDB will ignore it.  */
14855   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14856     return PC_BOUNDS_INVALID;
14857
14858   *lowpc = low;
14859   if (highpc)
14860     *highpc = high;
14861   return ret;
14862 }
14863
14864 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14865    its low and high PC addresses.  Do nothing if these addresses could not
14866    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14867    and HIGHPC to the high address if greater than HIGHPC.  */
14868
14869 static void
14870 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14871                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14872                                  struct dwarf2_cu *cu)
14873 {
14874   CORE_ADDR low, high;
14875   struct die_info *child = die->child;
14876
14877   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14878     {
14879       *lowpc = std::min (*lowpc, low);
14880       *highpc = std::max (*highpc, high);
14881     }
14882
14883   /* If the language does not allow nested subprograms (either inside
14884      subprograms or lexical blocks), we're done.  */
14885   if (cu->language != language_ada)
14886     return;
14887
14888   /* Check all the children of the given DIE.  If it contains nested
14889      subprograms, then check their pc bounds.  Likewise, we need to
14890      check lexical blocks as well, as they may also contain subprogram
14891      definitions.  */
14892   while (child && child->tag)
14893     {
14894       if (child->tag == DW_TAG_subprogram
14895           || child->tag == DW_TAG_lexical_block)
14896         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14897       child = sibling_die (child);
14898     }
14899 }
14900
14901 /* Get the low and high pc's represented by the scope DIE, and store
14902    them in *LOWPC and *HIGHPC.  If the correct values can't be
14903    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14904
14905 static void
14906 get_scope_pc_bounds (struct die_info *die,
14907                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14908                      struct dwarf2_cu *cu)
14909 {
14910   CORE_ADDR best_low = (CORE_ADDR) -1;
14911   CORE_ADDR best_high = (CORE_ADDR) 0;
14912   CORE_ADDR current_low, current_high;
14913
14914   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14915       >= PC_BOUNDS_RANGES)
14916     {
14917       best_low = current_low;
14918       best_high = current_high;
14919     }
14920   else
14921     {
14922       struct die_info *child = die->child;
14923
14924       while (child && child->tag)
14925         {
14926           switch (child->tag) {
14927           case DW_TAG_subprogram:
14928             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14929             break;
14930           case DW_TAG_namespace:
14931           case DW_TAG_module:
14932             /* FIXME: carlton/2004-01-16: Should we do this for
14933                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14934                that current GCC's always emit the DIEs corresponding
14935                to definitions of methods of classes as children of a
14936                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14937                the DIEs giving the declarations, which could be
14938                anywhere).  But I don't see any reason why the
14939                standards says that they have to be there.  */
14940             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14941
14942             if (current_low != ((CORE_ADDR) -1))
14943               {
14944                 best_low = std::min (best_low, current_low);
14945                 best_high = std::max (best_high, current_high);
14946               }
14947             break;
14948           default:
14949             /* Ignore.  */
14950             break;
14951           }
14952
14953           child = sibling_die (child);
14954         }
14955     }
14956
14957   *lowpc = best_low;
14958   *highpc = best_high;
14959 }
14960
14961 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14962    in DIE.  */
14963
14964 static void
14965 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14966                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14967 {
14968   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14969   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14970   struct attribute *attr;
14971   struct attribute *attr_high;
14972
14973   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14974   if (attr_high)
14975     {
14976       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14977       if (attr)
14978         {
14979           CORE_ADDR low = attr_value_as_address (attr);
14980           CORE_ADDR high = attr_value_as_address (attr_high);
14981
14982           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14983             high += low;
14984
14985           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14986           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14987           record_block_range (block, low, high - 1);
14988         }
14989     }
14990
14991   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14992   if (attr)
14993     {
14994       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14995          We take advantage of the fact that DW_AT_ranges does not appear
14996          in DW_TAG_compile_unit of DWO files.  */
14997       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14998
14999       /* The value of the DW_AT_ranges attribute is the offset of the
15000          address range list in the .debug_ranges section.  */
15001       unsigned long offset = (DW_UNSND (attr)
15002                               + (need_ranges_base ? cu->ranges_base : 0));
15003       const gdb_byte *buffer;
15004
15005       /* For some target architectures, but not others, the
15006          read_address function sign-extends the addresses it returns.
15007          To recognize base address selection entries, we need a
15008          mask.  */
15009       unsigned int addr_size = cu->header.addr_size;
15010       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15011
15012       /* The base address, to which the next pair is relative.  Note
15013          that this 'base' is a DWARF concept: most entries in a range
15014          list are relative, to reduce the number of relocs against the
15015          debugging information.  This is separate from this function's
15016          'baseaddr' argument, which GDB uses to relocate debugging
15017          information from a shared library based on the address at
15018          which the library was loaded.  */
15019       CORE_ADDR base = cu->base_address;
15020       int base_known = cu->base_known;
15021
15022       dwarf2_ranges_process (offset, cu,
15023         [&] (CORE_ADDR start, CORE_ADDR end)
15024         {
15025           start += baseaddr;
15026           end += baseaddr;
15027           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15028           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15029           record_block_range (block, start, end - 1);
15030         });
15031     }
15032 }
15033
15034 /* Check whether the producer field indicates either of GCC < 4.6, or the
15035    Intel C/C++ compiler, and cache the result in CU.  */
15036
15037 static void
15038 check_producer (struct dwarf2_cu *cu)
15039 {
15040   int major, minor;
15041
15042   if (cu->producer == NULL)
15043     {
15044       /* For unknown compilers expect their behavior is DWARF version
15045          compliant.
15046
15047          GCC started to support .debug_types sections by -gdwarf-4 since
15048          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15049          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15050          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15051          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15052     }
15053   else if (producer_is_gcc (cu->producer, &major, &minor))
15054     {
15055       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15056       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15057     }
15058   else if (producer_is_icc (cu->producer, &major, &minor))
15059     cu->producer_is_icc_lt_14 = major < 14;
15060   else
15061     {
15062       /* For other non-GCC compilers, expect their behavior is DWARF version
15063          compliant.  */
15064     }
15065
15066   cu->checked_producer = 1;
15067 }
15068
15069 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15070    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15071    during 4.6.0 experimental.  */
15072
15073 static int
15074 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15075 {
15076   if (!cu->checked_producer)
15077     check_producer (cu);
15078
15079   return cu->producer_is_gxx_lt_4_6;
15080 }
15081
15082 /* Return the default accessibility type if it is not overriden by
15083    DW_AT_accessibility.  */
15084
15085 static enum dwarf_access_attribute
15086 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15087 {
15088   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15089     {
15090       /* The default DWARF 2 accessibility for members is public, the default
15091          accessibility for inheritance is private.  */
15092
15093       if (die->tag != DW_TAG_inheritance)
15094         return DW_ACCESS_public;
15095       else
15096         return DW_ACCESS_private;
15097     }
15098   else
15099     {
15100       /* DWARF 3+ defines the default accessibility a different way.  The same
15101          rules apply now for DW_TAG_inheritance as for the members and it only
15102          depends on the container kind.  */
15103
15104       if (die->parent->tag == DW_TAG_class_type)
15105         return DW_ACCESS_private;
15106       else
15107         return DW_ACCESS_public;
15108     }
15109 }
15110
15111 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15112    offset.  If the attribute was not found return 0, otherwise return
15113    1.  If it was found but could not properly be handled, set *OFFSET
15114    to 0.  */
15115
15116 static int
15117 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15118                              LONGEST *offset)
15119 {
15120   struct attribute *attr;
15121
15122   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15123   if (attr != NULL)
15124     {
15125       *offset = 0;
15126
15127       /* Note that we do not check for a section offset first here.
15128          This is because DW_AT_data_member_location is new in DWARF 4,
15129          so if we see it, we can assume that a constant form is really
15130          a constant and not a section offset.  */
15131       if (attr_form_is_constant (attr))
15132         *offset = dwarf2_get_attr_constant_value (attr, 0);
15133       else if (attr_form_is_section_offset (attr))
15134         dwarf2_complex_location_expr_complaint ();
15135       else if (attr_form_is_block (attr))
15136         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15137       else
15138         dwarf2_complex_location_expr_complaint ();
15139
15140       return 1;
15141     }
15142
15143   return 0;
15144 }
15145
15146 /* Add an aggregate field to the field list.  */
15147
15148 static void
15149 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15150                   struct dwarf2_cu *cu)
15151 {
15152   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15153   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15154   struct nextfield *new_field;
15155   struct attribute *attr;
15156   struct field *fp;
15157   const char *fieldname = "";
15158
15159   /* Allocate a new field list entry and link it in.  */
15160   new_field = XNEW (struct nextfield);
15161   make_cleanup (xfree, new_field);
15162   memset (new_field, 0, sizeof (struct nextfield));
15163
15164   if (die->tag == DW_TAG_inheritance)
15165     {
15166       new_field->next = fip->baseclasses;
15167       fip->baseclasses = new_field;
15168     }
15169   else
15170     {
15171       new_field->next = fip->fields;
15172       fip->fields = new_field;
15173     }
15174   fip->nfields++;
15175
15176   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15177   if (attr)
15178     new_field->accessibility = DW_UNSND (attr);
15179   else
15180     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15181   if (new_field->accessibility != DW_ACCESS_public)
15182     fip->non_public_fields = 1;
15183
15184   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15185   if (attr)
15186     new_field->virtuality = DW_UNSND (attr);
15187   else
15188     new_field->virtuality = DW_VIRTUALITY_none;
15189
15190   fp = &new_field->field;
15191
15192   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15193     {
15194       LONGEST offset;
15195
15196       /* Data member other than a C++ static data member.  */
15197
15198       /* Get type of field.  */
15199       fp->type = die_type (die, cu);
15200
15201       SET_FIELD_BITPOS (*fp, 0);
15202
15203       /* Get bit size of field (zero if none).  */
15204       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15205       if (attr)
15206         {
15207           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15208         }
15209       else
15210         {
15211           FIELD_BITSIZE (*fp) = 0;
15212         }
15213
15214       /* Get bit offset of field.  */
15215       if (handle_data_member_location (die, cu, &offset))
15216         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15217       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15218       if (attr)
15219         {
15220           if (gdbarch_bits_big_endian (gdbarch))
15221             {
15222               /* For big endian bits, the DW_AT_bit_offset gives the
15223                  additional bit offset from the MSB of the containing
15224                  anonymous object to the MSB of the field.  We don't
15225                  have to do anything special since we don't need to
15226                  know the size of the anonymous object.  */
15227               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15228             }
15229           else
15230             {
15231               /* For little endian bits, compute the bit offset to the
15232                  MSB of the anonymous object, subtract off the number of
15233                  bits from the MSB of the field to the MSB of the
15234                  object, and then subtract off the number of bits of
15235                  the field itself.  The result is the bit offset of
15236                  the LSB of the field.  */
15237               int anonymous_size;
15238               int bit_offset = DW_UNSND (attr);
15239
15240               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15241               if (attr)
15242                 {
15243                   /* The size of the anonymous object containing
15244                      the bit field is explicit, so use the
15245                      indicated size (in bytes).  */
15246                   anonymous_size = DW_UNSND (attr);
15247                 }
15248               else
15249                 {
15250                   /* The size of the anonymous object containing
15251                      the bit field must be inferred from the type
15252                      attribute of the data member containing the
15253                      bit field.  */
15254                   anonymous_size = TYPE_LENGTH (fp->type);
15255                 }
15256               SET_FIELD_BITPOS (*fp,
15257                                 (FIELD_BITPOS (*fp)
15258                                  + anonymous_size * bits_per_byte
15259                                  - bit_offset - FIELD_BITSIZE (*fp)));
15260             }
15261         }
15262       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15263       if (attr != NULL)
15264         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15265                                 + dwarf2_get_attr_constant_value (attr, 0)));
15266
15267       /* Get name of field.  */
15268       fieldname = dwarf2_name (die, cu);
15269       if (fieldname == NULL)
15270         fieldname = "";
15271
15272       /* The name is already allocated along with this objfile, so we don't
15273          need to duplicate it for the type.  */
15274       fp->name = fieldname;
15275
15276       /* Change accessibility for artificial fields (e.g. virtual table
15277          pointer or virtual base class pointer) to private.  */
15278       if (dwarf2_attr (die, DW_AT_artificial, cu))
15279         {
15280           FIELD_ARTIFICIAL (*fp) = 1;
15281           new_field->accessibility = DW_ACCESS_private;
15282           fip->non_public_fields = 1;
15283         }
15284     }
15285   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15286     {
15287       /* C++ static member.  */
15288
15289       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15290          is a declaration, but all versions of G++ as of this writing
15291          (so through at least 3.2.1) incorrectly generate
15292          DW_TAG_variable tags.  */
15293
15294       const char *physname;
15295
15296       /* Get name of field.  */
15297       fieldname = dwarf2_name (die, cu);
15298       if (fieldname == NULL)
15299         return;
15300
15301       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15302       if (attr
15303           /* Only create a symbol if this is an external value.
15304              new_symbol checks this and puts the value in the global symbol
15305              table, which we want.  If it is not external, new_symbol
15306              will try to put the value in cu->list_in_scope which is wrong.  */
15307           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15308         {
15309           /* A static const member, not much different than an enum as far as
15310              we're concerned, except that we can support more types.  */
15311           new_symbol (die, NULL, cu);
15312         }
15313
15314       /* Get physical name.  */
15315       physname = dwarf2_physname (fieldname, die, cu);
15316
15317       /* The name is already allocated along with this objfile, so we don't
15318          need to duplicate it for the type.  */
15319       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15320       FIELD_TYPE (*fp) = die_type (die, cu);
15321       FIELD_NAME (*fp) = fieldname;
15322     }
15323   else if (die->tag == DW_TAG_inheritance)
15324     {
15325       LONGEST offset;
15326
15327       /* C++ base class field.  */
15328       if (handle_data_member_location (die, cu, &offset))
15329         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15330       FIELD_BITSIZE (*fp) = 0;
15331       FIELD_TYPE (*fp) = die_type (die, cu);
15332       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15333       fip->nbaseclasses++;
15334     }
15335 }
15336
15337 /* Can the type given by DIE define another type?  */
15338
15339 static bool
15340 type_can_define_types (const struct die_info *die)
15341 {
15342   switch (die->tag)
15343     {
15344     case DW_TAG_typedef:
15345     case DW_TAG_class_type:
15346     case DW_TAG_structure_type:
15347     case DW_TAG_union_type:
15348     case DW_TAG_enumeration_type:
15349       return true;
15350
15351     default:
15352       return false;
15353     }
15354 }
15355
15356 /* Add a type definition defined in the scope of the FIP's class.  */
15357
15358 static void
15359 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15360                       struct dwarf2_cu *cu)
15361 {
15362   struct decl_field_list *new_field;
15363   struct decl_field *fp;
15364
15365   /* Allocate a new field list entry and link it in.  */
15366   new_field = XCNEW (struct decl_field_list);
15367   make_cleanup (xfree, new_field);
15368
15369   gdb_assert (type_can_define_types (die));
15370
15371   fp = &new_field->field;
15372
15373   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15374   fp->name = dwarf2_name (die, cu);
15375   fp->type = read_type_die (die, cu);
15376
15377   /* Save accessibility.  */
15378   enum dwarf_access_attribute accessibility;
15379   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15380   if (attr != NULL)
15381     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15382   else
15383     accessibility = dwarf2_default_access_attribute (die, cu);
15384   switch (accessibility)
15385     {
15386     case DW_ACCESS_public:
15387       /* The assumed value if neither private nor protected.  */
15388       break;
15389     case DW_ACCESS_private:
15390       fp->is_private = 1;
15391       break;
15392     case DW_ACCESS_protected:
15393       fp->is_protected = 1;
15394       break;
15395     default:
15396       complaint (&symfile_complaints,
15397                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15398     }
15399
15400   if (die->tag == DW_TAG_typedef)
15401     {
15402       new_field->next = fip->typedef_field_list;
15403       fip->typedef_field_list = new_field;
15404       fip->typedef_field_list_count++;
15405     }
15406   else
15407     {
15408       new_field->next = fip->nested_types_list;
15409       fip->nested_types_list = new_field;
15410       fip->nested_types_list_count++;
15411     }
15412 }
15413
15414 /* Create the vector of fields, and attach it to the type.  */
15415
15416 static void
15417 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15418                               struct dwarf2_cu *cu)
15419 {
15420   int nfields = fip->nfields;
15421
15422   /* Record the field count, allocate space for the array of fields,
15423      and create blank accessibility bitfields if necessary.  */
15424   TYPE_NFIELDS (type) = nfields;
15425   TYPE_FIELDS (type) = (struct field *)
15426     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15427   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15428
15429   if (fip->non_public_fields && cu->language != language_ada)
15430     {
15431       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15432
15433       TYPE_FIELD_PRIVATE_BITS (type) =
15434         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15435       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15436
15437       TYPE_FIELD_PROTECTED_BITS (type) =
15438         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15439       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15440
15441       TYPE_FIELD_IGNORE_BITS (type) =
15442         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15443       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15444     }
15445
15446   /* If the type has baseclasses, allocate and clear a bit vector for
15447      TYPE_FIELD_VIRTUAL_BITS.  */
15448   if (fip->nbaseclasses && cu->language != language_ada)
15449     {
15450       int num_bytes = B_BYTES (fip->nbaseclasses);
15451       unsigned char *pointer;
15452
15453       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15454       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15455       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15456       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15457       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15458     }
15459
15460   /* Copy the saved-up fields into the field vector.  Start from the head of
15461      the list, adding to the tail of the field array, so that they end up in
15462      the same order in the array in which they were added to the list.  */
15463   while (nfields-- > 0)
15464     {
15465       struct nextfield *fieldp;
15466
15467       if (fip->fields)
15468         {
15469           fieldp = fip->fields;
15470           fip->fields = fieldp->next;
15471         }
15472       else
15473         {
15474           fieldp = fip->baseclasses;
15475           fip->baseclasses = fieldp->next;
15476         }
15477
15478       TYPE_FIELD (type, nfields) = fieldp->field;
15479       switch (fieldp->accessibility)
15480         {
15481         case DW_ACCESS_private:
15482           if (cu->language != language_ada)
15483             SET_TYPE_FIELD_PRIVATE (type, nfields);
15484           break;
15485
15486         case DW_ACCESS_protected:
15487           if (cu->language != language_ada)
15488             SET_TYPE_FIELD_PROTECTED (type, nfields);
15489           break;
15490
15491         case DW_ACCESS_public:
15492           break;
15493
15494         default:
15495           /* Unknown accessibility.  Complain and treat it as public.  */
15496           {
15497             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15498                        fieldp->accessibility);
15499           }
15500           break;
15501         }
15502       if (nfields < fip->nbaseclasses)
15503         {
15504           switch (fieldp->virtuality)
15505             {
15506             case DW_VIRTUALITY_virtual:
15507             case DW_VIRTUALITY_pure_virtual:
15508               if (cu->language == language_ada)
15509                 error (_("unexpected virtuality in component of Ada type"));
15510               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15511               break;
15512             }
15513         }
15514     }
15515 }
15516
15517 /* Return true if this member function is a constructor, false
15518    otherwise.  */
15519
15520 static int
15521 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15522 {
15523   const char *fieldname;
15524   const char *type_name;
15525   int len;
15526
15527   if (die->parent == NULL)
15528     return 0;
15529
15530   if (die->parent->tag != DW_TAG_structure_type
15531       && die->parent->tag != DW_TAG_union_type
15532       && die->parent->tag != DW_TAG_class_type)
15533     return 0;
15534
15535   fieldname = dwarf2_name (die, cu);
15536   type_name = dwarf2_name (die->parent, cu);
15537   if (fieldname == NULL || type_name == NULL)
15538     return 0;
15539
15540   len = strlen (fieldname);
15541   return (strncmp (fieldname, type_name, len) == 0
15542           && (type_name[len] == '\0' || type_name[len] == '<'));
15543 }
15544
15545 /* Add a member function to the proper fieldlist.  */
15546
15547 static void
15548 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15549                       struct type *type, struct dwarf2_cu *cu)
15550 {
15551   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15552   struct attribute *attr;
15553   struct fnfieldlist *flp;
15554   int i;
15555   struct fn_field *fnp;
15556   const char *fieldname;
15557   struct nextfnfield *new_fnfield;
15558   struct type *this_type;
15559   enum dwarf_access_attribute accessibility;
15560
15561   if (cu->language == language_ada)
15562     error (_("unexpected member function in Ada type"));
15563
15564   /* Get name of member function.  */
15565   fieldname = dwarf2_name (die, cu);
15566   if (fieldname == NULL)
15567     return;
15568
15569   /* Look up member function name in fieldlist.  */
15570   for (i = 0; i < fip->nfnfields; i++)
15571     {
15572       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15573         break;
15574     }
15575
15576   /* Create new list element if necessary.  */
15577   if (i < fip->nfnfields)
15578     flp = &fip->fnfieldlists[i];
15579   else
15580     {
15581       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15582         {
15583           fip->fnfieldlists = (struct fnfieldlist *)
15584             xrealloc (fip->fnfieldlists,
15585                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15586                       * sizeof (struct fnfieldlist));
15587           if (fip->nfnfields == 0)
15588             make_cleanup (free_current_contents, &fip->fnfieldlists);
15589         }
15590       flp = &fip->fnfieldlists[fip->nfnfields];
15591       flp->name = fieldname;
15592       flp->length = 0;
15593       flp->head = NULL;
15594       i = fip->nfnfields++;
15595     }
15596
15597   /* Create a new member function field and chain it to the field list
15598      entry.  */
15599   new_fnfield = XNEW (struct nextfnfield);
15600   make_cleanup (xfree, new_fnfield);
15601   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15602   new_fnfield->next = flp->head;
15603   flp->head = new_fnfield;
15604   flp->length++;
15605
15606   /* Fill in the member function field info.  */
15607   fnp = &new_fnfield->fnfield;
15608
15609   /* Delay processing of the physname until later.  */
15610   if (cu->language == language_cplus)
15611     {
15612       add_to_method_list (type, i, flp->length - 1, fieldname,
15613                           die, cu);
15614     }
15615   else
15616     {
15617       const char *physname = dwarf2_physname (fieldname, die, cu);
15618       fnp->physname = physname ? physname : "";
15619     }
15620
15621   fnp->type = alloc_type (objfile);
15622   this_type = read_type_die (die, cu);
15623   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15624     {
15625       int nparams = TYPE_NFIELDS (this_type);
15626
15627       /* TYPE is the domain of this method, and THIS_TYPE is the type
15628            of the method itself (TYPE_CODE_METHOD).  */
15629       smash_to_method_type (fnp->type, type,
15630                             TYPE_TARGET_TYPE (this_type),
15631                             TYPE_FIELDS (this_type),
15632                             TYPE_NFIELDS (this_type),
15633                             TYPE_VARARGS (this_type));
15634
15635       /* Handle static member functions.
15636          Dwarf2 has no clean way to discern C++ static and non-static
15637          member functions.  G++ helps GDB by marking the first
15638          parameter for non-static member functions (which is the this
15639          pointer) as artificial.  We obtain this information from
15640          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15641       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15642         fnp->voffset = VOFFSET_STATIC;
15643     }
15644   else
15645     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15646                dwarf2_full_name (fieldname, die, cu));
15647
15648   /* Get fcontext from DW_AT_containing_type if present.  */
15649   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15650     fnp->fcontext = die_containing_type (die, cu);
15651
15652   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15653      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15654
15655   /* Get accessibility.  */
15656   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15657   if (attr)
15658     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15659   else
15660     accessibility = dwarf2_default_access_attribute (die, cu);
15661   switch (accessibility)
15662     {
15663     case DW_ACCESS_private:
15664       fnp->is_private = 1;
15665       break;
15666     case DW_ACCESS_protected:
15667       fnp->is_protected = 1;
15668       break;
15669     }
15670
15671   /* Check for artificial methods.  */
15672   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15673   if (attr && DW_UNSND (attr) != 0)
15674     fnp->is_artificial = 1;
15675
15676   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15677
15678   /* Get index in virtual function table if it is a virtual member
15679      function.  For older versions of GCC, this is an offset in the
15680      appropriate virtual table, as specified by DW_AT_containing_type.
15681      For everyone else, it is an expression to be evaluated relative
15682      to the object address.  */
15683
15684   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15685   if (attr)
15686     {
15687       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15688         {
15689           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15690             {
15691               /* Old-style GCC.  */
15692               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15693             }
15694           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15695                    || (DW_BLOCK (attr)->size > 1
15696                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15697                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15698             {
15699               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15700               if ((fnp->voffset % cu->header.addr_size) != 0)
15701                 dwarf2_complex_location_expr_complaint ();
15702               else
15703                 fnp->voffset /= cu->header.addr_size;
15704               fnp->voffset += 2;
15705             }
15706           else
15707             dwarf2_complex_location_expr_complaint ();
15708
15709           if (!fnp->fcontext)
15710             {
15711               /* If there is no `this' field and no DW_AT_containing_type,
15712                  we cannot actually find a base class context for the
15713                  vtable!  */
15714               if (TYPE_NFIELDS (this_type) == 0
15715                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15716                 {
15717                   complaint (&symfile_complaints,
15718                              _("cannot determine context for virtual member "
15719                                "function \"%s\" (offset %s)"),
15720                              fieldname, sect_offset_str (die->sect_off));
15721                 }
15722               else
15723                 {
15724                   fnp->fcontext
15725                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15726                 }
15727             }
15728         }
15729       else if (attr_form_is_section_offset (attr))
15730         {
15731           dwarf2_complex_location_expr_complaint ();
15732         }
15733       else
15734         {
15735           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15736                                                  fieldname);
15737         }
15738     }
15739   else
15740     {
15741       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15742       if (attr && DW_UNSND (attr))
15743         {
15744           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15745           complaint (&symfile_complaints,
15746                      _("Member function \"%s\" (offset %s) is virtual "
15747                        "but the vtable offset is not specified"),
15748                      fieldname, sect_offset_str (die->sect_off));
15749           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15750           TYPE_CPLUS_DYNAMIC (type) = 1;
15751         }
15752     }
15753 }
15754
15755 /* Create the vector of member function fields, and attach it to the type.  */
15756
15757 static void
15758 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15759                                  struct dwarf2_cu *cu)
15760 {
15761   struct fnfieldlist *flp;
15762   int i;
15763
15764   if (cu->language == language_ada)
15765     error (_("unexpected member functions in Ada type"));
15766
15767   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15768   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15769     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15770
15771   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15772     {
15773       struct nextfnfield *nfp = flp->head;
15774       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15775       int k;
15776
15777       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15778       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15779       fn_flp->fn_fields = (struct fn_field *)
15780         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15781       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15782         fn_flp->fn_fields[k] = nfp->fnfield;
15783     }
15784
15785   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15786 }
15787
15788 /* Returns non-zero if NAME is the name of a vtable member in CU's
15789    language, zero otherwise.  */
15790 static int
15791 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15792 {
15793   static const char vptr[] = "_vptr";
15794
15795   /* Look for the C++ form of the vtable.  */
15796   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15797     return 1;
15798
15799   return 0;
15800 }
15801
15802 /* GCC outputs unnamed structures that are really pointers to member
15803    functions, with the ABI-specified layout.  If TYPE describes
15804    such a structure, smash it into a member function type.
15805
15806    GCC shouldn't do this; it should just output pointer to member DIEs.
15807    This is GCC PR debug/28767.  */
15808
15809 static void
15810 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15811 {
15812   struct type *pfn_type, *self_type, *new_type;
15813
15814   /* Check for a structure with no name and two children.  */
15815   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15816     return;
15817
15818   /* Check for __pfn and __delta members.  */
15819   if (TYPE_FIELD_NAME (type, 0) == NULL
15820       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15821       || TYPE_FIELD_NAME (type, 1) == NULL
15822       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15823     return;
15824
15825   /* Find the type of the method.  */
15826   pfn_type = TYPE_FIELD_TYPE (type, 0);
15827   if (pfn_type == NULL
15828       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15829       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15830     return;
15831
15832   /* Look for the "this" argument.  */
15833   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15834   if (TYPE_NFIELDS (pfn_type) == 0
15835       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15836       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15837     return;
15838
15839   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15840   new_type = alloc_type (objfile);
15841   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15842                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15843                         TYPE_VARARGS (pfn_type));
15844   smash_to_methodptr_type (type, new_type);
15845 }
15846
15847
15848 /* Called when we find the DIE that starts a structure or union scope
15849    (definition) to create a type for the structure or union.  Fill in
15850    the type's name and general properties; the members will not be
15851    processed until process_structure_scope.  A symbol table entry for
15852    the type will also not be done until process_structure_scope (assuming
15853    the type has a name).
15854
15855    NOTE: we need to call these functions regardless of whether or not the
15856    DIE has a DW_AT_name attribute, since it might be an anonymous
15857    structure or union.  This gets the type entered into our set of
15858    user defined types.  */
15859
15860 static struct type *
15861 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15862 {
15863   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15864   struct type *type;
15865   struct attribute *attr;
15866   const char *name;
15867
15868   /* If the definition of this type lives in .debug_types, read that type.
15869      Don't follow DW_AT_specification though, that will take us back up
15870      the chain and we want to go down.  */
15871   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15872   if (attr)
15873     {
15874       type = get_DW_AT_signature_type (die, attr, cu);
15875
15876       /* The type's CU may not be the same as CU.
15877          Ensure TYPE is recorded with CU in die_type_hash.  */
15878       return set_die_type (die, type, cu);
15879     }
15880
15881   type = alloc_type (objfile);
15882   INIT_CPLUS_SPECIFIC (type);
15883
15884   name = dwarf2_name (die, cu);
15885   if (name != NULL)
15886     {
15887       if (cu->language == language_cplus
15888           || cu->language == language_d
15889           || cu->language == language_rust)
15890         {
15891           const char *full_name = dwarf2_full_name (name, die, cu);
15892
15893           /* dwarf2_full_name might have already finished building the DIE's
15894              type.  If so, there is no need to continue.  */
15895           if (get_die_type (die, cu) != NULL)
15896             return get_die_type (die, cu);
15897
15898           TYPE_TAG_NAME (type) = full_name;
15899           if (die->tag == DW_TAG_structure_type
15900               || die->tag == DW_TAG_class_type)
15901             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15902         }
15903       else
15904         {
15905           /* The name is already allocated along with this objfile, so
15906              we don't need to duplicate it for the type.  */
15907           TYPE_TAG_NAME (type) = name;
15908           if (die->tag == DW_TAG_class_type)
15909             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15910         }
15911     }
15912
15913   if (die->tag == DW_TAG_structure_type)
15914     {
15915       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15916     }
15917   else if (die->tag == DW_TAG_union_type)
15918     {
15919       TYPE_CODE (type) = TYPE_CODE_UNION;
15920     }
15921   else
15922     {
15923       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15924     }
15925
15926   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15927     TYPE_DECLARED_CLASS (type) = 1;
15928
15929   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15930   if (attr)
15931     {
15932       if (attr_form_is_constant (attr))
15933         TYPE_LENGTH (type) = DW_UNSND (attr);
15934       else
15935         {
15936           /* For the moment, dynamic type sizes are not supported
15937              by GDB's struct type.  The actual size is determined
15938              on-demand when resolving the type of a given object,
15939              so set the type's length to zero for now.  Otherwise,
15940              we record an expression as the length, and that expression
15941              could lead to a very large value, which could eventually
15942              lead to us trying to allocate that much memory when creating
15943              a value of that type.  */
15944           TYPE_LENGTH (type) = 0;
15945         }
15946     }
15947   else
15948     {
15949       TYPE_LENGTH (type) = 0;
15950     }
15951
15952   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15953     {
15954       /* ICC<14 does not output the required DW_AT_declaration on
15955          incomplete types, but gives them a size of zero.  */
15956       TYPE_STUB (type) = 1;
15957     }
15958   else
15959     TYPE_STUB_SUPPORTED (type) = 1;
15960
15961   if (die_is_declaration (die, cu))
15962     TYPE_STUB (type) = 1;
15963   else if (attr == NULL && die->child == NULL
15964            && producer_is_realview (cu->producer))
15965     /* RealView does not output the required DW_AT_declaration
15966        on incomplete types.  */
15967     TYPE_STUB (type) = 1;
15968
15969   /* We need to add the type field to the die immediately so we don't
15970      infinitely recurse when dealing with pointers to the structure
15971      type within the structure itself.  */
15972   set_die_type (die, type, cu);
15973
15974   /* set_die_type should be already done.  */
15975   set_descriptive_type (type, die, cu);
15976
15977   return type;
15978 }
15979
15980 /* Finish creating a structure or union type, including filling in
15981    its members and creating a symbol for it.  */
15982
15983 static void
15984 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15985 {
15986   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15987   struct die_info *child_die;
15988   struct type *type;
15989
15990   type = get_die_type (die, cu);
15991   if (type == NULL)
15992     type = read_structure_type (die, cu);
15993
15994   if (die->child != NULL && ! die_is_declaration (die, cu))
15995     {
15996       struct field_info fi;
15997       std::vector<struct symbol *> template_args;
15998       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15999
16000       memset (&fi, 0, sizeof (struct field_info));
16001
16002       child_die = die->child;
16003
16004       while (child_die && child_die->tag)
16005         {
16006           if (child_die->tag == DW_TAG_member
16007               || child_die->tag == DW_TAG_variable)
16008             {
16009               /* NOTE: carlton/2002-11-05: A C++ static data member
16010                  should be a DW_TAG_member that is a declaration, but
16011                  all versions of G++ as of this writing (so through at
16012                  least 3.2.1) incorrectly generate DW_TAG_variable
16013                  tags for them instead.  */
16014               dwarf2_add_field (&fi, child_die, cu);
16015             }
16016           else if (child_die->tag == DW_TAG_subprogram)
16017             {
16018               /* Rust doesn't have member functions in the C++ sense.
16019                  However, it does emit ordinary functions as children
16020                  of a struct DIE.  */
16021               if (cu->language == language_rust)
16022                 read_func_scope (child_die, cu);
16023               else
16024                 {
16025                   /* C++ member function.  */
16026                   dwarf2_add_member_fn (&fi, child_die, type, cu);
16027                 }
16028             }
16029           else if (child_die->tag == DW_TAG_inheritance)
16030             {
16031               /* C++ base class field.  */
16032               dwarf2_add_field (&fi, child_die, cu);
16033             }
16034           else if (type_can_define_types (child_die))
16035             dwarf2_add_type_defn (&fi, child_die, cu);
16036           else if (child_die->tag == DW_TAG_template_type_param
16037                    || child_die->tag == DW_TAG_template_value_param)
16038             {
16039               struct symbol *arg = new_symbol (child_die, NULL, cu);
16040
16041               if (arg != NULL)
16042                 template_args.push_back (arg);
16043             }
16044
16045           child_die = sibling_die (child_die);
16046         }
16047
16048       /* Attach template arguments to type.  */
16049       if (!template_args.empty ())
16050         {
16051           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16052           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16053           TYPE_TEMPLATE_ARGUMENTS (type)
16054             = XOBNEWVEC (&objfile->objfile_obstack,
16055                          struct symbol *,
16056                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16057           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16058                   template_args.data (),
16059                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16060                    * sizeof (struct symbol *)));
16061         }
16062
16063       /* Attach fields and member functions to the type.  */
16064       if (fi.nfields)
16065         dwarf2_attach_fields_to_type (&fi, type, cu);
16066       if (fi.nfnfields)
16067         {
16068           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16069
16070           /* Get the type which refers to the base class (possibly this
16071              class itself) which contains the vtable pointer for the current
16072              class from the DW_AT_containing_type attribute.  This use of
16073              DW_AT_containing_type is a GNU extension.  */
16074
16075           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16076             {
16077               struct type *t = die_containing_type (die, cu);
16078
16079               set_type_vptr_basetype (type, t);
16080               if (type == t)
16081                 {
16082                   int i;
16083
16084                   /* Our own class provides vtbl ptr.  */
16085                   for (i = TYPE_NFIELDS (t) - 1;
16086                        i >= TYPE_N_BASECLASSES (t);
16087                        --i)
16088                     {
16089                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16090
16091                       if (is_vtable_name (fieldname, cu))
16092                         {
16093                           set_type_vptr_fieldno (type, i);
16094                           break;
16095                         }
16096                     }
16097
16098                   /* Complain if virtual function table field not found.  */
16099                   if (i < TYPE_N_BASECLASSES (t))
16100                     complaint (&symfile_complaints,
16101                                _("virtual function table pointer "
16102                                  "not found when defining class '%s'"),
16103                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16104                                "");
16105                 }
16106               else
16107                 {
16108                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16109                 }
16110             }
16111           else if (cu->producer
16112                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16113             {
16114               /* The IBM XLC compiler does not provide direct indication
16115                  of the containing type, but the vtable pointer is
16116                  always named __vfp.  */
16117
16118               int i;
16119
16120               for (i = TYPE_NFIELDS (type) - 1;
16121                    i >= TYPE_N_BASECLASSES (type);
16122                    --i)
16123                 {
16124                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16125                     {
16126                       set_type_vptr_fieldno (type, i);
16127                       set_type_vptr_basetype (type, type);
16128                       break;
16129                     }
16130                 }
16131             }
16132         }
16133
16134       /* Copy fi.typedef_field_list linked list elements content into the
16135          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16136       if (fi.typedef_field_list)
16137         {
16138           int i = fi.typedef_field_list_count;
16139
16140           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16141           TYPE_TYPEDEF_FIELD_ARRAY (type)
16142             = ((struct decl_field *)
16143                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16144           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16145
16146           /* Reverse the list order to keep the debug info elements order.  */
16147           while (--i >= 0)
16148             {
16149               struct decl_field *dest, *src;
16150
16151               dest = &TYPE_TYPEDEF_FIELD (type, i);
16152               src = &fi.typedef_field_list->field;
16153               fi.typedef_field_list = fi.typedef_field_list->next;
16154               *dest = *src;
16155             }
16156         }
16157
16158       /* Copy fi.nested_types_list linked list elements content into the
16159          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16160       if (fi.nested_types_list != NULL && cu->language != language_ada)
16161         {
16162           int i = fi.nested_types_list_count;
16163
16164           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16165           TYPE_NESTED_TYPES_ARRAY (type)
16166             = ((struct decl_field *)
16167                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16168           TYPE_NESTED_TYPES_COUNT (type) = i;
16169
16170           /* Reverse the list order to keep the debug info elements order.  */
16171           while (--i >= 0)
16172             {
16173               struct decl_field *dest, *src;
16174
16175               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16176               src = &fi.nested_types_list->field;
16177               fi.nested_types_list = fi.nested_types_list->next;
16178               *dest = *src;
16179             }
16180         }
16181
16182       do_cleanups (back_to);
16183     }
16184
16185   quirk_gcc_member_function_pointer (type, objfile);
16186
16187   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16188      snapshots) has been known to create a die giving a declaration
16189      for a class that has, as a child, a die giving a definition for a
16190      nested class.  So we have to process our children even if the
16191      current die is a declaration.  Normally, of course, a declaration
16192      won't have any children at all.  */
16193
16194   child_die = die->child;
16195
16196   while (child_die != NULL && child_die->tag)
16197     {
16198       if (child_die->tag == DW_TAG_member
16199           || child_die->tag == DW_TAG_variable
16200           || child_die->tag == DW_TAG_inheritance
16201           || child_die->tag == DW_TAG_template_value_param
16202           || child_die->tag == DW_TAG_template_type_param)
16203         {
16204           /* Do nothing.  */
16205         }
16206       else
16207         process_die (child_die, cu);
16208
16209       child_die = sibling_die (child_die);
16210     }
16211
16212   /* Do not consider external references.  According to the DWARF standard,
16213      these DIEs are identified by the fact that they have no byte_size
16214      attribute, and a declaration attribute.  */
16215   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16216       || !die_is_declaration (die, cu))
16217     new_symbol (die, type, cu);
16218 }
16219
16220 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16221    update TYPE using some information only available in DIE's children.  */
16222
16223 static void
16224 update_enumeration_type_from_children (struct die_info *die,
16225                                        struct type *type,
16226                                        struct dwarf2_cu *cu)
16227 {
16228   struct die_info *child_die;
16229   int unsigned_enum = 1;
16230   int flag_enum = 1;
16231   ULONGEST mask = 0;
16232
16233   auto_obstack obstack;
16234
16235   for (child_die = die->child;
16236        child_die != NULL && child_die->tag;
16237        child_die = sibling_die (child_die))
16238     {
16239       struct attribute *attr;
16240       LONGEST value;
16241       const gdb_byte *bytes;
16242       struct dwarf2_locexpr_baton *baton;
16243       const char *name;
16244
16245       if (child_die->tag != DW_TAG_enumerator)
16246         continue;
16247
16248       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16249       if (attr == NULL)
16250         continue;
16251
16252       name = dwarf2_name (child_die, cu);
16253       if (name == NULL)
16254         name = "<anonymous enumerator>";
16255
16256       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16257                                &value, &bytes, &baton);
16258       if (value < 0)
16259         {
16260           unsigned_enum = 0;
16261           flag_enum = 0;
16262         }
16263       else if ((mask & value) != 0)
16264         flag_enum = 0;
16265       else
16266         mask |= value;
16267
16268       /* If we already know that the enum type is neither unsigned, nor
16269          a flag type, no need to look at the rest of the enumerates.  */
16270       if (!unsigned_enum && !flag_enum)
16271         break;
16272     }
16273
16274   if (unsigned_enum)
16275     TYPE_UNSIGNED (type) = 1;
16276   if (flag_enum)
16277     TYPE_FLAG_ENUM (type) = 1;
16278 }
16279
16280 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16281    complete the type's fields yet, or create any symbols.  */
16282
16283 static struct type *
16284 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16285 {
16286   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16287   struct type *type;
16288   struct attribute *attr;
16289   const char *name;
16290
16291   /* If the definition of this type lives in .debug_types, read that type.
16292      Don't follow DW_AT_specification though, that will take us back up
16293      the chain and we want to go down.  */
16294   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16295   if (attr)
16296     {
16297       type = get_DW_AT_signature_type (die, attr, cu);
16298
16299       /* The type's CU may not be the same as CU.
16300          Ensure TYPE is recorded with CU in die_type_hash.  */
16301       return set_die_type (die, type, cu);
16302     }
16303
16304   type = alloc_type (objfile);
16305
16306   TYPE_CODE (type) = TYPE_CODE_ENUM;
16307   name = dwarf2_full_name (NULL, die, cu);
16308   if (name != NULL)
16309     TYPE_TAG_NAME (type) = name;
16310
16311   attr = dwarf2_attr (die, DW_AT_type, cu);
16312   if (attr != NULL)
16313     {
16314       struct type *underlying_type = die_type (die, cu);
16315
16316       TYPE_TARGET_TYPE (type) = underlying_type;
16317     }
16318
16319   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16320   if (attr)
16321     {
16322       TYPE_LENGTH (type) = DW_UNSND (attr);
16323     }
16324   else
16325     {
16326       TYPE_LENGTH (type) = 0;
16327     }
16328
16329   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16330      declared as private in the package spec, and then defined only
16331      inside the package body.  Such types are known as Taft Amendment
16332      Types.  When another package uses such a type, an incomplete DIE
16333      may be generated by the compiler.  */
16334   if (die_is_declaration (die, cu))
16335     TYPE_STUB (type) = 1;
16336
16337   /* Finish the creation of this type by using the enum's children.
16338      We must call this even when the underlying type has been provided
16339      so that we can determine if we're looking at a "flag" enum.  */
16340   update_enumeration_type_from_children (die, type, cu);
16341
16342   /* If this type has an underlying type that is not a stub, then we
16343      may use its attributes.  We always use the "unsigned" attribute
16344      in this situation, because ordinarily we guess whether the type
16345      is unsigned -- but the guess can be wrong and the underlying type
16346      can tell us the reality.  However, we defer to a local size
16347      attribute if one exists, because this lets the compiler override
16348      the underlying type if needed.  */
16349   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16350     {
16351       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16352       if (TYPE_LENGTH (type) == 0)
16353         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16354     }
16355
16356   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16357
16358   return set_die_type (die, type, cu);
16359 }
16360
16361 /* Given a pointer to a die which begins an enumeration, process all
16362    the dies that define the members of the enumeration, and create the
16363    symbol for the enumeration type.
16364
16365    NOTE: We reverse the order of the element list.  */
16366
16367 static void
16368 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16369 {
16370   struct type *this_type;
16371
16372   this_type = get_die_type (die, cu);
16373   if (this_type == NULL)
16374     this_type = read_enumeration_type (die, cu);
16375
16376   if (die->child != NULL)
16377     {
16378       struct die_info *child_die;
16379       struct symbol *sym;
16380       struct field *fields = NULL;
16381       int num_fields = 0;
16382       const char *name;
16383
16384       child_die = die->child;
16385       while (child_die && child_die->tag)
16386         {
16387           if (child_die->tag != DW_TAG_enumerator)
16388             {
16389               process_die (child_die, cu);
16390             }
16391           else
16392             {
16393               name = dwarf2_name (child_die, cu);
16394               if (name)
16395                 {
16396                   sym = new_symbol (child_die, this_type, cu);
16397
16398                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16399                     {
16400                       fields = (struct field *)
16401                         xrealloc (fields,
16402                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16403                                   * sizeof (struct field));
16404                     }
16405
16406                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16407                   FIELD_TYPE (fields[num_fields]) = NULL;
16408                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16409                   FIELD_BITSIZE (fields[num_fields]) = 0;
16410
16411                   num_fields++;
16412                 }
16413             }
16414
16415           child_die = sibling_die (child_die);
16416         }
16417
16418       if (num_fields)
16419         {
16420           TYPE_NFIELDS (this_type) = num_fields;
16421           TYPE_FIELDS (this_type) = (struct field *)
16422             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16423           memcpy (TYPE_FIELDS (this_type), fields,
16424                   sizeof (struct field) * num_fields);
16425           xfree (fields);
16426         }
16427     }
16428
16429   /* If we are reading an enum from a .debug_types unit, and the enum
16430      is a declaration, and the enum is not the signatured type in the
16431      unit, then we do not want to add a symbol for it.  Adding a
16432      symbol would in some cases obscure the true definition of the
16433      enum, giving users an incomplete type when the definition is
16434      actually available.  Note that we do not want to do this for all
16435      enums which are just declarations, because C++0x allows forward
16436      enum declarations.  */
16437   if (cu->per_cu->is_debug_types
16438       && die_is_declaration (die, cu))
16439     {
16440       struct signatured_type *sig_type;
16441
16442       sig_type = (struct signatured_type *) cu->per_cu;
16443       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16444       if (sig_type->type_offset_in_section != die->sect_off)
16445         return;
16446     }
16447
16448   new_symbol (die, this_type, cu);
16449 }
16450
16451 /* Extract all information from a DW_TAG_array_type DIE and put it in
16452    the DIE's type field.  For now, this only handles one dimensional
16453    arrays.  */
16454
16455 static struct type *
16456 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16457 {
16458   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16459   struct die_info *child_die;
16460   struct type *type;
16461   struct type *element_type, *range_type, *index_type;
16462   struct attribute *attr;
16463   const char *name;
16464   struct dynamic_prop *byte_stride_prop = NULL;
16465   unsigned int bit_stride = 0;
16466
16467   element_type = die_type (die, cu);
16468
16469   /* The die_type call above may have already set the type for this DIE.  */
16470   type = get_die_type (die, cu);
16471   if (type)
16472     return type;
16473
16474   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16475   if (attr != NULL)
16476     {
16477       int stride_ok;
16478
16479       byte_stride_prop
16480         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16481       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16482       if (!stride_ok)
16483         {
16484           complaint (&symfile_complaints,
16485                      _("unable to read array DW_AT_byte_stride "
16486                        " - DIE at %s [in module %s]"),
16487                      sect_offset_str (die->sect_off),
16488                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16489           /* Ignore this attribute.  We will likely not be able to print
16490              arrays of this type correctly, but there is little we can do
16491              to help if we cannot read the attribute's value.  */
16492           byte_stride_prop = NULL;
16493         }
16494     }
16495
16496   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16497   if (attr != NULL)
16498     bit_stride = DW_UNSND (attr);
16499
16500   /* Irix 6.2 native cc creates array types without children for
16501      arrays with unspecified length.  */
16502   if (die->child == NULL)
16503     {
16504       index_type = objfile_type (objfile)->builtin_int;
16505       range_type = create_static_range_type (NULL, index_type, 0, -1);
16506       type = create_array_type_with_stride (NULL, element_type, range_type,
16507                                             byte_stride_prop, bit_stride);
16508       return set_die_type (die, type, cu);
16509     }
16510
16511   std::vector<struct type *> range_types;
16512   child_die = die->child;
16513   while (child_die && child_die->tag)
16514     {
16515       if (child_die->tag == DW_TAG_subrange_type)
16516         {
16517           struct type *child_type = read_type_die (child_die, cu);
16518
16519           if (child_type != NULL)
16520             {
16521               /* The range type was succesfully read.  Save it for the
16522                  array type creation.  */
16523               range_types.push_back (child_type);
16524             }
16525         }
16526       child_die = sibling_die (child_die);
16527     }
16528
16529   /* Dwarf2 dimensions are output from left to right, create the
16530      necessary array types in backwards order.  */
16531
16532   type = element_type;
16533
16534   if (read_array_order (die, cu) == DW_ORD_col_major)
16535     {
16536       int i = 0;
16537
16538       while (i < range_types.size ())
16539         type = create_array_type_with_stride (NULL, type, range_types[i++],
16540                                               byte_stride_prop, bit_stride);
16541     }
16542   else
16543     {
16544       size_t ndim = range_types.size ();
16545       while (ndim-- > 0)
16546         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16547                                               byte_stride_prop, bit_stride);
16548     }
16549
16550   /* Understand Dwarf2 support for vector types (like they occur on
16551      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16552      array type.  This is not part of the Dwarf2/3 standard yet, but a
16553      custom vendor extension.  The main difference between a regular
16554      array and the vector variant is that vectors are passed by value
16555      to functions.  */
16556   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16557   if (attr)
16558     make_vector_type (type);
16559
16560   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16561      implementation may choose to implement triple vectors using this
16562      attribute.  */
16563   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16564   if (attr)
16565     {
16566       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16567         TYPE_LENGTH (type) = DW_UNSND (attr);
16568       else
16569         complaint (&symfile_complaints,
16570                    _("DW_AT_byte_size for array type smaller "
16571                      "than the total size of elements"));
16572     }
16573
16574   name = dwarf2_name (die, cu);
16575   if (name)
16576     TYPE_NAME (type) = name;
16577
16578   /* Install the type in the die.  */
16579   set_die_type (die, type, cu);
16580
16581   /* set_die_type should be already done.  */
16582   set_descriptive_type (type, die, cu);
16583
16584   return type;
16585 }
16586
16587 static enum dwarf_array_dim_ordering
16588 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16589 {
16590   struct attribute *attr;
16591
16592   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16593
16594   if (attr)
16595     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16596
16597   /* GNU F77 is a special case, as at 08/2004 array type info is the
16598      opposite order to the dwarf2 specification, but data is still
16599      laid out as per normal fortran.
16600
16601      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16602      version checking.  */
16603
16604   if (cu->language == language_fortran
16605       && cu->producer && strstr (cu->producer, "GNU F77"))
16606     {
16607       return DW_ORD_row_major;
16608     }
16609
16610   switch (cu->language_defn->la_array_ordering)
16611     {
16612     case array_column_major:
16613       return DW_ORD_col_major;
16614     case array_row_major:
16615     default:
16616       return DW_ORD_row_major;
16617     };
16618 }
16619
16620 /* Extract all information from a DW_TAG_set_type DIE and put it in
16621    the DIE's type field.  */
16622
16623 static struct type *
16624 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16625 {
16626   struct type *domain_type, *set_type;
16627   struct attribute *attr;
16628
16629   domain_type = die_type (die, cu);
16630
16631   /* The die_type call above may have already set the type for this DIE.  */
16632   set_type = get_die_type (die, cu);
16633   if (set_type)
16634     return set_type;
16635
16636   set_type = create_set_type (NULL, domain_type);
16637
16638   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16639   if (attr)
16640     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16641
16642   return set_die_type (die, set_type, cu);
16643 }
16644
16645 /* A helper for read_common_block that creates a locexpr baton.
16646    SYM is the symbol which we are marking as computed.
16647    COMMON_DIE is the DIE for the common block.
16648    COMMON_LOC is the location expression attribute for the common
16649    block itself.
16650    MEMBER_LOC is the location expression attribute for the particular
16651    member of the common block that we are processing.
16652    CU is the CU from which the above come.  */
16653
16654 static void
16655 mark_common_block_symbol_computed (struct symbol *sym,
16656                                    struct die_info *common_die,
16657                                    struct attribute *common_loc,
16658                                    struct attribute *member_loc,
16659                                    struct dwarf2_cu *cu)
16660 {
16661   struct dwarf2_per_objfile *dwarf2_per_objfile
16662     = cu->per_cu->dwarf2_per_objfile;
16663   struct objfile *objfile = dwarf2_per_objfile->objfile;
16664   struct dwarf2_locexpr_baton *baton;
16665   gdb_byte *ptr;
16666   unsigned int cu_off;
16667   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16668   LONGEST offset = 0;
16669
16670   gdb_assert (common_loc && member_loc);
16671   gdb_assert (attr_form_is_block (common_loc));
16672   gdb_assert (attr_form_is_block (member_loc)
16673               || attr_form_is_constant (member_loc));
16674
16675   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16676   baton->per_cu = cu->per_cu;
16677   gdb_assert (baton->per_cu);
16678
16679   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16680
16681   if (attr_form_is_constant (member_loc))
16682     {
16683       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16684       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16685     }
16686   else
16687     baton->size += DW_BLOCK (member_loc)->size;
16688
16689   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16690   baton->data = ptr;
16691
16692   *ptr++ = DW_OP_call4;
16693   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16694   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16695   ptr += 4;
16696
16697   if (attr_form_is_constant (member_loc))
16698     {
16699       *ptr++ = DW_OP_addr;
16700       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16701       ptr += cu->header.addr_size;
16702     }
16703   else
16704     {
16705       /* We have to copy the data here, because DW_OP_call4 will only
16706          use a DW_AT_location attribute.  */
16707       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16708       ptr += DW_BLOCK (member_loc)->size;
16709     }
16710
16711   *ptr++ = DW_OP_plus;
16712   gdb_assert (ptr - baton->data == baton->size);
16713
16714   SYMBOL_LOCATION_BATON (sym) = baton;
16715   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16716 }
16717
16718 /* Create appropriate locally-scoped variables for all the
16719    DW_TAG_common_block entries.  Also create a struct common_block
16720    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16721    is used to sepate the common blocks name namespace from regular
16722    variable names.  */
16723
16724 static void
16725 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16726 {
16727   struct attribute *attr;
16728
16729   attr = dwarf2_attr (die, DW_AT_location, cu);
16730   if (attr)
16731     {
16732       /* Support the .debug_loc offsets.  */
16733       if (attr_form_is_block (attr))
16734         {
16735           /* Ok.  */
16736         }
16737       else if (attr_form_is_section_offset (attr))
16738         {
16739           dwarf2_complex_location_expr_complaint ();
16740           attr = NULL;
16741         }
16742       else
16743         {
16744           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16745                                                  "common block member");
16746           attr = NULL;
16747         }
16748     }
16749
16750   if (die->child != NULL)
16751     {
16752       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16753       struct die_info *child_die;
16754       size_t n_entries = 0, size;
16755       struct common_block *common_block;
16756       struct symbol *sym;
16757
16758       for (child_die = die->child;
16759            child_die && child_die->tag;
16760            child_die = sibling_die (child_die))
16761         ++n_entries;
16762
16763       size = (sizeof (struct common_block)
16764               + (n_entries - 1) * sizeof (struct symbol *));
16765       common_block
16766         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16767                                                  size);
16768       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16769       common_block->n_entries = 0;
16770
16771       for (child_die = die->child;
16772            child_die && child_die->tag;
16773            child_die = sibling_die (child_die))
16774         {
16775           /* Create the symbol in the DW_TAG_common_block block in the current
16776              symbol scope.  */
16777           sym = new_symbol (child_die, NULL, cu);
16778           if (sym != NULL)
16779             {
16780               struct attribute *member_loc;
16781
16782               common_block->contents[common_block->n_entries++] = sym;
16783
16784               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16785                                         cu);
16786               if (member_loc)
16787                 {
16788                   /* GDB has handled this for a long time, but it is
16789                      not specified by DWARF.  It seems to have been
16790                      emitted by gfortran at least as recently as:
16791                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16792                   complaint (&symfile_complaints,
16793                              _("Variable in common block has "
16794                                "DW_AT_data_member_location "
16795                                "- DIE at %s [in module %s]"),
16796                                sect_offset_str (child_die->sect_off),
16797                              objfile_name (objfile));
16798
16799                   if (attr_form_is_section_offset (member_loc))
16800                     dwarf2_complex_location_expr_complaint ();
16801                   else if (attr_form_is_constant (member_loc)
16802                            || attr_form_is_block (member_loc))
16803                     {
16804                       if (attr)
16805                         mark_common_block_symbol_computed (sym, die, attr,
16806                                                            member_loc, cu);
16807                     }
16808                   else
16809                     dwarf2_complex_location_expr_complaint ();
16810                 }
16811             }
16812         }
16813
16814       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16815       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16816     }
16817 }
16818
16819 /* Create a type for a C++ namespace.  */
16820
16821 static struct type *
16822 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16823 {
16824   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16825   const char *previous_prefix, *name;
16826   int is_anonymous;
16827   struct type *type;
16828
16829   /* For extensions, reuse the type of the original namespace.  */
16830   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16831     {
16832       struct die_info *ext_die;
16833       struct dwarf2_cu *ext_cu = cu;
16834
16835       ext_die = dwarf2_extension (die, &ext_cu);
16836       type = read_type_die (ext_die, ext_cu);
16837
16838       /* EXT_CU may not be the same as CU.
16839          Ensure TYPE is recorded with CU in die_type_hash.  */
16840       return set_die_type (die, type, cu);
16841     }
16842
16843   name = namespace_name (die, &is_anonymous, cu);
16844
16845   /* Now build the name of the current namespace.  */
16846
16847   previous_prefix = determine_prefix (die, cu);
16848   if (previous_prefix[0] != '\0')
16849     name = typename_concat (&objfile->objfile_obstack,
16850                             previous_prefix, name, 0, cu);
16851
16852   /* Create the type.  */
16853   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16854   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16855
16856   return set_die_type (die, type, cu);
16857 }
16858
16859 /* Read a namespace scope.  */
16860
16861 static void
16862 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16863 {
16864   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16865   int is_anonymous;
16866
16867   /* Add a symbol associated to this if we haven't seen the namespace
16868      before.  Also, add a using directive if it's an anonymous
16869      namespace.  */
16870
16871   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16872     {
16873       struct type *type;
16874
16875       type = read_type_die (die, cu);
16876       new_symbol (die, type, cu);
16877
16878       namespace_name (die, &is_anonymous, cu);
16879       if (is_anonymous)
16880         {
16881           const char *previous_prefix = determine_prefix (die, cu);
16882
16883           std::vector<const char *> excludes;
16884           add_using_directive (using_directives (cu->language),
16885                                previous_prefix, TYPE_NAME (type), NULL,
16886                                NULL, excludes, 0, &objfile->objfile_obstack);
16887         }
16888     }
16889
16890   if (die->child != NULL)
16891     {
16892       struct die_info *child_die = die->child;
16893
16894       while (child_die && child_die->tag)
16895         {
16896           process_die (child_die, cu);
16897           child_die = sibling_die (child_die);
16898         }
16899     }
16900 }
16901
16902 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16903    imported module.  Still we need that type as local Fortran "use ... only"
16904    declaration imports depend on the created type in determine_prefix.  */
16905
16906 static struct type *
16907 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16908 {
16909   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16910   const char *module_name;
16911   struct type *type;
16912
16913   module_name = dwarf2_name (die, cu);
16914   if (!module_name)
16915     complaint (&symfile_complaints,
16916                _("DW_TAG_module has no name, offset %s"),
16917                sect_offset_str (die->sect_off));
16918   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16919
16920   /* determine_prefix uses TYPE_TAG_NAME.  */
16921   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16922
16923   return set_die_type (die, type, cu);
16924 }
16925
16926 /* Read a Fortran module.  */
16927
16928 static void
16929 read_module (struct die_info *die, struct dwarf2_cu *cu)
16930 {
16931   struct die_info *child_die = die->child;
16932   struct type *type;
16933
16934   type = read_type_die (die, cu);
16935   new_symbol (die, type, cu);
16936
16937   while (child_die && child_die->tag)
16938     {
16939       process_die (child_die, cu);
16940       child_die = sibling_die (child_die);
16941     }
16942 }
16943
16944 /* Return the name of the namespace represented by DIE.  Set
16945    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16946    namespace.  */
16947
16948 static const char *
16949 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16950 {
16951   struct die_info *current_die;
16952   const char *name = NULL;
16953
16954   /* Loop through the extensions until we find a name.  */
16955
16956   for (current_die = die;
16957        current_die != NULL;
16958        current_die = dwarf2_extension (die, &cu))
16959     {
16960       /* We don't use dwarf2_name here so that we can detect the absence
16961          of a name -> anonymous namespace.  */
16962       name = dwarf2_string_attr (die, DW_AT_name, cu);
16963
16964       if (name != NULL)
16965         break;
16966     }
16967
16968   /* Is it an anonymous namespace?  */
16969
16970   *is_anonymous = (name == NULL);
16971   if (*is_anonymous)
16972     name = CP_ANONYMOUS_NAMESPACE_STR;
16973
16974   return name;
16975 }
16976
16977 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16978    the user defined type vector.  */
16979
16980 static struct type *
16981 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16982 {
16983   struct gdbarch *gdbarch
16984     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16985   struct comp_unit_head *cu_header = &cu->header;
16986   struct type *type;
16987   struct attribute *attr_byte_size;
16988   struct attribute *attr_address_class;
16989   int byte_size, addr_class;
16990   struct type *target_type;
16991
16992   target_type = die_type (die, cu);
16993
16994   /* The die_type call above may have already set the type for this DIE.  */
16995   type = get_die_type (die, cu);
16996   if (type)
16997     return type;
16998
16999   type = lookup_pointer_type (target_type);
17000
17001   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17002   if (attr_byte_size)
17003     byte_size = DW_UNSND (attr_byte_size);
17004   else
17005     byte_size = cu_header->addr_size;
17006
17007   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17008   if (attr_address_class)
17009     addr_class = DW_UNSND (attr_address_class);
17010   else
17011     addr_class = DW_ADDR_none;
17012
17013   /* If the pointer size or address class is different than the
17014      default, create a type variant marked as such and set the
17015      length accordingly.  */
17016   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17017     {
17018       if (gdbarch_address_class_type_flags_p (gdbarch))
17019         {
17020           int type_flags;
17021
17022           type_flags = gdbarch_address_class_type_flags
17023                          (gdbarch, byte_size, addr_class);
17024           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17025                       == 0);
17026           type = make_type_with_address_space (type, type_flags);
17027         }
17028       else if (TYPE_LENGTH (type) != byte_size)
17029         {
17030           complaint (&symfile_complaints,
17031                      _("invalid pointer size %d"), byte_size);
17032         }
17033       else
17034         {
17035           /* Should we also complain about unhandled address classes?  */
17036         }
17037     }
17038
17039   TYPE_LENGTH (type) = byte_size;
17040   return set_die_type (die, type, cu);
17041 }
17042
17043 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17044    the user defined type vector.  */
17045
17046 static struct type *
17047 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17048 {
17049   struct type *type;
17050   struct type *to_type;
17051   struct type *domain;
17052
17053   to_type = die_type (die, cu);
17054   domain = die_containing_type (die, cu);
17055
17056   /* The calls above may have already set the type for this DIE.  */
17057   type = get_die_type (die, cu);
17058   if (type)
17059     return type;
17060
17061   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17062     type = lookup_methodptr_type (to_type);
17063   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17064     {
17065       struct type *new_type
17066         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17067
17068       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17069                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17070                             TYPE_VARARGS (to_type));
17071       type = lookup_methodptr_type (new_type);
17072     }
17073   else
17074     type = lookup_memberptr_type (to_type, domain);
17075
17076   return set_die_type (die, type, cu);
17077 }
17078
17079 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17080    the user defined type vector.  */
17081
17082 static struct type *
17083 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17084                           enum type_code refcode)
17085 {
17086   struct comp_unit_head *cu_header = &cu->header;
17087   struct type *type, *target_type;
17088   struct attribute *attr;
17089
17090   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17091
17092   target_type = die_type (die, cu);
17093
17094   /* The die_type call above may have already set the type for this DIE.  */
17095   type = get_die_type (die, cu);
17096   if (type)
17097     return type;
17098
17099   type = lookup_reference_type (target_type, refcode);
17100   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17101   if (attr)
17102     {
17103       TYPE_LENGTH (type) = DW_UNSND (attr);
17104     }
17105   else
17106     {
17107       TYPE_LENGTH (type) = cu_header->addr_size;
17108     }
17109   return set_die_type (die, type, cu);
17110 }
17111
17112 /* Add the given cv-qualifiers to the element type of the array.  GCC
17113    outputs DWARF type qualifiers that apply to an array, not the
17114    element type.  But GDB relies on the array element type to carry
17115    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17116    specification.  */
17117
17118 static struct type *
17119 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17120                    struct type *base_type, int cnst, int voltl)
17121 {
17122   struct type *el_type, *inner_array;
17123
17124   base_type = copy_type (base_type);
17125   inner_array = base_type;
17126
17127   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17128     {
17129       TYPE_TARGET_TYPE (inner_array) =
17130         copy_type (TYPE_TARGET_TYPE (inner_array));
17131       inner_array = TYPE_TARGET_TYPE (inner_array);
17132     }
17133
17134   el_type = TYPE_TARGET_TYPE (inner_array);
17135   cnst |= TYPE_CONST (el_type);
17136   voltl |= TYPE_VOLATILE (el_type);
17137   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17138
17139   return set_die_type (die, base_type, cu);
17140 }
17141
17142 static struct type *
17143 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17144 {
17145   struct type *base_type, *cv_type;
17146
17147   base_type = die_type (die, cu);
17148
17149   /* The die_type call above may have already set the type for this DIE.  */
17150   cv_type = get_die_type (die, cu);
17151   if (cv_type)
17152     return cv_type;
17153
17154   /* In case the const qualifier is applied to an array type, the element type
17155      is so qualified, not the array type (section 6.7.3 of C99).  */
17156   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17157     return add_array_cv_type (die, cu, base_type, 1, 0);
17158
17159   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17160   return set_die_type (die, cv_type, cu);
17161 }
17162
17163 static struct type *
17164 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17165 {
17166   struct type *base_type, *cv_type;
17167
17168   base_type = die_type (die, cu);
17169
17170   /* The die_type call above may have already set the type for this DIE.  */
17171   cv_type = get_die_type (die, cu);
17172   if (cv_type)
17173     return cv_type;
17174
17175   /* In case the volatile qualifier is applied to an array type, the
17176      element type is so qualified, not the array type (section 6.7.3
17177      of C99).  */
17178   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17179     return add_array_cv_type (die, cu, base_type, 0, 1);
17180
17181   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17182   return set_die_type (die, cv_type, cu);
17183 }
17184
17185 /* Handle DW_TAG_restrict_type.  */
17186
17187 static struct type *
17188 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17189 {
17190   struct type *base_type, *cv_type;
17191
17192   base_type = die_type (die, cu);
17193
17194   /* The die_type call above may have already set the type for this DIE.  */
17195   cv_type = get_die_type (die, cu);
17196   if (cv_type)
17197     return cv_type;
17198
17199   cv_type = make_restrict_type (base_type);
17200   return set_die_type (die, cv_type, cu);
17201 }
17202
17203 /* Handle DW_TAG_atomic_type.  */
17204
17205 static struct type *
17206 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17207 {
17208   struct type *base_type, *cv_type;
17209
17210   base_type = die_type (die, cu);
17211
17212   /* The die_type call above may have already set the type for this DIE.  */
17213   cv_type = get_die_type (die, cu);
17214   if (cv_type)
17215     return cv_type;
17216
17217   cv_type = make_atomic_type (base_type);
17218   return set_die_type (die, cv_type, cu);
17219 }
17220
17221 /* Extract all information from a DW_TAG_string_type DIE and add to
17222    the user defined type vector.  It isn't really a user defined type,
17223    but it behaves like one, with other DIE's using an AT_user_def_type
17224    attribute to reference it.  */
17225
17226 static struct type *
17227 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17228 {
17229   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17230   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17231   struct type *type, *range_type, *index_type, *char_type;
17232   struct attribute *attr;
17233   unsigned int length;
17234
17235   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17236   if (attr)
17237     {
17238       length = DW_UNSND (attr);
17239     }
17240   else
17241     {
17242       /* Check for the DW_AT_byte_size attribute.  */
17243       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17244       if (attr)
17245         {
17246           length = DW_UNSND (attr);
17247         }
17248       else
17249         {
17250           length = 1;
17251         }
17252     }
17253
17254   index_type = objfile_type (objfile)->builtin_int;
17255   range_type = create_static_range_type (NULL, index_type, 1, length);
17256   char_type = language_string_char_type (cu->language_defn, gdbarch);
17257   type = create_string_type (NULL, char_type, range_type);
17258
17259   return set_die_type (die, type, cu);
17260 }
17261
17262 /* Assuming that DIE corresponds to a function, returns nonzero
17263    if the function is prototyped.  */
17264
17265 static int
17266 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17267 {
17268   struct attribute *attr;
17269
17270   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17271   if (attr && (DW_UNSND (attr) != 0))
17272     return 1;
17273
17274   /* The DWARF standard implies that the DW_AT_prototyped attribute
17275      is only meaninful for C, but the concept also extends to other
17276      languages that allow unprototyped functions (Eg: Objective C).
17277      For all other languages, assume that functions are always
17278      prototyped.  */
17279   if (cu->language != language_c
17280       && cu->language != language_objc
17281       && cu->language != language_opencl)
17282     return 1;
17283
17284   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17285      prototyped and unprototyped functions; default to prototyped,
17286      since that is more common in modern code (and RealView warns
17287      about unprototyped functions).  */
17288   if (producer_is_realview (cu->producer))
17289     return 1;
17290
17291   return 0;
17292 }
17293
17294 /* Handle DIES due to C code like:
17295
17296    struct foo
17297    {
17298    int (*funcp)(int a, long l);
17299    int b;
17300    };
17301
17302    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17303
17304 static struct type *
17305 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17306 {
17307   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17308   struct type *type;            /* Type that this function returns.  */
17309   struct type *ftype;           /* Function that returns above type.  */
17310   struct attribute *attr;
17311
17312   type = die_type (die, cu);
17313
17314   /* The die_type call above may have already set the type for this DIE.  */
17315   ftype = get_die_type (die, cu);
17316   if (ftype)
17317     return ftype;
17318
17319   ftype = lookup_function_type (type);
17320
17321   if (prototyped_function_p (die, cu))
17322     TYPE_PROTOTYPED (ftype) = 1;
17323
17324   /* Store the calling convention in the type if it's available in
17325      the subroutine die.  Otherwise set the calling convention to
17326      the default value DW_CC_normal.  */
17327   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17328   if (attr)
17329     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17330   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17331     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17332   else
17333     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17334
17335   /* Record whether the function returns normally to its caller or not
17336      if the DWARF producer set that information.  */
17337   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17338   if (attr && (DW_UNSND (attr) != 0))
17339     TYPE_NO_RETURN (ftype) = 1;
17340
17341   /* We need to add the subroutine type to the die immediately so
17342      we don't infinitely recurse when dealing with parameters
17343      declared as the same subroutine type.  */
17344   set_die_type (die, ftype, cu);
17345
17346   if (die->child != NULL)
17347     {
17348       struct type *void_type = objfile_type (objfile)->builtin_void;
17349       struct die_info *child_die;
17350       int nparams, iparams;
17351
17352       /* Count the number of parameters.
17353          FIXME: GDB currently ignores vararg functions, but knows about
17354          vararg member functions.  */
17355       nparams = 0;
17356       child_die = die->child;
17357       while (child_die && child_die->tag)
17358         {
17359           if (child_die->tag == DW_TAG_formal_parameter)
17360             nparams++;
17361           else if (child_die->tag == DW_TAG_unspecified_parameters)
17362             TYPE_VARARGS (ftype) = 1;
17363           child_die = sibling_die (child_die);
17364         }
17365
17366       /* Allocate storage for parameters and fill them in.  */
17367       TYPE_NFIELDS (ftype) = nparams;
17368       TYPE_FIELDS (ftype) = (struct field *)
17369         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17370
17371       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17372          even if we error out during the parameters reading below.  */
17373       for (iparams = 0; iparams < nparams; iparams++)
17374         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17375
17376       iparams = 0;
17377       child_die = die->child;
17378       while (child_die && child_die->tag)
17379         {
17380           if (child_die->tag == DW_TAG_formal_parameter)
17381             {
17382               struct type *arg_type;
17383
17384               /* DWARF version 2 has no clean way to discern C++
17385                  static and non-static member functions.  G++ helps
17386                  GDB by marking the first parameter for non-static
17387                  member functions (which is the this pointer) as
17388                  artificial.  We pass this information to
17389                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17390
17391                  DWARF version 3 added DW_AT_object_pointer, which GCC
17392                  4.5 does not yet generate.  */
17393               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17394               if (attr)
17395                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17396               else
17397                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17398               arg_type = die_type (child_die, cu);
17399
17400               /* RealView does not mark THIS as const, which the testsuite
17401                  expects.  GCC marks THIS as const in method definitions,
17402                  but not in the class specifications (GCC PR 43053).  */
17403               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17404                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17405                 {
17406                   int is_this = 0;
17407                   struct dwarf2_cu *arg_cu = cu;
17408                   const char *name = dwarf2_name (child_die, cu);
17409
17410                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17411                   if (attr)
17412                     {
17413                       /* If the compiler emits this, use it.  */
17414                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17415                         is_this = 1;
17416                     }
17417                   else if (name && strcmp (name, "this") == 0)
17418                     /* Function definitions will have the argument names.  */
17419                     is_this = 1;
17420                   else if (name == NULL && iparams == 0)
17421                     /* Declarations may not have the names, so like
17422                        elsewhere in GDB, assume an artificial first
17423                        argument is "this".  */
17424                     is_this = 1;
17425
17426                   if (is_this)
17427                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17428                                              arg_type, 0);
17429                 }
17430
17431               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17432               iparams++;
17433             }
17434           child_die = sibling_die (child_die);
17435         }
17436     }
17437
17438   return ftype;
17439 }
17440
17441 static struct type *
17442 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17443 {
17444   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17445   const char *name = NULL;
17446   struct type *this_type, *target_type;
17447
17448   name = dwarf2_full_name (NULL, die, cu);
17449   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17450   TYPE_TARGET_STUB (this_type) = 1;
17451   set_die_type (die, this_type, cu);
17452   target_type = die_type (die, cu);
17453   if (target_type != this_type)
17454     TYPE_TARGET_TYPE (this_type) = target_type;
17455   else
17456     {
17457       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17458          spec and cause infinite loops in GDB.  */
17459       complaint (&symfile_complaints,
17460                  _("Self-referential DW_TAG_typedef "
17461                    "- DIE at %s [in module %s]"),
17462                  sect_offset_str (die->sect_off), objfile_name (objfile));
17463       TYPE_TARGET_TYPE (this_type) = NULL;
17464     }
17465   return this_type;
17466 }
17467
17468 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17469    (which may be different from NAME) to the architecture back-end to allow
17470    it to guess the correct format if necessary.  */
17471
17472 static struct type *
17473 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17474                         const char *name_hint)
17475 {
17476   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17477   const struct floatformat **format;
17478   struct type *type;
17479
17480   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17481   if (format)
17482     type = init_float_type (objfile, bits, name, format);
17483   else
17484     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17485
17486   return type;
17487 }
17488
17489 /* Find a representation of a given base type and install
17490    it in the TYPE field of the die.  */
17491
17492 static struct type *
17493 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17494 {
17495   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17496   struct type *type;
17497   struct attribute *attr;
17498   int encoding = 0, bits = 0;
17499   const char *name;
17500
17501   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17502   if (attr)
17503     {
17504       encoding = DW_UNSND (attr);
17505     }
17506   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17507   if (attr)
17508     {
17509       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17510     }
17511   name = dwarf2_name (die, cu);
17512   if (!name)
17513     {
17514       complaint (&symfile_complaints,
17515                  _("DW_AT_name missing from DW_TAG_base_type"));
17516     }
17517
17518   switch (encoding)
17519     {
17520       case DW_ATE_address:
17521         /* Turn DW_ATE_address into a void * pointer.  */
17522         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17523         type = init_pointer_type (objfile, bits, name, type);
17524         break;
17525       case DW_ATE_boolean:
17526         type = init_boolean_type (objfile, bits, 1, name);
17527         break;
17528       case DW_ATE_complex_float:
17529         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17530         type = init_complex_type (objfile, name, type);
17531         break;
17532       case DW_ATE_decimal_float:
17533         type = init_decfloat_type (objfile, bits, name);
17534         break;
17535       case DW_ATE_float:
17536         type = dwarf2_init_float_type (objfile, bits, name, name);
17537         break;
17538       case DW_ATE_signed:
17539         type = init_integer_type (objfile, bits, 0, name);
17540         break;
17541       case DW_ATE_unsigned:
17542         if (cu->language == language_fortran
17543             && name
17544             && startswith (name, "character("))
17545           type = init_character_type (objfile, bits, 1, name);
17546         else
17547           type = init_integer_type (objfile, bits, 1, name);
17548         break;
17549       case DW_ATE_signed_char:
17550         if (cu->language == language_ada || cu->language == language_m2
17551             || cu->language == language_pascal
17552             || cu->language == language_fortran)
17553           type = init_character_type (objfile, bits, 0, name);
17554         else
17555           type = init_integer_type (objfile, bits, 0, name);
17556         break;
17557       case DW_ATE_unsigned_char:
17558         if (cu->language == language_ada || cu->language == language_m2
17559             || cu->language == language_pascal
17560             || cu->language == language_fortran
17561             || cu->language == language_rust)
17562           type = init_character_type (objfile, bits, 1, name);
17563         else
17564           type = init_integer_type (objfile, bits, 1, name);
17565         break;
17566       case DW_ATE_UTF:
17567         {
17568           gdbarch *arch = get_objfile_arch (objfile);
17569
17570           if (bits == 16)
17571             type = builtin_type (arch)->builtin_char16;
17572           else if (bits == 32)
17573             type = builtin_type (arch)->builtin_char32;
17574           else
17575             {
17576               complaint (&symfile_complaints,
17577                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17578                          bits);
17579               type = init_integer_type (objfile, bits, 1, name);
17580             }
17581           return set_die_type (die, type, cu);
17582         }
17583         break;
17584
17585       default:
17586         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17587                    dwarf_type_encoding_name (encoding));
17588         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17589         break;
17590     }
17591
17592   if (name && strcmp (name, "char") == 0)
17593     TYPE_NOSIGN (type) = 1;
17594
17595   return set_die_type (die, type, cu);
17596 }
17597
17598 /* Parse dwarf attribute if it's a block, reference or constant and put the
17599    resulting value of the attribute into struct bound_prop.
17600    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17601
17602 static int
17603 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17604                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17605 {
17606   struct dwarf2_property_baton *baton;
17607   struct obstack *obstack
17608     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17609
17610   if (attr == NULL || prop == NULL)
17611     return 0;
17612
17613   if (attr_form_is_block (attr))
17614     {
17615       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17616       baton->referenced_type = NULL;
17617       baton->locexpr.per_cu = cu->per_cu;
17618       baton->locexpr.size = DW_BLOCK (attr)->size;
17619       baton->locexpr.data = DW_BLOCK (attr)->data;
17620       prop->data.baton = baton;
17621       prop->kind = PROP_LOCEXPR;
17622       gdb_assert (prop->data.baton != NULL);
17623     }
17624   else if (attr_form_is_ref (attr))
17625     {
17626       struct dwarf2_cu *target_cu = cu;
17627       struct die_info *target_die;
17628       struct attribute *target_attr;
17629
17630       target_die = follow_die_ref (die, attr, &target_cu);
17631       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17632       if (target_attr == NULL)
17633         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17634                                    target_cu);
17635       if (target_attr == NULL)
17636         return 0;
17637
17638       switch (target_attr->name)
17639         {
17640           case DW_AT_location:
17641             if (attr_form_is_section_offset (target_attr))
17642               {
17643                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17644                 baton->referenced_type = die_type (target_die, target_cu);
17645                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17646                 prop->data.baton = baton;
17647                 prop->kind = PROP_LOCLIST;
17648                 gdb_assert (prop->data.baton != NULL);
17649               }
17650             else if (attr_form_is_block (target_attr))
17651               {
17652                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17653                 baton->referenced_type = die_type (target_die, target_cu);
17654                 baton->locexpr.per_cu = cu->per_cu;
17655                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17656                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17657                 prop->data.baton = baton;
17658                 prop->kind = PROP_LOCEXPR;
17659                 gdb_assert (prop->data.baton != NULL);
17660               }
17661             else
17662               {
17663                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17664                                                        "dynamic property");
17665                 return 0;
17666               }
17667             break;
17668           case DW_AT_data_member_location:
17669             {
17670               LONGEST offset;
17671
17672               if (!handle_data_member_location (target_die, target_cu,
17673                                                 &offset))
17674                 return 0;
17675
17676               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17677               baton->referenced_type = read_type_die (target_die->parent,
17678                                                       target_cu);
17679               baton->offset_info.offset = offset;
17680               baton->offset_info.type = die_type (target_die, target_cu);
17681               prop->data.baton = baton;
17682               prop->kind = PROP_ADDR_OFFSET;
17683               break;
17684             }
17685         }
17686     }
17687   else if (attr_form_is_constant (attr))
17688     {
17689       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17690       prop->kind = PROP_CONST;
17691     }
17692   else
17693     {
17694       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17695                                              dwarf2_name (die, cu));
17696       return 0;
17697     }
17698
17699   return 1;
17700 }
17701
17702 /* Read the given DW_AT_subrange DIE.  */
17703
17704 static struct type *
17705 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17706 {
17707   struct type *base_type, *orig_base_type;
17708   struct type *range_type;
17709   struct attribute *attr;
17710   struct dynamic_prop low, high;
17711   int low_default_is_valid;
17712   int high_bound_is_count = 0;
17713   const char *name;
17714   LONGEST negative_mask;
17715
17716   orig_base_type = die_type (die, cu);
17717   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17718      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17719      creating the range type, but we use the result of check_typedef
17720      when examining properties of the type.  */
17721   base_type = check_typedef (orig_base_type);
17722
17723   /* The die_type call above may have already set the type for this DIE.  */
17724   range_type = get_die_type (die, cu);
17725   if (range_type)
17726     return range_type;
17727
17728   low.kind = PROP_CONST;
17729   high.kind = PROP_CONST;
17730   high.data.const_val = 0;
17731
17732   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17733      omitting DW_AT_lower_bound.  */
17734   switch (cu->language)
17735     {
17736     case language_c:
17737     case language_cplus:
17738       low.data.const_val = 0;
17739       low_default_is_valid = 1;
17740       break;
17741     case language_fortran:
17742       low.data.const_val = 1;
17743       low_default_is_valid = 1;
17744       break;
17745     case language_d:
17746     case language_objc:
17747     case language_rust:
17748       low.data.const_val = 0;
17749       low_default_is_valid = (cu->header.version >= 4);
17750       break;
17751     case language_ada:
17752     case language_m2:
17753     case language_pascal:
17754       low.data.const_val = 1;
17755       low_default_is_valid = (cu->header.version >= 4);
17756       break;
17757     default:
17758       low.data.const_val = 0;
17759       low_default_is_valid = 0;
17760       break;
17761     }
17762
17763   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17764   if (attr)
17765     attr_to_dynamic_prop (attr, die, cu, &low);
17766   else if (!low_default_is_valid)
17767     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17768                                       "- DIE at %s [in module %s]"),
17769                sect_offset_str (die->sect_off),
17770                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17771
17772   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17773   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17774     {
17775       attr = dwarf2_attr (die, DW_AT_count, cu);
17776       if (attr_to_dynamic_prop (attr, die, cu, &high))
17777         {
17778           /* If bounds are constant do the final calculation here.  */
17779           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17780             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17781           else
17782             high_bound_is_count = 1;
17783         }
17784     }
17785
17786   /* Dwarf-2 specifications explicitly allows to create subrange types
17787      without specifying a base type.
17788      In that case, the base type must be set to the type of
17789      the lower bound, upper bound or count, in that order, if any of these
17790      three attributes references an object that has a type.
17791      If no base type is found, the Dwarf-2 specifications say that
17792      a signed integer type of size equal to the size of an address should
17793      be used.
17794      For the following C code: `extern char gdb_int [];'
17795      GCC produces an empty range DIE.
17796      FIXME: muller/2010-05-28: Possible references to object for low bound,
17797      high bound or count are not yet handled by this code.  */
17798   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17799     {
17800       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17801       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17802       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17803       struct type *int_type = objfile_type (objfile)->builtin_int;
17804
17805       /* Test "int", "long int", and "long long int" objfile types,
17806          and select the first one having a size above or equal to the
17807          architecture address size.  */
17808       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17809         base_type = int_type;
17810       else
17811         {
17812           int_type = objfile_type (objfile)->builtin_long;
17813           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17814             base_type = int_type;
17815           else
17816             {
17817               int_type = objfile_type (objfile)->builtin_long_long;
17818               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17819                 base_type = int_type;
17820             }
17821         }
17822     }
17823
17824   /* Normally, the DWARF producers are expected to use a signed
17825      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17826      But this is unfortunately not always the case, as witnessed
17827      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17828      is used instead.  To work around that ambiguity, we treat
17829      the bounds as signed, and thus sign-extend their values, when
17830      the base type is signed.  */
17831   negative_mask =
17832     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17833   if (low.kind == PROP_CONST
17834       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17835     low.data.const_val |= negative_mask;
17836   if (high.kind == PROP_CONST
17837       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17838     high.data.const_val |= negative_mask;
17839
17840   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17841
17842   if (high_bound_is_count)
17843     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17844
17845   /* Ada expects an empty array on no boundary attributes.  */
17846   if (attr == NULL && cu->language != language_ada)
17847     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17848
17849   name = dwarf2_name (die, cu);
17850   if (name)
17851     TYPE_NAME (range_type) = name;
17852
17853   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17854   if (attr)
17855     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17856
17857   set_die_type (die, range_type, cu);
17858
17859   /* set_die_type should be already done.  */
17860   set_descriptive_type (range_type, die, cu);
17861
17862   return range_type;
17863 }
17864
17865 static struct type *
17866 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17867 {
17868   struct type *type;
17869
17870   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17871                     NULL);
17872   TYPE_NAME (type) = dwarf2_name (die, cu);
17873
17874   /* In Ada, an unspecified type is typically used when the description
17875      of the type is defered to a different unit.  When encountering
17876      such a type, we treat it as a stub, and try to resolve it later on,
17877      when needed.  */
17878   if (cu->language == language_ada)
17879     TYPE_STUB (type) = 1;
17880
17881   return set_die_type (die, type, cu);
17882 }
17883
17884 /* Read a single die and all its descendents.  Set the die's sibling
17885    field to NULL; set other fields in the die correctly, and set all
17886    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17887    location of the info_ptr after reading all of those dies.  PARENT
17888    is the parent of the die in question.  */
17889
17890 static struct die_info *
17891 read_die_and_children (const struct die_reader_specs *reader,
17892                        const gdb_byte *info_ptr,
17893                        const gdb_byte **new_info_ptr,
17894                        struct die_info *parent)
17895 {
17896   struct die_info *die;
17897   const gdb_byte *cur_ptr;
17898   int has_children;
17899
17900   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17901   if (die == NULL)
17902     {
17903       *new_info_ptr = cur_ptr;
17904       return NULL;
17905     }
17906   store_in_ref_table (die, reader->cu);
17907
17908   if (has_children)
17909     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17910   else
17911     {
17912       die->child = NULL;
17913       *new_info_ptr = cur_ptr;
17914     }
17915
17916   die->sibling = NULL;
17917   die->parent = parent;
17918   return die;
17919 }
17920
17921 /* Read a die, all of its descendents, and all of its siblings; set
17922    all of the fields of all of the dies correctly.  Arguments are as
17923    in read_die_and_children.  */
17924
17925 static struct die_info *
17926 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17927                          const gdb_byte *info_ptr,
17928                          const gdb_byte **new_info_ptr,
17929                          struct die_info *parent)
17930 {
17931   struct die_info *first_die, *last_sibling;
17932   const gdb_byte *cur_ptr;
17933
17934   cur_ptr = info_ptr;
17935   first_die = last_sibling = NULL;
17936
17937   while (1)
17938     {
17939       struct die_info *die
17940         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17941
17942       if (die == NULL)
17943         {
17944           *new_info_ptr = cur_ptr;
17945           return first_die;
17946         }
17947
17948       if (!first_die)
17949         first_die = die;
17950       else
17951         last_sibling->sibling = die;
17952
17953       last_sibling = die;
17954     }
17955 }
17956
17957 /* Read a die, all of its descendents, and all of its siblings; set
17958    all of the fields of all of the dies correctly.  Arguments are as
17959    in read_die_and_children.
17960    This the main entry point for reading a DIE and all its children.  */
17961
17962 static struct die_info *
17963 read_die_and_siblings (const struct die_reader_specs *reader,
17964                        const gdb_byte *info_ptr,
17965                        const gdb_byte **new_info_ptr,
17966                        struct die_info *parent)
17967 {
17968   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17969                                                   new_info_ptr, parent);
17970
17971   if (dwarf_die_debug)
17972     {
17973       fprintf_unfiltered (gdb_stdlog,
17974                           "Read die from %s@0x%x of %s:\n",
17975                           get_section_name (reader->die_section),
17976                           (unsigned) (info_ptr - reader->die_section->buffer),
17977                           bfd_get_filename (reader->abfd));
17978       dump_die (die, dwarf_die_debug);
17979     }
17980
17981   return die;
17982 }
17983
17984 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17985    attributes.
17986    The caller is responsible for filling in the extra attributes
17987    and updating (*DIEP)->num_attrs.
17988    Set DIEP to point to a newly allocated die with its information,
17989    except for its child, sibling, and parent fields.
17990    Set HAS_CHILDREN to tell whether the die has children or not.  */
17991
17992 static const gdb_byte *
17993 read_full_die_1 (const struct die_reader_specs *reader,
17994                  struct die_info **diep, const gdb_byte *info_ptr,
17995                  int *has_children, int num_extra_attrs)
17996 {
17997   unsigned int abbrev_number, bytes_read, i;
17998   struct abbrev_info *abbrev;
17999   struct die_info *die;
18000   struct dwarf2_cu *cu = reader->cu;
18001   bfd *abfd = reader->abfd;
18002
18003   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18004   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18005   info_ptr += bytes_read;
18006   if (!abbrev_number)
18007     {
18008       *diep = NULL;
18009       *has_children = 0;
18010       return info_ptr;
18011     }
18012
18013   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18014   if (!abbrev)
18015     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18016            abbrev_number,
18017            bfd_get_filename (abfd));
18018
18019   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18020   die->sect_off = sect_off;
18021   die->tag = abbrev->tag;
18022   die->abbrev = abbrev_number;
18023
18024   /* Make the result usable.
18025      The caller needs to update num_attrs after adding the extra
18026      attributes.  */
18027   die->num_attrs = abbrev->num_attrs;
18028
18029   for (i = 0; i < abbrev->num_attrs; ++i)
18030     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18031                                info_ptr);
18032
18033   *diep = die;
18034   *has_children = abbrev->has_children;
18035   return info_ptr;
18036 }
18037
18038 /* Read a die and all its attributes.
18039    Set DIEP to point to a newly allocated die with its information,
18040    except for its child, sibling, and parent fields.
18041    Set HAS_CHILDREN to tell whether the die has children or not.  */
18042
18043 static const gdb_byte *
18044 read_full_die (const struct die_reader_specs *reader,
18045                struct die_info **diep, const gdb_byte *info_ptr,
18046                int *has_children)
18047 {
18048   const gdb_byte *result;
18049
18050   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18051
18052   if (dwarf_die_debug)
18053     {
18054       fprintf_unfiltered (gdb_stdlog,
18055                           "Read die from %s@0x%x of %s:\n",
18056                           get_section_name (reader->die_section),
18057                           (unsigned) (info_ptr - reader->die_section->buffer),
18058                           bfd_get_filename (reader->abfd));
18059       dump_die (*diep, dwarf_die_debug);
18060     }
18061
18062   return result;
18063 }
18064 \f
18065 /* Abbreviation tables.
18066
18067    In DWARF version 2, the description of the debugging information is
18068    stored in a separate .debug_abbrev section.  Before we read any
18069    dies from a section we read in all abbreviations and install them
18070    in a hash table.  */
18071
18072 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18073
18074 struct abbrev_info *
18075 abbrev_table::alloc_abbrev ()
18076 {
18077   struct abbrev_info *abbrev;
18078
18079   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18080   memset (abbrev, 0, sizeof (struct abbrev_info));
18081
18082   return abbrev;
18083 }
18084
18085 /* Add an abbreviation to the table.  */
18086
18087 void
18088 abbrev_table::add_abbrev (unsigned int abbrev_number,
18089                           struct abbrev_info *abbrev)
18090 {
18091   unsigned int hash_number;
18092
18093   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18094   abbrev->next = m_abbrevs[hash_number];
18095   m_abbrevs[hash_number] = abbrev;
18096 }
18097
18098 /* Look up an abbrev in the table.
18099    Returns NULL if the abbrev is not found.  */
18100
18101 struct abbrev_info *
18102 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18103 {
18104   unsigned int hash_number;
18105   struct abbrev_info *abbrev;
18106
18107   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18108   abbrev = m_abbrevs[hash_number];
18109
18110   while (abbrev)
18111     {
18112       if (abbrev->number == abbrev_number)
18113         return abbrev;
18114       abbrev = abbrev->next;
18115     }
18116   return NULL;
18117 }
18118
18119 /* Read in an abbrev table.  */
18120
18121 static abbrev_table_up
18122 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18123                          struct dwarf2_section_info *section,
18124                          sect_offset sect_off)
18125 {
18126   struct objfile *objfile = dwarf2_per_objfile->objfile;
18127   bfd *abfd = get_section_bfd_owner (section);
18128   const gdb_byte *abbrev_ptr;
18129   struct abbrev_info *cur_abbrev;
18130   unsigned int abbrev_number, bytes_read, abbrev_name;
18131   unsigned int abbrev_form;
18132   struct attr_abbrev *cur_attrs;
18133   unsigned int allocated_attrs;
18134
18135   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18136
18137   dwarf2_read_section (objfile, section);
18138   abbrev_ptr = section->buffer + to_underlying (sect_off);
18139   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18140   abbrev_ptr += bytes_read;
18141
18142   allocated_attrs = ATTR_ALLOC_CHUNK;
18143   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18144
18145   /* Loop until we reach an abbrev number of 0.  */
18146   while (abbrev_number)
18147     {
18148       cur_abbrev = abbrev_table->alloc_abbrev ();
18149
18150       /* read in abbrev header */
18151       cur_abbrev->number = abbrev_number;
18152       cur_abbrev->tag
18153         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18154       abbrev_ptr += bytes_read;
18155       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18156       abbrev_ptr += 1;
18157
18158       /* now read in declarations */
18159       for (;;)
18160         {
18161           LONGEST implicit_const;
18162
18163           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18164           abbrev_ptr += bytes_read;
18165           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18166           abbrev_ptr += bytes_read;
18167           if (abbrev_form == DW_FORM_implicit_const)
18168             {
18169               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18170                                                    &bytes_read);
18171               abbrev_ptr += bytes_read;
18172             }
18173           else
18174             {
18175               /* Initialize it due to a false compiler warning.  */
18176               implicit_const = -1;
18177             }
18178
18179           if (abbrev_name == 0)
18180             break;
18181
18182           if (cur_abbrev->num_attrs == allocated_attrs)
18183             {
18184               allocated_attrs += ATTR_ALLOC_CHUNK;
18185               cur_attrs
18186                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18187             }
18188
18189           cur_attrs[cur_abbrev->num_attrs].name
18190             = (enum dwarf_attribute) abbrev_name;
18191           cur_attrs[cur_abbrev->num_attrs].form
18192             = (enum dwarf_form) abbrev_form;
18193           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18194           ++cur_abbrev->num_attrs;
18195         }
18196
18197       cur_abbrev->attrs =
18198         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18199                    cur_abbrev->num_attrs);
18200       memcpy (cur_abbrev->attrs, cur_attrs,
18201               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18202
18203       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18204
18205       /* Get next abbreviation.
18206          Under Irix6 the abbreviations for a compilation unit are not
18207          always properly terminated with an abbrev number of 0.
18208          Exit loop if we encounter an abbreviation which we have
18209          already read (which means we are about to read the abbreviations
18210          for the next compile unit) or if the end of the abbreviation
18211          table is reached.  */
18212       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18213         break;
18214       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18215       abbrev_ptr += bytes_read;
18216       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18217         break;
18218     }
18219
18220   xfree (cur_attrs);
18221   return abbrev_table;
18222 }
18223
18224 /* Returns nonzero if TAG represents a type that we might generate a partial
18225    symbol for.  */
18226
18227 static int
18228 is_type_tag_for_partial (int tag)
18229 {
18230   switch (tag)
18231     {
18232 #if 0
18233     /* Some types that would be reasonable to generate partial symbols for,
18234        that we don't at present.  */
18235     case DW_TAG_array_type:
18236     case DW_TAG_file_type:
18237     case DW_TAG_ptr_to_member_type:
18238     case DW_TAG_set_type:
18239     case DW_TAG_string_type:
18240     case DW_TAG_subroutine_type:
18241 #endif
18242     case DW_TAG_base_type:
18243     case DW_TAG_class_type:
18244     case DW_TAG_interface_type:
18245     case DW_TAG_enumeration_type:
18246     case DW_TAG_structure_type:
18247     case DW_TAG_subrange_type:
18248     case DW_TAG_typedef:
18249     case DW_TAG_union_type:
18250       return 1;
18251     default:
18252       return 0;
18253     }
18254 }
18255
18256 /* Load all DIEs that are interesting for partial symbols into memory.  */
18257
18258 static struct partial_die_info *
18259 load_partial_dies (const struct die_reader_specs *reader,
18260                    const gdb_byte *info_ptr, int building_psymtab)
18261 {
18262   struct dwarf2_cu *cu = reader->cu;
18263   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18264   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18265   unsigned int bytes_read;
18266   unsigned int load_all = 0;
18267   int nesting_level = 1;
18268
18269   parent_die = NULL;
18270   last_die = NULL;
18271
18272   gdb_assert (cu->per_cu != NULL);
18273   if (cu->per_cu->load_all_dies)
18274     load_all = 1;
18275
18276   cu->partial_dies
18277     = htab_create_alloc_ex (cu->header.length / 12,
18278                             partial_die_hash,
18279                             partial_die_eq,
18280                             NULL,
18281                             &cu->comp_unit_obstack,
18282                             hashtab_obstack_allocate,
18283                             dummy_obstack_deallocate);
18284
18285   while (1)
18286     {
18287       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18288
18289       /* A NULL abbrev means the end of a series of children.  */
18290       if (abbrev == NULL)
18291         {
18292           if (--nesting_level == 0)
18293             return first_die;
18294
18295           info_ptr += bytes_read;
18296           last_die = parent_die;
18297           parent_die = parent_die->die_parent;
18298           continue;
18299         }
18300
18301       /* Check for template arguments.  We never save these; if
18302          they're seen, we just mark the parent, and go on our way.  */
18303       if (parent_die != NULL
18304           && cu->language == language_cplus
18305           && (abbrev->tag == DW_TAG_template_type_param
18306               || abbrev->tag == DW_TAG_template_value_param))
18307         {
18308           parent_die->has_template_arguments = 1;
18309
18310           if (!load_all)
18311             {
18312               /* We don't need a partial DIE for the template argument.  */
18313               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18314               continue;
18315             }
18316         }
18317
18318       /* We only recurse into c++ subprograms looking for template arguments.
18319          Skip their other children.  */
18320       if (!load_all
18321           && cu->language == language_cplus
18322           && parent_die != NULL
18323           && parent_die->tag == DW_TAG_subprogram)
18324         {
18325           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18326           continue;
18327         }
18328
18329       /* Check whether this DIE is interesting enough to save.  Normally
18330          we would not be interested in members here, but there may be
18331          later variables referencing them via DW_AT_specification (for
18332          static members).  */
18333       if (!load_all
18334           && !is_type_tag_for_partial (abbrev->tag)
18335           && abbrev->tag != DW_TAG_constant
18336           && abbrev->tag != DW_TAG_enumerator
18337           && abbrev->tag != DW_TAG_subprogram
18338           && abbrev->tag != DW_TAG_inlined_subroutine
18339           && abbrev->tag != DW_TAG_lexical_block
18340           && abbrev->tag != DW_TAG_variable
18341           && abbrev->tag != DW_TAG_namespace
18342           && abbrev->tag != DW_TAG_module
18343           && abbrev->tag != DW_TAG_member
18344           && abbrev->tag != DW_TAG_imported_unit
18345           && abbrev->tag != DW_TAG_imported_declaration)
18346         {
18347           /* Otherwise we skip to the next sibling, if any.  */
18348           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18349           continue;
18350         }
18351
18352       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18353                                    abbrev);
18354
18355       info_ptr = read_partial_die (reader, &pdi, *abbrev,
18356                                    (const gdb_byte *) info_ptr + bytes_read);
18357
18358       /* This two-pass algorithm for processing partial symbols has a
18359          high cost in cache pressure.  Thus, handle some simple cases
18360          here which cover the majority of C partial symbols.  DIEs
18361          which neither have specification tags in them, nor could have
18362          specification tags elsewhere pointing at them, can simply be
18363          processed and discarded.
18364
18365          This segment is also optional; scan_partial_symbols and
18366          add_partial_symbol will handle these DIEs if we chain
18367          them in normally.  When compilers which do not emit large
18368          quantities of duplicate debug information are more common,
18369          this code can probably be removed.  */
18370
18371       /* Any complete simple types at the top level (pretty much all
18372          of them, for a language without namespaces), can be processed
18373          directly.  */
18374       if (parent_die == NULL
18375           && pdi.has_specification == 0
18376           && pdi.is_declaration == 0
18377           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18378               || pdi.tag == DW_TAG_base_type
18379               || pdi.tag == DW_TAG_subrange_type))
18380         {
18381           if (building_psymtab && pdi.name != NULL)
18382             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18383                                  VAR_DOMAIN, LOC_TYPEDEF,
18384                                  &objfile->static_psymbols,
18385                                  0, cu->language, objfile);
18386           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18387           continue;
18388         }
18389
18390       /* The exception for DW_TAG_typedef with has_children above is
18391          a workaround of GCC PR debug/47510.  In the case of this complaint
18392          type_name_no_tag_or_error will error on such types later.
18393
18394          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18395          it could not find the child DIEs referenced later, this is checked
18396          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18397
18398       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18399         complaint (&symfile_complaints,
18400                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18401                      "- DIE at %s [in module %s]"),
18402                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18403
18404       /* If we're at the second level, and we're an enumerator, and
18405          our parent has no specification (meaning possibly lives in a
18406          namespace elsewhere), then we can add the partial symbol now
18407          instead of queueing it.  */
18408       if (pdi.tag == DW_TAG_enumerator
18409           && parent_die != NULL
18410           && parent_die->die_parent == NULL
18411           && parent_die->tag == DW_TAG_enumeration_type
18412           && parent_die->has_specification == 0)
18413         {
18414           if (pdi.name == NULL)
18415             complaint (&symfile_complaints,
18416                        _("malformed enumerator DIE ignored"));
18417           else if (building_psymtab)
18418             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18419                                  VAR_DOMAIN, LOC_CONST,
18420                                  cu->language == language_cplus
18421                                  ? &objfile->global_psymbols
18422                                  : &objfile->static_psymbols,
18423                                  0, cu->language, objfile);
18424
18425           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18426           continue;
18427         }
18428
18429       struct partial_die_info *part_die
18430         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18431
18432       /* We'll save this DIE so link it in.  */
18433       part_die->die_parent = parent_die;
18434       part_die->die_sibling = NULL;
18435       part_die->die_child = NULL;
18436
18437       if (last_die && last_die == parent_die)
18438         last_die->die_child = part_die;
18439       else if (last_die)
18440         last_die->die_sibling = part_die;
18441
18442       last_die = part_die;
18443
18444       if (first_die == NULL)
18445         first_die = part_die;
18446
18447       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18448          find interesting need to be in the hash table, because we
18449          also have the parent/sibling/child chains; only those that we
18450          might refer to by offset later during partial symbol reading.
18451
18452          For now this means things that might have be the target of a
18453          DW_AT_specification, DW_AT_abstract_origin, or
18454          DW_AT_extension.  DW_AT_extension will refer only to
18455          namespaces; DW_AT_abstract_origin refers to functions (and
18456          many things under the function DIE, but we do not recurse
18457          into function DIEs during partial symbol reading) and
18458          possibly variables as well; DW_AT_specification refers to
18459          declarations.  Declarations ought to have the DW_AT_declaration
18460          flag.  It happens that GCC forgets to put it in sometimes, but
18461          only for functions, not for types.
18462
18463          Adding more things than necessary to the hash table is harmless
18464          except for the performance cost.  Adding too few will result in
18465          wasted time in find_partial_die, when we reread the compilation
18466          unit with load_all_dies set.  */
18467
18468       if (load_all
18469           || abbrev->tag == DW_TAG_constant
18470           || abbrev->tag == DW_TAG_subprogram
18471           || abbrev->tag == DW_TAG_variable
18472           || abbrev->tag == DW_TAG_namespace
18473           || part_die->is_declaration)
18474         {
18475           void **slot;
18476
18477           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18478                                            to_underlying (part_die->sect_off),
18479                                            INSERT);
18480           *slot = part_die;
18481         }
18482
18483       /* For some DIEs we want to follow their children (if any).  For C
18484          we have no reason to follow the children of structures; for other
18485          languages we have to, so that we can get at method physnames
18486          to infer fully qualified class names, for DW_AT_specification,
18487          and for C++ template arguments.  For C++, we also look one level
18488          inside functions to find template arguments (if the name of the
18489          function does not already contain the template arguments).
18490
18491          For Ada, we need to scan the children of subprograms and lexical
18492          blocks as well because Ada allows the definition of nested
18493          entities that could be interesting for the debugger, such as
18494          nested subprograms for instance.  */
18495       if (last_die->has_children
18496           && (load_all
18497               || last_die->tag == DW_TAG_namespace
18498               || last_die->tag == DW_TAG_module
18499               || last_die->tag == DW_TAG_enumeration_type
18500               || (cu->language == language_cplus
18501                   && last_die->tag == DW_TAG_subprogram
18502                   && (last_die->name == NULL
18503                       || strchr (last_die->name, '<') == NULL))
18504               || (cu->language != language_c
18505                   && (last_die->tag == DW_TAG_class_type
18506                       || last_die->tag == DW_TAG_interface_type
18507                       || last_die->tag == DW_TAG_structure_type
18508                       || last_die->tag == DW_TAG_union_type))
18509               || (cu->language == language_ada
18510                   && (last_die->tag == DW_TAG_subprogram
18511                       || last_die->tag == DW_TAG_lexical_block))))
18512         {
18513           nesting_level++;
18514           parent_die = last_die;
18515           continue;
18516         }
18517
18518       /* Otherwise we skip to the next sibling, if any.  */
18519       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18520
18521       /* Back to the top, do it again.  */
18522     }
18523 }
18524
18525 partial_die_info::partial_die_info (sect_offset sect_off_,
18526                                     struct abbrev_info *abbrev)
18527   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18528 {
18529 }
18530
18531 /* Read a minimal amount of information into the minimal die structure.
18532    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18533
18534 static const gdb_byte *
18535 read_partial_die (const struct die_reader_specs *reader,
18536                   struct partial_die_info *part_die,
18537                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18538                   const gdb_byte *info_ptr)
18539 {
18540   struct dwarf2_cu *cu = reader->cu;
18541   struct dwarf2_per_objfile *dwarf2_per_objfile
18542     = cu->per_cu->dwarf2_per_objfile;
18543   struct objfile *objfile = dwarf2_per_objfile->objfile;
18544   const gdb_byte *buffer = reader->buffer;
18545   unsigned int i;
18546   struct attribute attr;
18547   int has_low_pc_attr = 0;
18548   int has_high_pc_attr = 0;
18549   int high_pc_relative = 0;
18550
18551   for (i = 0; i < abbrev.num_attrs; ++i)
18552     {
18553       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18554
18555       /* Store the data if it is of an attribute we want to keep in a
18556          partial symbol table.  */
18557       switch (attr.name)
18558         {
18559         case DW_AT_name:
18560           switch (part_die->tag)
18561             {
18562             case DW_TAG_compile_unit:
18563             case DW_TAG_partial_unit:
18564             case DW_TAG_type_unit:
18565               /* Compilation units have a DW_AT_name that is a filename, not
18566                  a source language identifier.  */
18567             case DW_TAG_enumeration_type:
18568             case DW_TAG_enumerator:
18569               /* These tags always have simple identifiers already; no need
18570                  to canonicalize them.  */
18571               part_die->name = DW_STRING (&attr);
18572               break;
18573             default:
18574               part_die->name
18575                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18576                                             &objfile->per_bfd->storage_obstack);
18577               break;
18578             }
18579           break;
18580         case DW_AT_linkage_name:
18581         case DW_AT_MIPS_linkage_name:
18582           /* Note that both forms of linkage name might appear.  We
18583              assume they will be the same, and we only store the last
18584              one we see.  */
18585           if (cu->language == language_ada)
18586             part_die->name = DW_STRING (&attr);
18587           part_die->linkage_name = DW_STRING (&attr);
18588           break;
18589         case DW_AT_low_pc:
18590           has_low_pc_attr = 1;
18591           part_die->lowpc = attr_value_as_address (&attr);
18592           break;
18593         case DW_AT_high_pc:
18594           has_high_pc_attr = 1;
18595           part_die->highpc = attr_value_as_address (&attr);
18596           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18597                 high_pc_relative = 1;
18598           break;
18599         case DW_AT_location:
18600           /* Support the .debug_loc offsets.  */
18601           if (attr_form_is_block (&attr))
18602             {
18603                part_die->d.locdesc = DW_BLOCK (&attr);
18604             }
18605           else if (attr_form_is_section_offset (&attr))
18606             {
18607               dwarf2_complex_location_expr_complaint ();
18608             }
18609           else
18610             {
18611               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18612                                                      "partial symbol information");
18613             }
18614           break;
18615         case DW_AT_external:
18616           part_die->is_external = DW_UNSND (&attr);
18617           break;
18618         case DW_AT_declaration:
18619           part_die->is_declaration = DW_UNSND (&attr);
18620           break;
18621         case DW_AT_type:
18622           part_die->has_type = 1;
18623           break;
18624         case DW_AT_abstract_origin:
18625         case DW_AT_specification:
18626         case DW_AT_extension:
18627           part_die->has_specification = 1;
18628           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18629           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18630                                    || cu->per_cu->is_dwz);
18631           break;
18632         case DW_AT_sibling:
18633           /* Ignore absolute siblings, they might point outside of
18634              the current compile unit.  */
18635           if (attr.form == DW_FORM_ref_addr)
18636             complaint (&symfile_complaints,
18637                        _("ignoring absolute DW_AT_sibling"));
18638           else
18639             {
18640               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18641               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18642
18643               if (sibling_ptr < info_ptr)
18644                 complaint (&symfile_complaints,
18645                            _("DW_AT_sibling points backwards"));
18646               else if (sibling_ptr > reader->buffer_end)
18647                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18648               else
18649                 part_die->sibling = sibling_ptr;
18650             }
18651           break;
18652         case DW_AT_byte_size:
18653           part_die->has_byte_size = 1;
18654           break;
18655         case DW_AT_const_value:
18656           part_die->has_const_value = 1;
18657           break;
18658         case DW_AT_calling_convention:
18659           /* DWARF doesn't provide a way to identify a program's source-level
18660              entry point.  DW_AT_calling_convention attributes are only meant
18661              to describe functions' calling conventions.
18662
18663              However, because it's a necessary piece of information in
18664              Fortran, and before DWARF 4 DW_CC_program was the only
18665              piece of debugging information whose definition refers to
18666              a 'main program' at all, several compilers marked Fortran
18667              main programs with DW_CC_program --- even when those
18668              functions use the standard calling conventions.
18669
18670              Although DWARF now specifies a way to provide this
18671              information, we support this practice for backward
18672              compatibility.  */
18673           if (DW_UNSND (&attr) == DW_CC_program
18674               && cu->language == language_fortran)
18675             part_die->main_subprogram = 1;
18676           break;
18677         case DW_AT_inline:
18678           if (DW_UNSND (&attr) == DW_INL_inlined
18679               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18680             part_die->may_be_inlined = 1;
18681           break;
18682
18683         case DW_AT_import:
18684           if (part_die->tag == DW_TAG_imported_unit)
18685             {
18686               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18687               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18688                                   || cu->per_cu->is_dwz);
18689             }
18690           break;
18691
18692         case DW_AT_main_subprogram:
18693           part_die->main_subprogram = DW_UNSND (&attr);
18694           break;
18695
18696         default:
18697           break;
18698         }
18699     }
18700
18701   if (high_pc_relative)
18702     part_die->highpc += part_die->lowpc;
18703
18704   if (has_low_pc_attr && has_high_pc_attr)
18705     {
18706       /* When using the GNU linker, .gnu.linkonce. sections are used to
18707          eliminate duplicate copies of functions and vtables and such.
18708          The linker will arbitrarily choose one and discard the others.
18709          The AT_*_pc values for such functions refer to local labels in
18710          these sections.  If the section from that file was discarded, the
18711          labels are not in the output, so the relocs get a value of 0.
18712          If this is a discarded function, mark the pc bounds as invalid,
18713          so that GDB will ignore it.  */
18714       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18715         {
18716           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18717
18718           complaint (&symfile_complaints,
18719                      _("DW_AT_low_pc %s is zero "
18720                        "for DIE at %s [in module %s]"),
18721                      paddress (gdbarch, part_die->lowpc),
18722                      sect_offset_str (part_die->sect_off),
18723                      objfile_name (objfile));
18724         }
18725       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18726       else if (part_die->lowpc >= part_die->highpc)
18727         {
18728           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18729
18730           complaint (&symfile_complaints,
18731                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18732                        "for DIE at %s [in module %s]"),
18733                      paddress (gdbarch, part_die->lowpc),
18734                      paddress (gdbarch, part_die->highpc),
18735                      sect_offset_str (part_die->sect_off),
18736                      objfile_name (objfile));
18737         }
18738       else
18739         part_die->has_pc_info = 1;
18740     }
18741
18742   return info_ptr;
18743 }
18744
18745 /* Find a cached partial DIE at OFFSET in CU.  */
18746
18747 struct partial_die_info *
18748 dwarf2_cu::find_partial_die (sect_offset sect_off)
18749 {
18750   struct partial_die_info *lookup_die = NULL;
18751   struct partial_die_info part_die (sect_off);
18752
18753   lookup_die = ((struct partial_die_info *)
18754                 htab_find_with_hash (partial_dies, &part_die,
18755                                      to_underlying (sect_off)));
18756
18757   return lookup_die;
18758 }
18759
18760 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18761    except in the case of .debug_types DIEs which do not reference
18762    outside their CU (they do however referencing other types via
18763    DW_FORM_ref_sig8).  */
18764
18765 static struct partial_die_info *
18766 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18767 {
18768   struct dwarf2_per_objfile *dwarf2_per_objfile
18769     = cu->per_cu->dwarf2_per_objfile;
18770   struct objfile *objfile = dwarf2_per_objfile->objfile;
18771   struct dwarf2_per_cu_data *per_cu = NULL;
18772   struct partial_die_info *pd = NULL;
18773
18774   if (offset_in_dwz == cu->per_cu->is_dwz
18775       && offset_in_cu_p (&cu->header, sect_off))
18776     {
18777       pd = cu->find_partial_die (sect_off);
18778       if (pd != NULL)
18779         return pd;
18780       /* We missed recording what we needed.
18781          Load all dies and try again.  */
18782       per_cu = cu->per_cu;
18783     }
18784   else
18785     {
18786       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18787       if (cu->per_cu->is_debug_types)
18788         {
18789           error (_("Dwarf Error: Type Unit at offset %s contains"
18790                    " external reference to offset %s [in module %s].\n"),
18791                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18792                  bfd_get_filename (objfile->obfd));
18793         }
18794       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18795                                                  dwarf2_per_objfile);
18796
18797       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18798         load_partial_comp_unit (per_cu);
18799
18800       per_cu->cu->last_used = 0;
18801       pd = per_cu->cu->find_partial_die (sect_off);
18802     }
18803
18804   /* If we didn't find it, and not all dies have been loaded,
18805      load them all and try again.  */
18806
18807   if (pd == NULL && per_cu->load_all_dies == 0)
18808     {
18809       per_cu->load_all_dies = 1;
18810
18811       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18812          THIS_CU->cu may already be in use.  So we can't just free it and
18813          replace its DIEs with the ones we read in.  Instead, we leave those
18814          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18815          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18816          set.  */
18817       load_partial_comp_unit (per_cu);
18818
18819       pd = per_cu->cu->find_partial_die (sect_off);
18820     }
18821
18822   if (pd == NULL)
18823     internal_error (__FILE__, __LINE__,
18824                     _("could not find partial DIE %s "
18825                       "in cache [from module %s]\n"),
18826                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18827   return pd;
18828 }
18829
18830 /* See if we can figure out if the class lives in a namespace.  We do
18831    this by looking for a member function; its demangled name will
18832    contain namespace info, if there is any.  */
18833
18834 static void
18835 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18836                                   struct dwarf2_cu *cu)
18837 {
18838   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18839      what template types look like, because the demangler
18840      frequently doesn't give the same name as the debug info.  We
18841      could fix this by only using the demangled name to get the
18842      prefix (but see comment in read_structure_type).  */
18843
18844   struct partial_die_info *real_pdi;
18845   struct partial_die_info *child_pdi;
18846
18847   /* If this DIE (this DIE's specification, if any) has a parent, then
18848      we should not do this.  We'll prepend the parent's fully qualified
18849      name when we create the partial symbol.  */
18850
18851   real_pdi = struct_pdi;
18852   while (real_pdi->has_specification)
18853     real_pdi = find_partial_die (real_pdi->spec_offset,
18854                                  real_pdi->spec_is_dwz, cu);
18855
18856   if (real_pdi->die_parent != NULL)
18857     return;
18858
18859   for (child_pdi = struct_pdi->die_child;
18860        child_pdi != NULL;
18861        child_pdi = child_pdi->die_sibling)
18862     {
18863       if (child_pdi->tag == DW_TAG_subprogram
18864           && child_pdi->linkage_name != NULL)
18865         {
18866           char *actual_class_name
18867             = language_class_name_from_physname (cu->language_defn,
18868                                                  child_pdi->linkage_name);
18869           if (actual_class_name != NULL)
18870             {
18871               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18872               struct_pdi->name
18873                 = ((const char *)
18874                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18875                                   actual_class_name,
18876                                   strlen (actual_class_name)));
18877               xfree (actual_class_name);
18878             }
18879           break;
18880         }
18881     }
18882 }
18883
18884 void
18885 partial_die_info::fixup (struct dwarf2_cu *cu)
18886 {
18887   /* Once we've fixed up a die, there's no point in doing so again.
18888      This also avoids a memory leak if we were to call
18889      guess_partial_die_structure_name multiple times.  */
18890   if (fixup_called)
18891     return;
18892
18893   /* If we found a reference attribute and the DIE has no name, try
18894      to find a name in the referred to DIE.  */
18895
18896   if (name == NULL && has_specification)
18897     {
18898       struct partial_die_info *spec_die;
18899
18900       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18901
18902       spec_die->fixup (cu);
18903
18904       if (spec_die->name)
18905         {
18906           name = spec_die->name;
18907
18908           /* Copy DW_AT_external attribute if it is set.  */
18909           if (spec_die->is_external)
18910             is_external = spec_die->is_external;
18911         }
18912     }
18913
18914   /* Set default names for some unnamed DIEs.  */
18915
18916   if (name == NULL && tag == DW_TAG_namespace)
18917     name = CP_ANONYMOUS_NAMESPACE_STR;
18918
18919   /* If there is no parent die to provide a namespace, and there are
18920      children, see if we can determine the namespace from their linkage
18921      name.  */
18922   if (cu->language == language_cplus
18923       && !VEC_empty (dwarf2_section_info_def,
18924                      cu->per_cu->dwarf2_per_objfile->types)
18925       && die_parent == NULL
18926       && has_children
18927       && (tag == DW_TAG_class_type
18928           || tag == DW_TAG_structure_type
18929           || tag == DW_TAG_union_type))
18930     guess_partial_die_structure_name (this, cu);
18931
18932   /* GCC might emit a nameless struct or union that has a linkage
18933      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18934   if (name == NULL
18935       && (tag == DW_TAG_class_type
18936           || tag == DW_TAG_interface_type
18937           || tag == DW_TAG_structure_type
18938           || tag == DW_TAG_union_type)
18939       && linkage_name != NULL)
18940     {
18941       char *demangled;
18942
18943       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18944       if (demangled)
18945         {
18946           const char *base;
18947
18948           /* Strip any leading namespaces/classes, keep only the base name.
18949              DW_AT_name for named DIEs does not contain the prefixes.  */
18950           base = strrchr (demangled, ':');
18951           if (base && base > demangled && base[-1] == ':')
18952             base++;
18953           else
18954             base = demangled;
18955
18956           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18957           name
18958             = ((const char *)
18959                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18960                               base, strlen (base)));
18961           xfree (demangled);
18962         }
18963     }
18964
18965   fixup_called = 1;
18966 }
18967
18968 /* Read an attribute value described by an attribute form.  */
18969
18970 static const gdb_byte *
18971 read_attribute_value (const struct die_reader_specs *reader,
18972                       struct attribute *attr, unsigned form,
18973                       LONGEST implicit_const, const gdb_byte *info_ptr)
18974 {
18975   struct dwarf2_cu *cu = reader->cu;
18976   struct dwarf2_per_objfile *dwarf2_per_objfile
18977     = cu->per_cu->dwarf2_per_objfile;
18978   struct objfile *objfile = dwarf2_per_objfile->objfile;
18979   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18980   bfd *abfd = reader->abfd;
18981   struct comp_unit_head *cu_header = &cu->header;
18982   unsigned int bytes_read;
18983   struct dwarf_block *blk;
18984
18985   attr->form = (enum dwarf_form) form;
18986   switch (form)
18987     {
18988     case DW_FORM_ref_addr:
18989       if (cu->header.version == 2)
18990         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18991       else
18992         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18993                                        &cu->header, &bytes_read);
18994       info_ptr += bytes_read;
18995       break;
18996     case DW_FORM_GNU_ref_alt:
18997       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18998       info_ptr += bytes_read;
18999       break;
19000     case DW_FORM_addr:
19001       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19002       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19003       info_ptr += bytes_read;
19004       break;
19005     case DW_FORM_block2:
19006       blk = dwarf_alloc_block (cu);
19007       blk->size = read_2_bytes (abfd, info_ptr);
19008       info_ptr += 2;
19009       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19010       info_ptr += blk->size;
19011       DW_BLOCK (attr) = blk;
19012       break;
19013     case DW_FORM_block4:
19014       blk = dwarf_alloc_block (cu);
19015       blk->size = read_4_bytes (abfd, info_ptr);
19016       info_ptr += 4;
19017       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19018       info_ptr += blk->size;
19019       DW_BLOCK (attr) = blk;
19020       break;
19021     case DW_FORM_data2:
19022       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19023       info_ptr += 2;
19024       break;
19025     case DW_FORM_data4:
19026       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19027       info_ptr += 4;
19028       break;
19029     case DW_FORM_data8:
19030       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19031       info_ptr += 8;
19032       break;
19033     case DW_FORM_data16:
19034       blk = dwarf_alloc_block (cu);
19035       blk->size = 16;
19036       blk->data = read_n_bytes (abfd, info_ptr, 16);
19037       info_ptr += 16;
19038       DW_BLOCK (attr) = blk;
19039       break;
19040     case DW_FORM_sec_offset:
19041       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19042       info_ptr += bytes_read;
19043       break;
19044     case DW_FORM_string:
19045       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19046       DW_STRING_IS_CANONICAL (attr) = 0;
19047       info_ptr += bytes_read;
19048       break;
19049     case DW_FORM_strp:
19050       if (!cu->per_cu->is_dwz)
19051         {
19052           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19053                                                    abfd, info_ptr, cu_header,
19054                                                    &bytes_read);
19055           DW_STRING_IS_CANONICAL (attr) = 0;
19056           info_ptr += bytes_read;
19057           break;
19058         }
19059       /* FALLTHROUGH */
19060     case DW_FORM_line_strp:
19061       if (!cu->per_cu->is_dwz)
19062         {
19063           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19064                                                         abfd, info_ptr,
19065                                                         cu_header, &bytes_read);
19066           DW_STRING_IS_CANONICAL (attr) = 0;
19067           info_ptr += bytes_read;
19068           break;
19069         }
19070       /* FALLTHROUGH */
19071     case DW_FORM_GNU_strp_alt:
19072       {
19073         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19074         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19075                                           &bytes_read);
19076
19077         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19078                                                           dwz, str_offset);
19079         DW_STRING_IS_CANONICAL (attr) = 0;
19080         info_ptr += bytes_read;
19081       }
19082       break;
19083     case DW_FORM_exprloc:
19084     case DW_FORM_block:
19085       blk = dwarf_alloc_block (cu);
19086       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19087       info_ptr += bytes_read;
19088       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19089       info_ptr += blk->size;
19090       DW_BLOCK (attr) = blk;
19091       break;
19092     case DW_FORM_block1:
19093       blk = dwarf_alloc_block (cu);
19094       blk->size = read_1_byte (abfd, info_ptr);
19095       info_ptr += 1;
19096       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19097       info_ptr += blk->size;
19098       DW_BLOCK (attr) = blk;
19099       break;
19100     case DW_FORM_data1:
19101       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19102       info_ptr += 1;
19103       break;
19104     case DW_FORM_flag:
19105       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19106       info_ptr += 1;
19107       break;
19108     case DW_FORM_flag_present:
19109       DW_UNSND (attr) = 1;
19110       break;
19111     case DW_FORM_sdata:
19112       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19113       info_ptr += bytes_read;
19114       break;
19115     case DW_FORM_udata:
19116       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19117       info_ptr += bytes_read;
19118       break;
19119     case DW_FORM_ref1:
19120       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19121                          + read_1_byte (abfd, info_ptr));
19122       info_ptr += 1;
19123       break;
19124     case DW_FORM_ref2:
19125       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19126                          + read_2_bytes (abfd, info_ptr));
19127       info_ptr += 2;
19128       break;
19129     case DW_FORM_ref4:
19130       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19131                          + read_4_bytes (abfd, info_ptr));
19132       info_ptr += 4;
19133       break;
19134     case DW_FORM_ref8:
19135       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19136                          + read_8_bytes (abfd, info_ptr));
19137       info_ptr += 8;
19138       break;
19139     case DW_FORM_ref_sig8:
19140       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19141       info_ptr += 8;
19142       break;
19143     case DW_FORM_ref_udata:
19144       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19145                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19146       info_ptr += bytes_read;
19147       break;
19148     case DW_FORM_indirect:
19149       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19150       info_ptr += bytes_read;
19151       if (form == DW_FORM_implicit_const)
19152         {
19153           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19154           info_ptr += bytes_read;
19155         }
19156       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19157                                        info_ptr);
19158       break;
19159     case DW_FORM_implicit_const:
19160       DW_SND (attr) = implicit_const;
19161       break;
19162     case DW_FORM_GNU_addr_index:
19163       if (reader->dwo_file == NULL)
19164         {
19165           /* For now flag a hard error.
19166              Later we can turn this into a complaint.  */
19167           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19168                  dwarf_form_name (form),
19169                  bfd_get_filename (abfd));
19170         }
19171       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19172       info_ptr += bytes_read;
19173       break;
19174     case DW_FORM_GNU_str_index:
19175       if (reader->dwo_file == NULL)
19176         {
19177           /* For now flag a hard error.
19178              Later we can turn this into a complaint if warranted.  */
19179           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19180                  dwarf_form_name (form),
19181                  bfd_get_filename (abfd));
19182         }
19183       {
19184         ULONGEST str_index =
19185           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19186
19187         DW_STRING (attr) = read_str_index (reader, str_index);
19188         DW_STRING_IS_CANONICAL (attr) = 0;
19189         info_ptr += bytes_read;
19190       }
19191       break;
19192     default:
19193       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19194              dwarf_form_name (form),
19195              bfd_get_filename (abfd));
19196     }
19197
19198   /* Super hack.  */
19199   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19200     attr->form = DW_FORM_GNU_ref_alt;
19201
19202   /* We have seen instances where the compiler tried to emit a byte
19203      size attribute of -1 which ended up being encoded as an unsigned
19204      0xffffffff.  Although 0xffffffff is technically a valid size value,
19205      an object of this size seems pretty unlikely so we can relatively
19206      safely treat these cases as if the size attribute was invalid and
19207      treat them as zero by default.  */
19208   if (attr->name == DW_AT_byte_size
19209       && form == DW_FORM_data4
19210       && DW_UNSND (attr) >= 0xffffffff)
19211     {
19212       complaint
19213         (&symfile_complaints,
19214          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19215          hex_string (DW_UNSND (attr)));
19216       DW_UNSND (attr) = 0;
19217     }
19218
19219   return info_ptr;
19220 }
19221
19222 /* Read an attribute described by an abbreviated attribute.  */
19223
19224 static const gdb_byte *
19225 read_attribute (const struct die_reader_specs *reader,
19226                 struct attribute *attr, struct attr_abbrev *abbrev,
19227                 const gdb_byte *info_ptr)
19228 {
19229   attr->name = abbrev->name;
19230   return read_attribute_value (reader, attr, abbrev->form,
19231                                abbrev->implicit_const, info_ptr);
19232 }
19233
19234 /* Read dwarf information from a buffer.  */
19235
19236 static unsigned int
19237 read_1_byte (bfd *abfd, const gdb_byte *buf)
19238 {
19239   return bfd_get_8 (abfd, buf);
19240 }
19241
19242 static int
19243 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19244 {
19245   return bfd_get_signed_8 (abfd, buf);
19246 }
19247
19248 static unsigned int
19249 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19250 {
19251   return bfd_get_16 (abfd, buf);
19252 }
19253
19254 static int
19255 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19256 {
19257   return bfd_get_signed_16 (abfd, buf);
19258 }
19259
19260 static unsigned int
19261 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19262 {
19263   return bfd_get_32 (abfd, buf);
19264 }
19265
19266 static int
19267 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19268 {
19269   return bfd_get_signed_32 (abfd, buf);
19270 }
19271
19272 static ULONGEST
19273 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19274 {
19275   return bfd_get_64 (abfd, buf);
19276 }
19277
19278 static CORE_ADDR
19279 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19280               unsigned int *bytes_read)
19281 {
19282   struct comp_unit_head *cu_header = &cu->header;
19283   CORE_ADDR retval = 0;
19284
19285   if (cu_header->signed_addr_p)
19286     {
19287       switch (cu_header->addr_size)
19288         {
19289         case 2:
19290           retval = bfd_get_signed_16 (abfd, buf);
19291           break;
19292         case 4:
19293           retval = bfd_get_signed_32 (abfd, buf);
19294           break;
19295         case 8:
19296           retval = bfd_get_signed_64 (abfd, buf);
19297           break;
19298         default:
19299           internal_error (__FILE__, __LINE__,
19300                           _("read_address: bad switch, signed [in module %s]"),
19301                           bfd_get_filename (abfd));
19302         }
19303     }
19304   else
19305     {
19306       switch (cu_header->addr_size)
19307         {
19308         case 2:
19309           retval = bfd_get_16 (abfd, buf);
19310           break;
19311         case 4:
19312           retval = bfd_get_32 (abfd, buf);
19313           break;
19314         case 8:
19315           retval = bfd_get_64 (abfd, buf);
19316           break;
19317         default:
19318           internal_error (__FILE__, __LINE__,
19319                           _("read_address: bad switch, "
19320                             "unsigned [in module %s]"),
19321                           bfd_get_filename (abfd));
19322         }
19323     }
19324
19325   *bytes_read = cu_header->addr_size;
19326   return retval;
19327 }
19328
19329 /* Read the initial length from a section.  The (draft) DWARF 3
19330    specification allows the initial length to take up either 4 bytes
19331    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19332    bytes describe the length and all offsets will be 8 bytes in length
19333    instead of 4.
19334
19335    An older, non-standard 64-bit format is also handled by this
19336    function.  The older format in question stores the initial length
19337    as an 8-byte quantity without an escape value.  Lengths greater
19338    than 2^32 aren't very common which means that the initial 4 bytes
19339    is almost always zero.  Since a length value of zero doesn't make
19340    sense for the 32-bit format, this initial zero can be considered to
19341    be an escape value which indicates the presence of the older 64-bit
19342    format.  As written, the code can't detect (old format) lengths
19343    greater than 4GB.  If it becomes necessary to handle lengths
19344    somewhat larger than 4GB, we could allow other small values (such
19345    as the non-sensical values of 1, 2, and 3) to also be used as
19346    escape values indicating the presence of the old format.
19347
19348    The value returned via bytes_read should be used to increment the
19349    relevant pointer after calling read_initial_length().
19350
19351    [ Note:  read_initial_length() and read_offset() are based on the
19352      document entitled "DWARF Debugging Information Format", revision
19353      3, draft 8, dated November 19, 2001.  This document was obtained
19354      from:
19355
19356         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19357
19358      This document is only a draft and is subject to change.  (So beware.)
19359
19360      Details regarding the older, non-standard 64-bit format were
19361      determined empirically by examining 64-bit ELF files produced by
19362      the SGI toolchain on an IRIX 6.5 machine.
19363
19364      - Kevin, July 16, 2002
19365    ] */
19366
19367 static LONGEST
19368 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19369 {
19370   LONGEST length = bfd_get_32 (abfd, buf);
19371
19372   if (length == 0xffffffff)
19373     {
19374       length = bfd_get_64 (abfd, buf + 4);
19375       *bytes_read = 12;
19376     }
19377   else if (length == 0)
19378     {
19379       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19380       length = bfd_get_64 (abfd, buf);
19381       *bytes_read = 8;
19382     }
19383   else
19384     {
19385       *bytes_read = 4;
19386     }
19387
19388   return length;
19389 }
19390
19391 /* Cover function for read_initial_length.
19392    Returns the length of the object at BUF, and stores the size of the
19393    initial length in *BYTES_READ and stores the size that offsets will be in
19394    *OFFSET_SIZE.
19395    If the initial length size is not equivalent to that specified in
19396    CU_HEADER then issue a complaint.
19397    This is useful when reading non-comp-unit headers.  */
19398
19399 static LONGEST
19400 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19401                                         const struct comp_unit_head *cu_header,
19402                                         unsigned int *bytes_read,
19403                                         unsigned int *offset_size)
19404 {
19405   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19406
19407   gdb_assert (cu_header->initial_length_size == 4
19408               || cu_header->initial_length_size == 8
19409               || cu_header->initial_length_size == 12);
19410
19411   if (cu_header->initial_length_size != *bytes_read)
19412     complaint (&symfile_complaints,
19413                _("intermixed 32-bit and 64-bit DWARF sections"));
19414
19415   *offset_size = (*bytes_read == 4) ? 4 : 8;
19416   return length;
19417 }
19418
19419 /* Read an offset from the data stream.  The size of the offset is
19420    given by cu_header->offset_size.  */
19421
19422 static LONGEST
19423 read_offset (bfd *abfd, const gdb_byte *buf,
19424              const struct comp_unit_head *cu_header,
19425              unsigned int *bytes_read)
19426 {
19427   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19428
19429   *bytes_read = cu_header->offset_size;
19430   return offset;
19431 }
19432
19433 /* Read an offset from the data stream.  */
19434
19435 static LONGEST
19436 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19437 {
19438   LONGEST retval = 0;
19439
19440   switch (offset_size)
19441     {
19442     case 4:
19443       retval = bfd_get_32 (abfd, buf);
19444       break;
19445     case 8:
19446       retval = bfd_get_64 (abfd, buf);
19447       break;
19448     default:
19449       internal_error (__FILE__, __LINE__,
19450                       _("read_offset_1: bad switch [in module %s]"),
19451                       bfd_get_filename (abfd));
19452     }
19453
19454   return retval;
19455 }
19456
19457 static const gdb_byte *
19458 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19459 {
19460   /* If the size of a host char is 8 bits, we can return a pointer
19461      to the buffer, otherwise we have to copy the data to a buffer
19462      allocated on the temporary obstack.  */
19463   gdb_assert (HOST_CHAR_BIT == 8);
19464   return buf;
19465 }
19466
19467 static const char *
19468 read_direct_string (bfd *abfd, const gdb_byte *buf,
19469                     unsigned int *bytes_read_ptr)
19470 {
19471   /* If the size of a host char is 8 bits, we can return a pointer
19472      to the string, otherwise we have to copy the string to a buffer
19473      allocated on the temporary obstack.  */
19474   gdb_assert (HOST_CHAR_BIT == 8);
19475   if (*buf == '\0')
19476     {
19477       *bytes_read_ptr = 1;
19478       return NULL;
19479     }
19480   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19481   return (const char *) buf;
19482 }
19483
19484 /* Return pointer to string at section SECT offset STR_OFFSET with error
19485    reporting strings FORM_NAME and SECT_NAME.  */
19486
19487 static const char *
19488 read_indirect_string_at_offset_from (struct objfile *objfile,
19489                                      bfd *abfd, LONGEST str_offset,
19490                                      struct dwarf2_section_info *sect,
19491                                      const char *form_name,
19492                                      const char *sect_name)
19493 {
19494   dwarf2_read_section (objfile, sect);
19495   if (sect->buffer == NULL)
19496     error (_("%s used without %s section [in module %s]"),
19497            form_name, sect_name, bfd_get_filename (abfd));
19498   if (str_offset >= sect->size)
19499     error (_("%s pointing outside of %s section [in module %s]"),
19500            form_name, sect_name, bfd_get_filename (abfd));
19501   gdb_assert (HOST_CHAR_BIT == 8);
19502   if (sect->buffer[str_offset] == '\0')
19503     return NULL;
19504   return (const char *) (sect->buffer + str_offset);
19505 }
19506
19507 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19508
19509 static const char *
19510 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19511                                 bfd *abfd, LONGEST str_offset)
19512 {
19513   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19514                                               abfd, str_offset,
19515                                               &dwarf2_per_objfile->str,
19516                                               "DW_FORM_strp", ".debug_str");
19517 }
19518
19519 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19520
19521 static const char *
19522 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19523                                      bfd *abfd, LONGEST str_offset)
19524 {
19525   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19526                                               abfd, str_offset,
19527                                               &dwarf2_per_objfile->line_str,
19528                                               "DW_FORM_line_strp",
19529                                               ".debug_line_str");
19530 }
19531
19532 /* Read a string at offset STR_OFFSET in the .debug_str section from
19533    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19534    the string consists of a single NUL byte, return NULL; otherwise
19535    return a pointer to the string.  */
19536
19537 static const char *
19538 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19539                                LONGEST str_offset)
19540 {
19541   dwarf2_read_section (objfile, &dwz->str);
19542
19543   if (dwz->str.buffer == NULL)
19544     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19545              "section [in module %s]"),
19546            bfd_get_filename (dwz->dwz_bfd));
19547   if (str_offset >= dwz->str.size)
19548     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19549              ".debug_str section [in module %s]"),
19550            bfd_get_filename (dwz->dwz_bfd));
19551   gdb_assert (HOST_CHAR_BIT == 8);
19552   if (dwz->str.buffer[str_offset] == '\0')
19553     return NULL;
19554   return (const char *) (dwz->str.buffer + str_offset);
19555 }
19556
19557 /* Return pointer to string at .debug_str offset as read from BUF.
19558    BUF is assumed to be in a compilation unit described by CU_HEADER.
19559    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19560
19561 static const char *
19562 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19563                       const gdb_byte *buf,
19564                       const struct comp_unit_head *cu_header,
19565                       unsigned int *bytes_read_ptr)
19566 {
19567   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19568
19569   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19570 }
19571
19572 /* Return pointer to string at .debug_line_str offset as read from BUF.
19573    BUF is assumed to be in a compilation unit described by CU_HEADER.
19574    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19575
19576 static const char *
19577 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19578                            bfd *abfd, const gdb_byte *buf,
19579                            const struct comp_unit_head *cu_header,
19580                            unsigned int *bytes_read_ptr)
19581 {
19582   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19583
19584   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19585                                               str_offset);
19586 }
19587
19588 ULONGEST
19589 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19590                           unsigned int *bytes_read_ptr)
19591 {
19592   ULONGEST result;
19593   unsigned int num_read;
19594   int shift;
19595   unsigned char byte;
19596
19597   result = 0;
19598   shift = 0;
19599   num_read = 0;
19600   while (1)
19601     {
19602       byte = bfd_get_8 (abfd, buf);
19603       buf++;
19604       num_read++;
19605       result |= ((ULONGEST) (byte & 127) << shift);
19606       if ((byte & 128) == 0)
19607         {
19608           break;
19609         }
19610       shift += 7;
19611     }
19612   *bytes_read_ptr = num_read;
19613   return result;
19614 }
19615
19616 static LONGEST
19617 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19618                     unsigned int *bytes_read_ptr)
19619 {
19620   LONGEST result;
19621   int shift, num_read;
19622   unsigned char byte;
19623
19624   result = 0;
19625   shift = 0;
19626   num_read = 0;
19627   while (1)
19628     {
19629       byte = bfd_get_8 (abfd, buf);
19630       buf++;
19631       num_read++;
19632       result |= ((LONGEST) (byte & 127) << shift);
19633       shift += 7;
19634       if ((byte & 128) == 0)
19635         {
19636           break;
19637         }
19638     }
19639   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19640     result |= -(((LONGEST) 1) << shift);
19641   *bytes_read_ptr = num_read;
19642   return result;
19643 }
19644
19645 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19646    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19647    ADDR_SIZE is the size of addresses from the CU header.  */
19648
19649 static CORE_ADDR
19650 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19651                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19652 {
19653   struct objfile *objfile = dwarf2_per_objfile->objfile;
19654   bfd *abfd = objfile->obfd;
19655   const gdb_byte *info_ptr;
19656
19657   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19658   if (dwarf2_per_objfile->addr.buffer == NULL)
19659     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19660            objfile_name (objfile));
19661   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19662     error (_("DW_FORM_addr_index pointing outside of "
19663              ".debug_addr section [in module %s]"),
19664            objfile_name (objfile));
19665   info_ptr = (dwarf2_per_objfile->addr.buffer
19666               + addr_base + addr_index * addr_size);
19667   if (addr_size == 4)
19668     return bfd_get_32 (abfd, info_ptr);
19669   else
19670     return bfd_get_64 (abfd, info_ptr);
19671 }
19672
19673 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19674
19675 static CORE_ADDR
19676 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19677 {
19678   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19679                             cu->addr_base, cu->header.addr_size);
19680 }
19681
19682 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19683
19684 static CORE_ADDR
19685 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19686                              unsigned int *bytes_read)
19687 {
19688   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19689   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19690
19691   return read_addr_index (cu, addr_index);
19692 }
19693
19694 /* Data structure to pass results from dwarf2_read_addr_index_reader
19695    back to dwarf2_read_addr_index.  */
19696
19697 struct dwarf2_read_addr_index_data
19698 {
19699   ULONGEST addr_base;
19700   int addr_size;
19701 };
19702
19703 /* die_reader_func for dwarf2_read_addr_index.  */
19704
19705 static void
19706 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19707                                const gdb_byte *info_ptr,
19708                                struct die_info *comp_unit_die,
19709                                int has_children,
19710                                void *data)
19711 {
19712   struct dwarf2_cu *cu = reader->cu;
19713   struct dwarf2_read_addr_index_data *aidata =
19714     (struct dwarf2_read_addr_index_data *) data;
19715
19716   aidata->addr_base = cu->addr_base;
19717   aidata->addr_size = cu->header.addr_size;
19718 }
19719
19720 /* Given an index in .debug_addr, fetch the value.
19721    NOTE: This can be called during dwarf expression evaluation,
19722    long after the debug information has been read, and thus per_cu->cu
19723    may no longer exist.  */
19724
19725 CORE_ADDR
19726 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19727                         unsigned int addr_index)
19728 {
19729   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19730   struct objfile *objfile = dwarf2_per_objfile->objfile;
19731   struct dwarf2_cu *cu = per_cu->cu;
19732   ULONGEST addr_base;
19733   int addr_size;
19734
19735   /* We need addr_base and addr_size.
19736      If we don't have PER_CU->cu, we have to get it.
19737      Nasty, but the alternative is storing the needed info in PER_CU,
19738      which at this point doesn't seem justified: it's not clear how frequently
19739      it would get used and it would increase the size of every PER_CU.
19740      Entry points like dwarf2_per_cu_addr_size do a similar thing
19741      so we're not in uncharted territory here.
19742      Alas we need to be a bit more complicated as addr_base is contained
19743      in the DIE.
19744
19745      We don't need to read the entire CU(/TU).
19746      We just need the header and top level die.
19747
19748      IWBN to use the aging mechanism to let us lazily later discard the CU.
19749      For now we skip this optimization.  */
19750
19751   if (cu != NULL)
19752     {
19753       addr_base = cu->addr_base;
19754       addr_size = cu->header.addr_size;
19755     }
19756   else
19757     {
19758       struct dwarf2_read_addr_index_data aidata;
19759
19760       /* Note: We can't use init_cutu_and_read_dies_simple here,
19761          we need addr_base.  */
19762       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19763                                dwarf2_read_addr_index_reader, &aidata);
19764       addr_base = aidata.addr_base;
19765       addr_size = aidata.addr_size;
19766     }
19767
19768   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19769                             addr_size);
19770 }
19771
19772 /* Given a DW_FORM_GNU_str_index, fetch the string.
19773    This is only used by the Fission support.  */
19774
19775 static const char *
19776 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19777 {
19778   struct dwarf2_cu *cu = reader->cu;
19779   struct dwarf2_per_objfile *dwarf2_per_objfile
19780     = cu->per_cu->dwarf2_per_objfile;
19781   struct objfile *objfile = dwarf2_per_objfile->objfile;
19782   const char *objf_name = objfile_name (objfile);
19783   bfd *abfd = objfile->obfd;
19784   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19785   struct dwarf2_section_info *str_offsets_section =
19786     &reader->dwo_file->sections.str_offsets;
19787   const gdb_byte *info_ptr;
19788   ULONGEST str_offset;
19789   static const char form_name[] = "DW_FORM_GNU_str_index";
19790
19791   dwarf2_read_section (objfile, str_section);
19792   dwarf2_read_section (objfile, str_offsets_section);
19793   if (str_section->buffer == NULL)
19794     error (_("%s used without .debug_str.dwo section"
19795              " in CU at offset %s [in module %s]"),
19796            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19797   if (str_offsets_section->buffer == NULL)
19798     error (_("%s used without .debug_str_offsets.dwo section"
19799              " in CU at offset %s [in module %s]"),
19800            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19801   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19802     error (_("%s pointing outside of .debug_str_offsets.dwo"
19803              " section in CU at offset %s [in module %s]"),
19804            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19805   info_ptr = (str_offsets_section->buffer
19806               + str_index * cu->header.offset_size);
19807   if (cu->header.offset_size == 4)
19808     str_offset = bfd_get_32 (abfd, info_ptr);
19809   else
19810     str_offset = bfd_get_64 (abfd, info_ptr);
19811   if (str_offset >= str_section->size)
19812     error (_("Offset from %s pointing outside of"
19813              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19814            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19815   return (const char *) (str_section->buffer + str_offset);
19816 }
19817
19818 /* Return the length of an LEB128 number in BUF.  */
19819
19820 static int
19821 leb128_size (const gdb_byte *buf)
19822 {
19823   const gdb_byte *begin = buf;
19824   gdb_byte byte;
19825
19826   while (1)
19827     {
19828       byte = *buf++;
19829       if ((byte & 128) == 0)
19830         return buf - begin;
19831     }
19832 }
19833
19834 static void
19835 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19836 {
19837   switch (lang)
19838     {
19839     case DW_LANG_C89:
19840     case DW_LANG_C99:
19841     case DW_LANG_C11:
19842     case DW_LANG_C:
19843     case DW_LANG_UPC:
19844       cu->language = language_c;
19845       break;
19846     case DW_LANG_Java:
19847     case DW_LANG_C_plus_plus:
19848     case DW_LANG_C_plus_plus_11:
19849     case DW_LANG_C_plus_plus_14:
19850       cu->language = language_cplus;
19851       break;
19852     case DW_LANG_D:
19853       cu->language = language_d;
19854       break;
19855     case DW_LANG_Fortran77:
19856     case DW_LANG_Fortran90:
19857     case DW_LANG_Fortran95:
19858     case DW_LANG_Fortran03:
19859     case DW_LANG_Fortran08:
19860       cu->language = language_fortran;
19861       break;
19862     case DW_LANG_Go:
19863       cu->language = language_go;
19864       break;
19865     case DW_LANG_Mips_Assembler:
19866       cu->language = language_asm;
19867       break;
19868     case DW_LANG_Ada83:
19869     case DW_LANG_Ada95:
19870       cu->language = language_ada;
19871       break;
19872     case DW_LANG_Modula2:
19873       cu->language = language_m2;
19874       break;
19875     case DW_LANG_Pascal83:
19876       cu->language = language_pascal;
19877       break;
19878     case DW_LANG_ObjC:
19879       cu->language = language_objc;
19880       break;
19881     case DW_LANG_Rust:
19882     case DW_LANG_Rust_old:
19883       cu->language = language_rust;
19884       break;
19885     case DW_LANG_Cobol74:
19886     case DW_LANG_Cobol85:
19887     default:
19888       cu->language = language_minimal;
19889       break;
19890     }
19891   cu->language_defn = language_def (cu->language);
19892 }
19893
19894 /* Return the named attribute or NULL if not there.  */
19895
19896 static struct attribute *
19897 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19898 {
19899   for (;;)
19900     {
19901       unsigned int i;
19902       struct attribute *spec = NULL;
19903
19904       for (i = 0; i < die->num_attrs; ++i)
19905         {
19906           if (die->attrs[i].name == name)
19907             return &die->attrs[i];
19908           if (die->attrs[i].name == DW_AT_specification
19909               || die->attrs[i].name == DW_AT_abstract_origin)
19910             spec = &die->attrs[i];
19911         }
19912
19913       if (!spec)
19914         break;
19915
19916       die = follow_die_ref (die, spec, &cu);
19917     }
19918
19919   return NULL;
19920 }
19921
19922 /* Return the named attribute or NULL if not there,
19923    but do not follow DW_AT_specification, etc.
19924    This is for use in contexts where we're reading .debug_types dies.
19925    Following DW_AT_specification, DW_AT_abstract_origin will take us
19926    back up the chain, and we want to go down.  */
19927
19928 static struct attribute *
19929 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19930 {
19931   unsigned int i;
19932
19933   for (i = 0; i < die->num_attrs; ++i)
19934     if (die->attrs[i].name == name)
19935       return &die->attrs[i];
19936
19937   return NULL;
19938 }
19939
19940 /* Return the string associated with a string-typed attribute, or NULL if it
19941    is either not found or is of an incorrect type.  */
19942
19943 static const char *
19944 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19945 {
19946   struct attribute *attr;
19947   const char *str = NULL;
19948
19949   attr = dwarf2_attr (die, name, cu);
19950
19951   if (attr != NULL)
19952     {
19953       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19954           || attr->form == DW_FORM_string
19955           || attr->form == DW_FORM_GNU_str_index
19956           || attr->form == DW_FORM_GNU_strp_alt)
19957         str = DW_STRING (attr);
19958       else
19959         complaint (&symfile_complaints,
19960                    _("string type expected for attribute %s for "
19961                      "DIE at %s in module %s"),
19962                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19963                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19964     }
19965
19966   return str;
19967 }
19968
19969 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19970    and holds a non-zero value.  This function should only be used for
19971    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19972
19973 static int
19974 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19975 {
19976   struct attribute *attr = dwarf2_attr (die, name, cu);
19977
19978   return (attr && DW_UNSND (attr));
19979 }
19980
19981 static int
19982 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19983 {
19984   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19985      which value is non-zero.  However, we have to be careful with
19986      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19987      (via dwarf2_flag_true_p) follows this attribute.  So we may
19988      end up accidently finding a declaration attribute that belongs
19989      to a different DIE referenced by the specification attribute,
19990      even though the given DIE does not have a declaration attribute.  */
19991   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19992           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19993 }
19994
19995 /* Return the die giving the specification for DIE, if there is
19996    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19997    containing the return value on output.  If there is no
19998    specification, but there is an abstract origin, that is
19999    returned.  */
20000
20001 static struct die_info *
20002 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20003 {
20004   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20005                                              *spec_cu);
20006
20007   if (spec_attr == NULL)
20008     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20009
20010   if (spec_attr == NULL)
20011     return NULL;
20012   else
20013     return follow_die_ref (die, spec_attr, spec_cu);
20014 }
20015
20016 /* Stub for free_line_header to match void * callback types.  */
20017
20018 static void
20019 free_line_header_voidp (void *arg)
20020 {
20021   struct line_header *lh = (struct line_header *) arg;
20022
20023   delete lh;
20024 }
20025
20026 void
20027 line_header::add_include_dir (const char *include_dir)
20028 {
20029   if (dwarf_line_debug >= 2)
20030     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20031                         include_dirs.size () + 1, include_dir);
20032
20033   include_dirs.push_back (include_dir);
20034 }
20035
20036 void
20037 line_header::add_file_name (const char *name,
20038                             dir_index d_index,
20039                             unsigned int mod_time,
20040                             unsigned int length)
20041 {
20042   if (dwarf_line_debug >= 2)
20043     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20044                         (unsigned) file_names.size () + 1, name);
20045
20046   file_names.emplace_back (name, d_index, mod_time, length);
20047 }
20048
20049 /* A convenience function to find the proper .debug_line section for a CU.  */
20050
20051 static struct dwarf2_section_info *
20052 get_debug_line_section (struct dwarf2_cu *cu)
20053 {
20054   struct dwarf2_section_info *section;
20055   struct dwarf2_per_objfile *dwarf2_per_objfile
20056     = cu->per_cu->dwarf2_per_objfile;
20057
20058   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20059      DWO file.  */
20060   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20061     section = &cu->dwo_unit->dwo_file->sections.line;
20062   else if (cu->per_cu->is_dwz)
20063     {
20064       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20065
20066       section = &dwz->line;
20067     }
20068   else
20069     section = &dwarf2_per_objfile->line;
20070
20071   return section;
20072 }
20073
20074 /* Read directory or file name entry format, starting with byte of
20075    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20076    entries count and the entries themselves in the described entry
20077    format.  */
20078
20079 static void
20080 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20081                         bfd *abfd, const gdb_byte **bufp,
20082                         struct line_header *lh,
20083                         const struct comp_unit_head *cu_header,
20084                         void (*callback) (struct line_header *lh,
20085                                           const char *name,
20086                                           dir_index d_index,
20087                                           unsigned int mod_time,
20088                                           unsigned int length))
20089 {
20090   gdb_byte format_count, formati;
20091   ULONGEST data_count, datai;
20092   const gdb_byte *buf = *bufp;
20093   const gdb_byte *format_header_data;
20094   unsigned int bytes_read;
20095
20096   format_count = read_1_byte (abfd, buf);
20097   buf += 1;
20098   format_header_data = buf;
20099   for (formati = 0; formati < format_count; formati++)
20100     {
20101       read_unsigned_leb128 (abfd, buf, &bytes_read);
20102       buf += bytes_read;
20103       read_unsigned_leb128 (abfd, buf, &bytes_read);
20104       buf += bytes_read;
20105     }
20106
20107   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20108   buf += bytes_read;
20109   for (datai = 0; datai < data_count; datai++)
20110     {
20111       const gdb_byte *format = format_header_data;
20112       struct file_entry fe;
20113
20114       for (formati = 0; formati < format_count; formati++)
20115         {
20116           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20117           format += bytes_read;
20118
20119           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20120           format += bytes_read;
20121
20122           gdb::optional<const char *> string;
20123           gdb::optional<unsigned int> uint;
20124
20125           switch (form)
20126             {
20127             case DW_FORM_string:
20128               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20129               buf += bytes_read;
20130               break;
20131
20132             case DW_FORM_line_strp:
20133               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20134                                                          abfd, buf,
20135                                                          cu_header,
20136                                                          &bytes_read));
20137               buf += bytes_read;
20138               break;
20139
20140             case DW_FORM_data1:
20141               uint.emplace (read_1_byte (abfd, buf));
20142               buf += 1;
20143               break;
20144
20145             case DW_FORM_data2:
20146               uint.emplace (read_2_bytes (abfd, buf));
20147               buf += 2;
20148               break;
20149
20150             case DW_FORM_data4:
20151               uint.emplace (read_4_bytes (abfd, buf));
20152               buf += 4;
20153               break;
20154
20155             case DW_FORM_data8:
20156               uint.emplace (read_8_bytes (abfd, buf));
20157               buf += 8;
20158               break;
20159
20160             case DW_FORM_udata:
20161               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20162               buf += bytes_read;
20163               break;
20164
20165             case DW_FORM_block:
20166               /* It is valid only for DW_LNCT_timestamp which is ignored by
20167                  current GDB.  */
20168               break;
20169             }
20170
20171           switch (content_type)
20172             {
20173             case DW_LNCT_path:
20174               if (string.has_value ())
20175                 fe.name = *string;
20176               break;
20177             case DW_LNCT_directory_index:
20178               if (uint.has_value ())
20179                 fe.d_index = (dir_index) *uint;
20180               break;
20181             case DW_LNCT_timestamp:
20182               if (uint.has_value ())
20183                 fe.mod_time = *uint;
20184               break;
20185             case DW_LNCT_size:
20186               if (uint.has_value ())
20187                 fe.length = *uint;
20188               break;
20189             case DW_LNCT_MD5:
20190               break;
20191             default:
20192               complaint (&symfile_complaints,
20193                          _("Unknown format content type %s"),
20194                          pulongest (content_type));
20195             }
20196         }
20197
20198       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20199     }
20200
20201   *bufp = buf;
20202 }
20203
20204 /* Read the statement program header starting at OFFSET in
20205    .debug_line, or .debug_line.dwo.  Return a pointer
20206    to a struct line_header, allocated using xmalloc.
20207    Returns NULL if there is a problem reading the header, e.g., if it
20208    has a version we don't understand.
20209
20210    NOTE: the strings in the include directory and file name tables of
20211    the returned object point into the dwarf line section buffer,
20212    and must not be freed.  */
20213
20214 static line_header_up
20215 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20216 {
20217   const gdb_byte *line_ptr;
20218   unsigned int bytes_read, offset_size;
20219   int i;
20220   const char *cur_dir, *cur_file;
20221   struct dwarf2_section_info *section;
20222   bfd *abfd;
20223   struct dwarf2_per_objfile *dwarf2_per_objfile
20224     = cu->per_cu->dwarf2_per_objfile;
20225
20226   section = get_debug_line_section (cu);
20227   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20228   if (section->buffer == NULL)
20229     {
20230       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20231         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20232       else
20233         complaint (&symfile_complaints, _("missing .debug_line section"));
20234       return 0;
20235     }
20236
20237   /* We can't do this until we know the section is non-empty.
20238      Only then do we know we have such a section.  */
20239   abfd = get_section_bfd_owner (section);
20240
20241   /* Make sure that at least there's room for the total_length field.
20242      That could be 12 bytes long, but we're just going to fudge that.  */
20243   if (to_underlying (sect_off) + 4 >= section->size)
20244     {
20245       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20246       return 0;
20247     }
20248
20249   line_header_up lh (new line_header ());
20250
20251   lh->sect_off = sect_off;
20252   lh->offset_in_dwz = cu->per_cu->is_dwz;
20253
20254   line_ptr = section->buffer + to_underlying (sect_off);
20255
20256   /* Read in the header.  */
20257   lh->total_length =
20258     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20259                                             &bytes_read, &offset_size);
20260   line_ptr += bytes_read;
20261   if (line_ptr + lh->total_length > (section->buffer + section->size))
20262     {
20263       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20264       return 0;
20265     }
20266   lh->statement_program_end = line_ptr + lh->total_length;
20267   lh->version = read_2_bytes (abfd, line_ptr);
20268   line_ptr += 2;
20269   if (lh->version > 5)
20270     {
20271       /* This is a version we don't understand.  The format could have
20272          changed in ways we don't handle properly so just punt.  */
20273       complaint (&symfile_complaints,
20274                  _("unsupported version in .debug_line section"));
20275       return NULL;
20276     }
20277   if (lh->version >= 5)
20278     {
20279       gdb_byte segment_selector_size;
20280
20281       /* Skip address size.  */
20282       read_1_byte (abfd, line_ptr);
20283       line_ptr += 1;
20284
20285       segment_selector_size = read_1_byte (abfd, line_ptr);
20286       line_ptr += 1;
20287       if (segment_selector_size != 0)
20288         {
20289           complaint (&symfile_complaints,
20290                      _("unsupported segment selector size %u "
20291                        "in .debug_line section"),
20292                      segment_selector_size);
20293           return NULL;
20294         }
20295     }
20296   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20297   line_ptr += offset_size;
20298   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20299   line_ptr += 1;
20300   if (lh->version >= 4)
20301     {
20302       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20303       line_ptr += 1;
20304     }
20305   else
20306     lh->maximum_ops_per_instruction = 1;
20307
20308   if (lh->maximum_ops_per_instruction == 0)
20309     {
20310       lh->maximum_ops_per_instruction = 1;
20311       complaint (&symfile_complaints,
20312                  _("invalid maximum_ops_per_instruction "
20313                    "in `.debug_line' section"));
20314     }
20315
20316   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20317   line_ptr += 1;
20318   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20319   line_ptr += 1;
20320   lh->line_range = read_1_byte (abfd, line_ptr);
20321   line_ptr += 1;
20322   lh->opcode_base = read_1_byte (abfd, line_ptr);
20323   line_ptr += 1;
20324   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20325
20326   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20327   for (i = 1; i < lh->opcode_base; ++i)
20328     {
20329       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20330       line_ptr += 1;
20331     }
20332
20333   if (lh->version >= 5)
20334     {
20335       /* Read directory table.  */
20336       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20337                               &cu->header,
20338                               [] (struct line_header *lh, const char *name,
20339                                   dir_index d_index, unsigned int mod_time,
20340                                   unsigned int length)
20341         {
20342           lh->add_include_dir (name);
20343         });
20344
20345       /* Read file name table.  */
20346       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20347                               &cu->header,
20348                               [] (struct line_header *lh, const char *name,
20349                                   dir_index d_index, unsigned int mod_time,
20350                                   unsigned int length)
20351         {
20352           lh->add_file_name (name, d_index, mod_time, length);
20353         });
20354     }
20355   else
20356     {
20357       /* Read directory table.  */
20358       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20359         {
20360           line_ptr += bytes_read;
20361           lh->add_include_dir (cur_dir);
20362         }
20363       line_ptr += bytes_read;
20364
20365       /* Read file name table.  */
20366       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20367         {
20368           unsigned int mod_time, length;
20369           dir_index d_index;
20370
20371           line_ptr += bytes_read;
20372           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20373           line_ptr += bytes_read;
20374           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20375           line_ptr += bytes_read;
20376           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20377           line_ptr += bytes_read;
20378
20379           lh->add_file_name (cur_file, d_index, mod_time, length);
20380         }
20381       line_ptr += bytes_read;
20382     }
20383   lh->statement_program_start = line_ptr;
20384
20385   if (line_ptr > (section->buffer + section->size))
20386     complaint (&symfile_complaints,
20387                _("line number info header doesn't "
20388                  "fit in `.debug_line' section"));
20389
20390   return lh;
20391 }
20392
20393 /* Subroutine of dwarf_decode_lines to simplify it.
20394    Return the file name of the psymtab for included file FILE_INDEX
20395    in line header LH of PST.
20396    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20397    If space for the result is malloc'd, *NAME_HOLDER will be set.
20398    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20399
20400 static const char *
20401 psymtab_include_file_name (const struct line_header *lh, int file_index,
20402                            const struct partial_symtab *pst,
20403                            const char *comp_dir,
20404                            gdb::unique_xmalloc_ptr<char> *name_holder)
20405 {
20406   const file_entry &fe = lh->file_names[file_index];
20407   const char *include_name = fe.name;
20408   const char *include_name_to_compare = include_name;
20409   const char *pst_filename;
20410   int file_is_pst;
20411
20412   const char *dir_name = fe.include_dir (lh);
20413
20414   gdb::unique_xmalloc_ptr<char> hold_compare;
20415   if (!IS_ABSOLUTE_PATH (include_name)
20416       && (dir_name != NULL || comp_dir != NULL))
20417     {
20418       /* Avoid creating a duplicate psymtab for PST.
20419          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20420          Before we do the comparison, however, we need to account
20421          for DIR_NAME and COMP_DIR.
20422          First prepend dir_name (if non-NULL).  If we still don't
20423          have an absolute path prepend comp_dir (if non-NULL).
20424          However, the directory we record in the include-file's
20425          psymtab does not contain COMP_DIR (to match the
20426          corresponding symtab(s)).
20427
20428          Example:
20429
20430          bash$ cd /tmp
20431          bash$ gcc -g ./hello.c
20432          include_name = "hello.c"
20433          dir_name = "."
20434          DW_AT_comp_dir = comp_dir = "/tmp"
20435          DW_AT_name = "./hello.c"
20436
20437       */
20438
20439       if (dir_name != NULL)
20440         {
20441           name_holder->reset (concat (dir_name, SLASH_STRING,
20442                                       include_name, (char *) NULL));
20443           include_name = name_holder->get ();
20444           include_name_to_compare = include_name;
20445         }
20446       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20447         {
20448           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20449                                       include_name, (char *) NULL));
20450           include_name_to_compare = hold_compare.get ();
20451         }
20452     }
20453
20454   pst_filename = pst->filename;
20455   gdb::unique_xmalloc_ptr<char> copied_name;
20456   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20457     {
20458       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20459                                  pst_filename, (char *) NULL));
20460       pst_filename = copied_name.get ();
20461     }
20462
20463   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20464
20465   if (file_is_pst)
20466     return NULL;
20467   return include_name;
20468 }
20469
20470 /* State machine to track the state of the line number program.  */
20471
20472 class lnp_state_machine
20473 {
20474 public:
20475   /* Initialize a machine state for the start of a line number
20476      program.  */
20477   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20478
20479   file_entry *current_file ()
20480   {
20481     /* lh->file_names is 0-based, but the file name numbers in the
20482        statement program are 1-based.  */
20483     return m_line_header->file_name_at (m_file);
20484   }
20485
20486   /* Record the line in the state machine.  END_SEQUENCE is true if
20487      we're processing the end of a sequence.  */
20488   void record_line (bool end_sequence);
20489
20490   /* Check address and if invalid nop-out the rest of the lines in this
20491      sequence.  */
20492   void check_line_address (struct dwarf2_cu *cu,
20493                            const gdb_byte *line_ptr,
20494                            CORE_ADDR lowpc, CORE_ADDR address);
20495
20496   void handle_set_discriminator (unsigned int discriminator)
20497   {
20498     m_discriminator = discriminator;
20499     m_line_has_non_zero_discriminator |= discriminator != 0;
20500   }
20501
20502   /* Handle DW_LNE_set_address.  */
20503   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20504   {
20505     m_op_index = 0;
20506     address += baseaddr;
20507     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20508   }
20509
20510   /* Handle DW_LNS_advance_pc.  */
20511   void handle_advance_pc (CORE_ADDR adjust);
20512
20513   /* Handle a special opcode.  */
20514   void handle_special_opcode (unsigned char op_code);
20515
20516   /* Handle DW_LNS_advance_line.  */
20517   void handle_advance_line (int line_delta)
20518   {
20519     advance_line (line_delta);
20520   }
20521
20522   /* Handle DW_LNS_set_file.  */
20523   void handle_set_file (file_name_index file);
20524
20525   /* Handle DW_LNS_negate_stmt.  */
20526   void handle_negate_stmt ()
20527   {
20528     m_is_stmt = !m_is_stmt;
20529   }
20530
20531   /* Handle DW_LNS_const_add_pc.  */
20532   void handle_const_add_pc ();
20533
20534   /* Handle DW_LNS_fixed_advance_pc.  */
20535   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20536   {
20537     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20538     m_op_index = 0;
20539   }
20540
20541   /* Handle DW_LNS_copy.  */
20542   void handle_copy ()
20543   {
20544     record_line (false);
20545     m_discriminator = 0;
20546   }
20547
20548   /* Handle DW_LNE_end_sequence.  */
20549   void handle_end_sequence ()
20550   {
20551     m_record_line_callback = ::record_line;
20552   }
20553
20554 private:
20555   /* Advance the line by LINE_DELTA.  */
20556   void advance_line (int line_delta)
20557   {
20558     m_line += line_delta;
20559
20560     if (line_delta != 0)
20561       m_line_has_non_zero_discriminator = m_discriminator != 0;
20562   }
20563
20564   gdbarch *m_gdbarch;
20565
20566   /* True if we're recording lines.
20567      Otherwise we're building partial symtabs and are just interested in
20568      finding include files mentioned by the line number program.  */
20569   bool m_record_lines_p;
20570
20571   /* The line number header.  */
20572   line_header *m_line_header;
20573
20574   /* These are part of the standard DWARF line number state machine,
20575      and initialized according to the DWARF spec.  */
20576
20577   unsigned char m_op_index = 0;
20578   /* The line table index (1-based) of the current file.  */
20579   file_name_index m_file = (file_name_index) 1;
20580   unsigned int m_line = 1;
20581
20582   /* These are initialized in the constructor.  */
20583
20584   CORE_ADDR m_address;
20585   bool m_is_stmt;
20586   unsigned int m_discriminator;
20587
20588   /* Additional bits of state we need to track.  */
20589
20590   /* The last file that we called dwarf2_start_subfile for.
20591      This is only used for TLLs.  */
20592   unsigned int m_last_file = 0;
20593   /* The last file a line number was recorded for.  */
20594   struct subfile *m_last_subfile = NULL;
20595
20596   /* The function to call to record a line.  */
20597   record_line_ftype *m_record_line_callback = NULL;
20598
20599   /* The last line number that was recorded, used to coalesce
20600      consecutive entries for the same line.  This can happen, for
20601      example, when discriminators are present.  PR 17276.  */
20602   unsigned int m_last_line = 0;
20603   bool m_line_has_non_zero_discriminator = false;
20604 };
20605
20606 void
20607 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20608 {
20609   CORE_ADDR addr_adj = (((m_op_index + adjust)
20610                          / m_line_header->maximum_ops_per_instruction)
20611                         * m_line_header->minimum_instruction_length);
20612   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20613   m_op_index = ((m_op_index + adjust)
20614                 % m_line_header->maximum_ops_per_instruction);
20615 }
20616
20617 void
20618 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20619 {
20620   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20621   CORE_ADDR addr_adj = (((m_op_index
20622                           + (adj_opcode / m_line_header->line_range))
20623                          / m_line_header->maximum_ops_per_instruction)
20624                         * m_line_header->minimum_instruction_length);
20625   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20626   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20627                 % m_line_header->maximum_ops_per_instruction);
20628
20629   int line_delta = (m_line_header->line_base
20630                     + (adj_opcode % m_line_header->line_range));
20631   advance_line (line_delta);
20632   record_line (false);
20633   m_discriminator = 0;
20634 }
20635
20636 void
20637 lnp_state_machine::handle_set_file (file_name_index file)
20638 {
20639   m_file = file;
20640
20641   const file_entry *fe = current_file ();
20642   if (fe == NULL)
20643     dwarf2_debug_line_missing_file_complaint ();
20644   else if (m_record_lines_p)
20645     {
20646       const char *dir = fe->include_dir (m_line_header);
20647
20648       m_last_subfile = current_subfile;
20649       m_line_has_non_zero_discriminator = m_discriminator != 0;
20650       dwarf2_start_subfile (fe->name, dir);
20651     }
20652 }
20653
20654 void
20655 lnp_state_machine::handle_const_add_pc ()
20656 {
20657   CORE_ADDR adjust
20658     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20659
20660   CORE_ADDR addr_adj
20661     = (((m_op_index + adjust)
20662         / m_line_header->maximum_ops_per_instruction)
20663        * m_line_header->minimum_instruction_length);
20664
20665   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20666   m_op_index = ((m_op_index + adjust)
20667                 % m_line_header->maximum_ops_per_instruction);
20668 }
20669
20670 /* Ignore this record_line request.  */
20671
20672 static void
20673 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20674 {
20675   return;
20676 }
20677
20678 /* Return non-zero if we should add LINE to the line number table.
20679    LINE is the line to add, LAST_LINE is the last line that was added,
20680    LAST_SUBFILE is the subfile for LAST_LINE.
20681    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20682    had a non-zero discriminator.
20683
20684    We have to be careful in the presence of discriminators.
20685    E.g., for this line:
20686
20687      for (i = 0; i < 100000; i++);
20688
20689    clang can emit four line number entries for that one line,
20690    each with a different discriminator.
20691    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20692
20693    However, we want gdb to coalesce all four entries into one.
20694    Otherwise the user could stepi into the middle of the line and
20695    gdb would get confused about whether the pc really was in the
20696    middle of the line.
20697
20698    Things are further complicated by the fact that two consecutive
20699    line number entries for the same line is a heuristic used by gcc
20700    to denote the end of the prologue.  So we can't just discard duplicate
20701    entries, we have to be selective about it.  The heuristic we use is
20702    that we only collapse consecutive entries for the same line if at least
20703    one of those entries has a non-zero discriminator.  PR 17276.
20704
20705    Note: Addresses in the line number state machine can never go backwards
20706    within one sequence, thus this coalescing is ok.  */
20707
20708 static int
20709 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20710                      int line_has_non_zero_discriminator,
20711                      struct subfile *last_subfile)
20712 {
20713   if (current_subfile != last_subfile)
20714     return 1;
20715   if (line != last_line)
20716     return 1;
20717   /* Same line for the same file that we've seen already.
20718      As a last check, for pr 17276, only record the line if the line
20719      has never had a non-zero discriminator.  */
20720   if (!line_has_non_zero_discriminator)
20721     return 1;
20722   return 0;
20723 }
20724
20725 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20726    in the line table of subfile SUBFILE.  */
20727
20728 static void
20729 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20730                      unsigned int line, CORE_ADDR address,
20731                      record_line_ftype p_record_line)
20732 {
20733   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20734
20735   if (dwarf_line_debug)
20736     {
20737       fprintf_unfiltered (gdb_stdlog,
20738                           "Recording line %u, file %s, address %s\n",
20739                           line, lbasename (subfile->name),
20740                           paddress (gdbarch, address));
20741     }
20742
20743   (*p_record_line) (subfile, line, addr);
20744 }
20745
20746 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20747    Mark the end of a set of line number records.
20748    The arguments are the same as for dwarf_record_line_1.
20749    If SUBFILE is NULL the request is ignored.  */
20750
20751 static void
20752 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20753                    CORE_ADDR address, record_line_ftype p_record_line)
20754 {
20755   if (subfile == NULL)
20756     return;
20757
20758   if (dwarf_line_debug)
20759     {
20760       fprintf_unfiltered (gdb_stdlog,
20761                           "Finishing current line, file %s, address %s\n",
20762                           lbasename (subfile->name),
20763                           paddress (gdbarch, address));
20764     }
20765
20766   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20767 }
20768
20769 void
20770 lnp_state_machine::record_line (bool end_sequence)
20771 {
20772   if (dwarf_line_debug)
20773     {
20774       fprintf_unfiltered (gdb_stdlog,
20775                           "Processing actual line %u: file %u,"
20776                           " address %s, is_stmt %u, discrim %u\n",
20777                           m_line, to_underlying (m_file),
20778                           paddress (m_gdbarch, m_address),
20779                           m_is_stmt, m_discriminator);
20780     }
20781
20782   file_entry *fe = current_file ();
20783
20784   if (fe == NULL)
20785     dwarf2_debug_line_missing_file_complaint ();
20786   /* For now we ignore lines not starting on an instruction boundary.
20787      But not when processing end_sequence for compatibility with the
20788      previous version of the code.  */
20789   else if (m_op_index == 0 || end_sequence)
20790     {
20791       fe->included_p = 1;
20792       if (m_record_lines_p && m_is_stmt)
20793         {
20794           if (m_last_subfile != current_subfile || end_sequence)
20795             {
20796               dwarf_finish_line (m_gdbarch, m_last_subfile,
20797                                  m_address, m_record_line_callback);
20798             }
20799
20800           if (!end_sequence)
20801             {
20802               if (dwarf_record_line_p (m_line, m_last_line,
20803                                        m_line_has_non_zero_discriminator,
20804                                        m_last_subfile))
20805                 {
20806                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20807                                        m_line, m_address,
20808                                        m_record_line_callback);
20809                 }
20810               m_last_subfile = current_subfile;
20811               m_last_line = m_line;
20812             }
20813         }
20814     }
20815 }
20816
20817 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20818                                       bool record_lines_p)
20819 {
20820   m_gdbarch = arch;
20821   m_record_lines_p = record_lines_p;
20822   m_line_header = lh;
20823
20824   m_record_line_callback = ::record_line;
20825
20826   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20827      was a line entry for it so that the backend has a chance to adjust it
20828      and also record it in case it needs it.  This is currently used by MIPS
20829      code, cf. `mips_adjust_dwarf2_line'.  */
20830   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20831   m_is_stmt = lh->default_is_stmt;
20832   m_discriminator = 0;
20833 }
20834
20835 void
20836 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20837                                        const gdb_byte *line_ptr,
20838                                        CORE_ADDR lowpc, CORE_ADDR address)
20839 {
20840   /* If address < lowpc then it's not a usable value, it's outside the
20841      pc range of the CU.  However, we restrict the test to only address
20842      values of zero to preserve GDB's previous behaviour which is to
20843      handle the specific case of a function being GC'd by the linker.  */
20844
20845   if (address == 0 && address < lowpc)
20846     {
20847       /* This line table is for a function which has been
20848          GCd by the linker.  Ignore it.  PR gdb/12528 */
20849
20850       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20851       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20852
20853       complaint (&symfile_complaints,
20854                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20855                  line_offset, objfile_name (objfile));
20856       m_record_line_callback = noop_record_line;
20857       /* Note: record_line_callback is left as noop_record_line until
20858          we see DW_LNE_end_sequence.  */
20859     }
20860 }
20861
20862 /* Subroutine of dwarf_decode_lines to simplify it.
20863    Process the line number information in LH.
20864    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20865    program in order to set included_p for every referenced header.  */
20866
20867 static void
20868 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20869                       const int decode_for_pst_p, CORE_ADDR lowpc)
20870 {
20871   const gdb_byte *line_ptr, *extended_end;
20872   const gdb_byte *line_end;
20873   unsigned int bytes_read, extended_len;
20874   unsigned char op_code, extended_op;
20875   CORE_ADDR baseaddr;
20876   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20877   bfd *abfd = objfile->obfd;
20878   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20879   /* True if we're recording line info (as opposed to building partial
20880      symtabs and just interested in finding include files mentioned by
20881      the line number program).  */
20882   bool record_lines_p = !decode_for_pst_p;
20883
20884   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20885
20886   line_ptr = lh->statement_program_start;
20887   line_end = lh->statement_program_end;
20888
20889   /* Read the statement sequences until there's nothing left.  */
20890   while (line_ptr < line_end)
20891     {
20892       /* The DWARF line number program state machine.  Reset the state
20893          machine at the start of each sequence.  */
20894       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20895       bool end_sequence = false;
20896
20897       if (record_lines_p)
20898         {
20899           /* Start a subfile for the current file of the state
20900              machine.  */
20901           const file_entry *fe = state_machine.current_file ();
20902
20903           if (fe != NULL)
20904             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20905         }
20906
20907       /* Decode the table.  */
20908       while (line_ptr < line_end && !end_sequence)
20909         {
20910           op_code = read_1_byte (abfd, line_ptr);
20911           line_ptr += 1;
20912
20913           if (op_code >= lh->opcode_base)
20914             {
20915               /* Special opcode.  */
20916               state_machine.handle_special_opcode (op_code);
20917             }
20918           else switch (op_code)
20919             {
20920             case DW_LNS_extended_op:
20921               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20922                                                    &bytes_read);
20923               line_ptr += bytes_read;
20924               extended_end = line_ptr + extended_len;
20925               extended_op = read_1_byte (abfd, line_ptr);
20926               line_ptr += 1;
20927               switch (extended_op)
20928                 {
20929                 case DW_LNE_end_sequence:
20930                   state_machine.handle_end_sequence ();
20931                   end_sequence = true;
20932                   break;
20933                 case DW_LNE_set_address:
20934                   {
20935                     CORE_ADDR address
20936                       = read_address (abfd, line_ptr, cu, &bytes_read);
20937                     line_ptr += bytes_read;
20938
20939                     state_machine.check_line_address (cu, line_ptr,
20940                                                       lowpc, address);
20941                     state_machine.handle_set_address (baseaddr, address);
20942                   }
20943                   break;
20944                 case DW_LNE_define_file:
20945                   {
20946                     const char *cur_file;
20947                     unsigned int mod_time, length;
20948                     dir_index dindex;
20949
20950                     cur_file = read_direct_string (abfd, line_ptr,
20951                                                    &bytes_read);
20952                     line_ptr += bytes_read;
20953                     dindex = (dir_index)
20954                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20955                     line_ptr += bytes_read;
20956                     mod_time =
20957                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20958                     line_ptr += bytes_read;
20959                     length =
20960                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20961                     line_ptr += bytes_read;
20962                     lh->add_file_name (cur_file, dindex, mod_time, length);
20963                   }
20964                   break;
20965                 case DW_LNE_set_discriminator:
20966                   {
20967                     /* The discriminator is not interesting to the
20968                        debugger; just ignore it.  We still need to
20969                        check its value though:
20970                        if there are consecutive entries for the same
20971                        (non-prologue) line we want to coalesce them.
20972                        PR 17276.  */
20973                     unsigned int discr
20974                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20975                     line_ptr += bytes_read;
20976
20977                     state_machine.handle_set_discriminator (discr);
20978                   }
20979                   break;
20980                 default:
20981                   complaint (&symfile_complaints,
20982                              _("mangled .debug_line section"));
20983                   return;
20984                 }
20985               /* Make sure that we parsed the extended op correctly.  If e.g.
20986                  we expected a different address size than the producer used,
20987                  we may have read the wrong number of bytes.  */
20988               if (line_ptr != extended_end)
20989                 {
20990                   complaint (&symfile_complaints,
20991                              _("mangled .debug_line section"));
20992                   return;
20993                 }
20994               break;
20995             case DW_LNS_copy:
20996               state_machine.handle_copy ();
20997               break;
20998             case DW_LNS_advance_pc:
20999               {
21000                 CORE_ADDR adjust
21001                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21002                 line_ptr += bytes_read;
21003
21004                 state_machine.handle_advance_pc (adjust);
21005               }
21006               break;
21007             case DW_LNS_advance_line:
21008               {
21009                 int line_delta
21010                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21011                 line_ptr += bytes_read;
21012
21013                 state_machine.handle_advance_line (line_delta);
21014               }
21015               break;
21016             case DW_LNS_set_file:
21017               {
21018                 file_name_index file
21019                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21020                                                             &bytes_read);
21021                 line_ptr += bytes_read;
21022
21023                 state_machine.handle_set_file (file);
21024               }
21025               break;
21026             case DW_LNS_set_column:
21027               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21028               line_ptr += bytes_read;
21029               break;
21030             case DW_LNS_negate_stmt:
21031               state_machine.handle_negate_stmt ();
21032               break;
21033             case DW_LNS_set_basic_block:
21034               break;
21035             /* Add to the address register of the state machine the
21036                address increment value corresponding to special opcode
21037                255.  I.e., this value is scaled by the minimum
21038                instruction length since special opcode 255 would have
21039                scaled the increment.  */
21040             case DW_LNS_const_add_pc:
21041               state_machine.handle_const_add_pc ();
21042               break;
21043             case DW_LNS_fixed_advance_pc:
21044               {
21045                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21046                 line_ptr += 2;
21047
21048                 state_machine.handle_fixed_advance_pc (addr_adj);
21049               }
21050               break;
21051             default:
21052               {
21053                 /* Unknown standard opcode, ignore it.  */
21054                 int i;
21055
21056                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21057                   {
21058                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21059                     line_ptr += bytes_read;
21060                   }
21061               }
21062             }
21063         }
21064
21065       if (!end_sequence)
21066         dwarf2_debug_line_missing_end_sequence_complaint ();
21067
21068       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21069          in which case we still finish recording the last line).  */
21070       state_machine.record_line (true);
21071     }
21072 }
21073
21074 /* Decode the Line Number Program (LNP) for the given line_header
21075    structure and CU.  The actual information extracted and the type
21076    of structures created from the LNP depends on the value of PST.
21077
21078    1. If PST is NULL, then this procedure uses the data from the program
21079       to create all necessary symbol tables, and their linetables.
21080
21081    2. If PST is not NULL, this procedure reads the program to determine
21082       the list of files included by the unit represented by PST, and
21083       builds all the associated partial symbol tables.
21084
21085    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21086    It is used for relative paths in the line table.
21087    NOTE: When processing partial symtabs (pst != NULL),
21088    comp_dir == pst->dirname.
21089
21090    NOTE: It is important that psymtabs have the same file name (via strcmp)
21091    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21092    symtab we don't use it in the name of the psymtabs we create.
21093    E.g. expand_line_sal requires this when finding psymtabs to expand.
21094    A good testcase for this is mb-inline.exp.
21095
21096    LOWPC is the lowest address in CU (or 0 if not known).
21097
21098    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21099    for its PC<->lines mapping information.  Otherwise only the filename
21100    table is read in.  */
21101
21102 static void
21103 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21104                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21105                     CORE_ADDR lowpc, int decode_mapping)
21106 {
21107   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21108   const int decode_for_pst_p = (pst != NULL);
21109
21110   if (decode_mapping)
21111     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21112
21113   if (decode_for_pst_p)
21114     {
21115       int file_index;
21116
21117       /* Now that we're done scanning the Line Header Program, we can
21118          create the psymtab of each included file.  */
21119       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21120         if (lh->file_names[file_index].included_p == 1)
21121           {
21122             gdb::unique_xmalloc_ptr<char> name_holder;
21123             const char *include_name =
21124               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21125                                          &name_holder);
21126             if (include_name != NULL)
21127               dwarf2_create_include_psymtab (include_name, pst, objfile);
21128           }
21129     }
21130   else
21131     {
21132       /* Make sure a symtab is created for every file, even files
21133          which contain only variables (i.e. no code with associated
21134          line numbers).  */
21135       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21136       int i;
21137
21138       for (i = 0; i < lh->file_names.size (); i++)
21139         {
21140           file_entry &fe = lh->file_names[i];
21141
21142           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21143
21144           if (current_subfile->symtab == NULL)
21145             {
21146               current_subfile->symtab
21147                 = allocate_symtab (cust, current_subfile->name);
21148             }
21149           fe.symtab = current_subfile->symtab;
21150         }
21151     }
21152 }
21153
21154 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21155    DIRNAME the name of the source directory which contains FILENAME
21156    or NULL if not known.
21157    This routine tries to keep line numbers from identical absolute and
21158    relative file names in a common subfile.
21159
21160    Using the `list' example from the GDB testsuite, which resides in
21161    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21162    of /srcdir/list0.c yields the following debugging information for list0.c:
21163
21164    DW_AT_name:          /srcdir/list0.c
21165    DW_AT_comp_dir:      /compdir
21166    files.files[0].name: list0.h
21167    files.files[0].dir:  /srcdir
21168    files.files[1].name: list0.c
21169    files.files[1].dir:  /srcdir
21170
21171    The line number information for list0.c has to end up in a single
21172    subfile, so that `break /srcdir/list0.c:1' works as expected.
21173    start_subfile will ensure that this happens provided that we pass the
21174    concatenation of files.files[1].dir and files.files[1].name as the
21175    subfile's name.  */
21176
21177 static void
21178 dwarf2_start_subfile (const char *filename, const char *dirname)
21179 {
21180   char *copy = NULL;
21181
21182   /* In order not to lose the line information directory,
21183      we concatenate it to the filename when it makes sense.
21184      Note that the Dwarf3 standard says (speaking of filenames in line
21185      information): ``The directory index is ignored for file names
21186      that represent full path names''.  Thus ignoring dirname in the
21187      `else' branch below isn't an issue.  */
21188
21189   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21190     {
21191       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21192       filename = copy;
21193     }
21194
21195   start_subfile (filename);
21196
21197   if (copy != NULL)
21198     xfree (copy);
21199 }
21200
21201 /* Start a symtab for DWARF.
21202    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21203
21204 static struct compunit_symtab *
21205 dwarf2_start_symtab (struct dwarf2_cu *cu,
21206                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21207 {
21208   struct compunit_symtab *cust
21209     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21210                     low_pc, cu->language);
21211
21212   record_debugformat ("DWARF 2");
21213   record_producer (cu->producer);
21214
21215   /* We assume that we're processing GCC output.  */
21216   processing_gcc_compilation = 2;
21217
21218   cu->processing_has_namespace_info = 0;
21219
21220   return cust;
21221 }
21222
21223 static void
21224 var_decode_location (struct attribute *attr, struct symbol *sym,
21225                      struct dwarf2_cu *cu)
21226 {
21227   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21228   struct comp_unit_head *cu_header = &cu->header;
21229
21230   /* NOTE drow/2003-01-30: There used to be a comment and some special
21231      code here to turn a symbol with DW_AT_external and a
21232      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21233      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21234      with some versions of binutils) where shared libraries could have
21235      relocations against symbols in their debug information - the
21236      minimal symbol would have the right address, but the debug info
21237      would not.  It's no longer necessary, because we will explicitly
21238      apply relocations when we read in the debug information now.  */
21239
21240   /* A DW_AT_location attribute with no contents indicates that a
21241      variable has been optimized away.  */
21242   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21243     {
21244       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21245       return;
21246     }
21247
21248   /* Handle one degenerate form of location expression specially, to
21249      preserve GDB's previous behavior when section offsets are
21250      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21251      then mark this symbol as LOC_STATIC.  */
21252
21253   if (attr_form_is_block (attr)
21254       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21255            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21256           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21257               && (DW_BLOCK (attr)->size
21258                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21259     {
21260       unsigned int dummy;
21261
21262       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21263         SYMBOL_VALUE_ADDRESS (sym) =
21264           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21265       else
21266         SYMBOL_VALUE_ADDRESS (sym) =
21267           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21268       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21269       fixup_symbol_section (sym, objfile);
21270       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21271                                               SYMBOL_SECTION (sym));
21272       return;
21273     }
21274
21275   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21276      expression evaluator, and use LOC_COMPUTED only when necessary
21277      (i.e. when the value of a register or memory location is
21278      referenced, or a thread-local block, etc.).  Then again, it might
21279      not be worthwhile.  I'm assuming that it isn't unless performance
21280      or memory numbers show me otherwise.  */
21281
21282   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21283
21284   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21285     cu->has_loclist = 1;
21286 }
21287
21288 /* Given a pointer to a DWARF information entry, figure out if we need
21289    to make a symbol table entry for it, and if so, create a new entry
21290    and return a pointer to it.
21291    If TYPE is NULL, determine symbol type from the die, otherwise
21292    used the passed type.
21293    If SPACE is not NULL, use it to hold the new symbol.  If it is
21294    NULL, allocate a new symbol on the objfile's obstack.  */
21295
21296 static struct symbol *
21297 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21298             struct symbol *space)
21299 {
21300   struct dwarf2_per_objfile *dwarf2_per_objfile
21301     = cu->per_cu->dwarf2_per_objfile;
21302   struct objfile *objfile = dwarf2_per_objfile->objfile;
21303   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21304   struct symbol *sym = NULL;
21305   const char *name;
21306   struct attribute *attr = NULL;
21307   struct attribute *attr2 = NULL;
21308   CORE_ADDR baseaddr;
21309   struct pending **list_to_add = NULL;
21310
21311   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21312
21313   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21314
21315   name = dwarf2_name (die, cu);
21316   if (name)
21317     {
21318       const char *linkagename;
21319       int suppress_add = 0;
21320
21321       if (space)
21322         sym = space;
21323       else
21324         sym = allocate_symbol (objfile);
21325       OBJSTAT (objfile, n_syms++);
21326
21327       /* Cache this symbol's name and the name's demangled form (if any).  */
21328       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21329       linkagename = dwarf2_physname (name, die, cu);
21330       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21331
21332       /* Fortran does not have mangling standard and the mangling does differ
21333          between gfortran, iFort etc.  */
21334       if (cu->language == language_fortran
21335           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21336         symbol_set_demangled_name (&(sym->ginfo),
21337                                    dwarf2_full_name (name, die, cu),
21338                                    NULL);
21339
21340       /* Default assumptions.
21341          Use the passed type or decode it from the die.  */
21342       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21343       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21344       if (type != NULL)
21345         SYMBOL_TYPE (sym) = type;
21346       else
21347         SYMBOL_TYPE (sym) = die_type (die, cu);
21348       attr = dwarf2_attr (die,
21349                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21350                           cu);
21351       if (attr)
21352         {
21353           SYMBOL_LINE (sym) = DW_UNSND (attr);
21354         }
21355
21356       attr = dwarf2_attr (die,
21357                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21358                           cu);
21359       if (attr)
21360         {
21361           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21362           struct file_entry *fe;
21363
21364           if (cu->line_header != NULL)
21365             fe = cu->line_header->file_name_at (file_index);
21366           else
21367             fe = NULL;
21368
21369           if (fe == NULL)
21370             complaint (&symfile_complaints,
21371                        _("file index out of range"));
21372           else
21373             symbol_set_symtab (sym, fe->symtab);
21374         }
21375
21376       switch (die->tag)
21377         {
21378         case DW_TAG_label:
21379           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21380           if (attr)
21381             {
21382               CORE_ADDR addr;
21383
21384               addr = attr_value_as_address (attr);
21385               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21386               SYMBOL_VALUE_ADDRESS (sym) = addr;
21387             }
21388           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21389           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21390           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21391           add_symbol_to_list (sym, cu->list_in_scope);
21392           break;
21393         case DW_TAG_subprogram:
21394           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21395              finish_block.  */
21396           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21397           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21398           if ((attr2 && (DW_UNSND (attr2) != 0))
21399               || cu->language == language_ada)
21400             {
21401               /* Subprograms marked external are stored as a global symbol.
21402                  Ada subprograms, whether marked external or not, are always
21403                  stored as a global symbol, because we want to be able to
21404                  access them globally.  For instance, we want to be able
21405                  to break on a nested subprogram without having to
21406                  specify the context.  */
21407               list_to_add = &global_symbols;
21408             }
21409           else
21410             {
21411               list_to_add = cu->list_in_scope;
21412             }
21413           break;
21414         case DW_TAG_inlined_subroutine:
21415           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21416              finish_block.  */
21417           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21418           SYMBOL_INLINED (sym) = 1;
21419           list_to_add = cu->list_in_scope;
21420           break;
21421         case DW_TAG_template_value_param:
21422           suppress_add = 1;
21423           /* Fall through.  */
21424         case DW_TAG_constant:
21425         case DW_TAG_variable:
21426         case DW_TAG_member:
21427           /* Compilation with minimal debug info may result in
21428              variables with missing type entries.  Change the
21429              misleading `void' type to something sensible.  */
21430           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21431             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21432
21433           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21434           /* In the case of DW_TAG_member, we should only be called for
21435              static const members.  */
21436           if (die->tag == DW_TAG_member)
21437             {
21438               /* dwarf2_add_field uses die_is_declaration,
21439                  so we do the same.  */
21440               gdb_assert (die_is_declaration (die, cu));
21441               gdb_assert (attr);
21442             }
21443           if (attr)
21444             {
21445               dwarf2_const_value (attr, sym, cu);
21446               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21447               if (!suppress_add)
21448                 {
21449                   if (attr2 && (DW_UNSND (attr2) != 0))
21450                     list_to_add = &global_symbols;
21451                   else
21452                     list_to_add = cu->list_in_scope;
21453                 }
21454               break;
21455             }
21456           attr = dwarf2_attr (die, DW_AT_location, cu);
21457           if (attr)
21458             {
21459               var_decode_location (attr, sym, cu);
21460               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21461
21462               /* Fortran explicitly imports any global symbols to the local
21463                  scope by DW_TAG_common_block.  */
21464               if (cu->language == language_fortran && die->parent
21465                   && die->parent->tag == DW_TAG_common_block)
21466                 attr2 = NULL;
21467
21468               if (SYMBOL_CLASS (sym) == LOC_STATIC
21469                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21470                   && !dwarf2_per_objfile->has_section_at_zero)
21471                 {
21472                   /* When a static variable is eliminated by the linker,
21473                      the corresponding debug information is not stripped
21474                      out, but the variable address is set to null;
21475                      do not add such variables into symbol table.  */
21476                 }
21477               else if (attr2 && (DW_UNSND (attr2) != 0))
21478                 {
21479                   /* Workaround gfortran PR debug/40040 - it uses
21480                      DW_AT_location for variables in -fPIC libraries which may
21481                      get overriden by other libraries/executable and get
21482                      a different address.  Resolve it by the minimal symbol
21483                      which may come from inferior's executable using copy
21484                      relocation.  Make this workaround only for gfortran as for
21485                      other compilers GDB cannot guess the minimal symbol
21486                      Fortran mangling kind.  */
21487                   if (cu->language == language_fortran && die->parent
21488                       && die->parent->tag == DW_TAG_module
21489                       && cu->producer
21490                       && startswith (cu->producer, "GNU Fortran"))
21491                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21492
21493                   /* A variable with DW_AT_external is never static,
21494                      but it may be block-scoped.  */
21495                   list_to_add = (cu->list_in_scope == &file_symbols
21496                                  ? &global_symbols : cu->list_in_scope);
21497                 }
21498               else
21499                 list_to_add = cu->list_in_scope;
21500             }
21501           else
21502             {
21503               /* We do not know the address of this symbol.
21504                  If it is an external symbol and we have type information
21505                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21506                  The address of the variable will then be determined from
21507                  the minimal symbol table whenever the variable is
21508                  referenced.  */
21509               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21510
21511               /* Fortran explicitly imports any global symbols to the local
21512                  scope by DW_TAG_common_block.  */
21513               if (cu->language == language_fortran && die->parent
21514                   && die->parent->tag == DW_TAG_common_block)
21515                 {
21516                   /* SYMBOL_CLASS doesn't matter here because
21517                      read_common_block is going to reset it.  */
21518                   if (!suppress_add)
21519                     list_to_add = cu->list_in_scope;
21520                 }
21521               else if (attr2 && (DW_UNSND (attr2) != 0)
21522                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21523                 {
21524                   /* A variable with DW_AT_external is never static, but it
21525                      may be block-scoped.  */
21526                   list_to_add = (cu->list_in_scope == &file_symbols
21527                                  ? &global_symbols : cu->list_in_scope);
21528
21529                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21530                 }
21531               else if (!die_is_declaration (die, cu))
21532                 {
21533                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21534                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21535                   if (!suppress_add)
21536                     list_to_add = cu->list_in_scope;
21537                 }
21538             }
21539           break;
21540         case DW_TAG_formal_parameter:
21541           /* If we are inside a function, mark this as an argument.  If
21542              not, we might be looking at an argument to an inlined function
21543              when we do not have enough information to show inlined frames;
21544              pretend it's a local variable in that case so that the user can
21545              still see it.  */
21546           if (context_stack_depth > 0
21547               && context_stack[context_stack_depth - 1].name != NULL)
21548             SYMBOL_IS_ARGUMENT (sym) = 1;
21549           attr = dwarf2_attr (die, DW_AT_location, cu);
21550           if (attr)
21551             {
21552               var_decode_location (attr, sym, cu);
21553             }
21554           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21555           if (attr)
21556             {
21557               dwarf2_const_value (attr, sym, cu);
21558             }
21559
21560           list_to_add = cu->list_in_scope;
21561           break;
21562         case DW_TAG_unspecified_parameters:
21563           /* From varargs functions; gdb doesn't seem to have any
21564              interest in this information, so just ignore it for now.
21565              (FIXME?) */
21566           break;
21567         case DW_TAG_template_type_param:
21568           suppress_add = 1;
21569           /* Fall through.  */
21570         case DW_TAG_class_type:
21571         case DW_TAG_interface_type:
21572         case DW_TAG_structure_type:
21573         case DW_TAG_union_type:
21574         case DW_TAG_set_type:
21575         case DW_TAG_enumeration_type:
21576           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21577           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21578
21579           {
21580             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21581                really ever be static objects: otherwise, if you try
21582                to, say, break of a class's method and you're in a file
21583                which doesn't mention that class, it won't work unless
21584                the check for all static symbols in lookup_symbol_aux
21585                saves you.  See the OtherFileClass tests in
21586                gdb.c++/namespace.exp.  */
21587
21588             if (!suppress_add)
21589               {
21590                 list_to_add = (cu->list_in_scope == &file_symbols
21591                                && cu->language == language_cplus
21592                                ? &global_symbols : cu->list_in_scope);
21593
21594                 /* The semantics of C++ state that "struct foo {
21595                    ... }" also defines a typedef for "foo".  */
21596                 if (cu->language == language_cplus
21597                     || cu->language == language_ada
21598                     || cu->language == language_d
21599                     || cu->language == language_rust)
21600                   {
21601                     /* The symbol's name is already allocated along
21602                        with this objfile, so we don't need to
21603                        duplicate it for the type.  */
21604                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21605                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21606                   }
21607               }
21608           }
21609           break;
21610         case DW_TAG_typedef:
21611           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21612           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21613           list_to_add = cu->list_in_scope;
21614           break;
21615         case DW_TAG_base_type:
21616         case DW_TAG_subrange_type:
21617           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21618           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21619           list_to_add = cu->list_in_scope;
21620           break;
21621         case DW_TAG_enumerator:
21622           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21623           if (attr)
21624             {
21625               dwarf2_const_value (attr, sym, cu);
21626             }
21627           {
21628             /* NOTE: carlton/2003-11-10: See comment above in the
21629                DW_TAG_class_type, etc. block.  */
21630
21631             list_to_add = (cu->list_in_scope == &file_symbols
21632                            && cu->language == language_cplus
21633                            ? &global_symbols : cu->list_in_scope);
21634           }
21635           break;
21636         case DW_TAG_imported_declaration:
21637         case DW_TAG_namespace:
21638           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21639           list_to_add = &global_symbols;
21640           break;
21641         case DW_TAG_module:
21642           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21643           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21644           list_to_add = &global_symbols;
21645           break;
21646         case DW_TAG_common_block:
21647           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21648           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21649           add_symbol_to_list (sym, cu->list_in_scope);
21650           break;
21651         default:
21652           /* Not a tag we recognize.  Hopefully we aren't processing
21653              trash data, but since we must specifically ignore things
21654              we don't recognize, there is nothing else we should do at
21655              this point.  */
21656           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21657                      dwarf_tag_name (die->tag));
21658           break;
21659         }
21660
21661       if (suppress_add)
21662         {
21663           sym->hash_next = objfile->template_symbols;
21664           objfile->template_symbols = sym;
21665           list_to_add = NULL;
21666         }
21667
21668       if (list_to_add != NULL)
21669         add_symbol_to_list (sym, list_to_add);
21670
21671       /* For the benefit of old versions of GCC, check for anonymous
21672          namespaces based on the demangled name.  */
21673       if (!cu->processing_has_namespace_info
21674           && cu->language == language_cplus)
21675         cp_scan_for_anonymous_namespaces (sym, objfile);
21676     }
21677   return (sym);
21678 }
21679
21680 /* Given an attr with a DW_FORM_dataN value in host byte order,
21681    zero-extend it as appropriate for the symbol's type.  The DWARF
21682    standard (v4) is not entirely clear about the meaning of using
21683    DW_FORM_dataN for a constant with a signed type, where the type is
21684    wider than the data.  The conclusion of a discussion on the DWARF
21685    list was that this is unspecified.  We choose to always zero-extend
21686    because that is the interpretation long in use by GCC.  */
21687
21688 static gdb_byte *
21689 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21690                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21691 {
21692   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21693   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21694                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21695   LONGEST l = DW_UNSND (attr);
21696
21697   if (bits < sizeof (*value) * 8)
21698     {
21699       l &= ((LONGEST) 1 << bits) - 1;
21700       *value = l;
21701     }
21702   else if (bits == sizeof (*value) * 8)
21703     *value = l;
21704   else
21705     {
21706       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21707       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21708       return bytes;
21709     }
21710
21711   return NULL;
21712 }
21713
21714 /* Read a constant value from an attribute.  Either set *VALUE, or if
21715    the value does not fit in *VALUE, set *BYTES - either already
21716    allocated on the objfile obstack, or newly allocated on OBSTACK,
21717    or, set *BATON, if we translated the constant to a location
21718    expression.  */
21719
21720 static void
21721 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21722                          const char *name, struct obstack *obstack,
21723                          struct dwarf2_cu *cu,
21724                          LONGEST *value, const gdb_byte **bytes,
21725                          struct dwarf2_locexpr_baton **baton)
21726 {
21727   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21728   struct comp_unit_head *cu_header = &cu->header;
21729   struct dwarf_block *blk;
21730   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21731                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21732
21733   *value = 0;
21734   *bytes = NULL;
21735   *baton = NULL;
21736
21737   switch (attr->form)
21738     {
21739     case DW_FORM_addr:
21740     case DW_FORM_GNU_addr_index:
21741       {
21742         gdb_byte *data;
21743
21744         if (TYPE_LENGTH (type) != cu_header->addr_size)
21745           dwarf2_const_value_length_mismatch_complaint (name,
21746                                                         cu_header->addr_size,
21747                                                         TYPE_LENGTH (type));
21748         /* Symbols of this form are reasonably rare, so we just
21749            piggyback on the existing location code rather than writing
21750            a new implementation of symbol_computed_ops.  */
21751         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21752         (*baton)->per_cu = cu->per_cu;
21753         gdb_assert ((*baton)->per_cu);
21754
21755         (*baton)->size = 2 + cu_header->addr_size;
21756         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21757         (*baton)->data = data;
21758
21759         data[0] = DW_OP_addr;
21760         store_unsigned_integer (&data[1], cu_header->addr_size,
21761                                 byte_order, DW_ADDR (attr));
21762         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21763       }
21764       break;
21765     case DW_FORM_string:
21766     case DW_FORM_strp:
21767     case DW_FORM_GNU_str_index:
21768     case DW_FORM_GNU_strp_alt:
21769       /* DW_STRING is already allocated on the objfile obstack, point
21770          directly to it.  */
21771       *bytes = (const gdb_byte *) DW_STRING (attr);
21772       break;
21773     case DW_FORM_block1:
21774     case DW_FORM_block2:
21775     case DW_FORM_block4:
21776     case DW_FORM_block:
21777     case DW_FORM_exprloc:
21778     case DW_FORM_data16:
21779       blk = DW_BLOCK (attr);
21780       if (TYPE_LENGTH (type) != blk->size)
21781         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21782                                                       TYPE_LENGTH (type));
21783       *bytes = blk->data;
21784       break;
21785
21786       /* The DW_AT_const_value attributes are supposed to carry the
21787          symbol's value "represented as it would be on the target
21788          architecture."  By the time we get here, it's already been
21789          converted to host endianness, so we just need to sign- or
21790          zero-extend it as appropriate.  */
21791     case DW_FORM_data1:
21792       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21793       break;
21794     case DW_FORM_data2:
21795       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21796       break;
21797     case DW_FORM_data4:
21798       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21799       break;
21800     case DW_FORM_data8:
21801       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21802       break;
21803
21804     case DW_FORM_sdata:
21805     case DW_FORM_implicit_const:
21806       *value = DW_SND (attr);
21807       break;
21808
21809     case DW_FORM_udata:
21810       *value = DW_UNSND (attr);
21811       break;
21812
21813     default:
21814       complaint (&symfile_complaints,
21815                  _("unsupported const value attribute form: '%s'"),
21816                  dwarf_form_name (attr->form));
21817       *value = 0;
21818       break;
21819     }
21820 }
21821
21822
21823 /* Copy constant value from an attribute to a symbol.  */
21824
21825 static void
21826 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21827                     struct dwarf2_cu *cu)
21828 {
21829   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21830   LONGEST value;
21831   const gdb_byte *bytes;
21832   struct dwarf2_locexpr_baton *baton;
21833
21834   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21835                            SYMBOL_PRINT_NAME (sym),
21836                            &objfile->objfile_obstack, cu,
21837                            &value, &bytes, &baton);
21838
21839   if (baton != NULL)
21840     {
21841       SYMBOL_LOCATION_BATON (sym) = baton;
21842       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21843     }
21844   else if (bytes != NULL)
21845      {
21846       SYMBOL_VALUE_BYTES (sym) = bytes;
21847       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21848     }
21849   else
21850     {
21851       SYMBOL_VALUE (sym) = value;
21852       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21853     }
21854 }
21855
21856 /* Return the type of the die in question using its DW_AT_type attribute.  */
21857
21858 static struct type *
21859 die_type (struct die_info *die, struct dwarf2_cu *cu)
21860 {
21861   struct attribute *type_attr;
21862
21863   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21864   if (!type_attr)
21865     {
21866       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21867       /* A missing DW_AT_type represents a void type.  */
21868       return objfile_type (objfile)->builtin_void;
21869     }
21870
21871   return lookup_die_type (die, type_attr, cu);
21872 }
21873
21874 /* True iff CU's producer generates GNAT Ada auxiliary information
21875    that allows to find parallel types through that information instead
21876    of having to do expensive parallel lookups by type name.  */
21877
21878 static int
21879 need_gnat_info (struct dwarf2_cu *cu)
21880 {
21881   /* Assume that the Ada compiler was GNAT, which always produces
21882      the auxiliary information.  */
21883   return (cu->language == language_ada);
21884 }
21885
21886 /* Return the auxiliary type of the die in question using its
21887    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21888    attribute is not present.  */
21889
21890 static struct type *
21891 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21892 {
21893   struct attribute *type_attr;
21894
21895   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21896   if (!type_attr)
21897     return NULL;
21898
21899   return lookup_die_type (die, type_attr, cu);
21900 }
21901
21902 /* If DIE has a descriptive_type attribute, then set the TYPE's
21903    descriptive type accordingly.  */
21904
21905 static void
21906 set_descriptive_type (struct type *type, struct die_info *die,
21907                       struct dwarf2_cu *cu)
21908 {
21909   struct type *descriptive_type = die_descriptive_type (die, cu);
21910
21911   if (descriptive_type)
21912     {
21913       ALLOCATE_GNAT_AUX_TYPE (type);
21914       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21915     }
21916 }
21917
21918 /* Return the containing type of the die in question using its
21919    DW_AT_containing_type attribute.  */
21920
21921 static struct type *
21922 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21923 {
21924   struct attribute *type_attr;
21925   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21926
21927   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21928   if (!type_attr)
21929     error (_("Dwarf Error: Problem turning containing type into gdb type "
21930              "[in module %s]"), objfile_name (objfile));
21931
21932   return lookup_die_type (die, type_attr, cu);
21933 }
21934
21935 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21936
21937 static struct type *
21938 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21939 {
21940   struct dwarf2_per_objfile *dwarf2_per_objfile
21941     = cu->per_cu->dwarf2_per_objfile;
21942   struct objfile *objfile = dwarf2_per_objfile->objfile;
21943   char *message, *saved;
21944
21945   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21946                         objfile_name (objfile),
21947                         sect_offset_str (cu->header.sect_off),
21948                         sect_offset_str (die->sect_off));
21949   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21950                                   message, strlen (message));
21951   xfree (message);
21952
21953   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21954 }
21955
21956 /* Look up the type of DIE in CU using its type attribute ATTR.
21957    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21958    DW_AT_containing_type.
21959    If there is no type substitute an error marker.  */
21960
21961 static struct type *
21962 lookup_die_type (struct die_info *die, const struct attribute *attr,
21963                  struct dwarf2_cu *cu)
21964 {
21965   struct dwarf2_per_objfile *dwarf2_per_objfile
21966     = cu->per_cu->dwarf2_per_objfile;
21967   struct objfile *objfile = dwarf2_per_objfile->objfile;
21968   struct type *this_type;
21969
21970   gdb_assert (attr->name == DW_AT_type
21971               || attr->name == DW_AT_GNAT_descriptive_type
21972               || attr->name == DW_AT_containing_type);
21973
21974   /* First see if we have it cached.  */
21975
21976   if (attr->form == DW_FORM_GNU_ref_alt)
21977     {
21978       struct dwarf2_per_cu_data *per_cu;
21979       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21980
21981       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21982                                                  dwarf2_per_objfile);
21983       this_type = get_die_type_at_offset (sect_off, per_cu);
21984     }
21985   else if (attr_form_is_ref (attr))
21986     {
21987       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21988
21989       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21990     }
21991   else if (attr->form == DW_FORM_ref_sig8)
21992     {
21993       ULONGEST signature = DW_SIGNATURE (attr);
21994
21995       return get_signatured_type (die, signature, cu);
21996     }
21997   else
21998     {
21999       complaint (&symfile_complaints,
22000                  _("Dwarf Error: Bad type attribute %s in DIE"
22001                    " at %s [in module %s]"),
22002                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22003                  objfile_name (objfile));
22004       return build_error_marker_type (cu, die);
22005     }
22006
22007   /* If not cached we need to read it in.  */
22008
22009   if (this_type == NULL)
22010     {
22011       struct die_info *type_die = NULL;
22012       struct dwarf2_cu *type_cu = cu;
22013
22014       if (attr_form_is_ref (attr))
22015         type_die = follow_die_ref (die, attr, &type_cu);
22016       if (type_die == NULL)
22017         return build_error_marker_type (cu, die);
22018       /* If we find the type now, it's probably because the type came
22019          from an inter-CU reference and the type's CU got expanded before
22020          ours.  */
22021       this_type = read_type_die (type_die, type_cu);
22022     }
22023
22024   /* If we still don't have a type use an error marker.  */
22025
22026   if (this_type == NULL)
22027     return build_error_marker_type (cu, die);
22028
22029   return this_type;
22030 }
22031
22032 /* Return the type in DIE, CU.
22033    Returns NULL for invalid types.
22034
22035    This first does a lookup in die_type_hash,
22036    and only reads the die in if necessary.
22037
22038    NOTE: This can be called when reading in partial or full symbols.  */
22039
22040 static struct type *
22041 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22042 {
22043   struct type *this_type;
22044
22045   this_type = get_die_type (die, cu);
22046   if (this_type)
22047     return this_type;
22048
22049   return read_type_die_1 (die, cu);
22050 }
22051
22052 /* Read the type in DIE, CU.
22053    Returns NULL for invalid types.  */
22054
22055 static struct type *
22056 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22057 {
22058   struct type *this_type = NULL;
22059
22060   switch (die->tag)
22061     {
22062     case DW_TAG_class_type:
22063     case DW_TAG_interface_type:
22064     case DW_TAG_structure_type:
22065     case DW_TAG_union_type:
22066       this_type = read_structure_type (die, cu);
22067       break;
22068     case DW_TAG_enumeration_type:
22069       this_type = read_enumeration_type (die, cu);
22070       break;
22071     case DW_TAG_subprogram:
22072     case DW_TAG_subroutine_type:
22073     case DW_TAG_inlined_subroutine:
22074       this_type = read_subroutine_type (die, cu);
22075       break;
22076     case DW_TAG_array_type:
22077       this_type = read_array_type (die, cu);
22078       break;
22079     case DW_TAG_set_type:
22080       this_type = read_set_type (die, cu);
22081       break;
22082     case DW_TAG_pointer_type:
22083       this_type = read_tag_pointer_type (die, cu);
22084       break;
22085     case DW_TAG_ptr_to_member_type:
22086       this_type = read_tag_ptr_to_member_type (die, cu);
22087       break;
22088     case DW_TAG_reference_type:
22089       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22090       break;
22091     case DW_TAG_rvalue_reference_type:
22092       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22093       break;
22094     case DW_TAG_const_type:
22095       this_type = read_tag_const_type (die, cu);
22096       break;
22097     case DW_TAG_volatile_type:
22098       this_type = read_tag_volatile_type (die, cu);
22099       break;
22100     case DW_TAG_restrict_type:
22101       this_type = read_tag_restrict_type (die, cu);
22102       break;
22103     case DW_TAG_string_type:
22104       this_type = read_tag_string_type (die, cu);
22105       break;
22106     case DW_TAG_typedef:
22107       this_type = read_typedef (die, cu);
22108       break;
22109     case DW_TAG_subrange_type:
22110       this_type = read_subrange_type (die, cu);
22111       break;
22112     case DW_TAG_base_type:
22113       this_type = read_base_type (die, cu);
22114       break;
22115     case DW_TAG_unspecified_type:
22116       this_type = read_unspecified_type (die, cu);
22117       break;
22118     case DW_TAG_namespace:
22119       this_type = read_namespace_type (die, cu);
22120       break;
22121     case DW_TAG_module:
22122       this_type = read_module_type (die, cu);
22123       break;
22124     case DW_TAG_atomic_type:
22125       this_type = read_tag_atomic_type (die, cu);
22126       break;
22127     default:
22128       complaint (&symfile_complaints,
22129                  _("unexpected tag in read_type_die: '%s'"),
22130                  dwarf_tag_name (die->tag));
22131       break;
22132     }
22133
22134   return this_type;
22135 }
22136
22137 /* See if we can figure out if the class lives in a namespace.  We do
22138    this by looking for a member function; its demangled name will
22139    contain namespace info, if there is any.
22140    Return the computed name or NULL.
22141    Space for the result is allocated on the objfile's obstack.
22142    This is the full-die version of guess_partial_die_structure_name.
22143    In this case we know DIE has no useful parent.  */
22144
22145 static char *
22146 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22147 {
22148   struct die_info *spec_die;
22149   struct dwarf2_cu *spec_cu;
22150   struct die_info *child;
22151   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22152
22153   spec_cu = cu;
22154   spec_die = die_specification (die, &spec_cu);
22155   if (spec_die != NULL)
22156     {
22157       die = spec_die;
22158       cu = spec_cu;
22159     }
22160
22161   for (child = die->child;
22162        child != NULL;
22163        child = child->sibling)
22164     {
22165       if (child->tag == DW_TAG_subprogram)
22166         {
22167           const char *linkage_name = dw2_linkage_name (child, cu);
22168
22169           if (linkage_name != NULL)
22170             {
22171               char *actual_name
22172                 = language_class_name_from_physname (cu->language_defn,
22173                                                      linkage_name);
22174               char *name = NULL;
22175
22176               if (actual_name != NULL)
22177                 {
22178                   const char *die_name = dwarf2_name (die, cu);
22179
22180                   if (die_name != NULL
22181                       && strcmp (die_name, actual_name) != 0)
22182                     {
22183                       /* Strip off the class name from the full name.
22184                          We want the prefix.  */
22185                       int die_name_len = strlen (die_name);
22186                       int actual_name_len = strlen (actual_name);
22187
22188                       /* Test for '::' as a sanity check.  */
22189                       if (actual_name_len > die_name_len + 2
22190                           && actual_name[actual_name_len
22191                                          - die_name_len - 1] == ':')
22192                         name = (char *) obstack_copy0 (
22193                           &objfile->per_bfd->storage_obstack,
22194                           actual_name, actual_name_len - die_name_len - 2);
22195                     }
22196                 }
22197               xfree (actual_name);
22198               return name;
22199             }
22200         }
22201     }
22202
22203   return NULL;
22204 }
22205
22206 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22207    prefix part in such case.  See
22208    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22209
22210 static const char *
22211 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22212 {
22213   struct attribute *attr;
22214   const char *base;
22215
22216   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22217       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22218     return NULL;
22219
22220   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22221     return NULL;
22222
22223   attr = dw2_linkage_name_attr (die, cu);
22224   if (attr == NULL || DW_STRING (attr) == NULL)
22225     return NULL;
22226
22227   /* dwarf2_name had to be already called.  */
22228   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22229
22230   /* Strip the base name, keep any leading namespaces/classes.  */
22231   base = strrchr (DW_STRING (attr), ':');
22232   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22233     return "";
22234
22235   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22236   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22237                                  DW_STRING (attr),
22238                                  &base[-1] - DW_STRING (attr));
22239 }
22240
22241 /* Return the name of the namespace/class that DIE is defined within,
22242    or "" if we can't tell.  The caller should not xfree the result.
22243
22244    For example, if we're within the method foo() in the following
22245    code:
22246
22247    namespace N {
22248      class C {
22249        void foo () {
22250        }
22251      };
22252    }
22253
22254    then determine_prefix on foo's die will return "N::C".  */
22255
22256 static const char *
22257 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22258 {
22259   struct dwarf2_per_objfile *dwarf2_per_objfile
22260     = cu->per_cu->dwarf2_per_objfile;
22261   struct die_info *parent, *spec_die;
22262   struct dwarf2_cu *spec_cu;
22263   struct type *parent_type;
22264   const char *retval;
22265
22266   if (cu->language != language_cplus
22267       && cu->language != language_fortran && cu->language != language_d
22268       && cu->language != language_rust)
22269     return "";
22270
22271   retval = anonymous_struct_prefix (die, cu);
22272   if (retval)
22273     return retval;
22274
22275   /* We have to be careful in the presence of DW_AT_specification.
22276      For example, with GCC 3.4, given the code
22277
22278      namespace N {
22279        void foo() {
22280          // Definition of N::foo.
22281        }
22282      }
22283
22284      then we'll have a tree of DIEs like this:
22285
22286      1: DW_TAG_compile_unit
22287        2: DW_TAG_namespace        // N
22288          3: DW_TAG_subprogram     // declaration of N::foo
22289        4: DW_TAG_subprogram       // definition of N::foo
22290             DW_AT_specification   // refers to die #3
22291
22292      Thus, when processing die #4, we have to pretend that we're in
22293      the context of its DW_AT_specification, namely the contex of die
22294      #3.  */
22295   spec_cu = cu;
22296   spec_die = die_specification (die, &spec_cu);
22297   if (spec_die == NULL)
22298     parent = die->parent;
22299   else
22300     {
22301       parent = spec_die->parent;
22302       cu = spec_cu;
22303     }
22304
22305   if (parent == NULL)
22306     return "";
22307   else if (parent->building_fullname)
22308     {
22309       const char *name;
22310       const char *parent_name;
22311
22312       /* It has been seen on RealView 2.2 built binaries,
22313          DW_TAG_template_type_param types actually _defined_ as
22314          children of the parent class:
22315
22316          enum E {};
22317          template class <class Enum> Class{};
22318          Class<enum E> class_e;
22319
22320          1: DW_TAG_class_type (Class)
22321            2: DW_TAG_enumeration_type (E)
22322              3: DW_TAG_enumerator (enum1:0)
22323              3: DW_TAG_enumerator (enum2:1)
22324              ...
22325            2: DW_TAG_template_type_param
22326               DW_AT_type  DW_FORM_ref_udata (E)
22327
22328          Besides being broken debug info, it can put GDB into an
22329          infinite loop.  Consider:
22330
22331          When we're building the full name for Class<E>, we'll start
22332          at Class, and go look over its template type parameters,
22333          finding E.  We'll then try to build the full name of E, and
22334          reach here.  We're now trying to build the full name of E,
22335          and look over the parent DIE for containing scope.  In the
22336          broken case, if we followed the parent DIE of E, we'd again
22337          find Class, and once again go look at its template type
22338          arguments, etc., etc.  Simply don't consider such parent die
22339          as source-level parent of this die (it can't be, the language
22340          doesn't allow it), and break the loop here.  */
22341       name = dwarf2_name (die, cu);
22342       parent_name = dwarf2_name (parent, cu);
22343       complaint (&symfile_complaints,
22344                  _("template param type '%s' defined within parent '%s'"),
22345                  name ? name : "<unknown>",
22346                  parent_name ? parent_name : "<unknown>");
22347       return "";
22348     }
22349   else
22350     switch (parent->tag)
22351       {
22352       case DW_TAG_namespace:
22353         parent_type = read_type_die (parent, cu);
22354         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22355            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22356            Work around this problem here.  */
22357         if (cu->language == language_cplus
22358             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22359           return "";
22360         /* We give a name to even anonymous namespaces.  */
22361         return TYPE_TAG_NAME (parent_type);
22362       case DW_TAG_class_type:
22363       case DW_TAG_interface_type:
22364       case DW_TAG_structure_type:
22365       case DW_TAG_union_type:
22366       case DW_TAG_module:
22367         parent_type = read_type_die (parent, cu);
22368         if (TYPE_TAG_NAME (parent_type) != NULL)
22369           return TYPE_TAG_NAME (parent_type);
22370         else
22371           /* An anonymous structure is only allowed non-static data
22372              members; no typedefs, no member functions, et cetera.
22373              So it does not need a prefix.  */
22374           return "";
22375       case DW_TAG_compile_unit:
22376       case DW_TAG_partial_unit:
22377         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22378         if (cu->language == language_cplus
22379             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22380             && die->child != NULL
22381             && (die->tag == DW_TAG_class_type
22382                 || die->tag == DW_TAG_structure_type
22383                 || die->tag == DW_TAG_union_type))
22384           {
22385             char *name = guess_full_die_structure_name (die, cu);
22386             if (name != NULL)
22387               return name;
22388           }
22389         return "";
22390       case DW_TAG_enumeration_type:
22391         parent_type = read_type_die (parent, cu);
22392         if (TYPE_DECLARED_CLASS (parent_type))
22393           {
22394             if (TYPE_TAG_NAME (parent_type) != NULL)
22395               return TYPE_TAG_NAME (parent_type);
22396             return "";
22397           }
22398         /* Fall through.  */
22399       default:
22400         return determine_prefix (parent, cu);
22401       }
22402 }
22403
22404 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22405    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22406    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22407    an obconcat, otherwise allocate storage for the result.  The CU argument is
22408    used to determine the language and hence, the appropriate separator.  */
22409
22410 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22411
22412 static char *
22413 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22414                  int physname, struct dwarf2_cu *cu)
22415 {
22416   const char *lead = "";
22417   const char *sep;
22418
22419   if (suffix == NULL || suffix[0] == '\0'
22420       || prefix == NULL || prefix[0] == '\0')
22421     sep = "";
22422   else if (cu->language == language_d)
22423     {
22424       /* For D, the 'main' function could be defined in any module, but it
22425          should never be prefixed.  */
22426       if (strcmp (suffix, "D main") == 0)
22427         {
22428           prefix = "";
22429           sep = "";
22430         }
22431       else
22432         sep = ".";
22433     }
22434   else if (cu->language == language_fortran && physname)
22435     {
22436       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22437          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22438
22439       lead = "__";
22440       sep = "_MOD_";
22441     }
22442   else
22443     sep = "::";
22444
22445   if (prefix == NULL)
22446     prefix = "";
22447   if (suffix == NULL)
22448     suffix = "";
22449
22450   if (obs == NULL)
22451     {
22452       char *retval
22453         = ((char *)
22454            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22455
22456       strcpy (retval, lead);
22457       strcat (retval, prefix);
22458       strcat (retval, sep);
22459       strcat (retval, suffix);
22460       return retval;
22461     }
22462   else
22463     {
22464       /* We have an obstack.  */
22465       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22466     }
22467 }
22468
22469 /* Return sibling of die, NULL if no sibling.  */
22470
22471 static struct die_info *
22472 sibling_die (struct die_info *die)
22473 {
22474   return die->sibling;
22475 }
22476
22477 /* Get name of a die, return NULL if not found.  */
22478
22479 static const char *
22480 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22481                           struct obstack *obstack)
22482 {
22483   if (name && cu->language == language_cplus)
22484     {
22485       std::string canon_name = cp_canonicalize_string (name);
22486
22487       if (!canon_name.empty ())
22488         {
22489           if (canon_name != name)
22490             name = (const char *) obstack_copy0 (obstack,
22491                                                  canon_name.c_str (),
22492                                                  canon_name.length ());
22493         }
22494     }
22495
22496   return name;
22497 }
22498
22499 /* Get name of a die, return NULL if not found.
22500    Anonymous namespaces are converted to their magic string.  */
22501
22502 static const char *
22503 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22504 {
22505   struct attribute *attr;
22506   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22507
22508   attr = dwarf2_attr (die, DW_AT_name, cu);
22509   if ((!attr || !DW_STRING (attr))
22510       && die->tag != DW_TAG_namespace
22511       && die->tag != DW_TAG_class_type
22512       && die->tag != DW_TAG_interface_type
22513       && die->tag != DW_TAG_structure_type
22514       && die->tag != DW_TAG_union_type)
22515     return NULL;
22516
22517   switch (die->tag)
22518     {
22519     case DW_TAG_compile_unit:
22520     case DW_TAG_partial_unit:
22521       /* Compilation units have a DW_AT_name that is a filename, not
22522          a source language identifier.  */
22523     case DW_TAG_enumeration_type:
22524     case DW_TAG_enumerator:
22525       /* These tags always have simple identifiers already; no need
22526          to canonicalize them.  */
22527       return DW_STRING (attr);
22528
22529     case DW_TAG_namespace:
22530       if (attr != NULL && DW_STRING (attr) != NULL)
22531         return DW_STRING (attr);
22532       return CP_ANONYMOUS_NAMESPACE_STR;
22533
22534     case DW_TAG_class_type:
22535     case DW_TAG_interface_type:
22536     case DW_TAG_structure_type:
22537     case DW_TAG_union_type:
22538       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22539          structures or unions.  These were of the form "._%d" in GCC 4.1,
22540          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22541          and GCC 4.4.  We work around this problem by ignoring these.  */
22542       if (attr && DW_STRING (attr)
22543           && (startswith (DW_STRING (attr), "._")
22544               || startswith (DW_STRING (attr), "<anonymous")))
22545         return NULL;
22546
22547       /* GCC might emit a nameless typedef that has a linkage name.  See
22548          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22549       if (!attr || DW_STRING (attr) == NULL)
22550         {
22551           char *demangled = NULL;
22552
22553           attr = dw2_linkage_name_attr (die, cu);
22554           if (attr == NULL || DW_STRING (attr) == NULL)
22555             return NULL;
22556
22557           /* Avoid demangling DW_STRING (attr) the second time on a second
22558              call for the same DIE.  */
22559           if (!DW_STRING_IS_CANONICAL (attr))
22560             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22561
22562           if (demangled)
22563             {
22564               const char *base;
22565
22566               /* FIXME: we already did this for the partial symbol... */
22567               DW_STRING (attr)
22568                 = ((const char *)
22569                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22570                                   demangled, strlen (demangled)));
22571               DW_STRING_IS_CANONICAL (attr) = 1;
22572               xfree (demangled);
22573
22574               /* Strip any leading namespaces/classes, keep only the base name.
22575                  DW_AT_name for named DIEs does not contain the prefixes.  */
22576               base = strrchr (DW_STRING (attr), ':');
22577               if (base && base > DW_STRING (attr) && base[-1] == ':')
22578                 return &base[1];
22579               else
22580                 return DW_STRING (attr);
22581             }
22582         }
22583       break;
22584
22585     default:
22586       break;
22587     }
22588
22589   if (!DW_STRING_IS_CANONICAL (attr))
22590     {
22591       DW_STRING (attr)
22592         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22593                                     &objfile->per_bfd->storage_obstack);
22594       DW_STRING_IS_CANONICAL (attr) = 1;
22595     }
22596   return DW_STRING (attr);
22597 }
22598
22599 /* Return the die that this die in an extension of, or NULL if there
22600    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22601    containing the return value on output.  */
22602
22603 static struct die_info *
22604 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22605 {
22606   struct attribute *attr;
22607
22608   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22609   if (attr == NULL)
22610     return NULL;
22611
22612   return follow_die_ref (die, attr, ext_cu);
22613 }
22614
22615 /* Convert a DIE tag into its string name.  */
22616
22617 static const char *
22618 dwarf_tag_name (unsigned tag)
22619 {
22620   const char *name = get_DW_TAG_name (tag);
22621
22622   if (name == NULL)
22623     return "DW_TAG_<unknown>";
22624
22625   return name;
22626 }
22627
22628 /* Convert a DWARF attribute code into its string name.  */
22629
22630 static const char *
22631 dwarf_attr_name (unsigned attr)
22632 {
22633   const char *name;
22634
22635 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22636   if (attr == DW_AT_MIPS_fde)
22637     return "DW_AT_MIPS_fde";
22638 #else
22639   if (attr == DW_AT_HP_block_index)
22640     return "DW_AT_HP_block_index";
22641 #endif
22642
22643   name = get_DW_AT_name (attr);
22644
22645   if (name == NULL)
22646     return "DW_AT_<unknown>";
22647
22648   return name;
22649 }
22650
22651 /* Convert a DWARF value form code into its string name.  */
22652
22653 static const char *
22654 dwarf_form_name (unsigned form)
22655 {
22656   const char *name = get_DW_FORM_name (form);
22657
22658   if (name == NULL)
22659     return "DW_FORM_<unknown>";
22660
22661   return name;
22662 }
22663
22664 static const char *
22665 dwarf_bool_name (unsigned mybool)
22666 {
22667   if (mybool)
22668     return "TRUE";
22669   else
22670     return "FALSE";
22671 }
22672
22673 /* Convert a DWARF type code into its string name.  */
22674
22675 static const char *
22676 dwarf_type_encoding_name (unsigned enc)
22677 {
22678   const char *name = get_DW_ATE_name (enc);
22679
22680   if (name == NULL)
22681     return "DW_ATE_<unknown>";
22682
22683   return name;
22684 }
22685
22686 static void
22687 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22688 {
22689   unsigned int i;
22690
22691   print_spaces (indent, f);
22692   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22693                       dwarf_tag_name (die->tag), die->abbrev,
22694                       sect_offset_str (die->sect_off));
22695
22696   if (die->parent != NULL)
22697     {
22698       print_spaces (indent, f);
22699       fprintf_unfiltered (f, "  parent at offset: %s\n",
22700                           sect_offset_str (die->parent->sect_off));
22701     }
22702
22703   print_spaces (indent, f);
22704   fprintf_unfiltered (f, "  has children: %s\n",
22705            dwarf_bool_name (die->child != NULL));
22706
22707   print_spaces (indent, f);
22708   fprintf_unfiltered (f, "  attributes:\n");
22709
22710   for (i = 0; i < die->num_attrs; ++i)
22711     {
22712       print_spaces (indent, f);
22713       fprintf_unfiltered (f, "    %s (%s) ",
22714                dwarf_attr_name (die->attrs[i].name),
22715                dwarf_form_name (die->attrs[i].form));
22716
22717       switch (die->attrs[i].form)
22718         {
22719         case DW_FORM_addr:
22720         case DW_FORM_GNU_addr_index:
22721           fprintf_unfiltered (f, "address: ");
22722           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22723           break;
22724         case DW_FORM_block2:
22725         case DW_FORM_block4:
22726         case DW_FORM_block:
22727         case DW_FORM_block1:
22728           fprintf_unfiltered (f, "block: size %s",
22729                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22730           break;
22731         case DW_FORM_exprloc:
22732           fprintf_unfiltered (f, "expression: size %s",
22733                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22734           break;
22735         case DW_FORM_data16:
22736           fprintf_unfiltered (f, "constant of 16 bytes");
22737           break;
22738         case DW_FORM_ref_addr:
22739           fprintf_unfiltered (f, "ref address: ");
22740           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22741           break;
22742         case DW_FORM_GNU_ref_alt:
22743           fprintf_unfiltered (f, "alt ref address: ");
22744           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22745           break;
22746         case DW_FORM_ref1:
22747         case DW_FORM_ref2:
22748         case DW_FORM_ref4:
22749         case DW_FORM_ref8:
22750         case DW_FORM_ref_udata:
22751           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22752                               (long) (DW_UNSND (&die->attrs[i])));
22753           break;
22754         case DW_FORM_data1:
22755         case DW_FORM_data2:
22756         case DW_FORM_data4:
22757         case DW_FORM_data8:
22758         case DW_FORM_udata:
22759         case DW_FORM_sdata:
22760           fprintf_unfiltered (f, "constant: %s",
22761                               pulongest (DW_UNSND (&die->attrs[i])));
22762           break;
22763         case DW_FORM_sec_offset:
22764           fprintf_unfiltered (f, "section offset: %s",
22765                               pulongest (DW_UNSND (&die->attrs[i])));
22766           break;
22767         case DW_FORM_ref_sig8:
22768           fprintf_unfiltered (f, "signature: %s",
22769                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22770           break;
22771         case DW_FORM_string:
22772         case DW_FORM_strp:
22773         case DW_FORM_line_strp:
22774         case DW_FORM_GNU_str_index:
22775         case DW_FORM_GNU_strp_alt:
22776           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22777                    DW_STRING (&die->attrs[i])
22778                    ? DW_STRING (&die->attrs[i]) : "",
22779                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22780           break;
22781         case DW_FORM_flag:
22782           if (DW_UNSND (&die->attrs[i]))
22783             fprintf_unfiltered (f, "flag: TRUE");
22784           else
22785             fprintf_unfiltered (f, "flag: FALSE");
22786           break;
22787         case DW_FORM_flag_present:
22788           fprintf_unfiltered (f, "flag: TRUE");
22789           break;
22790         case DW_FORM_indirect:
22791           /* The reader will have reduced the indirect form to
22792              the "base form" so this form should not occur.  */
22793           fprintf_unfiltered (f, 
22794                               "unexpected attribute form: DW_FORM_indirect");
22795           break;
22796         case DW_FORM_implicit_const:
22797           fprintf_unfiltered (f, "constant: %s",
22798                               plongest (DW_SND (&die->attrs[i])));
22799           break;
22800         default:
22801           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22802                    die->attrs[i].form);
22803           break;
22804         }
22805       fprintf_unfiltered (f, "\n");
22806     }
22807 }
22808
22809 static void
22810 dump_die_for_error (struct die_info *die)
22811 {
22812   dump_die_shallow (gdb_stderr, 0, die);
22813 }
22814
22815 static void
22816 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22817 {
22818   int indent = level * 4;
22819
22820   gdb_assert (die != NULL);
22821
22822   if (level >= max_level)
22823     return;
22824
22825   dump_die_shallow (f, indent, die);
22826
22827   if (die->child != NULL)
22828     {
22829       print_spaces (indent, f);
22830       fprintf_unfiltered (f, "  Children:");
22831       if (level + 1 < max_level)
22832         {
22833           fprintf_unfiltered (f, "\n");
22834           dump_die_1 (f, level + 1, max_level, die->child);
22835         }
22836       else
22837         {
22838           fprintf_unfiltered (f,
22839                               " [not printed, max nesting level reached]\n");
22840         }
22841     }
22842
22843   if (die->sibling != NULL && level > 0)
22844     {
22845       dump_die_1 (f, level, max_level, die->sibling);
22846     }
22847 }
22848
22849 /* This is called from the pdie macro in gdbinit.in.
22850    It's not static so gcc will keep a copy callable from gdb.  */
22851
22852 void
22853 dump_die (struct die_info *die, int max_level)
22854 {
22855   dump_die_1 (gdb_stdlog, 0, max_level, die);
22856 }
22857
22858 static void
22859 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22860 {
22861   void **slot;
22862
22863   slot = htab_find_slot_with_hash (cu->die_hash, die,
22864                                    to_underlying (die->sect_off),
22865                                    INSERT);
22866
22867   *slot = die;
22868 }
22869
22870 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22871    required kind.  */
22872
22873 static sect_offset
22874 dwarf2_get_ref_die_offset (const struct attribute *attr)
22875 {
22876   if (attr_form_is_ref (attr))
22877     return (sect_offset) DW_UNSND (attr);
22878
22879   complaint (&symfile_complaints,
22880              _("unsupported die ref attribute form: '%s'"),
22881              dwarf_form_name (attr->form));
22882   return {};
22883 }
22884
22885 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22886  * the value held by the attribute is not constant.  */
22887
22888 static LONGEST
22889 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22890 {
22891   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22892     return DW_SND (attr);
22893   else if (attr->form == DW_FORM_udata
22894            || attr->form == DW_FORM_data1
22895            || attr->form == DW_FORM_data2
22896            || attr->form == DW_FORM_data4
22897            || attr->form == DW_FORM_data8)
22898     return DW_UNSND (attr);
22899   else
22900     {
22901       /* For DW_FORM_data16 see attr_form_is_constant.  */
22902       complaint (&symfile_complaints,
22903                  _("Attribute value is not a constant (%s)"),
22904                  dwarf_form_name (attr->form));
22905       return default_value;
22906     }
22907 }
22908
22909 /* Follow reference or signature attribute ATTR of SRC_DIE.
22910    On entry *REF_CU is the CU of SRC_DIE.
22911    On exit *REF_CU is the CU of the result.  */
22912
22913 static struct die_info *
22914 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22915                        struct dwarf2_cu **ref_cu)
22916 {
22917   struct die_info *die;
22918
22919   if (attr_form_is_ref (attr))
22920     die = follow_die_ref (src_die, attr, ref_cu);
22921   else if (attr->form == DW_FORM_ref_sig8)
22922     die = follow_die_sig (src_die, attr, ref_cu);
22923   else
22924     {
22925       dump_die_for_error (src_die);
22926       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22927              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22928     }
22929
22930   return die;
22931 }
22932
22933 /* Follow reference OFFSET.
22934    On entry *REF_CU is the CU of the source die referencing OFFSET.
22935    On exit *REF_CU is the CU of the result.
22936    Returns NULL if OFFSET is invalid.  */
22937
22938 static struct die_info *
22939 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22940                    struct dwarf2_cu **ref_cu)
22941 {
22942   struct die_info temp_die;
22943   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22944   struct dwarf2_per_objfile *dwarf2_per_objfile
22945     = cu->per_cu->dwarf2_per_objfile;
22946   struct objfile *objfile = dwarf2_per_objfile->objfile;
22947
22948   gdb_assert (cu->per_cu != NULL);
22949
22950   target_cu = cu;
22951
22952   if (cu->per_cu->is_debug_types)
22953     {
22954       /* .debug_types CUs cannot reference anything outside their CU.
22955          If they need to, they have to reference a signatured type via
22956          DW_FORM_ref_sig8.  */
22957       if (!offset_in_cu_p (&cu->header, sect_off))
22958         return NULL;
22959     }
22960   else if (offset_in_dwz != cu->per_cu->is_dwz
22961            || !offset_in_cu_p (&cu->header, sect_off))
22962     {
22963       struct dwarf2_per_cu_data *per_cu;
22964
22965       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22966                                                  dwarf2_per_objfile);
22967
22968       /* If necessary, add it to the queue and load its DIEs.  */
22969       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22970         load_full_comp_unit (per_cu, cu->language);
22971
22972       target_cu = per_cu->cu;
22973     }
22974   else if (cu->dies == NULL)
22975     {
22976       /* We're loading full DIEs during partial symbol reading.  */
22977       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22978       load_full_comp_unit (cu->per_cu, language_minimal);
22979     }
22980
22981   *ref_cu = target_cu;
22982   temp_die.sect_off = sect_off;
22983   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22984                                                   &temp_die,
22985                                                   to_underlying (sect_off));
22986 }
22987
22988 /* Follow reference attribute ATTR of SRC_DIE.
22989    On entry *REF_CU is the CU of SRC_DIE.
22990    On exit *REF_CU is the CU of the result.  */
22991
22992 static struct die_info *
22993 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22994                 struct dwarf2_cu **ref_cu)
22995 {
22996   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22997   struct dwarf2_cu *cu = *ref_cu;
22998   struct die_info *die;
22999
23000   die = follow_die_offset (sect_off,
23001                            (attr->form == DW_FORM_GNU_ref_alt
23002                             || cu->per_cu->is_dwz),
23003                            ref_cu);
23004   if (!die)
23005     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23006            "at %s [in module %s]"),
23007            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23008            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23009
23010   return die;
23011 }
23012
23013 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23014    Returned value is intended for DW_OP_call*.  Returned
23015    dwarf2_locexpr_baton->data has lifetime of
23016    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23017
23018 struct dwarf2_locexpr_baton
23019 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23020                                struct dwarf2_per_cu_data *per_cu,
23021                                CORE_ADDR (*get_frame_pc) (void *baton),
23022                                void *baton)
23023 {
23024   struct dwarf2_cu *cu;
23025   struct die_info *die;
23026   struct attribute *attr;
23027   struct dwarf2_locexpr_baton retval;
23028   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23029   struct dwarf2_per_objfile *dwarf2_per_objfile
23030     = get_dwarf2_per_objfile (objfile);
23031
23032   if (per_cu->cu == NULL)
23033     load_cu (per_cu);
23034   cu = per_cu->cu;
23035   if (cu == NULL)
23036     {
23037       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23038          Instead just throw an error, not much else we can do.  */
23039       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23040              sect_offset_str (sect_off), objfile_name (objfile));
23041     }
23042
23043   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23044   if (!die)
23045     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23046            sect_offset_str (sect_off), objfile_name (objfile));
23047
23048   attr = dwarf2_attr (die, DW_AT_location, cu);
23049   if (!attr)
23050     {
23051       /* DWARF: "If there is no such attribute, then there is no effect.".
23052          DATA is ignored if SIZE is 0.  */
23053
23054       retval.data = NULL;
23055       retval.size = 0;
23056     }
23057   else if (attr_form_is_section_offset (attr))
23058     {
23059       struct dwarf2_loclist_baton loclist_baton;
23060       CORE_ADDR pc = (*get_frame_pc) (baton);
23061       size_t size;
23062
23063       fill_in_loclist_baton (cu, &loclist_baton, attr);
23064
23065       retval.data = dwarf2_find_location_expression (&loclist_baton,
23066                                                      &size, pc);
23067       retval.size = size;
23068     }
23069   else
23070     {
23071       if (!attr_form_is_block (attr))
23072         error (_("Dwarf Error: DIE at %s referenced in module %s "
23073                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23074                sect_offset_str (sect_off), objfile_name (objfile));
23075
23076       retval.data = DW_BLOCK (attr)->data;
23077       retval.size = DW_BLOCK (attr)->size;
23078     }
23079   retval.per_cu = cu->per_cu;
23080
23081   age_cached_comp_units (dwarf2_per_objfile);
23082
23083   return retval;
23084 }
23085
23086 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23087    offset.  */
23088
23089 struct dwarf2_locexpr_baton
23090 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23091                              struct dwarf2_per_cu_data *per_cu,
23092                              CORE_ADDR (*get_frame_pc) (void *baton),
23093                              void *baton)
23094 {
23095   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23096
23097   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23098 }
23099
23100 /* Write a constant of a given type as target-ordered bytes into
23101    OBSTACK.  */
23102
23103 static const gdb_byte *
23104 write_constant_as_bytes (struct obstack *obstack,
23105                          enum bfd_endian byte_order,
23106                          struct type *type,
23107                          ULONGEST value,
23108                          LONGEST *len)
23109 {
23110   gdb_byte *result;
23111
23112   *len = TYPE_LENGTH (type);
23113   result = (gdb_byte *) obstack_alloc (obstack, *len);
23114   store_unsigned_integer (result, *len, byte_order, value);
23115
23116   return result;
23117 }
23118
23119 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23120    pointer to the constant bytes and set LEN to the length of the
23121    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23122    does not have a DW_AT_const_value, return NULL.  */
23123
23124 const gdb_byte *
23125 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23126                              struct dwarf2_per_cu_data *per_cu,
23127                              struct obstack *obstack,
23128                              LONGEST *len)
23129 {
23130   struct dwarf2_cu *cu;
23131   struct die_info *die;
23132   struct attribute *attr;
23133   const gdb_byte *result = NULL;
23134   struct type *type;
23135   LONGEST value;
23136   enum bfd_endian byte_order;
23137   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23138
23139   if (per_cu->cu == NULL)
23140     load_cu (per_cu);
23141   cu = per_cu->cu;
23142   if (cu == NULL)
23143     {
23144       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23145          Instead just throw an error, not much else we can do.  */
23146       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23147              sect_offset_str (sect_off), objfile_name (objfile));
23148     }
23149
23150   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23151   if (!die)
23152     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23153            sect_offset_str (sect_off), objfile_name (objfile));
23154
23155   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23156   if (attr == NULL)
23157     return NULL;
23158
23159   byte_order = (bfd_big_endian (objfile->obfd)
23160                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23161
23162   switch (attr->form)
23163     {
23164     case DW_FORM_addr:
23165     case DW_FORM_GNU_addr_index:
23166       {
23167         gdb_byte *tem;
23168
23169         *len = cu->header.addr_size;
23170         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23171         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23172         result = tem;
23173       }
23174       break;
23175     case DW_FORM_string:
23176     case DW_FORM_strp:
23177     case DW_FORM_GNU_str_index:
23178     case DW_FORM_GNU_strp_alt:
23179       /* DW_STRING is already allocated on the objfile obstack, point
23180          directly to it.  */
23181       result = (const gdb_byte *) DW_STRING (attr);
23182       *len = strlen (DW_STRING (attr));
23183       break;
23184     case DW_FORM_block1:
23185     case DW_FORM_block2:
23186     case DW_FORM_block4:
23187     case DW_FORM_block:
23188     case DW_FORM_exprloc:
23189     case DW_FORM_data16:
23190       result = DW_BLOCK (attr)->data;
23191       *len = DW_BLOCK (attr)->size;
23192       break;
23193
23194       /* The DW_AT_const_value attributes are supposed to carry the
23195          symbol's value "represented as it would be on the target
23196          architecture."  By the time we get here, it's already been
23197          converted to host endianness, so we just need to sign- or
23198          zero-extend it as appropriate.  */
23199     case DW_FORM_data1:
23200       type = die_type (die, cu);
23201       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23202       if (result == NULL)
23203         result = write_constant_as_bytes (obstack, byte_order,
23204                                           type, value, len);
23205       break;
23206     case DW_FORM_data2:
23207       type = die_type (die, cu);
23208       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23209       if (result == NULL)
23210         result = write_constant_as_bytes (obstack, byte_order,
23211                                           type, value, len);
23212       break;
23213     case DW_FORM_data4:
23214       type = die_type (die, cu);
23215       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23216       if (result == NULL)
23217         result = write_constant_as_bytes (obstack, byte_order,
23218                                           type, value, len);
23219       break;
23220     case DW_FORM_data8:
23221       type = die_type (die, cu);
23222       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23223       if (result == NULL)
23224         result = write_constant_as_bytes (obstack, byte_order,
23225                                           type, value, len);
23226       break;
23227
23228     case DW_FORM_sdata:
23229     case DW_FORM_implicit_const:
23230       type = die_type (die, cu);
23231       result = write_constant_as_bytes (obstack, byte_order,
23232                                         type, DW_SND (attr), len);
23233       break;
23234
23235     case DW_FORM_udata:
23236       type = die_type (die, cu);
23237       result = write_constant_as_bytes (obstack, byte_order,
23238                                         type, DW_UNSND (attr), len);
23239       break;
23240
23241     default:
23242       complaint (&symfile_complaints,
23243                  _("unsupported const value attribute form: '%s'"),
23244                  dwarf_form_name (attr->form));
23245       break;
23246     }
23247
23248   return result;
23249 }
23250
23251 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23252    valid type for this die is found.  */
23253
23254 struct type *
23255 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23256                                 struct dwarf2_per_cu_data *per_cu)
23257 {
23258   struct dwarf2_cu *cu;
23259   struct die_info *die;
23260
23261   if (per_cu->cu == NULL)
23262     load_cu (per_cu);
23263   cu = per_cu->cu;
23264   if (!cu)
23265     return NULL;
23266
23267   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23268   if (!die)
23269     return NULL;
23270
23271   return die_type (die, cu);
23272 }
23273
23274 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23275    PER_CU.  */
23276
23277 struct type *
23278 dwarf2_get_die_type (cu_offset die_offset,
23279                      struct dwarf2_per_cu_data *per_cu)
23280 {
23281   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23282   return get_die_type_at_offset (die_offset_sect, per_cu);
23283 }
23284
23285 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23286    On entry *REF_CU is the CU of SRC_DIE.
23287    On exit *REF_CU is the CU of the result.
23288    Returns NULL if the referenced DIE isn't found.  */
23289
23290 static struct die_info *
23291 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23292                   struct dwarf2_cu **ref_cu)
23293 {
23294   struct die_info temp_die;
23295   struct dwarf2_cu *sig_cu;
23296   struct die_info *die;
23297
23298   /* While it might be nice to assert sig_type->type == NULL here,
23299      we can get here for DW_AT_imported_declaration where we need
23300      the DIE not the type.  */
23301
23302   /* If necessary, add it to the queue and load its DIEs.  */
23303
23304   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23305     read_signatured_type (sig_type);
23306
23307   sig_cu = sig_type->per_cu.cu;
23308   gdb_assert (sig_cu != NULL);
23309   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23310   temp_die.sect_off = sig_type->type_offset_in_section;
23311   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23312                                                  to_underlying (temp_die.sect_off));
23313   if (die)
23314     {
23315       struct dwarf2_per_objfile *dwarf2_per_objfile
23316         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23317
23318       /* For .gdb_index version 7 keep track of included TUs.
23319          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23320       if (dwarf2_per_objfile->index_table != NULL
23321           && dwarf2_per_objfile->index_table->version <= 7)
23322         {
23323           VEC_safe_push (dwarf2_per_cu_ptr,
23324                          (*ref_cu)->per_cu->imported_symtabs,
23325                          sig_cu->per_cu);
23326         }
23327
23328       *ref_cu = sig_cu;
23329       return die;
23330     }
23331
23332   return NULL;
23333 }
23334
23335 /* Follow signatured type referenced by ATTR in SRC_DIE.
23336    On entry *REF_CU is the CU of SRC_DIE.
23337    On exit *REF_CU is the CU of the result.
23338    The result is the DIE of the type.
23339    If the referenced type cannot be found an error is thrown.  */
23340
23341 static struct die_info *
23342 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23343                 struct dwarf2_cu **ref_cu)
23344 {
23345   ULONGEST signature = DW_SIGNATURE (attr);
23346   struct signatured_type *sig_type;
23347   struct die_info *die;
23348
23349   gdb_assert (attr->form == DW_FORM_ref_sig8);
23350
23351   sig_type = lookup_signatured_type (*ref_cu, signature);
23352   /* sig_type will be NULL if the signatured type is missing from
23353      the debug info.  */
23354   if (sig_type == NULL)
23355     {
23356       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23357                " from DIE at %s [in module %s]"),
23358              hex_string (signature), sect_offset_str (src_die->sect_off),
23359              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23360     }
23361
23362   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23363   if (die == NULL)
23364     {
23365       dump_die_for_error (src_die);
23366       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23367                " from DIE at %s [in module %s]"),
23368              hex_string (signature), sect_offset_str (src_die->sect_off),
23369              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23370     }
23371
23372   return die;
23373 }
23374
23375 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23376    reading in and processing the type unit if necessary.  */
23377
23378 static struct type *
23379 get_signatured_type (struct die_info *die, ULONGEST signature,
23380                      struct dwarf2_cu *cu)
23381 {
23382   struct dwarf2_per_objfile *dwarf2_per_objfile
23383     = cu->per_cu->dwarf2_per_objfile;
23384   struct signatured_type *sig_type;
23385   struct dwarf2_cu *type_cu;
23386   struct die_info *type_die;
23387   struct type *type;
23388
23389   sig_type = lookup_signatured_type (cu, signature);
23390   /* sig_type will be NULL if the signatured type is missing from
23391      the debug info.  */
23392   if (sig_type == NULL)
23393     {
23394       complaint (&symfile_complaints,
23395                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23396                    " from DIE at %s [in module %s]"),
23397                  hex_string (signature), sect_offset_str (die->sect_off),
23398                  objfile_name (dwarf2_per_objfile->objfile));
23399       return build_error_marker_type (cu, die);
23400     }
23401
23402   /* If we already know the type we're done.  */
23403   if (sig_type->type != NULL)
23404     return sig_type->type;
23405
23406   type_cu = cu;
23407   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23408   if (type_die != NULL)
23409     {
23410       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23411          is created.  This is important, for example, because for c++ classes
23412          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23413       type = read_type_die (type_die, type_cu);
23414       if (type == NULL)
23415         {
23416           complaint (&symfile_complaints,
23417                      _("Dwarf Error: Cannot build signatured type %s"
23418                        " referenced from DIE at %s [in module %s]"),
23419                      hex_string (signature), sect_offset_str (die->sect_off),
23420                      objfile_name (dwarf2_per_objfile->objfile));
23421           type = build_error_marker_type (cu, die);
23422         }
23423     }
23424   else
23425     {
23426       complaint (&symfile_complaints,
23427                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23428                    " from DIE at %s [in module %s]"),
23429                  hex_string (signature), sect_offset_str (die->sect_off),
23430                  objfile_name (dwarf2_per_objfile->objfile));
23431       type = build_error_marker_type (cu, die);
23432     }
23433   sig_type->type = type;
23434
23435   return type;
23436 }
23437
23438 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23439    reading in and processing the type unit if necessary.  */
23440
23441 static struct type *
23442 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23443                           struct dwarf2_cu *cu) /* ARI: editCase function */
23444 {
23445   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23446   if (attr_form_is_ref (attr))
23447     {
23448       struct dwarf2_cu *type_cu = cu;
23449       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23450
23451       return read_type_die (type_die, type_cu);
23452     }
23453   else if (attr->form == DW_FORM_ref_sig8)
23454     {
23455       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23456     }
23457   else
23458     {
23459       struct dwarf2_per_objfile *dwarf2_per_objfile
23460         = cu->per_cu->dwarf2_per_objfile;
23461
23462       complaint (&symfile_complaints,
23463                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23464                    " at %s [in module %s]"),
23465                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23466                  objfile_name (dwarf2_per_objfile->objfile));
23467       return build_error_marker_type (cu, die);
23468     }
23469 }
23470
23471 /* Load the DIEs associated with type unit PER_CU into memory.  */
23472
23473 static void
23474 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23475 {
23476   struct signatured_type *sig_type;
23477
23478   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23479   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23480
23481   /* We have the per_cu, but we need the signatured_type.
23482      Fortunately this is an easy translation.  */
23483   gdb_assert (per_cu->is_debug_types);
23484   sig_type = (struct signatured_type *) per_cu;
23485
23486   gdb_assert (per_cu->cu == NULL);
23487
23488   read_signatured_type (sig_type);
23489
23490   gdb_assert (per_cu->cu != NULL);
23491 }
23492
23493 /* die_reader_func for read_signatured_type.
23494    This is identical to load_full_comp_unit_reader,
23495    but is kept separate for now.  */
23496
23497 static void
23498 read_signatured_type_reader (const struct die_reader_specs *reader,
23499                              const gdb_byte *info_ptr,
23500                              struct die_info *comp_unit_die,
23501                              int has_children,
23502                              void *data)
23503 {
23504   struct dwarf2_cu *cu = reader->cu;
23505
23506   gdb_assert (cu->die_hash == NULL);
23507   cu->die_hash =
23508     htab_create_alloc_ex (cu->header.length / 12,
23509                           die_hash,
23510                           die_eq,
23511                           NULL,
23512                           &cu->comp_unit_obstack,
23513                           hashtab_obstack_allocate,
23514                           dummy_obstack_deallocate);
23515
23516   if (has_children)
23517     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23518                                                   &info_ptr, comp_unit_die);
23519   cu->dies = comp_unit_die;
23520   /* comp_unit_die is not stored in die_hash, no need.  */
23521
23522   /* We try not to read any attributes in this function, because not
23523      all CUs needed for references have been loaded yet, and symbol
23524      table processing isn't initialized.  But we have to set the CU language,
23525      or we won't be able to build types correctly.
23526      Similarly, if we do not read the producer, we can not apply
23527      producer-specific interpretation.  */
23528   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23529 }
23530
23531 /* Read in a signatured type and build its CU and DIEs.
23532    If the type is a stub for the real type in a DWO file,
23533    read in the real type from the DWO file as well.  */
23534
23535 static void
23536 read_signatured_type (struct signatured_type *sig_type)
23537 {
23538   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23539
23540   gdb_assert (per_cu->is_debug_types);
23541   gdb_assert (per_cu->cu == NULL);
23542
23543   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23544                            read_signatured_type_reader, NULL);
23545   sig_type->per_cu.tu_read = 1;
23546 }
23547
23548 /* Decode simple location descriptions.
23549    Given a pointer to a dwarf block that defines a location, compute
23550    the location and return the value.
23551
23552    NOTE drow/2003-11-18: This function is called in two situations
23553    now: for the address of static or global variables (partial symbols
23554    only) and for offsets into structures which are expected to be
23555    (more or less) constant.  The partial symbol case should go away,
23556    and only the constant case should remain.  That will let this
23557    function complain more accurately.  A few special modes are allowed
23558    without complaint for global variables (for instance, global
23559    register values and thread-local values).
23560
23561    A location description containing no operations indicates that the
23562    object is optimized out.  The return value is 0 for that case.
23563    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23564    callers will only want a very basic result and this can become a
23565    complaint.
23566
23567    Note that stack[0] is unused except as a default error return.  */
23568
23569 static CORE_ADDR
23570 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23571 {
23572   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23573   size_t i;
23574   size_t size = blk->size;
23575   const gdb_byte *data = blk->data;
23576   CORE_ADDR stack[64];
23577   int stacki;
23578   unsigned int bytes_read, unsnd;
23579   gdb_byte op;
23580
23581   i = 0;
23582   stacki = 0;
23583   stack[stacki] = 0;
23584   stack[++stacki] = 0;
23585
23586   while (i < size)
23587     {
23588       op = data[i++];
23589       switch (op)
23590         {
23591         case DW_OP_lit0:
23592         case DW_OP_lit1:
23593         case DW_OP_lit2:
23594         case DW_OP_lit3:
23595         case DW_OP_lit4:
23596         case DW_OP_lit5:
23597         case DW_OP_lit6:
23598         case DW_OP_lit7:
23599         case DW_OP_lit8:
23600         case DW_OP_lit9:
23601         case DW_OP_lit10:
23602         case DW_OP_lit11:
23603         case DW_OP_lit12:
23604         case DW_OP_lit13:
23605         case DW_OP_lit14:
23606         case DW_OP_lit15:
23607         case DW_OP_lit16:
23608         case DW_OP_lit17:
23609         case DW_OP_lit18:
23610         case DW_OP_lit19:
23611         case DW_OP_lit20:
23612         case DW_OP_lit21:
23613         case DW_OP_lit22:
23614         case DW_OP_lit23:
23615         case DW_OP_lit24:
23616         case DW_OP_lit25:
23617         case DW_OP_lit26:
23618         case DW_OP_lit27:
23619         case DW_OP_lit28:
23620         case DW_OP_lit29:
23621         case DW_OP_lit30:
23622         case DW_OP_lit31:
23623           stack[++stacki] = op - DW_OP_lit0;
23624           break;
23625
23626         case DW_OP_reg0:
23627         case DW_OP_reg1:
23628         case DW_OP_reg2:
23629         case DW_OP_reg3:
23630         case DW_OP_reg4:
23631         case DW_OP_reg5:
23632         case DW_OP_reg6:
23633         case DW_OP_reg7:
23634         case DW_OP_reg8:
23635         case DW_OP_reg9:
23636         case DW_OP_reg10:
23637         case DW_OP_reg11:
23638         case DW_OP_reg12:
23639         case DW_OP_reg13:
23640         case DW_OP_reg14:
23641         case DW_OP_reg15:
23642         case DW_OP_reg16:
23643         case DW_OP_reg17:
23644         case DW_OP_reg18:
23645         case DW_OP_reg19:
23646         case DW_OP_reg20:
23647         case DW_OP_reg21:
23648         case DW_OP_reg22:
23649         case DW_OP_reg23:
23650         case DW_OP_reg24:
23651         case DW_OP_reg25:
23652         case DW_OP_reg26:
23653         case DW_OP_reg27:
23654         case DW_OP_reg28:
23655         case DW_OP_reg29:
23656         case DW_OP_reg30:
23657         case DW_OP_reg31:
23658           stack[++stacki] = op - DW_OP_reg0;
23659           if (i < size)
23660             dwarf2_complex_location_expr_complaint ();
23661           break;
23662
23663         case DW_OP_regx:
23664           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23665           i += bytes_read;
23666           stack[++stacki] = unsnd;
23667           if (i < size)
23668             dwarf2_complex_location_expr_complaint ();
23669           break;
23670
23671         case DW_OP_addr:
23672           stack[++stacki] = read_address (objfile->obfd, &data[i],
23673                                           cu, &bytes_read);
23674           i += bytes_read;
23675           break;
23676
23677         case DW_OP_const1u:
23678           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23679           i += 1;
23680           break;
23681
23682         case DW_OP_const1s:
23683           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23684           i += 1;
23685           break;
23686
23687         case DW_OP_const2u:
23688           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23689           i += 2;
23690           break;
23691
23692         case DW_OP_const2s:
23693           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23694           i += 2;
23695           break;
23696
23697         case DW_OP_const4u:
23698           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23699           i += 4;
23700           break;
23701
23702         case DW_OP_const4s:
23703           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23704           i += 4;
23705           break;
23706
23707         case DW_OP_const8u:
23708           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23709           i += 8;
23710           break;
23711
23712         case DW_OP_constu:
23713           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23714                                                   &bytes_read);
23715           i += bytes_read;
23716           break;
23717
23718         case DW_OP_consts:
23719           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23720           i += bytes_read;
23721           break;
23722
23723         case DW_OP_dup:
23724           stack[stacki + 1] = stack[stacki];
23725           stacki++;
23726           break;
23727
23728         case DW_OP_plus:
23729           stack[stacki - 1] += stack[stacki];
23730           stacki--;
23731           break;
23732
23733         case DW_OP_plus_uconst:
23734           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23735                                                  &bytes_read);
23736           i += bytes_read;
23737           break;
23738
23739         case DW_OP_minus:
23740           stack[stacki - 1] -= stack[stacki];
23741           stacki--;
23742           break;
23743
23744         case DW_OP_deref:
23745           /* If we're not the last op, then we definitely can't encode
23746              this using GDB's address_class enum.  This is valid for partial
23747              global symbols, although the variable's address will be bogus
23748              in the psymtab.  */
23749           if (i < size)
23750             dwarf2_complex_location_expr_complaint ();
23751           break;
23752
23753         case DW_OP_GNU_push_tls_address:
23754         case DW_OP_form_tls_address:
23755           /* The top of the stack has the offset from the beginning
23756              of the thread control block at which the variable is located.  */
23757           /* Nothing should follow this operator, so the top of stack would
23758              be returned.  */
23759           /* This is valid for partial global symbols, but the variable's
23760              address will be bogus in the psymtab.  Make it always at least
23761              non-zero to not look as a variable garbage collected by linker
23762              which have DW_OP_addr 0.  */
23763           if (i < size)
23764             dwarf2_complex_location_expr_complaint ();
23765           stack[stacki]++;
23766           break;
23767
23768         case DW_OP_GNU_uninit:
23769           break;
23770
23771         case DW_OP_GNU_addr_index:
23772         case DW_OP_GNU_const_index:
23773           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23774                                                          &bytes_read);
23775           i += bytes_read;
23776           break;
23777
23778         default:
23779           {
23780             const char *name = get_DW_OP_name (op);
23781
23782             if (name)
23783               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23784                          name);
23785             else
23786               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23787                          op);
23788           }
23789
23790           return (stack[stacki]);
23791         }
23792
23793       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23794          outside of the allocated space.  Also enforce minimum>0.  */
23795       if (stacki >= ARRAY_SIZE (stack) - 1)
23796         {
23797           complaint (&symfile_complaints,
23798                      _("location description stack overflow"));
23799           return 0;
23800         }
23801
23802       if (stacki <= 0)
23803         {
23804           complaint (&symfile_complaints,
23805                      _("location description stack underflow"));
23806           return 0;
23807         }
23808     }
23809   return (stack[stacki]);
23810 }
23811
23812 /* memory allocation interface */
23813
23814 static struct dwarf_block *
23815 dwarf_alloc_block (struct dwarf2_cu *cu)
23816 {
23817   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23818 }
23819
23820 static struct die_info *
23821 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23822 {
23823   struct die_info *die;
23824   size_t size = sizeof (struct die_info);
23825
23826   if (num_attrs > 1)
23827     size += (num_attrs - 1) * sizeof (struct attribute);
23828
23829   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23830   memset (die, 0, sizeof (struct die_info));
23831   return (die);
23832 }
23833
23834 \f
23835 /* Macro support.  */
23836
23837 /* Return file name relative to the compilation directory of file number I in
23838    *LH's file name table.  The result is allocated using xmalloc; the caller is
23839    responsible for freeing it.  */
23840
23841 static char *
23842 file_file_name (int file, struct line_header *lh)
23843 {
23844   /* Is the file number a valid index into the line header's file name
23845      table?  Remember that file numbers start with one, not zero.  */
23846   if (1 <= file && file <= lh->file_names.size ())
23847     {
23848       const file_entry &fe = lh->file_names[file - 1];
23849
23850       if (!IS_ABSOLUTE_PATH (fe.name))
23851         {
23852           const char *dir = fe.include_dir (lh);
23853           if (dir != NULL)
23854             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23855         }
23856       return xstrdup (fe.name);
23857     }
23858   else
23859     {
23860       /* The compiler produced a bogus file number.  We can at least
23861          record the macro definitions made in the file, even if we
23862          won't be able to find the file by name.  */
23863       char fake_name[80];
23864
23865       xsnprintf (fake_name, sizeof (fake_name),
23866                  "<bad macro file number %d>", file);
23867
23868       complaint (&symfile_complaints,
23869                  _("bad file number in macro information (%d)"),
23870                  file);
23871
23872       return xstrdup (fake_name);
23873     }
23874 }
23875
23876 /* Return the full name of file number I in *LH's file name table.
23877    Use COMP_DIR as the name of the current directory of the
23878    compilation.  The result is allocated using xmalloc; the caller is
23879    responsible for freeing it.  */
23880 static char *
23881 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23882 {
23883   /* Is the file number a valid index into the line header's file name
23884      table?  Remember that file numbers start with one, not zero.  */
23885   if (1 <= file && file <= lh->file_names.size ())
23886     {
23887       char *relative = file_file_name (file, lh);
23888
23889       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23890         return relative;
23891       return reconcat (relative, comp_dir, SLASH_STRING,
23892                        relative, (char *) NULL);
23893     }
23894   else
23895     return file_file_name (file, lh);
23896 }
23897
23898
23899 static struct macro_source_file *
23900 macro_start_file (int file, int line,
23901                   struct macro_source_file *current_file,
23902                   struct line_header *lh)
23903 {
23904   /* File name relative to the compilation directory of this source file.  */
23905   char *file_name = file_file_name (file, lh);
23906
23907   if (! current_file)
23908     {
23909       /* Note: We don't create a macro table for this compilation unit
23910          at all until we actually get a filename.  */
23911       struct macro_table *macro_table = get_macro_table ();
23912
23913       /* If we have no current file, then this must be the start_file
23914          directive for the compilation unit's main source file.  */
23915       current_file = macro_set_main (macro_table, file_name);
23916       macro_define_special (macro_table);
23917     }
23918   else
23919     current_file = macro_include (current_file, line, file_name);
23920
23921   xfree (file_name);
23922
23923   return current_file;
23924 }
23925
23926 static const char *
23927 consume_improper_spaces (const char *p, const char *body)
23928 {
23929   if (*p == ' ')
23930     {
23931       complaint (&symfile_complaints,
23932                  _("macro definition contains spaces "
23933                    "in formal argument list:\n`%s'"),
23934                  body);
23935
23936       while (*p == ' ')
23937         p++;
23938     }
23939
23940   return p;
23941 }
23942
23943
23944 static void
23945 parse_macro_definition (struct macro_source_file *file, int line,
23946                         const char *body)
23947 {
23948   const char *p;
23949
23950   /* The body string takes one of two forms.  For object-like macro
23951      definitions, it should be:
23952
23953         <macro name> " " <definition>
23954
23955      For function-like macro definitions, it should be:
23956
23957         <macro name> "() " <definition>
23958      or
23959         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23960
23961      Spaces may appear only where explicitly indicated, and in the
23962      <definition>.
23963
23964      The Dwarf 2 spec says that an object-like macro's name is always
23965      followed by a space, but versions of GCC around March 2002 omit
23966      the space when the macro's definition is the empty string.
23967
23968      The Dwarf 2 spec says that there should be no spaces between the
23969      formal arguments in a function-like macro's formal argument list,
23970      but versions of GCC around March 2002 include spaces after the
23971      commas.  */
23972
23973
23974   /* Find the extent of the macro name.  The macro name is terminated
23975      by either a space or null character (for an object-like macro) or
23976      an opening paren (for a function-like macro).  */
23977   for (p = body; *p; p++)
23978     if (*p == ' ' || *p == '(')
23979       break;
23980
23981   if (*p == ' ' || *p == '\0')
23982     {
23983       /* It's an object-like macro.  */
23984       int name_len = p - body;
23985       char *name = savestring (body, name_len);
23986       const char *replacement;
23987
23988       if (*p == ' ')
23989         replacement = body + name_len + 1;
23990       else
23991         {
23992           dwarf2_macro_malformed_definition_complaint (body);
23993           replacement = body + name_len;
23994         }
23995
23996       macro_define_object (file, line, name, replacement);
23997
23998       xfree (name);
23999     }
24000   else if (*p == '(')
24001     {
24002       /* It's a function-like macro.  */
24003       char *name = savestring (body, p - body);
24004       int argc = 0;
24005       int argv_size = 1;
24006       char **argv = XNEWVEC (char *, argv_size);
24007
24008       p++;
24009
24010       p = consume_improper_spaces (p, body);
24011
24012       /* Parse the formal argument list.  */
24013       while (*p && *p != ')')
24014         {
24015           /* Find the extent of the current argument name.  */
24016           const char *arg_start = p;
24017
24018           while (*p && *p != ',' && *p != ')' && *p != ' ')
24019             p++;
24020
24021           if (! *p || p == arg_start)
24022             dwarf2_macro_malformed_definition_complaint (body);
24023           else
24024             {
24025               /* Make sure argv has room for the new argument.  */
24026               if (argc >= argv_size)
24027                 {
24028                   argv_size *= 2;
24029                   argv = XRESIZEVEC (char *, argv, argv_size);
24030                 }
24031
24032               argv[argc++] = savestring (arg_start, p - arg_start);
24033             }
24034
24035           p = consume_improper_spaces (p, body);
24036
24037           /* Consume the comma, if present.  */
24038           if (*p == ',')
24039             {
24040               p++;
24041
24042               p = consume_improper_spaces (p, body);
24043             }
24044         }
24045
24046       if (*p == ')')
24047         {
24048           p++;
24049
24050           if (*p == ' ')
24051             /* Perfectly formed definition, no complaints.  */
24052             macro_define_function (file, line, name,
24053                                    argc, (const char **) argv,
24054                                    p + 1);
24055           else if (*p == '\0')
24056             {
24057               /* Complain, but do define it.  */
24058               dwarf2_macro_malformed_definition_complaint (body);
24059               macro_define_function (file, line, name,
24060                                      argc, (const char **) argv,
24061                                      p);
24062             }
24063           else
24064             /* Just complain.  */
24065             dwarf2_macro_malformed_definition_complaint (body);
24066         }
24067       else
24068         /* Just complain.  */
24069         dwarf2_macro_malformed_definition_complaint (body);
24070
24071       xfree (name);
24072       {
24073         int i;
24074
24075         for (i = 0; i < argc; i++)
24076           xfree (argv[i]);
24077       }
24078       xfree (argv);
24079     }
24080   else
24081     dwarf2_macro_malformed_definition_complaint (body);
24082 }
24083
24084 /* Skip some bytes from BYTES according to the form given in FORM.
24085    Returns the new pointer.  */
24086
24087 static const gdb_byte *
24088 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24089                  enum dwarf_form form,
24090                  unsigned int offset_size,
24091                  struct dwarf2_section_info *section)
24092 {
24093   unsigned int bytes_read;
24094
24095   switch (form)
24096     {
24097     case DW_FORM_data1:
24098     case DW_FORM_flag:
24099       ++bytes;
24100       break;
24101
24102     case DW_FORM_data2:
24103       bytes += 2;
24104       break;
24105
24106     case DW_FORM_data4:
24107       bytes += 4;
24108       break;
24109
24110     case DW_FORM_data8:
24111       bytes += 8;
24112       break;
24113
24114     case DW_FORM_data16:
24115       bytes += 16;
24116       break;
24117
24118     case DW_FORM_string:
24119       read_direct_string (abfd, bytes, &bytes_read);
24120       bytes += bytes_read;
24121       break;
24122
24123     case DW_FORM_sec_offset:
24124     case DW_FORM_strp:
24125     case DW_FORM_GNU_strp_alt:
24126       bytes += offset_size;
24127       break;
24128
24129     case DW_FORM_block:
24130       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24131       bytes += bytes_read;
24132       break;
24133
24134     case DW_FORM_block1:
24135       bytes += 1 + read_1_byte (abfd, bytes);
24136       break;
24137     case DW_FORM_block2:
24138       bytes += 2 + read_2_bytes (abfd, bytes);
24139       break;
24140     case DW_FORM_block4:
24141       bytes += 4 + read_4_bytes (abfd, bytes);
24142       break;
24143
24144     case DW_FORM_sdata:
24145     case DW_FORM_udata:
24146     case DW_FORM_GNU_addr_index:
24147     case DW_FORM_GNU_str_index:
24148       bytes = gdb_skip_leb128 (bytes, buffer_end);
24149       if (bytes == NULL)
24150         {
24151           dwarf2_section_buffer_overflow_complaint (section);
24152           return NULL;
24153         }
24154       break;
24155
24156     case DW_FORM_implicit_const:
24157       break;
24158
24159     default:
24160       {
24161         complaint (&symfile_complaints,
24162                    _("invalid form 0x%x in `%s'"),
24163                    form, get_section_name (section));
24164         return NULL;
24165       }
24166     }
24167
24168   return bytes;
24169 }
24170
24171 /* A helper for dwarf_decode_macros that handles skipping an unknown
24172    opcode.  Returns an updated pointer to the macro data buffer; or,
24173    on error, issues a complaint and returns NULL.  */
24174
24175 static const gdb_byte *
24176 skip_unknown_opcode (unsigned int opcode,
24177                      const gdb_byte **opcode_definitions,
24178                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24179                      bfd *abfd,
24180                      unsigned int offset_size,
24181                      struct dwarf2_section_info *section)
24182 {
24183   unsigned int bytes_read, i;
24184   unsigned long arg;
24185   const gdb_byte *defn;
24186
24187   if (opcode_definitions[opcode] == NULL)
24188     {
24189       complaint (&symfile_complaints,
24190                  _("unrecognized DW_MACFINO opcode 0x%x"),
24191                  opcode);
24192       return NULL;
24193     }
24194
24195   defn = opcode_definitions[opcode];
24196   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24197   defn += bytes_read;
24198
24199   for (i = 0; i < arg; ++i)
24200     {
24201       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24202                                  (enum dwarf_form) defn[i], offset_size,
24203                                  section);
24204       if (mac_ptr == NULL)
24205         {
24206           /* skip_form_bytes already issued the complaint.  */
24207           return NULL;
24208         }
24209     }
24210
24211   return mac_ptr;
24212 }
24213
24214 /* A helper function which parses the header of a macro section.
24215    If the macro section is the extended (for now called "GNU") type,
24216    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24217    the header, or issues a complaint and returns NULL on error.  */
24218
24219 static const gdb_byte *
24220 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24221                           bfd *abfd,
24222                           const gdb_byte *mac_ptr,
24223                           unsigned int *offset_size,
24224                           int section_is_gnu)
24225 {
24226   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24227
24228   if (section_is_gnu)
24229     {
24230       unsigned int version, flags;
24231
24232       version = read_2_bytes (abfd, mac_ptr);
24233       if (version != 4 && version != 5)
24234         {
24235           complaint (&symfile_complaints,
24236                      _("unrecognized version `%d' in .debug_macro section"),
24237                      version);
24238           return NULL;
24239         }
24240       mac_ptr += 2;
24241
24242       flags = read_1_byte (abfd, mac_ptr);
24243       ++mac_ptr;
24244       *offset_size = (flags & 1) ? 8 : 4;
24245
24246       if ((flags & 2) != 0)
24247         /* We don't need the line table offset.  */
24248         mac_ptr += *offset_size;
24249
24250       /* Vendor opcode descriptions.  */
24251       if ((flags & 4) != 0)
24252         {
24253           unsigned int i, count;
24254
24255           count = read_1_byte (abfd, mac_ptr);
24256           ++mac_ptr;
24257           for (i = 0; i < count; ++i)
24258             {
24259               unsigned int opcode, bytes_read;
24260               unsigned long arg;
24261
24262               opcode = read_1_byte (abfd, mac_ptr);
24263               ++mac_ptr;
24264               opcode_definitions[opcode] = mac_ptr;
24265               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24266               mac_ptr += bytes_read;
24267               mac_ptr += arg;
24268             }
24269         }
24270     }
24271
24272   return mac_ptr;
24273 }
24274
24275 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24276    including DW_MACRO_import.  */
24277
24278 static void
24279 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24280                           bfd *abfd,
24281                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24282                           struct macro_source_file *current_file,
24283                           struct line_header *lh,
24284                           struct dwarf2_section_info *section,
24285                           int section_is_gnu, int section_is_dwz,
24286                           unsigned int offset_size,
24287                           htab_t include_hash)
24288 {
24289   struct objfile *objfile = dwarf2_per_objfile->objfile;
24290   enum dwarf_macro_record_type macinfo_type;
24291   int at_commandline;
24292   const gdb_byte *opcode_definitions[256];
24293
24294   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24295                                       &offset_size, section_is_gnu);
24296   if (mac_ptr == NULL)
24297     {
24298       /* We already issued a complaint.  */
24299       return;
24300     }
24301
24302   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24303      GDB is still reading the definitions from command line.  First
24304      DW_MACINFO_start_file will need to be ignored as it was already executed
24305      to create CURRENT_FILE for the main source holding also the command line
24306      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24307      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24308
24309   at_commandline = 1;
24310
24311   do
24312     {
24313       /* Do we at least have room for a macinfo type byte?  */
24314       if (mac_ptr >= mac_end)
24315         {
24316           dwarf2_section_buffer_overflow_complaint (section);
24317           break;
24318         }
24319
24320       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24321       mac_ptr++;
24322
24323       /* Note that we rely on the fact that the corresponding GNU and
24324          DWARF constants are the same.  */
24325       DIAGNOSTIC_PUSH
24326       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24327       switch (macinfo_type)
24328         {
24329           /* A zero macinfo type indicates the end of the macro
24330              information.  */
24331         case 0:
24332           break;
24333
24334         case DW_MACRO_define:
24335         case DW_MACRO_undef:
24336         case DW_MACRO_define_strp:
24337         case DW_MACRO_undef_strp:
24338         case DW_MACRO_define_sup:
24339         case DW_MACRO_undef_sup:
24340           {
24341             unsigned int bytes_read;
24342             int line;
24343             const char *body;
24344             int is_define;
24345
24346             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24347             mac_ptr += bytes_read;
24348
24349             if (macinfo_type == DW_MACRO_define
24350                 || macinfo_type == DW_MACRO_undef)
24351               {
24352                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24353                 mac_ptr += bytes_read;
24354               }
24355             else
24356               {
24357                 LONGEST str_offset;
24358
24359                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24360                 mac_ptr += offset_size;
24361
24362                 if (macinfo_type == DW_MACRO_define_sup
24363                     || macinfo_type == DW_MACRO_undef_sup
24364                     || section_is_dwz)
24365                   {
24366                     struct dwz_file *dwz
24367                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24368
24369                     body = read_indirect_string_from_dwz (objfile,
24370                                                           dwz, str_offset);
24371                   }
24372                 else
24373                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24374                                                          abfd, str_offset);
24375               }
24376
24377             is_define = (macinfo_type == DW_MACRO_define
24378                          || macinfo_type == DW_MACRO_define_strp
24379                          || macinfo_type == DW_MACRO_define_sup);
24380             if (! current_file)
24381               {
24382                 /* DWARF violation as no main source is present.  */
24383                 complaint (&symfile_complaints,
24384                            _("debug info with no main source gives macro %s "
24385                              "on line %d: %s"),
24386                            is_define ? _("definition") : _("undefinition"),
24387                            line, body);
24388                 break;
24389               }
24390             if ((line == 0 && !at_commandline)
24391                 || (line != 0 && at_commandline))
24392               complaint (&symfile_complaints,
24393                          _("debug info gives %s macro %s with %s line %d: %s"),
24394                          at_commandline ? _("command-line") : _("in-file"),
24395                          is_define ? _("definition") : _("undefinition"),
24396                          line == 0 ? _("zero") : _("non-zero"), line, body);
24397
24398             if (is_define)
24399               parse_macro_definition (current_file, line, body);
24400             else
24401               {
24402                 gdb_assert (macinfo_type == DW_MACRO_undef
24403                             || macinfo_type == DW_MACRO_undef_strp
24404                             || macinfo_type == DW_MACRO_undef_sup);
24405                 macro_undef (current_file, line, body);
24406               }
24407           }
24408           break;
24409
24410         case DW_MACRO_start_file:
24411           {
24412             unsigned int bytes_read;
24413             int line, file;
24414
24415             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24416             mac_ptr += bytes_read;
24417             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24418             mac_ptr += bytes_read;
24419
24420             if ((line == 0 && !at_commandline)
24421                 || (line != 0 && at_commandline))
24422               complaint (&symfile_complaints,
24423                          _("debug info gives source %d included "
24424                            "from %s at %s line %d"),
24425                          file, at_commandline ? _("command-line") : _("file"),
24426                          line == 0 ? _("zero") : _("non-zero"), line);
24427
24428             if (at_commandline)
24429               {
24430                 /* This DW_MACRO_start_file was executed in the
24431                    pass one.  */
24432                 at_commandline = 0;
24433               }
24434             else
24435               current_file = macro_start_file (file, line, current_file, lh);
24436           }
24437           break;
24438
24439         case DW_MACRO_end_file:
24440           if (! current_file)
24441             complaint (&symfile_complaints,
24442                        _("macro debug info has an unmatched "
24443                          "`close_file' directive"));
24444           else
24445             {
24446               current_file = current_file->included_by;
24447               if (! current_file)
24448                 {
24449                   enum dwarf_macro_record_type next_type;
24450
24451                   /* GCC circa March 2002 doesn't produce the zero
24452                      type byte marking the end of the compilation
24453                      unit.  Complain if it's not there, but exit no
24454                      matter what.  */
24455
24456                   /* Do we at least have room for a macinfo type byte?  */
24457                   if (mac_ptr >= mac_end)
24458                     {
24459                       dwarf2_section_buffer_overflow_complaint (section);
24460                       return;
24461                     }
24462
24463                   /* We don't increment mac_ptr here, so this is just
24464                      a look-ahead.  */
24465                   next_type
24466                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24467                                                                   mac_ptr);
24468                   if (next_type != 0)
24469                     complaint (&symfile_complaints,
24470                                _("no terminating 0-type entry for "
24471                                  "macros in `.debug_macinfo' section"));
24472
24473                   return;
24474                 }
24475             }
24476           break;
24477
24478         case DW_MACRO_import:
24479         case DW_MACRO_import_sup:
24480           {
24481             LONGEST offset;
24482             void **slot;
24483             bfd *include_bfd = abfd;
24484             struct dwarf2_section_info *include_section = section;
24485             const gdb_byte *include_mac_end = mac_end;
24486             int is_dwz = section_is_dwz;
24487             const gdb_byte *new_mac_ptr;
24488
24489             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24490             mac_ptr += offset_size;
24491
24492             if (macinfo_type == DW_MACRO_import_sup)
24493               {
24494                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24495
24496                 dwarf2_read_section (objfile, &dwz->macro);
24497
24498                 include_section = &dwz->macro;
24499                 include_bfd = get_section_bfd_owner (include_section);
24500                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24501                 is_dwz = 1;
24502               }
24503
24504             new_mac_ptr = include_section->buffer + offset;
24505             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24506
24507             if (*slot != NULL)
24508               {
24509                 /* This has actually happened; see
24510                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24511                 complaint (&symfile_complaints,
24512                            _("recursive DW_MACRO_import in "
24513                              ".debug_macro section"));
24514               }
24515             else
24516               {
24517                 *slot = (void *) new_mac_ptr;
24518
24519                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24520                                           include_bfd, new_mac_ptr,
24521                                           include_mac_end, current_file, lh,
24522                                           section, section_is_gnu, is_dwz,
24523                                           offset_size, include_hash);
24524
24525                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24526               }
24527           }
24528           break;
24529
24530         case DW_MACINFO_vendor_ext:
24531           if (!section_is_gnu)
24532             {
24533               unsigned int bytes_read;
24534
24535               /* This reads the constant, but since we don't recognize
24536                  any vendor extensions, we ignore it.  */
24537               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24538               mac_ptr += bytes_read;
24539               read_direct_string (abfd, mac_ptr, &bytes_read);
24540               mac_ptr += bytes_read;
24541
24542               /* We don't recognize any vendor extensions.  */
24543               break;
24544             }
24545           /* FALLTHROUGH */
24546
24547         default:
24548           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24549                                          mac_ptr, mac_end, abfd, offset_size,
24550                                          section);
24551           if (mac_ptr == NULL)
24552             return;
24553           break;
24554         }
24555       DIAGNOSTIC_POP
24556     } while (macinfo_type != 0);
24557 }
24558
24559 static void
24560 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24561                      int section_is_gnu)
24562 {
24563   struct dwarf2_per_objfile *dwarf2_per_objfile
24564     = cu->per_cu->dwarf2_per_objfile;
24565   struct objfile *objfile = dwarf2_per_objfile->objfile;
24566   struct line_header *lh = cu->line_header;
24567   bfd *abfd;
24568   const gdb_byte *mac_ptr, *mac_end;
24569   struct macro_source_file *current_file = 0;
24570   enum dwarf_macro_record_type macinfo_type;
24571   unsigned int offset_size = cu->header.offset_size;
24572   const gdb_byte *opcode_definitions[256];
24573   void **slot;
24574   struct dwarf2_section_info *section;
24575   const char *section_name;
24576
24577   if (cu->dwo_unit != NULL)
24578     {
24579       if (section_is_gnu)
24580         {
24581           section = &cu->dwo_unit->dwo_file->sections.macro;
24582           section_name = ".debug_macro.dwo";
24583         }
24584       else
24585         {
24586           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24587           section_name = ".debug_macinfo.dwo";
24588         }
24589     }
24590   else
24591     {
24592       if (section_is_gnu)
24593         {
24594           section = &dwarf2_per_objfile->macro;
24595           section_name = ".debug_macro";
24596         }
24597       else
24598         {
24599           section = &dwarf2_per_objfile->macinfo;
24600           section_name = ".debug_macinfo";
24601         }
24602     }
24603
24604   dwarf2_read_section (objfile, section);
24605   if (section->buffer == NULL)
24606     {
24607       complaint (&symfile_complaints, _("missing %s section"), section_name);
24608       return;
24609     }
24610   abfd = get_section_bfd_owner (section);
24611
24612   /* First pass: Find the name of the base filename.
24613      This filename is needed in order to process all macros whose definition
24614      (or undefinition) comes from the command line.  These macros are defined
24615      before the first DW_MACINFO_start_file entry, and yet still need to be
24616      associated to the base file.
24617
24618      To determine the base file name, we scan the macro definitions until we
24619      reach the first DW_MACINFO_start_file entry.  We then initialize
24620      CURRENT_FILE accordingly so that any macro definition found before the
24621      first DW_MACINFO_start_file can still be associated to the base file.  */
24622
24623   mac_ptr = section->buffer + offset;
24624   mac_end = section->buffer + section->size;
24625
24626   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24627                                       &offset_size, section_is_gnu);
24628   if (mac_ptr == NULL)
24629     {
24630       /* We already issued a complaint.  */
24631       return;
24632     }
24633
24634   do
24635     {
24636       /* Do we at least have room for a macinfo type byte?  */
24637       if (mac_ptr >= mac_end)
24638         {
24639           /* Complaint is printed during the second pass as GDB will probably
24640              stop the first pass earlier upon finding
24641              DW_MACINFO_start_file.  */
24642           break;
24643         }
24644
24645       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24646       mac_ptr++;
24647
24648       /* Note that we rely on the fact that the corresponding GNU and
24649          DWARF constants are the same.  */
24650       DIAGNOSTIC_PUSH
24651       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24652       switch (macinfo_type)
24653         {
24654           /* A zero macinfo type indicates the end of the macro
24655              information.  */
24656         case 0:
24657           break;
24658
24659         case DW_MACRO_define:
24660         case DW_MACRO_undef:
24661           /* Only skip the data by MAC_PTR.  */
24662           {
24663             unsigned int bytes_read;
24664
24665             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24666             mac_ptr += bytes_read;
24667             read_direct_string (abfd, mac_ptr, &bytes_read);
24668             mac_ptr += bytes_read;
24669           }
24670           break;
24671
24672         case DW_MACRO_start_file:
24673           {
24674             unsigned int bytes_read;
24675             int line, file;
24676
24677             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24678             mac_ptr += bytes_read;
24679             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24680             mac_ptr += bytes_read;
24681
24682             current_file = macro_start_file (file, line, current_file, lh);
24683           }
24684           break;
24685
24686         case DW_MACRO_end_file:
24687           /* No data to skip by MAC_PTR.  */
24688           break;
24689
24690         case DW_MACRO_define_strp:
24691         case DW_MACRO_undef_strp:
24692         case DW_MACRO_define_sup:
24693         case DW_MACRO_undef_sup:
24694           {
24695             unsigned int bytes_read;
24696
24697             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24698             mac_ptr += bytes_read;
24699             mac_ptr += offset_size;
24700           }
24701           break;
24702
24703         case DW_MACRO_import:
24704         case DW_MACRO_import_sup:
24705           /* Note that, according to the spec, a transparent include
24706              chain cannot call DW_MACRO_start_file.  So, we can just
24707              skip this opcode.  */
24708           mac_ptr += offset_size;
24709           break;
24710
24711         case DW_MACINFO_vendor_ext:
24712           /* Only skip the data by MAC_PTR.  */
24713           if (!section_is_gnu)
24714             {
24715               unsigned int bytes_read;
24716
24717               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24718               mac_ptr += bytes_read;
24719               read_direct_string (abfd, mac_ptr, &bytes_read);
24720               mac_ptr += bytes_read;
24721             }
24722           /* FALLTHROUGH */
24723
24724         default:
24725           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24726                                          mac_ptr, mac_end, abfd, offset_size,
24727                                          section);
24728           if (mac_ptr == NULL)
24729             return;
24730           break;
24731         }
24732       DIAGNOSTIC_POP
24733     } while (macinfo_type != 0 && current_file == NULL);
24734
24735   /* Second pass: Process all entries.
24736
24737      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24738      command-line macro definitions/undefinitions.  This flag is unset when we
24739      reach the first DW_MACINFO_start_file entry.  */
24740
24741   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24742                                            htab_eq_pointer,
24743                                            NULL, xcalloc, xfree));
24744   mac_ptr = section->buffer + offset;
24745   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24746   *slot = (void *) mac_ptr;
24747   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24748                             abfd, mac_ptr, mac_end,
24749                             current_file, lh, section,
24750                             section_is_gnu, 0, offset_size,
24751                             include_hash.get ());
24752 }
24753
24754 /* Check if the attribute's form is a DW_FORM_block*
24755    if so return true else false.  */
24756
24757 static int
24758 attr_form_is_block (const struct attribute *attr)
24759 {
24760   return (attr == NULL ? 0 :
24761       attr->form == DW_FORM_block1
24762       || attr->form == DW_FORM_block2
24763       || attr->form == DW_FORM_block4
24764       || attr->form == DW_FORM_block
24765       || attr->form == DW_FORM_exprloc);
24766 }
24767
24768 /* Return non-zero if ATTR's value is a section offset --- classes
24769    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24770    You may use DW_UNSND (attr) to retrieve such offsets.
24771
24772    Section 7.5.4, "Attribute Encodings", explains that no attribute
24773    may have a value that belongs to more than one of these classes; it
24774    would be ambiguous if we did, because we use the same forms for all
24775    of them.  */
24776
24777 static int
24778 attr_form_is_section_offset (const struct attribute *attr)
24779 {
24780   return (attr->form == DW_FORM_data4
24781           || attr->form == DW_FORM_data8
24782           || attr->form == DW_FORM_sec_offset);
24783 }
24784
24785 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24786    zero otherwise.  When this function returns true, you can apply
24787    dwarf2_get_attr_constant_value to it.
24788
24789    However, note that for some attributes you must check
24790    attr_form_is_section_offset before using this test.  DW_FORM_data4
24791    and DW_FORM_data8 are members of both the constant class, and of
24792    the classes that contain offsets into other debug sections
24793    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24794    that, if an attribute's can be either a constant or one of the
24795    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24796    taken as section offsets, not constants.
24797
24798    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24799    cannot handle that.  */
24800
24801 static int
24802 attr_form_is_constant (const struct attribute *attr)
24803 {
24804   switch (attr->form)
24805     {
24806     case DW_FORM_sdata:
24807     case DW_FORM_udata:
24808     case DW_FORM_data1:
24809     case DW_FORM_data2:
24810     case DW_FORM_data4:
24811     case DW_FORM_data8:
24812     case DW_FORM_implicit_const:
24813       return 1;
24814     default:
24815       return 0;
24816     }
24817 }
24818
24819
24820 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24821    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24822
24823 static int
24824 attr_form_is_ref (const struct attribute *attr)
24825 {
24826   switch (attr->form)
24827     {
24828     case DW_FORM_ref_addr:
24829     case DW_FORM_ref1:
24830     case DW_FORM_ref2:
24831     case DW_FORM_ref4:
24832     case DW_FORM_ref8:
24833     case DW_FORM_ref_udata:
24834     case DW_FORM_GNU_ref_alt:
24835       return 1;
24836     default:
24837       return 0;
24838     }
24839 }
24840
24841 /* Return the .debug_loc section to use for CU.
24842    For DWO files use .debug_loc.dwo.  */
24843
24844 static struct dwarf2_section_info *
24845 cu_debug_loc_section (struct dwarf2_cu *cu)
24846 {
24847   struct dwarf2_per_objfile *dwarf2_per_objfile
24848     = cu->per_cu->dwarf2_per_objfile;
24849
24850   if (cu->dwo_unit)
24851     {
24852       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24853       
24854       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24855     }
24856   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24857                                   : &dwarf2_per_objfile->loc);
24858 }
24859
24860 /* A helper function that fills in a dwarf2_loclist_baton.  */
24861
24862 static void
24863 fill_in_loclist_baton (struct dwarf2_cu *cu,
24864                        struct dwarf2_loclist_baton *baton,
24865                        const struct attribute *attr)
24866 {
24867   struct dwarf2_per_objfile *dwarf2_per_objfile
24868     = cu->per_cu->dwarf2_per_objfile;
24869   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24870
24871   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24872
24873   baton->per_cu = cu->per_cu;
24874   gdb_assert (baton->per_cu);
24875   /* We don't know how long the location list is, but make sure we
24876      don't run off the edge of the section.  */
24877   baton->size = section->size - DW_UNSND (attr);
24878   baton->data = section->buffer + DW_UNSND (attr);
24879   baton->base_address = cu->base_address;
24880   baton->from_dwo = cu->dwo_unit != NULL;
24881 }
24882
24883 static void
24884 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24885                              struct dwarf2_cu *cu, int is_block)
24886 {
24887   struct dwarf2_per_objfile *dwarf2_per_objfile
24888     = cu->per_cu->dwarf2_per_objfile;
24889   struct objfile *objfile = dwarf2_per_objfile->objfile;
24890   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24891
24892   if (attr_form_is_section_offset (attr)
24893       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24894          the section.  If so, fall through to the complaint in the
24895          other branch.  */
24896       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24897     {
24898       struct dwarf2_loclist_baton *baton;
24899
24900       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24901
24902       fill_in_loclist_baton (cu, baton, attr);
24903
24904       if (cu->base_known == 0)
24905         complaint (&symfile_complaints,
24906                    _("Location list used without "
24907                      "specifying the CU base address."));
24908
24909       SYMBOL_ACLASS_INDEX (sym) = (is_block
24910                                    ? dwarf2_loclist_block_index
24911                                    : dwarf2_loclist_index);
24912       SYMBOL_LOCATION_BATON (sym) = baton;
24913     }
24914   else
24915     {
24916       struct dwarf2_locexpr_baton *baton;
24917
24918       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24919       baton->per_cu = cu->per_cu;
24920       gdb_assert (baton->per_cu);
24921
24922       if (attr_form_is_block (attr))
24923         {
24924           /* Note that we're just copying the block's data pointer
24925              here, not the actual data.  We're still pointing into the
24926              info_buffer for SYM's objfile; right now we never release
24927              that buffer, but when we do clean up properly this may
24928              need to change.  */
24929           baton->size = DW_BLOCK (attr)->size;
24930           baton->data = DW_BLOCK (attr)->data;
24931         }
24932       else
24933         {
24934           dwarf2_invalid_attrib_class_complaint ("location description",
24935                                                  SYMBOL_NATURAL_NAME (sym));
24936           baton->size = 0;
24937         }
24938
24939       SYMBOL_ACLASS_INDEX (sym) = (is_block
24940                                    ? dwarf2_locexpr_block_index
24941                                    : dwarf2_locexpr_index);
24942       SYMBOL_LOCATION_BATON (sym) = baton;
24943     }
24944 }
24945
24946 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24947    came from a separate debuginfo file, then the master objfile is
24948    returned.  */
24949
24950 struct objfile *
24951 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24952 {
24953   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24954
24955   /* Return the master objfile, so that we can report and look up the
24956      correct file containing this variable.  */
24957   if (objfile->separate_debug_objfile_backlink)
24958     objfile = objfile->separate_debug_objfile_backlink;
24959
24960   return objfile;
24961 }
24962
24963 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24964    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24965    CU_HEADERP first.  */
24966
24967 static const struct comp_unit_head *
24968 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24969                        struct dwarf2_per_cu_data *per_cu)
24970 {
24971   const gdb_byte *info_ptr;
24972
24973   if (per_cu->cu)
24974     return &per_cu->cu->header;
24975
24976   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24977
24978   memset (cu_headerp, 0, sizeof (*cu_headerp));
24979   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24980                        rcuh_kind::COMPILE);
24981
24982   return cu_headerp;
24983 }
24984
24985 /* Return the address size given in the compilation unit header for CU.  */
24986
24987 int
24988 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24989 {
24990   struct comp_unit_head cu_header_local;
24991   const struct comp_unit_head *cu_headerp;
24992
24993   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24994
24995   return cu_headerp->addr_size;
24996 }
24997
24998 /* Return the offset size given in the compilation unit header for CU.  */
24999
25000 int
25001 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25002 {
25003   struct comp_unit_head cu_header_local;
25004   const struct comp_unit_head *cu_headerp;
25005
25006   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25007
25008   return cu_headerp->offset_size;
25009 }
25010
25011 /* See its dwarf2loc.h declaration.  */
25012
25013 int
25014 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25015 {
25016   struct comp_unit_head cu_header_local;
25017   const struct comp_unit_head *cu_headerp;
25018
25019   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25020
25021   if (cu_headerp->version == 2)
25022     return cu_headerp->addr_size;
25023   else
25024     return cu_headerp->offset_size;
25025 }
25026
25027 /* Return the text offset of the CU.  The returned offset comes from
25028    this CU's objfile.  If this objfile came from a separate debuginfo
25029    file, then the offset may be different from the corresponding
25030    offset in the parent objfile.  */
25031
25032 CORE_ADDR
25033 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25034 {
25035   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25036
25037   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25038 }
25039
25040 /* Return DWARF version number of PER_CU.  */
25041
25042 short
25043 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25044 {
25045   return per_cu->dwarf_version;
25046 }
25047
25048 /* Locate the .debug_info compilation unit from CU's objfile which contains
25049    the DIE at OFFSET.  Raises an error on failure.  */
25050
25051 static struct dwarf2_per_cu_data *
25052 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25053                                   unsigned int offset_in_dwz,
25054                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25055 {
25056   struct dwarf2_per_cu_data *this_cu;
25057   int low, high;
25058   const sect_offset *cu_off;
25059
25060   low = 0;
25061   high = dwarf2_per_objfile->n_comp_units - 1;
25062   while (high > low)
25063     {
25064       struct dwarf2_per_cu_data *mid_cu;
25065       int mid = low + (high - low) / 2;
25066
25067       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25068       cu_off = &mid_cu->sect_off;
25069       if (mid_cu->is_dwz > offset_in_dwz
25070           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25071         high = mid;
25072       else
25073         low = mid + 1;
25074     }
25075   gdb_assert (low == high);
25076   this_cu = dwarf2_per_objfile->all_comp_units[low];
25077   cu_off = &this_cu->sect_off;
25078   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25079     {
25080       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25081         error (_("Dwarf Error: could not find partial DIE containing "
25082                "offset %s [in module %s]"),
25083                sect_offset_str (sect_off),
25084                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25085
25086       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25087                   <= sect_off);
25088       return dwarf2_per_objfile->all_comp_units[low-1];
25089     }
25090   else
25091     {
25092       this_cu = dwarf2_per_objfile->all_comp_units[low];
25093       if (low == dwarf2_per_objfile->n_comp_units - 1
25094           && sect_off >= this_cu->sect_off + this_cu->length)
25095         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25096       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25097       return this_cu;
25098     }
25099 }
25100
25101 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25102
25103 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25104   : per_cu (per_cu_),
25105     mark (0),
25106     has_loclist (0),
25107     checked_producer (0),
25108     producer_is_gxx_lt_4_6 (0),
25109     producer_is_gcc_lt_4_3 (0),
25110     producer_is_icc_lt_14 (0),
25111     processing_has_namespace_info (0)
25112 {
25113   per_cu->cu = this;
25114 }
25115
25116 /* Destroy a dwarf2_cu.  */
25117
25118 dwarf2_cu::~dwarf2_cu ()
25119 {
25120   per_cu->cu = NULL;
25121 }
25122
25123 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25124
25125 static void
25126 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25127                        enum language pretend_language)
25128 {
25129   struct attribute *attr;
25130
25131   /* Set the language we're debugging.  */
25132   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25133   if (attr)
25134     set_cu_language (DW_UNSND (attr), cu);
25135   else
25136     {
25137       cu->language = pretend_language;
25138       cu->language_defn = language_def (cu->language);
25139     }
25140
25141   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25142 }
25143
25144 /* Free all cached compilation units.  */
25145
25146 static void
25147 free_cached_comp_units (void *data)
25148 {
25149   struct dwarf2_per_objfile *dwarf2_per_objfile
25150     = (struct dwarf2_per_objfile *) data;
25151
25152   dwarf2_per_objfile->free_cached_comp_units ();
25153 }
25154
25155 /* Increase the age counter on each cached compilation unit, and free
25156    any that are too old.  */
25157
25158 static void
25159 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25160 {
25161   struct dwarf2_per_cu_data *per_cu, **last_chain;
25162
25163   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25164   per_cu = dwarf2_per_objfile->read_in_chain;
25165   while (per_cu != NULL)
25166     {
25167       per_cu->cu->last_used ++;
25168       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25169         dwarf2_mark (per_cu->cu);
25170       per_cu = per_cu->cu->read_in_chain;
25171     }
25172
25173   per_cu = dwarf2_per_objfile->read_in_chain;
25174   last_chain = &dwarf2_per_objfile->read_in_chain;
25175   while (per_cu != NULL)
25176     {
25177       struct dwarf2_per_cu_data *next_cu;
25178
25179       next_cu = per_cu->cu->read_in_chain;
25180
25181       if (!per_cu->cu->mark)
25182         {
25183           delete per_cu->cu;
25184           *last_chain = next_cu;
25185         }
25186       else
25187         last_chain = &per_cu->cu->read_in_chain;
25188
25189       per_cu = next_cu;
25190     }
25191 }
25192
25193 /* Remove a single compilation unit from the cache.  */
25194
25195 static void
25196 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25197 {
25198   struct dwarf2_per_cu_data *per_cu, **last_chain;
25199   struct dwarf2_per_objfile *dwarf2_per_objfile
25200     = target_per_cu->dwarf2_per_objfile;
25201
25202   per_cu = dwarf2_per_objfile->read_in_chain;
25203   last_chain = &dwarf2_per_objfile->read_in_chain;
25204   while (per_cu != NULL)
25205     {
25206       struct dwarf2_per_cu_data *next_cu;
25207
25208       next_cu = per_cu->cu->read_in_chain;
25209
25210       if (per_cu == target_per_cu)
25211         {
25212           delete per_cu->cu;
25213           per_cu->cu = NULL;
25214           *last_chain = next_cu;
25215           break;
25216         }
25217       else
25218         last_chain = &per_cu->cu->read_in_chain;
25219
25220       per_cu = next_cu;
25221     }
25222 }
25223
25224 /* Release all extra memory associated with OBJFILE.  */
25225
25226 void
25227 dwarf2_free_objfile (struct objfile *objfile)
25228 {
25229   struct dwarf2_per_objfile *dwarf2_per_objfile
25230     = get_dwarf2_per_objfile (objfile);
25231
25232   delete dwarf2_per_objfile;
25233 }
25234
25235 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25236    We store these in a hash table separate from the DIEs, and preserve them
25237    when the DIEs are flushed out of cache.
25238
25239    The CU "per_cu" pointer is needed because offset alone is not enough to
25240    uniquely identify the type.  A file may have multiple .debug_types sections,
25241    or the type may come from a DWO file.  Furthermore, while it's more logical
25242    to use per_cu->section+offset, with Fission the section with the data is in
25243    the DWO file but we don't know that section at the point we need it.
25244    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25245    because we can enter the lookup routine, get_die_type_at_offset, from
25246    outside this file, and thus won't necessarily have PER_CU->cu.
25247    Fortunately, PER_CU is stable for the life of the objfile.  */
25248
25249 struct dwarf2_per_cu_offset_and_type
25250 {
25251   const struct dwarf2_per_cu_data *per_cu;
25252   sect_offset sect_off;
25253   struct type *type;
25254 };
25255
25256 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25257
25258 static hashval_t
25259 per_cu_offset_and_type_hash (const void *item)
25260 {
25261   const struct dwarf2_per_cu_offset_and_type *ofs
25262     = (const struct dwarf2_per_cu_offset_and_type *) item;
25263
25264   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25265 }
25266
25267 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25268
25269 static int
25270 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25271 {
25272   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25273     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25274   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25275     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25276
25277   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25278           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25279 }
25280
25281 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25282    table if necessary.  For convenience, return TYPE.
25283
25284    The DIEs reading must have careful ordering to:
25285     * Not cause infite loops trying to read in DIEs as a prerequisite for
25286       reading current DIE.
25287     * Not trying to dereference contents of still incompletely read in types
25288       while reading in other DIEs.
25289     * Enable referencing still incompletely read in types just by a pointer to
25290       the type without accessing its fields.
25291
25292    Therefore caller should follow these rules:
25293      * Try to fetch any prerequisite types we may need to build this DIE type
25294        before building the type and calling set_die_type.
25295      * After building type call set_die_type for current DIE as soon as
25296        possible before fetching more types to complete the current type.
25297      * Make the type as complete as possible before fetching more types.  */
25298
25299 static struct type *
25300 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25301 {
25302   struct dwarf2_per_objfile *dwarf2_per_objfile
25303     = cu->per_cu->dwarf2_per_objfile;
25304   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25305   struct objfile *objfile = dwarf2_per_objfile->objfile;
25306   struct attribute *attr;
25307   struct dynamic_prop prop;
25308
25309   /* For Ada types, make sure that the gnat-specific data is always
25310      initialized (if not already set).  There are a few types where
25311      we should not be doing so, because the type-specific area is
25312      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25313      where the type-specific area is used to store the floatformat).
25314      But this is not a problem, because the gnat-specific information
25315      is actually not needed for these types.  */
25316   if (need_gnat_info (cu)
25317       && TYPE_CODE (type) != TYPE_CODE_FUNC
25318       && TYPE_CODE (type) != TYPE_CODE_FLT
25319       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25320       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25321       && TYPE_CODE (type) != TYPE_CODE_METHOD
25322       && !HAVE_GNAT_AUX_INFO (type))
25323     INIT_GNAT_SPECIFIC (type);
25324
25325   /* Read DW_AT_allocated and set in type.  */
25326   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25327   if (attr_form_is_block (attr))
25328     {
25329       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25330         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25331     }
25332   else if (attr != NULL)
25333     {
25334       complaint (&symfile_complaints,
25335                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25336                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25337                  sect_offset_str (die->sect_off));
25338     }
25339
25340   /* Read DW_AT_associated and set in type.  */
25341   attr = dwarf2_attr (die, DW_AT_associated, cu);
25342   if (attr_form_is_block (attr))
25343     {
25344       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25345         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25346     }
25347   else if (attr != NULL)
25348     {
25349       complaint (&symfile_complaints,
25350                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25351                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25352                  sect_offset_str (die->sect_off));
25353     }
25354
25355   /* Read DW_AT_data_location and set in type.  */
25356   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25357   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25358     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25359
25360   if (dwarf2_per_objfile->die_type_hash == NULL)
25361     {
25362       dwarf2_per_objfile->die_type_hash =
25363         htab_create_alloc_ex (127,
25364                               per_cu_offset_and_type_hash,
25365                               per_cu_offset_and_type_eq,
25366                               NULL,
25367                               &objfile->objfile_obstack,
25368                               hashtab_obstack_allocate,
25369                               dummy_obstack_deallocate);
25370     }
25371
25372   ofs.per_cu = cu->per_cu;
25373   ofs.sect_off = die->sect_off;
25374   ofs.type = type;
25375   slot = (struct dwarf2_per_cu_offset_and_type **)
25376     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25377   if (*slot)
25378     complaint (&symfile_complaints,
25379                _("A problem internal to GDB: DIE %s has type already set"),
25380                sect_offset_str (die->sect_off));
25381   *slot = XOBNEW (&objfile->objfile_obstack,
25382                   struct dwarf2_per_cu_offset_and_type);
25383   **slot = ofs;
25384   return type;
25385 }
25386
25387 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25388    or return NULL if the die does not have a saved type.  */
25389
25390 static struct type *
25391 get_die_type_at_offset (sect_offset sect_off,
25392                         struct dwarf2_per_cu_data *per_cu)
25393 {
25394   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25395   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25396
25397   if (dwarf2_per_objfile->die_type_hash == NULL)
25398     return NULL;
25399
25400   ofs.per_cu = per_cu;
25401   ofs.sect_off = sect_off;
25402   slot = ((struct dwarf2_per_cu_offset_and_type *)
25403           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25404   if (slot)
25405     return slot->type;
25406   else
25407     return NULL;
25408 }
25409
25410 /* Look up the type for DIE in CU in die_type_hash,
25411    or return NULL if DIE does not have a saved type.  */
25412
25413 static struct type *
25414 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25415 {
25416   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25417 }
25418
25419 /* Add a dependence relationship from CU to REF_PER_CU.  */
25420
25421 static void
25422 dwarf2_add_dependence (struct dwarf2_cu *cu,
25423                        struct dwarf2_per_cu_data *ref_per_cu)
25424 {
25425   void **slot;
25426
25427   if (cu->dependencies == NULL)
25428     cu->dependencies
25429       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25430                               NULL, &cu->comp_unit_obstack,
25431                               hashtab_obstack_allocate,
25432                               dummy_obstack_deallocate);
25433
25434   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25435   if (*slot == NULL)
25436     *slot = ref_per_cu;
25437 }
25438
25439 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25440    Set the mark field in every compilation unit in the
25441    cache that we must keep because we are keeping CU.  */
25442
25443 static int
25444 dwarf2_mark_helper (void **slot, void *data)
25445 {
25446   struct dwarf2_per_cu_data *per_cu;
25447
25448   per_cu = (struct dwarf2_per_cu_data *) *slot;
25449
25450   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25451      reading of the chain.  As such dependencies remain valid it is not much
25452      useful to track and undo them during QUIT cleanups.  */
25453   if (per_cu->cu == NULL)
25454     return 1;
25455
25456   if (per_cu->cu->mark)
25457     return 1;
25458   per_cu->cu->mark = 1;
25459
25460   if (per_cu->cu->dependencies != NULL)
25461     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25462
25463   return 1;
25464 }
25465
25466 /* Set the mark field in CU and in every other compilation unit in the
25467    cache that we must keep because we are keeping CU.  */
25468
25469 static void
25470 dwarf2_mark (struct dwarf2_cu *cu)
25471 {
25472   if (cu->mark)
25473     return;
25474   cu->mark = 1;
25475   if (cu->dependencies != NULL)
25476     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25477 }
25478
25479 static void
25480 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25481 {
25482   while (per_cu)
25483     {
25484       per_cu->cu->mark = 0;
25485       per_cu = per_cu->cu->read_in_chain;
25486     }
25487 }
25488
25489 /* Trivial hash function for partial_die_info: the hash value of a DIE
25490    is its offset in .debug_info for this objfile.  */
25491
25492 static hashval_t
25493 partial_die_hash (const void *item)
25494 {
25495   const struct partial_die_info *part_die
25496     = (const struct partial_die_info *) item;
25497
25498   return to_underlying (part_die->sect_off);
25499 }
25500
25501 /* Trivial comparison function for partial_die_info structures: two DIEs
25502    are equal if they have the same offset.  */
25503
25504 static int
25505 partial_die_eq (const void *item_lhs, const void *item_rhs)
25506 {
25507   const struct partial_die_info *part_die_lhs
25508     = (const struct partial_die_info *) item_lhs;
25509   const struct partial_die_info *part_die_rhs
25510     = (const struct partial_die_info *) item_rhs;
25511
25512   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25513 }
25514
25515 static struct cmd_list_element *set_dwarf_cmdlist;
25516 static struct cmd_list_element *show_dwarf_cmdlist;
25517
25518 static void
25519 set_dwarf_cmd (const char *args, int from_tty)
25520 {
25521   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25522              gdb_stdout);
25523 }
25524
25525 static void
25526 show_dwarf_cmd (const char *args, int from_tty)
25527 {
25528   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25529 }
25530
25531 /* The "save gdb-index" command.  */
25532
25533 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25534    error checking.  */
25535
25536 static void
25537 file_write (FILE *file, const void *data, size_t size)
25538 {
25539   if (fwrite (data, 1, size, file) != size)
25540     error (_("couldn't data write to file"));
25541 }
25542
25543 /* Write the contents of VEC to FILE, with error checking.  */
25544
25545 template<typename Elem, typename Alloc>
25546 static void
25547 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25548 {
25549   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25550 }
25551
25552 /* In-memory buffer to prepare data to be written later to a file.  */
25553 class data_buf
25554 {
25555 public:
25556   /* Copy DATA to the end of the buffer.  */
25557   template<typename T>
25558   void append_data (const T &data)
25559   {
25560     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25561                reinterpret_cast<const gdb_byte *> (&data + 1),
25562                grow (sizeof (data)));
25563   }
25564
25565   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25566      terminating zero is appended too.  */
25567   void append_cstr0 (const char *cstr)
25568   {
25569     const size_t size = strlen (cstr) + 1;
25570     std::copy (cstr, cstr + size, grow (size));
25571   }
25572
25573   /* Store INPUT as ULEB128 to the end of buffer.  */
25574   void append_unsigned_leb128 (ULONGEST input)
25575   {
25576     for (;;)
25577       {
25578         gdb_byte output = input & 0x7f;
25579         input >>= 7;
25580         if (input)
25581           output |= 0x80;
25582         append_data (output);
25583         if (input == 0)
25584           break;
25585       }
25586   }
25587
25588   /* Accept a host-format integer in VAL and append it to the buffer
25589      as a target-format integer which is LEN bytes long.  */
25590   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25591   {
25592     ::store_unsigned_integer (grow (len), len, byte_order, val);
25593   }
25594
25595   /* Return the size of the buffer.  */
25596   size_t size () const
25597   {
25598     return m_vec.size ();
25599   }
25600
25601   /* Return true iff the buffer is empty.  */
25602   bool empty () const
25603   {
25604     return m_vec.empty ();
25605   }
25606
25607   /* Write the buffer to FILE.  */
25608   void file_write (FILE *file) const
25609   {
25610     ::file_write (file, m_vec);
25611   }
25612
25613 private:
25614   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25615      the start of the new block.  */
25616   gdb_byte *grow (size_t size)
25617   {
25618     m_vec.resize (m_vec.size () + size);
25619     return &*m_vec.end () - size;
25620   }
25621
25622   gdb::byte_vector m_vec;
25623 };
25624
25625 /* An entry in the symbol table.  */
25626 struct symtab_index_entry
25627 {
25628   /* The name of the symbol.  */
25629   const char *name;
25630   /* The offset of the name in the constant pool.  */
25631   offset_type index_offset;
25632   /* A sorted vector of the indices of all the CUs that hold an object
25633      of this name.  */
25634   std::vector<offset_type> cu_indices;
25635 };
25636
25637 /* The symbol table.  This is a power-of-2-sized hash table.  */
25638 struct mapped_symtab
25639 {
25640   mapped_symtab ()
25641   {
25642     data.resize (1024);
25643   }
25644
25645   offset_type n_elements = 0;
25646   std::vector<symtab_index_entry> data;
25647 };
25648
25649 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25650    the slot.
25651    
25652    Function is used only during write_hash_table so no index format backward
25653    compatibility is needed.  */
25654
25655 static symtab_index_entry &
25656 find_slot (struct mapped_symtab *symtab, const char *name)
25657 {
25658   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25659
25660   index = hash & (symtab->data.size () - 1);
25661   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25662
25663   for (;;)
25664     {
25665       if (symtab->data[index].name == NULL
25666           || strcmp (name, symtab->data[index].name) == 0)
25667         return symtab->data[index];
25668       index = (index + step) & (symtab->data.size () - 1);
25669     }
25670 }
25671
25672 /* Expand SYMTAB's hash table.  */
25673
25674 static void
25675 hash_expand (struct mapped_symtab *symtab)
25676 {
25677   auto old_entries = std::move (symtab->data);
25678
25679   symtab->data.clear ();
25680   symtab->data.resize (old_entries.size () * 2);
25681
25682   for (auto &it : old_entries)
25683     if (it.name != NULL)
25684       {
25685         auto &ref = find_slot (symtab, it.name);
25686         ref = std::move (it);
25687       }
25688 }
25689
25690 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25691    CU_INDEX is the index of the CU in which the symbol appears.
25692    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25693
25694 static void
25695 add_index_entry (struct mapped_symtab *symtab, const char *name,
25696                  int is_static, gdb_index_symbol_kind kind,
25697                  offset_type cu_index)
25698 {
25699   offset_type cu_index_and_attrs;
25700
25701   ++symtab->n_elements;
25702   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25703     hash_expand (symtab);
25704
25705   symtab_index_entry &slot = find_slot (symtab, name);
25706   if (slot.name == NULL)
25707     {
25708       slot.name = name;
25709       /* index_offset is set later.  */
25710     }
25711
25712   cu_index_and_attrs = 0;
25713   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25714   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25715   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25716
25717   /* We don't want to record an index value twice as we want to avoid the
25718      duplication.
25719      We process all global symbols and then all static symbols
25720      (which would allow us to avoid the duplication by only having to check
25721      the last entry pushed), but a symbol could have multiple kinds in one CU.
25722      To keep things simple we don't worry about the duplication here and
25723      sort and uniqufy the list after we've processed all symbols.  */
25724   slot.cu_indices.push_back (cu_index_and_attrs);
25725 }
25726
25727 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25728
25729 static void
25730 uniquify_cu_indices (struct mapped_symtab *symtab)
25731 {
25732   for (auto &entry : symtab->data)
25733     {
25734       if (entry.name != NULL && !entry.cu_indices.empty ())
25735         {
25736           auto &cu_indices = entry.cu_indices;
25737           std::sort (cu_indices.begin (), cu_indices.end ());
25738           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25739           cu_indices.erase (from, cu_indices.end ());
25740         }
25741     }
25742 }
25743
25744 /* A form of 'const char *' suitable for container keys.  Only the
25745    pointer is stored.  The strings themselves are compared, not the
25746    pointers.  */
25747 class c_str_view
25748 {
25749 public:
25750   c_str_view (const char *cstr)
25751     : m_cstr (cstr)
25752   {}
25753
25754   bool operator== (const c_str_view &other) const
25755   {
25756     return strcmp (m_cstr, other.m_cstr) == 0;
25757   }
25758
25759   /* Return the underlying C string.  Note, the returned string is
25760      only a reference with lifetime of this object.  */
25761   const char *c_str () const
25762   {
25763     return m_cstr;
25764   }
25765
25766 private:
25767   friend class c_str_view_hasher;
25768   const char *const m_cstr;
25769 };
25770
25771 /* A std::unordered_map::hasher for c_str_view that uses the right
25772    hash function for strings in a mapped index.  */
25773 class c_str_view_hasher
25774 {
25775 public:
25776   size_t operator () (const c_str_view &x) const
25777   {
25778     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25779   }
25780 };
25781
25782 /* A std::unordered_map::hasher for std::vector<>.  */
25783 template<typename T>
25784 class vector_hasher
25785 {
25786 public:
25787   size_t operator () (const std::vector<T> &key) const
25788   {
25789     return iterative_hash (key.data (),
25790                            sizeof (key.front ()) * key.size (), 0);
25791   }
25792 };
25793
25794 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25795    constant pool entries going into the data buffer CPOOL.  */
25796
25797 static void
25798 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25799 {
25800   {
25801     /* Elements are sorted vectors of the indices of all the CUs that
25802        hold an object of this name.  */
25803     std::unordered_map<std::vector<offset_type>, offset_type,
25804                        vector_hasher<offset_type>>
25805       symbol_hash_table;
25806
25807     /* We add all the index vectors to the constant pool first, to
25808        ensure alignment is ok.  */
25809     for (symtab_index_entry &entry : symtab->data)
25810       {
25811         if (entry.name == NULL)
25812           continue;
25813         gdb_assert (entry.index_offset == 0);
25814
25815         /* Finding before inserting is faster than always trying to
25816            insert, because inserting always allocates a node, does the
25817            lookup, and then destroys the new node if another node
25818            already had the same key.  C++17 try_emplace will avoid
25819            this.  */
25820         const auto found
25821           = symbol_hash_table.find (entry.cu_indices);
25822         if (found != symbol_hash_table.end ())
25823           {
25824             entry.index_offset = found->second;
25825             continue;
25826           }
25827
25828         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25829         entry.index_offset = cpool.size ();
25830         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25831         for (const auto index : entry.cu_indices)
25832           cpool.append_data (MAYBE_SWAP (index));
25833       }
25834   }
25835
25836   /* Now write out the hash table.  */
25837   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25838   for (const auto &entry : symtab->data)
25839     {
25840       offset_type str_off, vec_off;
25841
25842       if (entry.name != NULL)
25843         {
25844           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25845           if (insertpair.second)
25846             cpool.append_cstr0 (entry.name);
25847           str_off = insertpair.first->second;
25848           vec_off = entry.index_offset;
25849         }
25850       else
25851         {
25852           /* While 0 is a valid constant pool index, it is not valid
25853              to have 0 for both offsets.  */
25854           str_off = 0;
25855           vec_off = 0;
25856         }
25857
25858       output.append_data (MAYBE_SWAP (str_off));
25859       output.append_data (MAYBE_SWAP (vec_off));
25860     }
25861 }
25862
25863 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25864
25865 /* Helper struct for building the address table.  */
25866 struct addrmap_index_data
25867 {
25868   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25869     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25870   {}
25871
25872   struct objfile *objfile;
25873   data_buf &addr_vec;
25874   psym_index_map &cu_index_htab;
25875
25876   /* Non-zero if the previous_* fields are valid.
25877      We can't write an entry until we see the next entry (since it is only then
25878      that we know the end of the entry).  */
25879   int previous_valid;
25880   /* Index of the CU in the table of all CUs in the index file.  */
25881   unsigned int previous_cu_index;
25882   /* Start address of the CU.  */
25883   CORE_ADDR previous_cu_start;
25884 };
25885
25886 /* Write an address entry to ADDR_VEC.  */
25887
25888 static void
25889 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25890                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25891 {
25892   CORE_ADDR baseaddr;
25893
25894   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25895
25896   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25897   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25898   addr_vec.append_data (MAYBE_SWAP (cu_index));
25899 }
25900
25901 /* Worker function for traversing an addrmap to build the address table.  */
25902
25903 static int
25904 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25905 {
25906   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25907   struct partial_symtab *pst = (struct partial_symtab *) obj;
25908
25909   if (data->previous_valid)
25910     add_address_entry (data->objfile, data->addr_vec,
25911                        data->previous_cu_start, start_addr,
25912                        data->previous_cu_index);
25913
25914   data->previous_cu_start = start_addr;
25915   if (pst != NULL)
25916     {
25917       const auto it = data->cu_index_htab.find (pst);
25918       gdb_assert (it != data->cu_index_htab.cend ());
25919       data->previous_cu_index = it->second;
25920       data->previous_valid = 1;
25921     }
25922   else
25923     data->previous_valid = 0;
25924
25925   return 0;
25926 }
25927
25928 /* Write OBJFILE's address map to ADDR_VEC.
25929    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25930    in the index file.  */
25931
25932 static void
25933 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25934                    psym_index_map &cu_index_htab)
25935 {
25936   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25937
25938   /* When writing the address table, we have to cope with the fact that
25939      the addrmap iterator only provides the start of a region; we have to
25940      wait until the next invocation to get the start of the next region.  */
25941
25942   addrmap_index_data.objfile = objfile;
25943   addrmap_index_data.previous_valid = 0;
25944
25945   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25946                    &addrmap_index_data);
25947
25948   /* It's highly unlikely the last entry (end address = 0xff...ff)
25949      is valid, but we should still handle it.
25950      The end address is recorded as the start of the next region, but that
25951      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25952      anyway.  */
25953   if (addrmap_index_data.previous_valid)
25954     add_address_entry (objfile, addr_vec,
25955                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25956                        addrmap_index_data.previous_cu_index);
25957 }
25958
25959 /* Return the symbol kind of PSYM.  */
25960
25961 static gdb_index_symbol_kind
25962 symbol_kind (struct partial_symbol *psym)
25963 {
25964   domain_enum domain = PSYMBOL_DOMAIN (psym);
25965   enum address_class aclass = PSYMBOL_CLASS (psym);
25966
25967   switch (domain)
25968     {
25969     case VAR_DOMAIN:
25970       switch (aclass)
25971         {
25972         case LOC_BLOCK:
25973           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25974         case LOC_TYPEDEF:
25975           return GDB_INDEX_SYMBOL_KIND_TYPE;
25976         case LOC_COMPUTED:
25977         case LOC_CONST_BYTES:
25978         case LOC_OPTIMIZED_OUT:
25979         case LOC_STATIC:
25980           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25981         case LOC_CONST:
25982           /* Note: It's currently impossible to recognize psyms as enum values
25983              short of reading the type info.  For now punt.  */
25984           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25985         default:
25986           /* There are other LOC_FOO values that one might want to classify
25987              as variables, but dwarf2read.c doesn't currently use them.  */
25988           return GDB_INDEX_SYMBOL_KIND_OTHER;
25989         }
25990     case STRUCT_DOMAIN:
25991       return GDB_INDEX_SYMBOL_KIND_TYPE;
25992     default:
25993       return GDB_INDEX_SYMBOL_KIND_OTHER;
25994     }
25995 }
25996
25997 /* Add a list of partial symbols to SYMTAB.  */
25998
25999 static void
26000 write_psymbols (struct mapped_symtab *symtab,
26001                 std::unordered_set<partial_symbol *> &psyms_seen,
26002                 struct partial_symbol **psymp,
26003                 int count,
26004                 offset_type cu_index,
26005                 int is_static)
26006 {
26007   for (; count-- > 0; ++psymp)
26008     {
26009       struct partial_symbol *psym = *psymp;
26010
26011       if (SYMBOL_LANGUAGE (psym) == language_ada)
26012         error (_("Ada is not currently supported by the index"));
26013
26014       /* Only add a given psymbol once.  */
26015       if (psyms_seen.insert (psym).second)
26016         {
26017           gdb_index_symbol_kind kind = symbol_kind (psym);
26018
26019           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26020                            is_static, kind, cu_index);
26021         }
26022     }
26023 }
26024
26025 /* A helper struct used when iterating over debug_types.  */
26026 struct signatured_type_index_data
26027 {
26028   signatured_type_index_data (data_buf &types_list_,
26029                               std::unordered_set<partial_symbol *> &psyms_seen_)
26030     : types_list (types_list_), psyms_seen (psyms_seen_)
26031   {}
26032
26033   struct objfile *objfile;
26034   struct mapped_symtab *symtab;
26035   data_buf &types_list;
26036   std::unordered_set<partial_symbol *> &psyms_seen;
26037   int cu_index;
26038 };
26039
26040 /* A helper function that writes a single signatured_type to an
26041    obstack.  */
26042
26043 static int
26044 write_one_signatured_type (void **slot, void *d)
26045 {
26046   struct signatured_type_index_data *info
26047     = (struct signatured_type_index_data *) d;
26048   struct signatured_type *entry = (struct signatured_type *) *slot;
26049   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26050
26051   write_psymbols (info->symtab,
26052                   info->psyms_seen,
26053                   &info->objfile->global_psymbols[psymtab->globals_offset],
26054                   psymtab->n_global_syms, info->cu_index,
26055                   0);
26056   write_psymbols (info->symtab,
26057                   info->psyms_seen,
26058                   &info->objfile->static_psymbols[psymtab->statics_offset],
26059                   psymtab->n_static_syms, info->cu_index,
26060                   1);
26061
26062   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26063                                 to_underlying (entry->per_cu.sect_off));
26064   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26065                                 to_underlying (entry->type_offset_in_tu));
26066   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26067
26068   ++info->cu_index;
26069
26070   return 1;
26071 }
26072
26073 /* Recurse into all "included" dependencies and count their symbols as
26074    if they appeared in this psymtab.  */
26075
26076 static void
26077 recursively_count_psymbols (struct partial_symtab *psymtab,
26078                             size_t &psyms_seen)
26079 {
26080   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26081     if (psymtab->dependencies[i]->user != NULL)
26082       recursively_count_psymbols (psymtab->dependencies[i],
26083                                   psyms_seen);
26084
26085   psyms_seen += psymtab->n_global_syms;
26086   psyms_seen += psymtab->n_static_syms;
26087 }
26088
26089 /* Recurse into all "included" dependencies and write their symbols as
26090    if they appeared in this psymtab.  */
26091
26092 static void
26093 recursively_write_psymbols (struct objfile *objfile,
26094                             struct partial_symtab *psymtab,
26095                             struct mapped_symtab *symtab,
26096                             std::unordered_set<partial_symbol *> &psyms_seen,
26097                             offset_type cu_index)
26098 {
26099   int i;
26100
26101   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26102     if (psymtab->dependencies[i]->user != NULL)
26103       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26104                                   symtab, psyms_seen, cu_index);
26105
26106   write_psymbols (symtab,
26107                   psyms_seen,
26108                   &objfile->global_psymbols[psymtab->globals_offset],
26109                   psymtab->n_global_syms, cu_index,
26110                   0);
26111   write_psymbols (symtab,
26112                   psyms_seen,
26113                   &objfile->static_psymbols[psymtab->statics_offset],
26114                   psymtab->n_static_syms, cu_index,
26115                   1);
26116 }
26117
26118 /* DWARF-5 .debug_names builder.  */
26119 class debug_names
26120 {
26121 public:
26122   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26123                bfd_endian dwarf5_byte_order)
26124     : m_dwarf5_byte_order (dwarf5_byte_order),
26125       m_dwarf32 (dwarf5_byte_order),
26126       m_dwarf64 (dwarf5_byte_order),
26127       m_dwarf (is_dwarf64
26128                ? static_cast<dwarf &> (m_dwarf64)
26129                : static_cast<dwarf &> (m_dwarf32)),
26130       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26131       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26132       m_debugstrlookup (dwarf2_per_objfile)
26133   {}
26134
26135   int dwarf5_offset_size () const
26136   {
26137     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26138     return dwarf5_is_dwarf64 ? 8 : 4;
26139   }
26140
26141   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26142   enum class unit_kind { cu, tu };
26143
26144   /* Insert one symbol.  */
26145   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26146                unit_kind kind)
26147   {
26148     const int dwarf_tag = psymbol_tag (psym);
26149     if (dwarf_tag == 0)
26150       return;
26151     const char *const name = SYMBOL_SEARCH_NAME (psym);
26152     const auto insertpair
26153       = m_name_to_value_set.emplace (c_str_view (name),
26154                                      std::set<symbol_value> ());
26155     std::set<symbol_value> &value_set = insertpair.first->second;
26156     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26157   }
26158
26159   /* Build all the tables.  All symbols must be already inserted.
26160      This function does not call file_write, caller has to do it
26161      afterwards.  */
26162   void build ()
26163   {
26164     /* Verify the build method has not be called twice.  */
26165     gdb_assert (m_abbrev_table.empty ());
26166     const size_t name_count = m_name_to_value_set.size ();
26167     m_bucket_table.resize
26168       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26169     m_hash_table.reserve (name_count);
26170     m_name_table_string_offs.reserve (name_count);
26171     m_name_table_entry_offs.reserve (name_count);
26172
26173     /* Map each hash of symbol to its name and value.  */
26174     struct hash_it_pair
26175     {
26176       uint32_t hash;
26177       decltype (m_name_to_value_set)::const_iterator it;
26178     };
26179     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26180     bucket_hash.resize (m_bucket_table.size ());
26181     for (decltype (m_name_to_value_set)::const_iterator it
26182            = m_name_to_value_set.cbegin ();
26183          it != m_name_to_value_set.cend ();
26184          ++it)
26185       {
26186         const char *const name = it->first.c_str ();
26187         const uint32_t hash = dwarf5_djb_hash (name);
26188         hash_it_pair hashitpair;
26189         hashitpair.hash = hash;
26190         hashitpair.it = it;
26191         auto &slot = bucket_hash[hash % bucket_hash.size()];
26192         slot.push_front (std::move (hashitpair));
26193       }
26194     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26195       {
26196         const std::forward_list<hash_it_pair> &hashitlist
26197           = bucket_hash[bucket_ix];
26198         if (hashitlist.empty ())
26199           continue;
26200         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26201         /* The hashes array is indexed starting at 1.  */
26202         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26203                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26204                                 m_hash_table.size () + 1);
26205         for (const hash_it_pair &hashitpair : hashitlist)
26206           {
26207             m_hash_table.push_back (0);
26208             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26209                                                         (&m_hash_table.back ()),
26210                                     sizeof (m_hash_table.back ()),
26211                                     m_dwarf5_byte_order, hashitpair.hash);
26212             const c_str_view &name = hashitpair.it->first;
26213             const std::set<symbol_value> &value_set = hashitpair.it->second;
26214             m_name_table_string_offs.push_back_reorder
26215               (m_debugstrlookup.lookup (name.c_str ()));
26216             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26217             gdb_assert (!value_set.empty ());
26218             for (const symbol_value &value : value_set)
26219               {
26220                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26221                                                         value.is_static,
26222                                                         value.kind)];
26223                 if (idx == 0)
26224                   {
26225                     idx = m_idx_next++;
26226                     m_abbrev_table.append_unsigned_leb128 (idx);
26227                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26228                     m_abbrev_table.append_unsigned_leb128
26229                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26230                                                            : DW_IDX_type_unit);
26231                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26232                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26233                                                            ? DW_IDX_GNU_internal
26234                                                            : DW_IDX_GNU_external);
26235                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26236
26237                     /* Terminate attributes list.  */
26238                     m_abbrev_table.append_unsigned_leb128 (0);
26239                     m_abbrev_table.append_unsigned_leb128 (0);
26240                   }
26241
26242                 m_entry_pool.append_unsigned_leb128 (idx);
26243                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26244               }
26245
26246             /* Terminate the list of CUs.  */
26247             m_entry_pool.append_unsigned_leb128 (0);
26248           }
26249       }
26250     gdb_assert (m_hash_table.size () == name_count);
26251
26252     /* Terminate tags list.  */
26253     m_abbrev_table.append_unsigned_leb128 (0);
26254   }
26255
26256   /* Return .debug_names bucket count.  This must be called only after
26257      calling the build method.  */
26258   uint32_t bucket_count () const
26259   {
26260     /* Verify the build method has been already called.  */
26261     gdb_assert (!m_abbrev_table.empty ());
26262     const uint32_t retval = m_bucket_table.size ();
26263
26264     /* Check for overflow.  */
26265     gdb_assert (retval == m_bucket_table.size ());
26266     return retval;
26267   }
26268
26269   /* Return .debug_names names count.  This must be called only after
26270      calling the build method.  */
26271   uint32_t name_count () const
26272   {
26273     /* Verify the build method has been already called.  */
26274     gdb_assert (!m_abbrev_table.empty ());
26275     const uint32_t retval = m_hash_table.size ();
26276
26277     /* Check for overflow.  */
26278     gdb_assert (retval == m_hash_table.size ());
26279     return retval;
26280   }
26281
26282   /* Return number of bytes of .debug_names abbreviation table.  This
26283      must be called only after calling the build method.  */
26284   uint32_t abbrev_table_bytes () const
26285   {
26286     gdb_assert (!m_abbrev_table.empty ());
26287     return m_abbrev_table.size ();
26288   }
26289
26290   /* Recurse into all "included" dependencies and store their symbols
26291      as if they appeared in this psymtab.  */
26292   void recursively_write_psymbols
26293     (struct objfile *objfile,
26294      struct partial_symtab *psymtab,
26295      std::unordered_set<partial_symbol *> &psyms_seen,
26296      int cu_index)
26297   {
26298     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26299       if (psymtab->dependencies[i]->user != NULL)
26300         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26301                                     psyms_seen, cu_index);
26302
26303     write_psymbols (psyms_seen,
26304                     &objfile->global_psymbols[psymtab->globals_offset],
26305                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26306     write_psymbols (psyms_seen,
26307                     &objfile->static_psymbols[psymtab->statics_offset],
26308                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26309   }
26310
26311   /* Return number of bytes the .debug_names section will have.  This
26312      must be called only after calling the build method.  */
26313   size_t bytes () const
26314   {
26315     /* Verify the build method has been already called.  */
26316     gdb_assert (!m_abbrev_table.empty ());
26317     size_t expected_bytes = 0;
26318     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26319     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26320     expected_bytes += m_name_table_string_offs.bytes ();
26321     expected_bytes += m_name_table_entry_offs.bytes ();
26322     expected_bytes += m_abbrev_table.size ();
26323     expected_bytes += m_entry_pool.size ();
26324     return expected_bytes;
26325   }
26326
26327   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26328      FILE_STR.  This must be called only after calling the build
26329      method.  */
26330   void file_write (FILE *file_names, FILE *file_str) const
26331   {
26332     /* Verify the build method has been already called.  */
26333     gdb_assert (!m_abbrev_table.empty ());
26334     ::file_write (file_names, m_bucket_table);
26335     ::file_write (file_names, m_hash_table);
26336     m_name_table_string_offs.file_write (file_names);
26337     m_name_table_entry_offs.file_write (file_names);
26338     m_abbrev_table.file_write (file_names);
26339     m_entry_pool.file_write (file_names);
26340     m_debugstrlookup.file_write (file_str);
26341   }
26342
26343   /* A helper user data for write_one_signatured_type.  */
26344   class write_one_signatured_type_data
26345   {
26346   public:
26347     write_one_signatured_type_data (debug_names &nametable_,
26348                                     signatured_type_index_data &&info_)
26349     : nametable (nametable_), info (std::move (info_))
26350     {}
26351     debug_names &nametable;
26352     struct signatured_type_index_data info;
26353   };
26354
26355   /* A helper function to pass write_one_signatured_type to
26356      htab_traverse_noresize.  */
26357   static int
26358   write_one_signatured_type (void **slot, void *d)
26359   {
26360     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26361     struct signatured_type_index_data *info = &data->info;
26362     struct signatured_type *entry = (struct signatured_type *) *slot;
26363
26364     data->nametable.write_one_signatured_type (entry, info);
26365
26366     return 1;
26367   }
26368
26369 private:
26370
26371   /* Storage for symbol names mapping them to their .debug_str section
26372      offsets.  */
26373   class debug_str_lookup
26374   {
26375   public:
26376
26377     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26378        All .debug_str section strings are automatically stored.  */
26379     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26380       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26381         m_dwarf2_per_objfile (dwarf2_per_objfile)
26382     {
26383       dwarf2_read_section (dwarf2_per_objfile->objfile,
26384                            &dwarf2_per_objfile->str);
26385       if (dwarf2_per_objfile->str.buffer == NULL)
26386         return;
26387       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26388            data < (dwarf2_per_objfile->str.buffer
26389                    + dwarf2_per_objfile->str.size);)
26390         {
26391           const char *const s = reinterpret_cast<const char *> (data);
26392           const auto insertpair
26393             = m_str_table.emplace (c_str_view (s),
26394                                    data - dwarf2_per_objfile->str.buffer);
26395           if (!insertpair.second)
26396             complaint (&symfile_complaints,
26397                        _("Duplicate string \"%s\" in "
26398                          ".debug_str section [in module %s]"),
26399                        s, bfd_get_filename (m_abfd));
26400           data += strlen (s) + 1;
26401         }
26402     }
26403
26404     /* Return offset of symbol name S in the .debug_str section.  Add
26405        such symbol to the section's end if it does not exist there
26406        yet.  */
26407     size_t lookup (const char *s)
26408     {
26409       const auto it = m_str_table.find (c_str_view (s));
26410       if (it != m_str_table.end ())
26411         return it->second;
26412       const size_t offset = (m_dwarf2_per_objfile->str.size
26413                              + m_str_add_buf.size ());
26414       m_str_table.emplace (c_str_view (s), offset);
26415       m_str_add_buf.append_cstr0 (s);
26416       return offset;
26417     }
26418
26419     /* Append the end of the .debug_str section to FILE.  */
26420     void file_write (FILE *file) const
26421     {
26422       m_str_add_buf.file_write (file);
26423     }
26424
26425   private:
26426     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26427     bfd *const m_abfd;
26428     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26429
26430     /* Data to add at the end of .debug_str for new needed symbol names.  */
26431     data_buf m_str_add_buf;
26432   };
26433
26434   /* Container to map used DWARF tags to their .debug_names abbreviation
26435      tags.  */
26436   class index_key
26437   {
26438   public:
26439     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26440       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26441     {
26442     }
26443
26444     bool
26445     operator== (const index_key &other) const
26446     {
26447       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26448               && kind == other.kind);
26449     }
26450
26451     const int dwarf_tag;
26452     const bool is_static;
26453     const unit_kind kind;
26454   };
26455
26456   /* Provide std::unordered_map::hasher for index_key.  */
26457   class index_key_hasher
26458   {
26459   public:
26460     size_t
26461     operator () (const index_key &key) const
26462     {
26463       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26464     }
26465   };
26466
26467   /* Parameters of one symbol entry.  */
26468   class symbol_value
26469   {
26470   public:
26471     const int dwarf_tag, cu_index;
26472     const bool is_static;
26473     const unit_kind kind;
26474
26475     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26476                   unit_kind kind_)
26477       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26478         kind (kind_)
26479     {}
26480
26481     bool
26482     operator< (const symbol_value &other) const
26483     {
26484 #define X(n) \
26485   do \
26486     { \
26487       if (n < other.n) \
26488         return true; \
26489       if (n > other.n) \
26490         return false; \
26491     } \
26492   while (0)
26493       X (dwarf_tag);
26494       X (is_static);
26495       X (kind);
26496       X (cu_index);
26497 #undef X
26498       return false;
26499     }
26500   };
26501
26502   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26503      output.  */
26504   class offset_vec
26505   {
26506   protected:
26507     const bfd_endian dwarf5_byte_order;
26508   public:
26509     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26510       : dwarf5_byte_order (dwarf5_byte_order_)
26511     {}
26512
26513     /* Call std::vector::reserve for NELEM elements.  */
26514     virtual void reserve (size_t nelem) = 0;
26515
26516     /* Call std::vector::push_back with store_unsigned_integer byte
26517        reordering for ELEM.  */
26518     virtual void push_back_reorder (size_t elem) = 0;
26519
26520     /* Return expected output size in bytes.  */
26521     virtual size_t bytes () const = 0;
26522
26523     /* Write name table to FILE.  */
26524     virtual void file_write (FILE *file) const = 0;
26525   };
26526
26527   /* Template to unify DWARF-32 and DWARF-64 output.  */
26528   template<typename OffsetSize>
26529   class offset_vec_tmpl : public offset_vec
26530   {
26531   public:
26532     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26533       : offset_vec (dwarf5_byte_order_)
26534     {}
26535
26536     /* Implement offset_vec::reserve.  */
26537     void reserve (size_t nelem) override
26538     {
26539       m_vec.reserve (nelem);
26540     }
26541
26542     /* Implement offset_vec::push_back_reorder.  */
26543     void push_back_reorder (size_t elem) override
26544     {
26545       m_vec.push_back (elem);
26546       /* Check for overflow.  */
26547       gdb_assert (m_vec.back () == elem);
26548       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26549                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26550     }
26551
26552     /* Implement offset_vec::bytes.  */
26553     size_t bytes () const override
26554     {
26555       return m_vec.size () * sizeof (m_vec[0]);
26556     }
26557
26558     /* Implement offset_vec::file_write.  */
26559     void file_write (FILE *file) const override
26560     {
26561       ::file_write (file, m_vec);
26562     }
26563
26564   private:
26565     std::vector<OffsetSize> m_vec;
26566   };
26567
26568   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26569      respecting name table width.  */
26570   class dwarf
26571   {
26572   public:
26573     offset_vec &name_table_string_offs, &name_table_entry_offs;
26574
26575     dwarf (offset_vec &name_table_string_offs_,
26576            offset_vec &name_table_entry_offs_)
26577       : name_table_string_offs (name_table_string_offs_),
26578         name_table_entry_offs (name_table_entry_offs_)
26579     {
26580     }
26581   };
26582
26583   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26584      respecting name table width.  */
26585   template<typename OffsetSize>
26586   class dwarf_tmpl : public dwarf
26587   {
26588   public:
26589     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26590       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26591         m_name_table_string_offs (dwarf5_byte_order_),
26592         m_name_table_entry_offs (dwarf5_byte_order_)
26593     {}
26594
26595   private:
26596     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26597     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26598   };
26599
26600   /* Try to reconstruct original DWARF tag for given partial_symbol.
26601      This function is not DWARF-5 compliant but it is sufficient for
26602      GDB as a DWARF-5 index consumer.  */
26603   static int psymbol_tag (const struct partial_symbol *psym)
26604   {
26605     domain_enum domain = PSYMBOL_DOMAIN (psym);
26606     enum address_class aclass = PSYMBOL_CLASS (psym);
26607
26608     switch (domain)
26609       {
26610       case VAR_DOMAIN:
26611         switch (aclass)
26612           {
26613           case LOC_BLOCK:
26614             return DW_TAG_subprogram;
26615           case LOC_TYPEDEF:
26616             return DW_TAG_typedef;
26617           case LOC_COMPUTED:
26618           case LOC_CONST_BYTES:
26619           case LOC_OPTIMIZED_OUT:
26620           case LOC_STATIC:
26621             return DW_TAG_variable;
26622           case LOC_CONST:
26623             /* Note: It's currently impossible to recognize psyms as enum values
26624                short of reading the type info.  For now punt.  */
26625             return DW_TAG_variable;
26626           default:
26627             /* There are other LOC_FOO values that one might want to classify
26628                as variables, but dwarf2read.c doesn't currently use them.  */
26629             return DW_TAG_variable;
26630           }
26631       case STRUCT_DOMAIN:
26632         return DW_TAG_structure_type;
26633       default:
26634         return 0;
26635       }
26636   }
26637
26638   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26639   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26640                        struct partial_symbol **psymp, int count, int cu_index,
26641                        bool is_static, unit_kind kind)
26642   {
26643     for (; count-- > 0; ++psymp)
26644       {
26645         struct partial_symbol *psym = *psymp;
26646
26647         if (SYMBOL_LANGUAGE (psym) == language_ada)
26648           error (_("Ada is not currently supported by the index"));
26649
26650         /* Only add a given psymbol once.  */
26651         if (psyms_seen.insert (psym).second)
26652           insert (psym, cu_index, is_static, kind);
26653       }
26654   }
26655
26656   /* A helper function that writes a single signatured_type
26657      to a debug_names.  */
26658   void
26659   write_one_signatured_type (struct signatured_type *entry,
26660                              struct signatured_type_index_data *info)
26661   {
26662     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26663
26664     write_psymbols (info->psyms_seen,
26665                     &info->objfile->global_psymbols[psymtab->globals_offset],
26666                     psymtab->n_global_syms, info->cu_index, false,
26667                     unit_kind::tu);
26668     write_psymbols (info->psyms_seen,
26669                     &info->objfile->static_psymbols[psymtab->statics_offset],
26670                     psymtab->n_static_syms, info->cu_index, true,
26671                     unit_kind::tu);
26672
26673     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26674                                   to_underlying (entry->per_cu.sect_off));
26675
26676     ++info->cu_index;
26677   }
26678
26679   /* Store value of each symbol.  */
26680   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26681     m_name_to_value_set;
26682
26683   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26684      order.  */
26685   std::vector<uint32_t> m_bucket_table;
26686   std::vector<uint32_t> m_hash_table;
26687
26688   const bfd_endian m_dwarf5_byte_order;
26689   dwarf_tmpl<uint32_t> m_dwarf32;
26690   dwarf_tmpl<uint64_t> m_dwarf64;
26691   dwarf &m_dwarf;
26692   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26693   debug_str_lookup m_debugstrlookup;
26694
26695   /* Map each used .debug_names abbreviation tag parameter to its
26696      index value.  */
26697   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26698
26699   /* Next unused .debug_names abbreviation tag for
26700      m_indexkey_to_idx.  */
26701   int m_idx_next = 1;
26702
26703   /* .debug_names abbreviation table.  */
26704   data_buf m_abbrev_table;
26705
26706   /* .debug_names entry pool.  */
26707   data_buf m_entry_pool;
26708 };
26709
26710 /* Return iff any of the needed offsets does not fit into 32-bit
26711    .debug_names section.  */
26712
26713 static bool
26714 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26715 {
26716   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26717     {
26718       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26719
26720       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26721         return true;
26722     }
26723   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26724     {
26725       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26726       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26727
26728       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26729         return true;
26730     }
26731   return false;
26732 }
26733
26734 /* The psyms_seen set is potentially going to be largish (~40k
26735    elements when indexing a -g3 build of GDB itself).  Estimate the
26736    number of elements in order to avoid too many rehashes, which
26737    require rebuilding buckets and thus many trips to
26738    malloc/free.  */
26739
26740 static size_t
26741 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26742 {
26743   size_t psyms_count = 0;
26744   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26745     {
26746       struct dwarf2_per_cu_data *per_cu
26747         = dwarf2_per_objfile->all_comp_units[i];
26748       struct partial_symtab *psymtab = per_cu->v.psymtab;
26749
26750       if (psymtab != NULL && psymtab->user == NULL)
26751         recursively_count_psymbols (psymtab, psyms_count);
26752     }
26753   /* Generating an index for gdb itself shows a ratio of
26754      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26755   return psyms_count / 4;
26756 }
26757
26758 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26759    Return how many bytes were expected to be written into OUT_FILE.  */
26760
26761 static size_t
26762 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26763 {
26764   struct objfile *objfile = dwarf2_per_objfile->objfile;
26765   mapped_symtab symtab;
26766   data_buf cu_list;
26767
26768   /* While we're scanning CU's create a table that maps a psymtab pointer
26769      (which is what addrmap records) to its index (which is what is recorded
26770      in the index file).  This will later be needed to write the address
26771      table.  */
26772   psym_index_map cu_index_htab;
26773   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26774
26775   /* The CU list is already sorted, so we don't need to do additional
26776      work here.  Also, the debug_types entries do not appear in
26777      all_comp_units, but only in their own hash table.  */
26778
26779   std::unordered_set<partial_symbol *> psyms_seen
26780     (psyms_seen_size (dwarf2_per_objfile));
26781   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26782     {
26783       struct dwarf2_per_cu_data *per_cu
26784         = dwarf2_per_objfile->all_comp_units[i];
26785       struct partial_symtab *psymtab = per_cu->v.psymtab;
26786
26787       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26788          It may be referenced from a local scope but in such case it does not
26789          need to be present in .gdb_index.  */
26790       if (psymtab == NULL)
26791         continue;
26792
26793       if (psymtab->user == NULL)
26794         recursively_write_psymbols (objfile, psymtab, &symtab,
26795                                     psyms_seen, i);
26796
26797       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26798       gdb_assert (insertpair.second);
26799
26800       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26801                            to_underlying (per_cu->sect_off));
26802       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26803     }
26804
26805   /* Dump the address map.  */
26806   data_buf addr_vec;
26807   write_address_map (objfile, addr_vec, cu_index_htab);
26808
26809   /* Write out the .debug_type entries, if any.  */
26810   data_buf types_cu_list;
26811   if (dwarf2_per_objfile->signatured_types)
26812     {
26813       signatured_type_index_data sig_data (types_cu_list,
26814                                            psyms_seen);
26815
26816       sig_data.objfile = objfile;
26817       sig_data.symtab = &symtab;
26818       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26819       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26820                               write_one_signatured_type, &sig_data);
26821     }
26822
26823   /* Now that we've processed all symbols we can shrink their cu_indices
26824      lists.  */
26825   uniquify_cu_indices (&symtab);
26826
26827   data_buf symtab_vec, constant_pool;
26828   write_hash_table (&symtab, symtab_vec, constant_pool);
26829
26830   data_buf contents;
26831   const offset_type size_of_contents = 6 * sizeof (offset_type);
26832   offset_type total_len = size_of_contents;
26833
26834   /* The version number.  */
26835   contents.append_data (MAYBE_SWAP (8));
26836
26837   /* The offset of the CU list from the start of the file.  */
26838   contents.append_data (MAYBE_SWAP (total_len));
26839   total_len += cu_list.size ();
26840
26841   /* The offset of the types CU list from the start of the file.  */
26842   contents.append_data (MAYBE_SWAP (total_len));
26843   total_len += types_cu_list.size ();
26844
26845   /* The offset of the address table from the start of the file.  */
26846   contents.append_data (MAYBE_SWAP (total_len));
26847   total_len += addr_vec.size ();
26848
26849   /* The offset of the symbol table from the start of the file.  */
26850   contents.append_data (MAYBE_SWAP (total_len));
26851   total_len += symtab_vec.size ();
26852
26853   /* The offset of the constant pool from the start of the file.  */
26854   contents.append_data (MAYBE_SWAP (total_len));
26855   total_len += constant_pool.size ();
26856
26857   gdb_assert (contents.size () == size_of_contents);
26858
26859   contents.file_write (out_file);
26860   cu_list.file_write (out_file);
26861   types_cu_list.file_write (out_file);
26862   addr_vec.file_write (out_file);
26863   symtab_vec.file_write (out_file);
26864   constant_pool.file_write (out_file);
26865
26866   return total_len;
26867 }
26868
26869 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26870 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26871
26872 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26873    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26874    many bytes were expected to be written into OUT_FILE.  */
26875
26876 static size_t
26877 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26878                    FILE *out_file, FILE *out_file_str)
26879 {
26880   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26881   struct objfile *objfile = dwarf2_per_objfile->objfile;
26882   const enum bfd_endian dwarf5_byte_order
26883     = gdbarch_byte_order (get_objfile_arch (objfile));
26884
26885   /* The CU list is already sorted, so we don't need to do additional
26886      work here.  Also, the debug_types entries do not appear in
26887      all_comp_units, but only in their own hash table.  */
26888   data_buf cu_list;
26889   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26890                          dwarf5_byte_order);
26891   std::unordered_set<partial_symbol *>
26892     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26893   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26894     {
26895       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26896       partial_symtab *psymtab = per_cu->v.psymtab;
26897
26898       /* CU of a shared file from 'dwz -m' may be unused by this main
26899          file.  It may be referenced from a local scope but in such
26900          case it does not need to be present in .debug_names.  */
26901       if (psymtab == NULL)
26902         continue;
26903
26904       if (psymtab->user == NULL)
26905         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26906
26907       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26908                            to_underlying (per_cu->sect_off));
26909     }
26910
26911   /* Write out the .debug_type entries, if any.  */
26912   data_buf types_cu_list;
26913   if (dwarf2_per_objfile->signatured_types)
26914     {
26915       debug_names::write_one_signatured_type_data sig_data (nametable,
26916                         signatured_type_index_data (types_cu_list, psyms_seen));
26917
26918       sig_data.info.objfile = objfile;
26919       /* It is used only for gdb_index.  */
26920       sig_data.info.symtab = nullptr;
26921       sig_data.info.cu_index = 0;
26922       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26923                               debug_names::write_one_signatured_type,
26924                               &sig_data);
26925     }
26926
26927   nametable.build ();
26928
26929   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26930
26931   const offset_type bytes_of_header
26932     = ((dwarf5_is_dwarf64 ? 12 : 4)
26933        + 2 + 2 + 7 * 4
26934        + sizeof (dwarf5_gdb_augmentation));
26935   size_t expected_bytes = 0;
26936   expected_bytes += bytes_of_header;
26937   expected_bytes += cu_list.size ();
26938   expected_bytes += types_cu_list.size ();
26939   expected_bytes += nametable.bytes ();
26940   data_buf header;
26941
26942   if (!dwarf5_is_dwarf64)
26943     {
26944       const uint64_t size64 = expected_bytes - 4;
26945       gdb_assert (size64 < 0xfffffff0);
26946       header.append_uint (4, dwarf5_byte_order, size64);
26947     }
26948   else
26949     {
26950       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26951       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26952     }
26953
26954   /* The version number.  */
26955   header.append_uint (2, dwarf5_byte_order, 5);
26956
26957   /* Padding.  */
26958   header.append_uint (2, dwarf5_byte_order, 0);
26959
26960   /* comp_unit_count - The number of CUs in the CU list.  */
26961   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26962
26963   /* local_type_unit_count - The number of TUs in the local TU
26964      list.  */
26965   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26966
26967   /* foreign_type_unit_count - The number of TUs in the foreign TU
26968      list.  */
26969   header.append_uint (4, dwarf5_byte_order, 0);
26970
26971   /* bucket_count - The number of hash buckets in the hash lookup
26972      table.  */
26973   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26974
26975   /* name_count - The number of unique names in the index.  */
26976   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26977
26978   /* abbrev_table_size - The size in bytes of the abbreviations
26979      table.  */
26980   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26981
26982   /* augmentation_string_size - The size in bytes of the augmentation
26983      string.  This value is rounded up to a multiple of 4.  */
26984   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26985   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26986   header.append_data (dwarf5_gdb_augmentation);
26987
26988   gdb_assert (header.size () == bytes_of_header);
26989
26990   header.file_write (out_file);
26991   cu_list.file_write (out_file);
26992   types_cu_list.file_write (out_file);
26993   nametable.file_write (out_file, out_file_str);
26994
26995   return expected_bytes;
26996 }
26997
26998 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26999    position is at the end of the file.  */
27000
27001 static void
27002 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27003 {
27004   const auto file_size = ftell (file);
27005   if (file_size == -1)
27006     error (_("Can't get `%s' size"), filename);
27007   gdb_assert (file_size == expected_size);
27008 }
27009
27010 /* Create an index file for OBJFILE in the directory DIR.  */
27011
27012 static void
27013 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27014                          const char *dir,
27015                          dw_index_kind index_kind)
27016 {
27017   struct objfile *objfile = dwarf2_per_objfile->objfile;
27018
27019   if (dwarf2_per_objfile->using_index)
27020     error (_("Cannot use an index to create the index"));
27021
27022   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27023     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27024
27025   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27026     return;
27027
27028   struct stat st;
27029   if (stat (objfile_name (objfile), &st) < 0)
27030     perror_with_name (objfile_name (objfile));
27031
27032   std::string filename (std::string (dir) + SLASH_STRING
27033                         + lbasename (objfile_name (objfile))
27034                         + (index_kind == dw_index_kind::DEBUG_NAMES
27035                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27036
27037   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27038   if (!out_file)
27039     error (_("Can't open `%s' for writing"), filename.c_str ());
27040
27041   /* Order matters here; we want FILE to be closed before FILENAME is
27042      unlinked, because on MS-Windows one cannot delete a file that is
27043      still open.  (Don't call anything here that might throw until
27044      file_closer is created.)  */
27045   gdb::unlinker unlink_file (filename.c_str ());
27046   gdb_file_up close_out_file (out_file);
27047
27048   if (index_kind == dw_index_kind::DEBUG_NAMES)
27049     {
27050       std::string filename_str (std::string (dir) + SLASH_STRING
27051                                 + lbasename (objfile_name (objfile))
27052                                 + DEBUG_STR_SUFFIX);
27053       FILE *out_file_str
27054         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27055       if (!out_file_str)
27056         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27057       gdb::unlinker unlink_file_str (filename_str.c_str ());
27058       gdb_file_up close_out_file_str (out_file_str);
27059
27060       const size_t total_len
27061         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27062       assert_file_size (out_file, filename.c_str (), total_len);
27063
27064       /* We want to keep the file .debug_str file too.  */
27065       unlink_file_str.keep ();
27066     }
27067   else
27068     {
27069       const size_t total_len
27070         = write_gdbindex (dwarf2_per_objfile, out_file);
27071       assert_file_size (out_file, filename.c_str (), total_len);
27072     }
27073
27074   /* We want to keep the file.  */
27075   unlink_file.keep ();
27076 }
27077
27078 /* Implementation of the `save gdb-index' command.
27079    
27080    Note that the .gdb_index file format used by this command is
27081    documented in the GDB manual.  Any changes here must be documented
27082    there.  */
27083
27084 static void
27085 save_gdb_index_command (const char *arg, int from_tty)
27086 {
27087   struct objfile *objfile;
27088   const char dwarf5space[] = "-dwarf-5 ";
27089   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27090
27091   if (!arg)
27092     arg = "";
27093
27094   arg = skip_spaces (arg);
27095   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27096     {
27097       index_kind = dw_index_kind::DEBUG_NAMES;
27098       arg += strlen (dwarf5space);
27099       arg = skip_spaces (arg);
27100     }
27101
27102   if (!*arg)
27103     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27104
27105   ALL_OBJFILES (objfile)
27106   {
27107     struct stat st;
27108
27109     /* If the objfile does not correspond to an actual file, skip it.  */
27110     if (stat (objfile_name (objfile), &st) < 0)
27111       continue;
27112
27113     struct dwarf2_per_objfile *dwarf2_per_objfile
27114       = get_dwarf2_per_objfile (objfile);
27115
27116     if (dwarf2_per_objfile != NULL)
27117       {
27118         TRY
27119           {
27120             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27121           }
27122         CATCH (except, RETURN_MASK_ERROR)
27123           {
27124             exception_fprintf (gdb_stderr, except,
27125                                _("Error while writing index for `%s': "),
27126                                objfile_name (objfile));
27127           }
27128         END_CATCH
27129       }
27130
27131   }
27132 }
27133
27134 \f
27135
27136 int dwarf_always_disassemble;
27137
27138 static void
27139 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27140                                struct cmd_list_element *c, const char *value)
27141 {
27142   fprintf_filtered (file,
27143                     _("Whether to always disassemble "
27144                       "DWARF expressions is %s.\n"),
27145                     value);
27146 }
27147
27148 static void
27149 show_check_physname (struct ui_file *file, int from_tty,
27150                      struct cmd_list_element *c, const char *value)
27151 {
27152   fprintf_filtered (file,
27153                     _("Whether to check \"physname\" is %s.\n"),
27154                     value);
27155 }
27156
27157 void
27158 _initialize_dwarf2_read (void)
27159 {
27160   struct cmd_list_element *c;
27161
27162   dwarf2_objfile_data_key = register_objfile_data ();
27163
27164   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27165 Set DWARF specific variables.\n\
27166 Configure DWARF variables such as the cache size"),
27167                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27168                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27169
27170   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27171 Show DWARF specific variables\n\
27172 Show DWARF variables such as the cache size"),
27173                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27174                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27175
27176   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27177                             &dwarf_max_cache_age, _("\
27178 Set the upper bound on the age of cached DWARF compilation units."), _("\
27179 Show the upper bound on the age of cached DWARF compilation units."), _("\
27180 A higher limit means that cached compilation units will be stored\n\
27181 in memory longer, and more total memory will be used.  Zero disables\n\
27182 caching, which can slow down startup."),
27183                             NULL,
27184                             show_dwarf_max_cache_age,
27185                             &set_dwarf_cmdlist,
27186                             &show_dwarf_cmdlist);
27187
27188   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27189                            &dwarf_always_disassemble, _("\
27190 Set whether `info address' always disassembles DWARF expressions."), _("\
27191 Show whether `info address' always disassembles DWARF expressions."), _("\
27192 When enabled, DWARF expressions are always printed in an assembly-like\n\
27193 syntax.  When disabled, expressions will be printed in a more\n\
27194 conversational style, when possible."),
27195                            NULL,
27196                            show_dwarf_always_disassemble,
27197                            &set_dwarf_cmdlist,
27198                            &show_dwarf_cmdlist);
27199
27200   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27201 Set debugging of the DWARF reader."), _("\
27202 Show debugging of the DWARF reader."), _("\
27203 When enabled (non-zero), debugging messages are printed during DWARF\n\
27204 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27205 information.  A value greater than 1 provides more verbose information."),
27206                             NULL,
27207                             NULL,
27208                             &setdebuglist, &showdebuglist);
27209
27210   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27211 Set debugging of the DWARF DIE reader."), _("\
27212 Show debugging of the DWARF DIE reader."), _("\
27213 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27214 The value is the maximum depth to print."),
27215                              NULL,
27216                              NULL,
27217                              &setdebuglist, &showdebuglist);
27218
27219   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27220 Set debugging of the dwarf line reader."), _("\
27221 Show debugging of the dwarf line reader."), _("\
27222 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27223 A value of 1 (one) provides basic information.\n\
27224 A value greater than 1 provides more verbose information."),
27225                              NULL,
27226                              NULL,
27227                              &setdebuglist, &showdebuglist);
27228
27229   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27230 Set cross-checking of \"physname\" code against demangler."), _("\
27231 Show cross-checking of \"physname\" code against demangler."), _("\
27232 When enabled, GDB's internal \"physname\" code is checked against\n\
27233 the demangler."),
27234                            NULL, show_check_physname,
27235                            &setdebuglist, &showdebuglist);
27236
27237   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27238                            no_class, &use_deprecated_index_sections, _("\
27239 Set whether to use deprecated gdb_index sections."), _("\
27240 Show whether to use deprecated gdb_index sections."), _("\
27241 When enabled, deprecated .gdb_index sections are used anyway.\n\
27242 Normally they are ignored either because of a missing feature or\n\
27243 performance issue.\n\
27244 Warning: This option must be enabled before gdb reads the file."),
27245                            NULL,
27246                            NULL,
27247                            &setlist, &showlist);
27248
27249   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27250                _("\
27251 Save a gdb-index file.\n\
27252 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27253 \n\
27254 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27255 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27256 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27257                &save_cmdlist);
27258   set_cmd_completer (c, filename_completer);
27259
27260   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27261                                                         &dwarf2_locexpr_funcs);
27262   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27263                                                         &dwarf2_loclist_funcs);
27264
27265   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27266                                         &dwarf2_block_frame_base_locexpr_funcs);
27267   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27268                                         &dwarf2_block_frame_base_loclist_funcs);
27269
27270 #if GDB_SELF_TEST
27271   selftests::register_test ("dw2_expand_symtabs_matching",
27272                             selftests::dw2_expand_symtabs_matching::run_test);
27273 #endif
27274 }