]> Git Repo - binutils.git/blob - gdb/dwarf2read.c
Change map_matching_symbols to take a symbol_found_callback_ftype
[binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2019 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck ([email protected]), 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 "dwarf2read.h"
33 #include "dwarf-index-cache.h"
34 #include "dwarf-index-common.h"
35 #include "bfd.h"
36 #include "elf-bfd.h"
37 #include "symtab.h"
38 #include "gdbtypes.h"
39 #include "objfiles.h"
40 #include "dwarf2.h"
41 #include "buildsym.h"
42 #include "demangle.h"
43 #include "gdb-demangle.h"
44 #include "expression.h"
45 #include "filenames.h"  /* for DOSish file names */
46 #include "macrotab.h"
47 #include "language.h"
48 #include "complaints.h"
49 #include "dwarf2expr.h"
50 #include "dwarf2loc.h"
51 #include "cp-support.h"
52 #include "hashtab.h"
53 #include "command.h"
54 #include "gdbcmd.h"
55 #include "block.h"
56 #include "addrmap.h"
57 #include "typeprint.h"
58 #include "psympriv.h"
59 #include <sys/stat.h>
60 #include "completer.h"
61 #include "gdbsupport/vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "gdbsupport/filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "gdbsupport/gdb_unlinker.h"
75 #include "gdbsupport/function-view.h"
76 #include "gdbsupport/gdb_optional.h"
77 #include "gdbsupport/underlying.h"
78 #include "gdbsupport/byte-vector.h"
79 #include "gdbsupport/hash_enum.h"
80 #include "filename-seen-cache.h"
81 #include "producer.h"
82 #include <fcntl.h>
83 #include <sys/types.h>
84 #include <algorithm>
85 #include <unordered_set>
86 #include <unordered_map>
87 #include "gdbsupport/selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "gdbsupport/pathstuff.h"
93
94 /* When == 1, print basic high level tracing messages.
95    When > 1, be more verbose.
96    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
97 static unsigned int dwarf_read_debug = 0;
98
99 /* When non-zero, dump DIEs after they are read in.  */
100 static unsigned int dwarf_die_debug = 0;
101
102 /* When non-zero, dump line number entries as they are read in.  */
103 static unsigned int dwarf_line_debug = 0;
104
105 /* When non-zero, cross-check physname against demangler.  */
106 static int check_physname = 0;
107
108 /* When non-zero, do not reject deprecated .gdb_index sections.  */
109 static int use_deprecated_index_sections = 0;
110
111 static const struct objfile_key<dwarf2_per_objfile> dwarf2_objfile_data_key;
112
113 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
114
115 static int dwarf2_locexpr_index;
116 static int dwarf2_loclist_index;
117 static int dwarf2_locexpr_block_index;
118 static int dwarf2_loclist_block_index;
119
120 /* An index into a (C++) symbol name component in a symbol name as
121    recorded in the mapped_index's symbol table.  For each C++ symbol
122    in the symbol table, we record one entry for the start of each
123    component in the symbol in a table of name components, and then
124    sort the table, in order to be able to binary search symbol names,
125    ignoring leading namespaces, both completion and regular look up.
126    For example, for symbol "A::B::C", we'll have an entry that points
127    to "A::B::C", another that points to "B::C", and another for "C".
128    Note that function symbols in GDB index have no parameter
129    information, just the function/method names.  You can convert a
130    name_component to a "const char *" using the
131    'mapped_index::symbol_name_at(offset_type)' method.  */
132
133 struct name_component
134 {
135   /* Offset in the symbol name where the component starts.  Stored as
136      a (32-bit) offset instead of a pointer to save memory and improve
137      locality on 64-bit architectures.  */
138   offset_type name_offset;
139
140   /* The symbol's index in the symbol and constant pool tables of a
141      mapped_index.  */
142   offset_type idx;
143 };
144
145 /* Base class containing bits shared by both .gdb_index and
146    .debug_name indexes.  */
147
148 struct mapped_index_base
149 {
150   mapped_index_base () = default;
151   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
152
153   /* The name_component table (a sorted vector).  See name_component's
154      description above.  */
155   std::vector<name_component> name_components;
156
157   /* How NAME_COMPONENTS is sorted.  */
158   enum case_sensitivity name_components_casing;
159
160   /* Return the number of names in the symbol table.  */
161   virtual size_t symbol_name_count () const = 0;
162
163   /* Get the name of the symbol at IDX in the symbol table.  */
164   virtual const char *symbol_name_at (offset_type idx) const = 0;
165
166   /* Return whether the name at IDX in the symbol table should be
167      ignored.  */
168   virtual bool symbol_name_slot_invalid (offset_type idx) const
169   {
170     return false;
171   }
172
173   /* Build the symbol name component sorted vector, if we haven't
174      yet.  */
175   void build_name_components ();
176
177   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
178      possible matches for LN_NO_PARAMS in the name component
179      vector.  */
180   std::pair<std::vector<name_component>::const_iterator,
181             std::vector<name_component>::const_iterator>
182     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
183
184   /* Prevent deleting/destroying via a base class pointer.  */
185 protected:
186   ~mapped_index_base() = default;
187 };
188
189 /* A description of the mapped index.  The file format is described in
190    a comment by the code that writes the index.  */
191 struct mapped_index final : public mapped_index_base
192 {
193   /* A slot/bucket in the symbol table hash.  */
194   struct symbol_table_slot
195   {
196     const offset_type name;
197     const offset_type vec;
198   };
199
200   /* Index data format version.  */
201   int version = 0;
202
203   /* The address table data.  */
204   gdb::array_view<const gdb_byte> address_table;
205
206   /* The symbol table, implemented as a hash table.  */
207   gdb::array_view<symbol_table_slot> symbol_table;
208
209   /* A pointer to the constant pool.  */
210   const char *constant_pool = nullptr;
211
212   bool symbol_name_slot_invalid (offset_type idx) const override
213   {
214     const auto &bucket = this->symbol_table[idx];
215     return bucket.name == 0 && bucket.vec == 0;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return dwarf2_objfile_data_key.get (objfile);
285 }
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_loclists", ".zdebug_loclists" },
299   { ".debug_macinfo", ".zdebug_macinfo" },
300   { ".debug_macro", ".zdebug_macro" },
301   { ".debug_str", ".zdebug_str" },
302   { ".debug_line_str", ".zdebug_line_str" },
303   { ".debug_ranges", ".zdebug_ranges" },
304   { ".debug_rnglists", ".zdebug_rnglists" },
305   { ".debug_types", ".zdebug_types" },
306   { ".debug_addr", ".zdebug_addr" },
307   { ".debug_frame", ".zdebug_frame" },
308   { ".eh_frame", NULL },
309   { ".gdb_index", ".zgdb_index" },
310   { ".debug_names", ".zdebug_names" },
311   { ".debug_aranges", ".zdebug_aranges" },
312   23
313 };
314
315 /* List of DWO/DWP sections.  */
316
317 static const struct dwop_section_names
318 {
319   struct dwarf2_section_names abbrev_dwo;
320   struct dwarf2_section_names info_dwo;
321   struct dwarf2_section_names line_dwo;
322   struct dwarf2_section_names loc_dwo;
323   struct dwarf2_section_names loclists_dwo;
324   struct dwarf2_section_names macinfo_dwo;
325   struct dwarf2_section_names macro_dwo;
326   struct dwarf2_section_names str_dwo;
327   struct dwarf2_section_names str_offsets_dwo;
328   struct dwarf2_section_names types_dwo;
329   struct dwarf2_section_names cu_index;
330   struct dwarf2_section_names tu_index;
331 }
332 dwop_section_names =
333 {
334   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
335   { ".debug_info.dwo", ".zdebug_info.dwo" },
336   { ".debug_line.dwo", ".zdebug_line.dwo" },
337   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
338   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
339   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
340   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
341   { ".debug_str.dwo", ".zdebug_str.dwo" },
342   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
343   { ".debug_types.dwo", ".zdebug_types.dwo" },
344   { ".debug_cu_index", ".zdebug_cu_index" },
345   { ".debug_tu_index", ".zdebug_tu_index" },
346 };
347
348 /* local data types */
349
350 /* The data in a compilation unit header, after target2host
351    translation, looks like this.  */
352 struct comp_unit_head
353 {
354   unsigned int length;
355   short version;
356   unsigned char addr_size;
357   unsigned char signed_addr_p;
358   sect_offset abbrev_sect_off;
359
360   /* Size of file offsets; either 4 or 8.  */
361   unsigned int offset_size;
362
363   /* Size of the length field; either 4 or 12.  */
364   unsigned int initial_length_size;
365
366   enum dwarf_unit_type unit_type;
367
368   /* Offset to the first byte of this compilation unit header in the
369      .debug_info section, for resolving relative reference dies.  */
370   sect_offset sect_off;
371
372   /* Offset to first die in this cu from the start of the cu.
373      This will be the first byte following the compilation unit header.  */
374   cu_offset first_die_cu_offset;
375
376
377   /* 64-bit signature of this unit. For type units, it denotes the signature of
378      the type (DW_UT_type in DWARF 4, additionally DW_UT_split_type in DWARF 5).
379      Also used in DWARF 5, to denote the dwo id when the unit type is
380      DW_UT_skeleton or DW_UT_split_compile.  */
381   ULONGEST signature;
382
383   /* For types, offset in the type's DIE of the type defined by this TU.  */
384   cu_offset type_cu_offset_in_tu;
385 };
386
387 /* Type used for delaying computation of method physnames.
388    See comments for compute_delayed_physnames.  */
389 struct delayed_method_info
390 {
391   /* The type to which the method is attached, i.e., its parent class.  */
392   struct type *type;
393
394   /* The index of the method in the type's function fieldlists.  */
395   int fnfield_index;
396
397   /* The index of the method in the fieldlist.  */
398   int index;
399
400   /* The name of the DIE.  */
401   const char *name;
402
403   /*  The DIE associated with this method.  */
404   struct die_info *die;
405 };
406
407 /* Internal state when decoding a particular compilation unit.  */
408 struct dwarf2_cu
409 {
410   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
411   ~dwarf2_cu ();
412
413   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
414
415   /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
416      Create the set of symtabs used by this TU, or if this TU is sharing
417      symtabs with another TU and the symtabs have already been created
418      then restore those symtabs in the line header.
419      We don't need the pc/line-number mapping for type units.  */
420   void setup_type_unit_groups (struct die_info *die);
421
422   /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
423      buildsym_compunit constructor.  */
424   struct compunit_symtab *start_symtab (const char *name,
425                                         const char *comp_dir,
426                                         CORE_ADDR low_pc);
427
428   /* Reset the builder.  */
429   void reset_builder () { m_builder.reset (); }
430
431   /* The header of the compilation unit.  */
432   struct comp_unit_head header {};
433
434   /* Base address of this compilation unit.  */
435   CORE_ADDR base_address = 0;
436
437   /* Non-zero if base_address has been set.  */
438   int base_known = 0;
439
440   /* The language we are debugging.  */
441   enum language language = language_unknown;
442   const struct language_defn *language_defn = nullptr;
443
444   const char *producer = nullptr;
445
446 private:
447   /* The symtab builder for this CU.  This is only non-NULL when full
448      symbols are being read.  */
449   std::unique_ptr<buildsym_compunit> m_builder;
450
451 public:
452   /* The generic symbol table building routines have separate lists for
453      file scope symbols and all all other scopes (local scopes).  So
454      we need to select the right one to pass to add_symbol_to_list().
455      We do it by keeping a pointer to the correct list in list_in_scope.
456
457      FIXME: The original dwarf code just treated the file scope as the
458      first local scope, and all other local scopes as nested local
459      scopes, and worked fine.  Check to see if we really need to
460      distinguish these in buildsym.c.  */
461   struct pending **list_in_scope = nullptr;
462
463   /* Hash table holding all the loaded partial DIEs
464      with partial_die->offset.SECT_OFF as hash.  */
465   htab_t partial_dies = nullptr;
466
467   /* Storage for things with the same lifetime as this read-in compilation
468      unit, including partial DIEs.  */
469   auto_obstack comp_unit_obstack;
470
471   /* When multiple dwarf2_cu structures are living in memory, this field
472      chains them all together, so that they can be released efficiently.
473      We will probably also want a generation counter so that most-recently-used
474      compilation units are cached...  */
475   struct dwarf2_per_cu_data *read_in_chain = nullptr;
476
477   /* Backlink to our per_cu entry.  */
478   struct dwarf2_per_cu_data *per_cu;
479
480   /* How many compilation units ago was this CU last referenced?  */
481   int last_used = 0;
482
483   /* A hash table of DIE cu_offset for following references with
484      die_info->offset.sect_off as hash.  */
485   htab_t die_hash = nullptr;
486
487   /* Full DIEs if read in.  */
488   struct die_info *dies = nullptr;
489
490   /* A set of pointers to dwarf2_per_cu_data objects for compilation
491      units referenced by this one.  Only set during full symbol processing;
492      partial symbol tables do not have dependencies.  */
493   htab_t dependencies = nullptr;
494
495   /* Header data from the line table, during full symbol processing.  */
496   struct line_header *line_header = nullptr;
497   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
498      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
499      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
500      to the line header as long as this DIE is being processed.  See
501      process_die_scope.  */
502   die_info *line_header_die_owner = nullptr;
503
504   /* A list of methods which need to have physnames computed
505      after all type information has been read.  */
506   std::vector<delayed_method_info> method_list;
507
508   /* To be copied to symtab->call_site_htab.  */
509   htab_t call_site_htab = nullptr;
510
511   /* Non-NULL if this CU came from a DWO file.
512      There is an invariant here that is important to remember:
513      Except for attributes copied from the top level DIE in the "main"
514      (or "stub") file in preparation for reading the DWO file
515      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
516      Either there isn't a DWO file (in which case this is NULL and the point
517      is moot), or there is and either we're not going to read it (in which
518      case this is NULL) or there is and we are reading it (in which case this
519      is non-NULL).  */
520   struct dwo_unit *dwo_unit = nullptr;
521
522   /* The DW_AT_addr_base attribute if present, zero otherwise
523      (zero is a valid value though).
524      Note this value comes from the Fission stub CU/TU's DIE.  */
525   ULONGEST addr_base = 0;
526
527   /* The DW_AT_ranges_base attribute if present, zero otherwise
528      (zero is a valid value though).
529      Note this value comes from the Fission stub CU/TU's DIE.
530      Also note that the value is zero in the non-DWO case so this value can
531      be used without needing to know whether DWO files are in use or not.
532      N.B. This does not apply to DW_AT_ranges appearing in
533      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
534      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
535      DW_AT_ranges_base *would* have to be applied, and we'd have to care
536      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
537   ULONGEST ranges_base = 0;
538
539   /* When reading debug info generated by older versions of rustc, we
540      have to rewrite some union types to be struct types with a
541      variant part.  This rewriting must be done after the CU is fully
542      read in, because otherwise at the point of rewriting some struct
543      type might not have been fully processed.  So, we keep a list of
544      all such types here and process them after expansion.  */
545   std::vector<struct type *> rust_unions;
546
547   /* Mark used when releasing cached dies.  */
548   bool mark : 1;
549
550   /* This CU references .debug_loc.  See the symtab->locations_valid field.
551      This test is imperfect as there may exist optimized debug code not using
552      any location list and still facing inlining issues if handled as
553      unoptimized code.  For a future better test see GCC PR other/32998.  */
554   bool has_loclist : 1;
555
556   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
557      if all the producer_is_* fields are valid.  This information is cached
558      because profiling CU expansion showed excessive time spent in
559      producer_is_gxx_lt_4_6.  */
560   bool checked_producer : 1;
561   bool producer_is_gxx_lt_4_6 : 1;
562   bool producer_is_gcc_lt_4_3 : 1;
563   bool producer_is_icc : 1;
564   bool producer_is_icc_lt_14 : 1;
565   bool producer_is_codewarrior : 1;
566
567   /* When true, the file that we're processing is known to have
568      debugging info for C++ namespaces.  GCC 3.3.x did not produce
569      this information, but later versions do.  */
570
571   bool processing_has_namespace_info : 1;
572
573   struct partial_die_info *find_partial_die (sect_offset sect_off);
574
575   /* If this CU was inherited by another CU (via specification,
576      abstract_origin, etc), this is the ancestor CU.  */
577   dwarf2_cu *ancestor;
578
579   /* Get the buildsym_compunit for this CU.  */
580   buildsym_compunit *get_builder ()
581   {
582     /* If this CU has a builder associated with it, use that.  */
583     if (m_builder != nullptr)
584       return m_builder.get ();
585
586     /* Otherwise, search ancestors for a valid builder.  */
587     if (ancestor != nullptr)
588       return ancestor->get_builder ();
589
590     return nullptr;
591   }
592 };
593
594 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
595    This includes type_unit_group and quick_file_names.  */
596
597 struct stmt_list_hash
598 {
599   /* The DWO unit this table is from or NULL if there is none.  */
600   struct dwo_unit *dwo_unit;
601
602   /* Offset in .debug_line or .debug_line.dwo.  */
603   sect_offset line_sect_off;
604 };
605
606 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
607    an object of this type.  */
608
609 struct type_unit_group
610 {
611   /* dwarf2read.c's main "handle" on a TU symtab.
612      To simplify things we create an artificial CU that "includes" all the
613      type units using this stmt_list so that the rest of the code still has
614      a "per_cu" handle on the symtab.
615      This PER_CU is recognized by having no section.  */
616 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
617   struct dwarf2_per_cu_data per_cu;
618
619   /* The TUs that share this DW_AT_stmt_list entry.
620      This is added to while parsing type units to build partial symtabs,
621      and is deleted afterwards and not used again.  */
622   VEC (sig_type_ptr) *tus;
623
624   /* The compunit symtab.
625      Type units in a group needn't all be defined in the same source file,
626      so we create an essentially anonymous symtab as the compunit symtab.  */
627   struct compunit_symtab *compunit_symtab;
628
629   /* The data used to construct the hash key.  */
630   struct stmt_list_hash hash;
631
632   /* The number of symtabs from the line header.
633      The value here must match line_header.num_file_names.  */
634   unsigned int num_symtabs;
635
636   /* The symbol tables for this TU (obtained from the files listed in
637      DW_AT_stmt_list).
638      WARNING: The order of entries here must match the order of entries
639      in the line header.  After the first TU using this type_unit_group, the
640      line header for the subsequent TUs is recreated from this.  This is done
641      because we need to use the same symtabs for each TU using the same
642      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
643      there's no guarantee the line header doesn't have duplicate entries.  */
644   struct symtab **symtabs;
645 };
646
647 /* These sections are what may appear in a (real or virtual) DWO file.  */
648
649 struct dwo_sections
650 {
651   struct dwarf2_section_info abbrev;
652   struct dwarf2_section_info line;
653   struct dwarf2_section_info loc;
654   struct dwarf2_section_info loclists;
655   struct dwarf2_section_info macinfo;
656   struct dwarf2_section_info macro;
657   struct dwarf2_section_info str;
658   struct dwarf2_section_info str_offsets;
659   /* In the case of a virtual DWO file, these two are unused.  */
660   struct dwarf2_section_info info;
661   std::vector<dwarf2_section_info> types;
662 };
663
664 /* CUs/TUs in DWP/DWO files.  */
665
666 struct dwo_unit
667 {
668   /* Backlink to the containing struct dwo_file.  */
669   struct dwo_file *dwo_file;
670
671   /* The "id" that distinguishes this CU/TU.
672      .debug_info calls this "dwo_id", .debug_types calls this "signature".
673      Since signatures came first, we stick with it for consistency.  */
674   ULONGEST signature;
675
676   /* The section this CU/TU lives in, in the DWO file.  */
677   struct dwarf2_section_info *section;
678
679   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
680   sect_offset sect_off;
681   unsigned int length;
682
683   /* For types, offset in the type's DIE of the type defined by this TU.  */
684   cu_offset type_offset_in_tu;
685 };
686
687 /* include/dwarf2.h defines the DWP section codes.
688    It defines a max value but it doesn't define a min value, which we
689    use for error checking, so provide one.  */
690
691 enum dwp_v2_section_ids
692 {
693   DW_SECT_MIN = 1
694 };
695
696 /* Data for one DWO file.
697
698    This includes virtual DWO files (a virtual DWO file is a DWO file as it
699    appears in a DWP file).  DWP files don't really have DWO files per se -
700    comdat folding of types "loses" the DWO file they came from, and from
701    a high level view DWP files appear to contain a mass of random types.
702    However, to maintain consistency with the non-DWP case we pretend DWP
703    files contain virtual DWO files, and we assign each TU with one virtual
704    DWO file (generally based on the line and abbrev section offsets -
705    a heuristic that seems to work in practice).  */
706
707 struct dwo_file
708 {
709   dwo_file () = default;
710   DISABLE_COPY_AND_ASSIGN (dwo_file);
711
712   /* The DW_AT_GNU_dwo_name attribute.
713      For virtual DWO files the name is constructed from the section offsets
714      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
715      from related CU+TUs.  */
716   const char *dwo_name = nullptr;
717
718   /* The DW_AT_comp_dir attribute.  */
719   const char *comp_dir = nullptr;
720
721   /* The bfd, when the file is open.  Otherwise this is NULL.
722      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
723   gdb_bfd_ref_ptr dbfd;
724
725   /* The sections that make up this DWO file.
726      Remember that for virtual DWO files in DWP V2, these are virtual
727      sections (for lack of a better name).  */
728   struct dwo_sections sections {};
729
730   /* The CUs in the file.
731      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
732      an extension to handle LLVM's Link Time Optimization output (where
733      multiple source files may be compiled into a single object/dwo pair). */
734   htab_t cus {};
735
736   /* Table of TUs in the file.
737      Each element is a struct dwo_unit.  */
738   htab_t tus {};
739 };
740
741 /* These sections are what may appear in a DWP file.  */
742
743 struct dwp_sections
744 {
745   /* These are used by both DWP version 1 and 2.  */
746   struct dwarf2_section_info str;
747   struct dwarf2_section_info cu_index;
748   struct dwarf2_section_info tu_index;
749
750   /* These are only used by DWP version 2 files.
751      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
752      sections are referenced by section number, and are not recorded here.
753      In DWP version 2 there is at most one copy of all these sections, each
754      section being (effectively) comprised of the concatenation of all of the
755      individual sections that exist in the version 1 format.
756      To keep the code simple we treat each of these concatenated pieces as a
757      section itself (a virtual section?).  */
758   struct dwarf2_section_info abbrev;
759   struct dwarf2_section_info info;
760   struct dwarf2_section_info line;
761   struct dwarf2_section_info loc;
762   struct dwarf2_section_info macinfo;
763   struct dwarf2_section_info macro;
764   struct dwarf2_section_info str_offsets;
765   struct dwarf2_section_info types;
766 };
767
768 /* These sections are what may appear in a virtual DWO file in DWP version 1.
769    A virtual DWO file is a DWO file as it appears in a DWP file.  */
770
771 struct virtual_v1_dwo_sections
772 {
773   struct dwarf2_section_info abbrev;
774   struct dwarf2_section_info line;
775   struct dwarf2_section_info loc;
776   struct dwarf2_section_info macinfo;
777   struct dwarf2_section_info macro;
778   struct dwarf2_section_info str_offsets;
779   /* Each DWP hash table entry records one CU or one TU.
780      That is recorded here, and copied to dwo_unit.section.  */
781   struct dwarf2_section_info info_or_types;
782 };
783
784 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
785    In version 2, the sections of the DWO files are concatenated together
786    and stored in one section of that name.  Thus each ELF section contains
787    several "virtual" sections.  */
788
789 struct virtual_v2_dwo_sections
790 {
791   bfd_size_type abbrev_offset;
792   bfd_size_type abbrev_size;
793
794   bfd_size_type line_offset;
795   bfd_size_type line_size;
796
797   bfd_size_type loc_offset;
798   bfd_size_type loc_size;
799
800   bfd_size_type macinfo_offset;
801   bfd_size_type macinfo_size;
802
803   bfd_size_type macro_offset;
804   bfd_size_type macro_size;
805
806   bfd_size_type str_offsets_offset;
807   bfd_size_type str_offsets_size;
808
809   /* Each DWP hash table entry records one CU or one TU.
810      That is recorded here, and copied to dwo_unit.section.  */
811   bfd_size_type info_or_types_offset;
812   bfd_size_type info_or_types_size;
813 };
814
815 /* Contents of DWP hash tables.  */
816
817 struct dwp_hash_table
818 {
819   uint32_t version, nr_columns;
820   uint32_t nr_units, nr_slots;
821   const gdb_byte *hash_table, *unit_table;
822   union
823   {
824     struct
825     {
826       const gdb_byte *indices;
827     } v1;
828     struct
829     {
830       /* This is indexed by column number and gives the id of the section
831          in that column.  */
832 #define MAX_NR_V2_DWO_SECTIONS \
833   (1 /* .debug_info or .debug_types */ \
834    + 1 /* .debug_abbrev */ \
835    + 1 /* .debug_line */ \
836    + 1 /* .debug_loc */ \
837    + 1 /* .debug_str_offsets */ \
838    + 1 /* .debug_macro or .debug_macinfo */)
839       int section_ids[MAX_NR_V2_DWO_SECTIONS];
840       const gdb_byte *offsets;
841       const gdb_byte *sizes;
842     } v2;
843   } section_pool;
844 };
845
846 /* Data for one DWP file.  */
847
848 struct dwp_file
849 {
850   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
851     : name (name_),
852       dbfd (std::move (abfd))
853   {
854   }
855
856   /* Name of the file.  */
857   const char *name;
858
859   /* File format version.  */
860   int version = 0;
861
862   /* The bfd.  */
863   gdb_bfd_ref_ptr dbfd;
864
865   /* Section info for this file.  */
866   struct dwp_sections sections {};
867
868   /* Table of CUs in the file.  */
869   const struct dwp_hash_table *cus = nullptr;
870
871   /* Table of TUs in the file.  */
872   const struct dwp_hash_table *tus = nullptr;
873
874   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
875   htab_t loaded_cus {};
876   htab_t loaded_tus {};
877
878   /* Table to map ELF section numbers to their sections.
879      This is only needed for the DWP V1 file format.  */
880   unsigned int num_sections = 0;
881   asection **elf_sections = nullptr;
882 };
883
884 /* Struct used to pass misc. parameters to read_die_and_children, et
885    al.  which are used for both .debug_info and .debug_types dies.
886    All parameters here are unchanging for the life of the call.  This
887    struct exists to abstract away the constant parameters of die reading.  */
888
889 struct die_reader_specs
890 {
891   /* The bfd of die_section.  */
892   bfd* abfd;
893
894   /* The CU of the DIE we are parsing.  */
895   struct dwarf2_cu *cu;
896
897   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
898   struct dwo_file *dwo_file;
899
900   /* The section the die comes from.
901      This is either .debug_info or .debug_types, or the .dwo variants.  */
902   struct dwarf2_section_info *die_section;
903
904   /* die_section->buffer.  */
905   const gdb_byte *buffer;
906
907   /* The end of the buffer.  */
908   const gdb_byte *buffer_end;
909
910   /* The value of the DW_AT_comp_dir attribute.  */
911   const char *comp_dir;
912
913   /* The abbreviation table to use when reading the DIEs.  */
914   struct abbrev_table *abbrev_table;
915 };
916
917 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
918 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
919                                       const gdb_byte *info_ptr,
920                                       struct die_info *comp_unit_die,
921                                       int has_children,
922                                       void *data);
923
924 /* A 1-based directory index.  This is a strong typedef to prevent
925    accidentally using a directory index as a 0-based index into an
926    array/vector.  */
927 enum class dir_index : unsigned int {};
928
929 /* Likewise, a 1-based file name index.  */
930 enum class file_name_index : unsigned int {};
931
932 struct file_entry
933 {
934   file_entry () = default;
935
936   file_entry (const char *name_, dir_index d_index_,
937               unsigned int mod_time_, unsigned int length_)
938     : name (name_),
939       d_index (d_index_),
940       mod_time (mod_time_),
941       length (length_)
942   {}
943
944   /* Return the include directory at D_INDEX stored in LH.  Returns
945      NULL if D_INDEX is out of bounds.  */
946   const char *include_dir (const line_header *lh) const;
947
948   /* The file name.  Note this is an observing pointer.  The memory is
949      owned by debug_line_buffer.  */
950   const char *name {};
951
952   /* The directory index (1-based).  */
953   dir_index d_index {};
954
955   unsigned int mod_time {};
956
957   unsigned int length {};
958
959   /* True if referenced by the Line Number Program.  */
960   bool included_p {};
961
962   /* The associated symbol table, if any.  */
963   struct symtab *symtab {};
964 };
965
966 /* The line number information for a compilation unit (found in the
967    .debug_line section) begins with a "statement program header",
968    which contains the following information.  */
969 struct line_header
970 {
971   line_header ()
972     : offset_in_dwz {}
973   {}
974
975   /* Add an entry to the include directory table.  */
976   void add_include_dir (const char *include_dir);
977
978   /* Add an entry to the file name table.  */
979   void add_file_name (const char *name, dir_index d_index,
980                       unsigned int mod_time, unsigned int length);
981
982   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
983      is out of bounds.  */
984   const char *include_dir_at (dir_index index) const
985   {
986     /* Convert directory index number (1-based) to vector index
987        (0-based).  */
988     size_t vec_index = to_underlying (index) - 1;
989
990     if (vec_index >= include_dirs.size ())
991       return NULL;
992     return include_dirs[vec_index];
993   }
994
995   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
996      is out of bounds.  */
997   file_entry *file_name_at (file_name_index index)
998   {
999     /* Convert file name index number (1-based) to vector index
1000        (0-based).  */
1001     size_t vec_index = to_underlying (index) - 1;
1002
1003     if (vec_index >= file_names.size ())
1004       return NULL;
1005     return &file_names[vec_index];
1006   }
1007
1008   /* Offset of line number information in .debug_line section.  */
1009   sect_offset sect_off {};
1010
1011   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1012   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1013
1014   unsigned int total_length {};
1015   unsigned short version {};
1016   unsigned int header_length {};
1017   unsigned char minimum_instruction_length {};
1018   unsigned char maximum_ops_per_instruction {};
1019   unsigned char default_is_stmt {};
1020   int line_base {};
1021   unsigned char line_range {};
1022   unsigned char opcode_base {};
1023
1024   /* standard_opcode_lengths[i] is the number of operands for the
1025      standard opcode whose value is i.  This means that
1026      standard_opcode_lengths[0] is unused, and the last meaningful
1027      element is standard_opcode_lengths[opcode_base - 1].  */
1028   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1029
1030   /* The include_directories table.  Note these are observing
1031      pointers.  The memory is owned by debug_line_buffer.  */
1032   std::vector<const char *> include_dirs;
1033
1034   /* The file_names table.  */
1035   std::vector<file_entry> file_names;
1036
1037   /* The start and end of the statement program following this
1038      header.  These point into dwarf2_per_objfile->line_buffer.  */
1039   const gdb_byte *statement_program_start {}, *statement_program_end {};
1040 };
1041
1042 typedef std::unique_ptr<line_header> line_header_up;
1043
1044 const char *
1045 file_entry::include_dir (const line_header *lh) const
1046 {
1047   return lh->include_dir_at (d_index);
1048 }
1049
1050 /* When we construct a partial symbol table entry we only
1051    need this much information.  */
1052 struct partial_die_info : public allocate_on_obstack
1053   {
1054     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1055
1056     /* Disable assign but still keep copy ctor, which is needed
1057        load_partial_dies.   */
1058     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1059
1060     /* Adjust the partial die before generating a symbol for it.  This
1061        function may set the is_external flag or change the DIE's
1062        name.  */
1063     void fixup (struct dwarf2_cu *cu);
1064
1065     /* Read a minimal amount of information into the minimal die
1066        structure.  */
1067     const gdb_byte *read (const struct die_reader_specs *reader,
1068                           const struct abbrev_info &abbrev,
1069                           const gdb_byte *info_ptr);
1070
1071     /* Offset of this DIE.  */
1072     const sect_offset sect_off;
1073
1074     /* DWARF-2 tag for this DIE.  */
1075     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1076
1077     /* Assorted flags describing the data found in this DIE.  */
1078     const unsigned int has_children : 1;
1079
1080     unsigned int is_external : 1;
1081     unsigned int is_declaration : 1;
1082     unsigned int has_type : 1;
1083     unsigned int has_specification : 1;
1084     unsigned int has_pc_info : 1;
1085     unsigned int may_be_inlined : 1;
1086
1087     /* This DIE has been marked DW_AT_main_subprogram.  */
1088     unsigned int main_subprogram : 1;
1089
1090     /* Flag set if the SCOPE field of this structure has been
1091        computed.  */
1092     unsigned int scope_set : 1;
1093
1094     /* Flag set if the DIE has a byte_size attribute.  */
1095     unsigned int has_byte_size : 1;
1096
1097     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1098     unsigned int has_const_value : 1;
1099
1100     /* Flag set if any of the DIE's children are template arguments.  */
1101     unsigned int has_template_arguments : 1;
1102
1103     /* Flag set if fixup has been called on this die.  */
1104     unsigned int fixup_called : 1;
1105
1106     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1107     unsigned int is_dwz : 1;
1108
1109     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1110     unsigned int spec_is_dwz : 1;
1111
1112     /* The name of this DIE.  Normally the value of DW_AT_name, but
1113        sometimes a default name for unnamed DIEs.  */
1114     const char *name = nullptr;
1115
1116     /* The linkage name, if present.  */
1117     const char *linkage_name = nullptr;
1118
1119     /* The scope to prepend to our children.  This is generally
1120        allocated on the comp_unit_obstack, so will disappear
1121        when this compilation unit leaves the cache.  */
1122     const char *scope = nullptr;
1123
1124     /* Some data associated with the partial DIE.  The tag determines
1125        which field is live.  */
1126     union
1127     {
1128       /* The location description associated with this DIE, if any.  */
1129       struct dwarf_block *locdesc;
1130       /* The offset of an import, for DW_TAG_imported_unit.  */
1131       sect_offset sect_off;
1132     } d {};
1133
1134     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1135     CORE_ADDR lowpc = 0;
1136     CORE_ADDR highpc = 0;
1137
1138     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1139        DW_AT_sibling, if any.  */
1140     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1141        could return DW_AT_sibling values to its caller load_partial_dies.  */
1142     const gdb_byte *sibling = nullptr;
1143
1144     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1145        DW_AT_specification (or DW_AT_abstract_origin or
1146        DW_AT_extension).  */
1147     sect_offset spec_offset {};
1148
1149     /* Pointers to this DIE's parent, first child, and next sibling,
1150        if any.  */
1151     struct partial_die_info *die_parent = nullptr;
1152     struct partial_die_info *die_child = nullptr;
1153     struct partial_die_info *die_sibling = nullptr;
1154
1155     friend struct partial_die_info *
1156     dwarf2_cu::find_partial_die (sect_offset sect_off);
1157
1158   private:
1159     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1160     partial_die_info (sect_offset sect_off)
1161       : partial_die_info (sect_off, DW_TAG_padding, 0)
1162     {
1163     }
1164
1165     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1166                       int has_children_)
1167       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1168     {
1169       is_external = 0;
1170       is_declaration = 0;
1171       has_type = 0;
1172       has_specification = 0;
1173       has_pc_info = 0;
1174       may_be_inlined = 0;
1175       main_subprogram = 0;
1176       scope_set = 0;
1177       has_byte_size = 0;
1178       has_const_value = 0;
1179       has_template_arguments = 0;
1180       fixup_called = 0;
1181       is_dwz = 0;
1182       spec_is_dwz = 0;
1183     }
1184   };
1185
1186 /* This data structure holds the information of an abbrev.  */
1187 struct abbrev_info
1188   {
1189     unsigned int number;        /* number identifying abbrev */
1190     enum dwarf_tag tag;         /* dwarf tag */
1191     unsigned short has_children;                /* boolean */
1192     unsigned short num_attrs;   /* number of attributes */
1193     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1194     struct abbrev_info *next;   /* next in chain */
1195   };
1196
1197 struct attr_abbrev
1198   {
1199     ENUM_BITFIELD(dwarf_attribute) name : 16;
1200     ENUM_BITFIELD(dwarf_form) form : 16;
1201
1202     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1203     LONGEST implicit_const;
1204   };
1205
1206 /* Size of abbrev_table.abbrev_hash_table.  */
1207 #define ABBREV_HASH_SIZE 121
1208
1209 /* Top level data structure to contain an abbreviation table.  */
1210
1211 struct abbrev_table
1212 {
1213   explicit abbrev_table (sect_offset off)
1214     : sect_off (off)
1215   {
1216     m_abbrevs =
1217       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1218     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1219   }
1220
1221   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1222
1223   /* Allocate space for a struct abbrev_info object in
1224      ABBREV_TABLE.  */
1225   struct abbrev_info *alloc_abbrev ();
1226
1227   /* Add an abbreviation to the table.  */
1228   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1229
1230   /* Look up an abbrev in the table.
1231      Returns NULL if the abbrev is not found.  */
1232
1233   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1234
1235
1236   /* Where the abbrev table came from.
1237      This is used as a sanity check when the table is used.  */
1238   const sect_offset sect_off;
1239
1240   /* Storage for the abbrev table.  */
1241   auto_obstack abbrev_obstack;
1242
1243 private:
1244
1245   /* Hash table of abbrevs.
1246      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1247      It could be statically allocated, but the previous code didn't so we
1248      don't either.  */
1249   struct abbrev_info **m_abbrevs;
1250 };
1251
1252 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1253
1254 /* Attributes have a name and a value.  */
1255 struct attribute
1256   {
1257     ENUM_BITFIELD(dwarf_attribute) name : 16;
1258     ENUM_BITFIELD(dwarf_form) form : 15;
1259
1260     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1261        field should be in u.str (existing only for DW_STRING) but it is kept
1262        here for better struct attribute alignment.  */
1263     unsigned int string_is_canonical : 1;
1264
1265     union
1266       {
1267         const char *str;
1268         struct dwarf_block *blk;
1269         ULONGEST unsnd;
1270         LONGEST snd;
1271         CORE_ADDR addr;
1272         ULONGEST signature;
1273       }
1274     u;
1275   };
1276
1277 /* This data structure holds a complete die structure.  */
1278 struct die_info
1279   {
1280     /* DWARF-2 tag for this DIE.  */
1281     ENUM_BITFIELD(dwarf_tag) tag : 16;
1282
1283     /* Number of attributes */
1284     unsigned char num_attrs;
1285
1286     /* True if we're presently building the full type name for the
1287        type derived from this DIE.  */
1288     unsigned char building_fullname : 1;
1289
1290     /* True if this die is in process.  PR 16581.  */
1291     unsigned char in_process : 1;
1292
1293     /* Abbrev number */
1294     unsigned int abbrev;
1295
1296     /* Offset in .debug_info or .debug_types section.  */
1297     sect_offset sect_off;
1298
1299     /* The dies in a compilation unit form an n-ary tree.  PARENT
1300        points to this die's parent; CHILD points to the first child of
1301        this node; and all the children of a given node are chained
1302        together via their SIBLING fields.  */
1303     struct die_info *child;     /* Its first child, if any.  */
1304     struct die_info *sibling;   /* Its next sibling, if any.  */
1305     struct die_info *parent;    /* Its parent, if any.  */
1306
1307     /* An array of attributes, with NUM_ATTRS elements.  There may be
1308        zero, but it's not common and zero-sized arrays are not
1309        sufficiently portable C.  */
1310     struct attribute attrs[1];
1311   };
1312
1313 /* Get at parts of an attribute structure.  */
1314
1315 #define DW_STRING(attr)    ((attr)->u.str)
1316 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1317 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1318 #define DW_BLOCK(attr)     ((attr)->u.blk)
1319 #define DW_SND(attr)       ((attr)->u.snd)
1320 #define DW_ADDR(attr)      ((attr)->u.addr)
1321 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1322
1323 /* Blocks are a bunch of untyped bytes.  */
1324 struct dwarf_block
1325   {
1326     size_t size;
1327
1328     /* Valid only if SIZE is not zero.  */
1329     const gdb_byte *data;
1330   };
1331
1332 #ifndef ATTR_ALLOC_CHUNK
1333 #define ATTR_ALLOC_CHUNK 4
1334 #endif
1335
1336 /* Allocate fields for structs, unions and enums in this size.  */
1337 #ifndef DW_FIELD_ALLOC_CHUNK
1338 #define DW_FIELD_ALLOC_CHUNK 4
1339 #endif
1340
1341 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1342    but this would require a corresponding change in unpack_field_as_long
1343    and friends.  */
1344 static int bits_per_byte = 8;
1345
1346 /* When reading a variant or variant part, we track a bit more
1347    information about the field, and store it in an object of this
1348    type.  */
1349
1350 struct variant_field
1351 {
1352   /* If we see a DW_TAG_variant, then this will be the discriminant
1353      value.  */
1354   ULONGEST discriminant_value;
1355   /* If we see a DW_TAG_variant, then this will be set if this is the
1356      default branch.  */
1357   bool default_branch;
1358   /* While reading a DW_TAG_variant_part, this will be set if this
1359      field is the discriminant.  */
1360   bool is_discriminant;
1361 };
1362
1363 struct nextfield
1364 {
1365   int accessibility = 0;
1366   int virtuality = 0;
1367   /* Extra information to describe a variant or variant part.  */
1368   struct variant_field variant {};
1369   struct field field {};
1370 };
1371
1372 struct fnfieldlist
1373 {
1374   const char *name = nullptr;
1375   std::vector<struct fn_field> fnfields;
1376 };
1377
1378 /* The routines that read and process dies for a C struct or C++ class
1379    pass lists of data member fields and lists of member function fields
1380    in an instance of a field_info structure, as defined below.  */
1381 struct field_info
1382   {
1383     /* List of data member and baseclasses fields.  */
1384     std::vector<struct nextfield> fields;
1385     std::vector<struct nextfield> baseclasses;
1386
1387     /* Number of fields (including baseclasses).  */
1388     int nfields = 0;
1389
1390     /* Set if the accesibility of one of the fields is not public.  */
1391     int non_public_fields = 0;
1392
1393     /* Member function fieldlist array, contains name of possibly overloaded
1394        member function, number of overloaded member functions and a pointer
1395        to the head of the member function field chain.  */
1396     std::vector<struct fnfieldlist> fnfieldlists;
1397
1398     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1399        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1400     std::vector<struct decl_field> typedef_field_list;
1401
1402     /* Nested types defined by this class and the number of elements in this
1403        list.  */
1404     std::vector<struct decl_field> nested_types_list;
1405   };
1406
1407 /* One item on the queue of compilation units to read in full symbols
1408    for.  */
1409 struct dwarf2_queue_item
1410 {
1411   struct dwarf2_per_cu_data *per_cu;
1412   enum language pretend_language;
1413   struct dwarf2_queue_item *next;
1414 };
1415
1416 /* The current queue.  */
1417 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1418
1419 /* Loaded secondary compilation units are kept in memory until they
1420    have not been referenced for the processing of this many
1421    compilation units.  Set this to zero to disable caching.  Cache
1422    sizes of up to at least twenty will improve startup time for
1423    typical inter-CU-reference binaries, at an obvious memory cost.  */
1424 static int dwarf_max_cache_age = 5;
1425 static void
1426 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1427                           struct cmd_list_element *c, const char *value)
1428 {
1429   fprintf_filtered (file, _("The upper bound on the age of cached "
1430                             "DWARF compilation units is %s.\n"),
1431                     value);
1432 }
1433 \f
1434 /* local function prototypes */
1435
1436 static const char *get_section_name (const struct dwarf2_section_info *);
1437
1438 static const char *get_section_file_name (const struct dwarf2_section_info *);
1439
1440 static void dwarf2_find_base_address (struct die_info *die,
1441                                       struct dwarf2_cu *cu);
1442
1443 static struct partial_symtab *create_partial_symtab
1444   (struct dwarf2_per_cu_data *per_cu, const char *name);
1445
1446 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1447                                         const gdb_byte *info_ptr,
1448                                         struct die_info *type_unit_die,
1449                                         int has_children, void *data);
1450
1451 static void dwarf2_build_psymtabs_hard
1452   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1453
1454 static void scan_partial_symbols (struct partial_die_info *,
1455                                   CORE_ADDR *, CORE_ADDR *,
1456                                   int, struct dwarf2_cu *);
1457
1458 static void add_partial_symbol (struct partial_die_info *,
1459                                 struct dwarf2_cu *);
1460
1461 static void add_partial_namespace (struct partial_die_info *pdi,
1462                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1463                                    int set_addrmap, struct dwarf2_cu *cu);
1464
1465 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1466                                 CORE_ADDR *highpc, int set_addrmap,
1467                                 struct dwarf2_cu *cu);
1468
1469 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1470                                      struct dwarf2_cu *cu);
1471
1472 static void add_partial_subprogram (struct partial_die_info *pdi,
1473                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1474                                     int need_pc, struct dwarf2_cu *cu);
1475
1476 static void dwarf2_read_symtab (struct partial_symtab *,
1477                                 struct objfile *);
1478
1479 static void psymtab_to_symtab_1 (struct partial_symtab *);
1480
1481 static abbrev_table_up abbrev_table_read_table
1482   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1483    sect_offset);
1484
1485 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1486
1487 static struct partial_die_info *load_partial_dies
1488   (const struct die_reader_specs *, const gdb_byte *, int);
1489
1490 /* A pair of partial_die_info and compilation unit.  */
1491 struct cu_partial_die_info
1492 {
1493   /* The compilation unit of the partial_die_info.  */
1494   struct dwarf2_cu *cu;
1495   /* A partial_die_info.  */
1496   struct partial_die_info *pdi;
1497
1498   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1499     : cu (cu),
1500       pdi (pdi)
1501   { /* Nothhing.  */ }
1502
1503 private:
1504   cu_partial_die_info () = delete;
1505 };
1506
1507 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1508                                                           struct dwarf2_cu *);
1509
1510 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1511                                        struct attribute *, struct attr_abbrev *,
1512                                        const gdb_byte *);
1513
1514 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1515
1516 static int read_1_signed_byte (bfd *, const gdb_byte *);
1517
1518 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1519
1520 /* Read the next three bytes (little-endian order) as an unsigned integer.  */
1521 static unsigned int read_3_bytes (bfd *, const gdb_byte *);
1522
1523 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1524
1525 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1526
1527 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1528                                unsigned int *);
1529
1530 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1531
1532 static LONGEST read_checked_initial_length_and_offset
1533   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1534    unsigned int *, unsigned int *);
1535
1536 static LONGEST read_offset (bfd *, const gdb_byte *,
1537                             const struct comp_unit_head *,
1538                             unsigned int *);
1539
1540 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1541
1542 static sect_offset read_abbrev_offset
1543   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1544    struct dwarf2_section_info *, sect_offset);
1545
1546 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1547
1548 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1549
1550 static const char *read_indirect_string
1551   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1552    const struct comp_unit_head *, unsigned int *);
1553
1554 static const char *read_indirect_line_string
1555   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1556    const struct comp_unit_head *, unsigned int *);
1557
1558 static const char *read_indirect_string_at_offset
1559   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1560    LONGEST str_offset);
1561
1562 static const char *read_indirect_string_from_dwz
1563   (struct objfile *objfile, struct dwz_file *, LONGEST);
1564
1565 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1566
1567 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1568                                               const gdb_byte *,
1569                                               unsigned int *);
1570
1571 static const char *read_str_index (const struct die_reader_specs *reader,
1572                                    ULONGEST str_index);
1573
1574 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1575
1576 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1577                                       struct dwarf2_cu *);
1578
1579 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1580                                                 unsigned int);
1581
1582 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1583                                        struct dwarf2_cu *cu);
1584
1585 static const char *dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu);
1586
1587 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1588                                struct dwarf2_cu *cu);
1589
1590 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1591
1592 static struct die_info *die_specification (struct die_info *die,
1593                                            struct dwarf2_cu **);
1594
1595 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1596                                                 struct dwarf2_cu *cu);
1597
1598 static void dwarf_decode_lines (struct line_header *, const char *,
1599                                 struct dwarf2_cu *, struct partial_symtab *,
1600                                 CORE_ADDR, int decode_mapping);
1601
1602 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1603                                   const char *);
1604
1605 static struct symbol *new_symbol (struct die_info *, struct type *,
1606                                   struct dwarf2_cu *, struct symbol * = NULL);
1607
1608 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1609                                 struct dwarf2_cu *);
1610
1611 static void dwarf2_const_value_attr (const struct attribute *attr,
1612                                      struct type *type,
1613                                      const char *name,
1614                                      struct obstack *obstack,
1615                                      struct dwarf2_cu *cu, LONGEST *value,
1616                                      const gdb_byte **bytes,
1617                                      struct dwarf2_locexpr_baton **baton);
1618
1619 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1620
1621 static int need_gnat_info (struct dwarf2_cu *);
1622
1623 static struct type *die_descriptive_type (struct die_info *,
1624                                           struct dwarf2_cu *);
1625
1626 static void set_descriptive_type (struct type *, struct die_info *,
1627                                   struct dwarf2_cu *);
1628
1629 static struct type *die_containing_type (struct die_info *,
1630                                          struct dwarf2_cu *);
1631
1632 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1633                                      struct dwarf2_cu *);
1634
1635 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1636
1637 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1638
1639 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1640
1641 static char *typename_concat (struct obstack *obs, const char *prefix,
1642                               const char *suffix, int physname,
1643                               struct dwarf2_cu *cu);
1644
1645 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1646
1647 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1648
1649 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1650
1651 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1652
1653 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1654
1655 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1656
1657 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1658                                struct dwarf2_cu *, struct partial_symtab *);
1659
1660 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1661    values.  Keep the items ordered with increasing constraints compliance.  */
1662 enum pc_bounds_kind
1663 {
1664   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1665   PC_BOUNDS_NOT_PRESENT,
1666
1667   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1668      were present but they do not form a valid range of PC addresses.  */
1669   PC_BOUNDS_INVALID,
1670
1671   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1672   PC_BOUNDS_RANGES,
1673
1674   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1675   PC_BOUNDS_HIGH_LOW,
1676 };
1677
1678 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1679                                                  CORE_ADDR *, CORE_ADDR *,
1680                                                  struct dwarf2_cu *,
1681                                                  struct partial_symtab *);
1682
1683 static void get_scope_pc_bounds (struct die_info *,
1684                                  CORE_ADDR *, CORE_ADDR *,
1685                                  struct dwarf2_cu *);
1686
1687 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1688                                         CORE_ADDR, struct dwarf2_cu *);
1689
1690 static void dwarf2_add_field (struct field_info *, struct die_info *,
1691                               struct dwarf2_cu *);
1692
1693 static void dwarf2_attach_fields_to_type (struct field_info *,
1694                                           struct type *, struct dwarf2_cu *);
1695
1696 static void dwarf2_add_member_fn (struct field_info *,
1697                                   struct die_info *, struct type *,
1698                                   struct dwarf2_cu *);
1699
1700 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1701                                              struct type *,
1702                                              struct dwarf2_cu *);
1703
1704 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1705
1706 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1707
1708 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1709
1710 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1711
1712 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1713
1714 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1715
1716 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1717
1718 static struct type *read_module_type (struct die_info *die,
1719                                       struct dwarf2_cu *cu);
1720
1721 static const char *namespace_name (struct die_info *die,
1722                                    int *is_anonymous, struct dwarf2_cu *);
1723
1724 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1725
1726 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1727
1728 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1729                                                        struct dwarf2_cu *);
1730
1731 static struct die_info *read_die_and_siblings_1
1732   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1733    struct die_info *);
1734
1735 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1736                                                const gdb_byte *info_ptr,
1737                                                const gdb_byte **new_info_ptr,
1738                                                struct die_info *parent);
1739
1740 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1741                                         struct die_info **, const gdb_byte *,
1742                                         int *, int);
1743
1744 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1745                                       struct die_info **, const gdb_byte *,
1746                                       int *);
1747
1748 static void process_die (struct die_info *, struct dwarf2_cu *);
1749
1750 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1751                                              struct obstack *);
1752
1753 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1754
1755 static const char *dwarf2_full_name (const char *name,
1756                                      struct die_info *die,
1757                                      struct dwarf2_cu *cu);
1758
1759 static const char *dwarf2_physname (const char *name, struct die_info *die,
1760                                     struct dwarf2_cu *cu);
1761
1762 static struct die_info *dwarf2_extension (struct die_info *die,
1763                                           struct dwarf2_cu **);
1764
1765 static const char *dwarf_tag_name (unsigned int);
1766
1767 static const char *dwarf_attr_name (unsigned int);
1768
1769 static const char *dwarf_unit_type_name (int unit_type);
1770
1771 static const char *dwarf_form_name (unsigned int);
1772
1773 static const char *dwarf_bool_name (unsigned int);
1774
1775 static const char *dwarf_type_encoding_name (unsigned int);
1776
1777 static struct die_info *sibling_die (struct die_info *);
1778
1779 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1780
1781 static void dump_die_for_error (struct die_info *);
1782
1783 static void dump_die_1 (struct ui_file *, int level, int max_level,
1784                         struct die_info *);
1785
1786 /*static*/ void dump_die (struct die_info *, int max_level);
1787
1788 static void store_in_ref_table (struct die_info *,
1789                                 struct dwarf2_cu *);
1790
1791 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1792
1793 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1794
1795 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1796                                                const struct attribute *,
1797                                                struct dwarf2_cu **);
1798
1799 static struct die_info *follow_die_ref (struct die_info *,
1800                                         const struct attribute *,
1801                                         struct dwarf2_cu **);
1802
1803 static struct die_info *follow_die_sig (struct die_info *,
1804                                         const struct attribute *,
1805                                         struct dwarf2_cu **);
1806
1807 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1808                                          struct dwarf2_cu *);
1809
1810 static struct type *get_DW_AT_signature_type (struct die_info *,
1811                                               const struct attribute *,
1812                                               struct dwarf2_cu *);
1813
1814 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1815
1816 static void read_signatured_type (struct signatured_type *);
1817
1818 static int attr_to_dynamic_prop (const struct attribute *attr,
1819                                  struct die_info *die, struct dwarf2_cu *cu,
1820                                  struct dynamic_prop *prop, struct type *type);
1821
1822 /* memory allocation interface */
1823
1824 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1825
1826 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1827
1828 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1829
1830 static int attr_form_is_block (const struct attribute *);
1831
1832 static int attr_form_is_section_offset (const struct attribute *);
1833
1834 static int attr_form_is_constant (const struct attribute *);
1835
1836 static int attr_form_is_ref (const struct attribute *);
1837
1838 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1839                                    struct dwarf2_loclist_baton *baton,
1840                                    const struct attribute *attr);
1841
1842 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1843                                          struct symbol *sym,
1844                                          struct dwarf2_cu *cu,
1845                                          int is_block);
1846
1847 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1848                                      const gdb_byte *info_ptr,
1849                                      struct abbrev_info *abbrev);
1850
1851 static hashval_t partial_die_hash (const void *item);
1852
1853 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1854
1855 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1856   (sect_offset sect_off, unsigned int offset_in_dwz,
1857    struct dwarf2_per_objfile *dwarf2_per_objfile);
1858
1859 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1860                                    struct die_info *comp_unit_die,
1861                                    enum language pretend_language);
1862
1863 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1864
1865 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1866
1867 static struct type *set_die_type (struct die_info *, struct type *,
1868                                   struct dwarf2_cu *);
1869
1870 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1871
1872 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1873
1874 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1875                                  enum language);
1876
1877 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1878                                     enum language);
1879
1880 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1881                                     enum language);
1882
1883 static void dwarf2_add_dependence (struct dwarf2_cu *,
1884                                    struct dwarf2_per_cu_data *);
1885
1886 static void dwarf2_mark (struct dwarf2_cu *);
1887
1888 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1889
1890 static struct type *get_die_type_at_offset (sect_offset,
1891                                             struct dwarf2_per_cu_data *);
1892
1893 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1894
1895 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1896                              enum language pretend_language);
1897
1898 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1899
1900 static struct type *dwarf2_per_cu_addr_type (struct dwarf2_per_cu_data *per_cu);
1901 static struct type *dwarf2_per_cu_addr_sized_int_type
1902         (struct dwarf2_per_cu_data *per_cu, bool unsigned_p);
1903
1904 /* Class, the destructor of which frees all allocated queue entries.  This
1905    will only have work to do if an error was thrown while processing the
1906    dwarf.  If no error was thrown then the queue entries should have all
1907    been processed, and freed, as we went along.  */
1908
1909 class dwarf2_queue_guard
1910 {
1911 public:
1912   dwarf2_queue_guard () = default;
1913
1914   /* Free any entries remaining on the queue.  There should only be
1915      entries left if we hit an error while processing the dwarf.  */
1916   ~dwarf2_queue_guard ()
1917   {
1918     struct dwarf2_queue_item *item, *last;
1919
1920     item = dwarf2_queue;
1921     while (item)
1922       {
1923         /* Anything still marked queued is likely to be in an
1924            inconsistent state, so discard it.  */
1925         if (item->per_cu->queued)
1926           {
1927             if (item->per_cu->cu != NULL)
1928               free_one_cached_comp_unit (item->per_cu);
1929             item->per_cu->queued = 0;
1930           }
1931
1932         last = item;
1933         item = item->next;
1934         xfree (last);
1935       }
1936
1937     dwarf2_queue = dwarf2_queue_tail = NULL;
1938   }
1939 };
1940
1941 /* The return type of find_file_and_directory.  Note, the enclosed
1942    string pointers are only valid while this object is valid.  */
1943
1944 struct file_and_directory
1945 {
1946   /* The filename.  This is never NULL.  */
1947   const char *name;
1948
1949   /* The compilation directory.  NULL if not known.  If we needed to
1950      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1951      points directly to the DW_AT_comp_dir string attribute owned by
1952      the obstack that owns the DIE.  */
1953   const char *comp_dir;
1954
1955   /* If we needed to build a new string for comp_dir, this is what
1956      owns the storage.  */
1957   std::string comp_dir_storage;
1958 };
1959
1960 static file_and_directory find_file_and_directory (struct die_info *die,
1961                                                    struct dwarf2_cu *cu);
1962
1963 static char *file_full_name (int file, struct line_header *lh,
1964                              const char *comp_dir);
1965
1966 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1967 enum class rcuh_kind { COMPILE, TYPE };
1968
1969 static const gdb_byte *read_and_check_comp_unit_head
1970   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1971    struct comp_unit_head *header,
1972    struct dwarf2_section_info *section,
1973    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1974    rcuh_kind section_kind);
1975
1976 static void init_cutu_and_read_dies
1977   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1978    int use_existing_cu, int keep, bool skip_partial,
1979    die_reader_func_ftype *die_reader_func, void *data);
1980
1981 static void init_cutu_and_read_dies_simple
1982   (struct dwarf2_per_cu_data *this_cu,
1983    die_reader_func_ftype *die_reader_func, void *data);
1984
1985 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1986
1987 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1988
1989 static struct dwo_unit *lookup_dwo_unit_in_dwp
1990   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1991    struct dwp_file *dwp_file, const char *comp_dir,
1992    ULONGEST signature, int is_debug_types);
1993
1994 static struct dwp_file *get_dwp_file
1995   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1996
1997 static struct dwo_unit *lookup_dwo_comp_unit
1998   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1999
2000 static struct dwo_unit *lookup_dwo_type_unit
2001   (struct signatured_type *, const char *, const char *);
2002
2003 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2004
2005 /* A unique pointer to a dwo_file.  */
2006
2007 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
2008
2009 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2010
2011 static void check_producer (struct dwarf2_cu *cu);
2012
2013 static void free_line_header_voidp (void *arg);
2014 \f
2015 /* Various complaints about symbol reading that don't abort the process.  */
2016
2017 static void
2018 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2019 {
2020   complaint (_("statement list doesn't fit in .debug_line section"));
2021 }
2022
2023 static void
2024 dwarf2_debug_line_missing_file_complaint (void)
2025 {
2026   complaint (_(".debug_line section has line data without a file"));
2027 }
2028
2029 static void
2030 dwarf2_debug_line_missing_end_sequence_complaint (void)
2031 {
2032   complaint (_(".debug_line section has line "
2033                "program sequence without an end"));
2034 }
2035
2036 static void
2037 dwarf2_complex_location_expr_complaint (void)
2038 {
2039   complaint (_("location expression too complex"));
2040 }
2041
2042 static void
2043 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2044                                               int arg3)
2045 {
2046   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2047              arg1, arg2, arg3);
2048 }
2049
2050 static void
2051 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2052 {
2053   complaint (_("debug info runs off end of %s section"
2054                " [in module %s]"),
2055              get_section_name (section),
2056              get_section_file_name (section));
2057 }
2058
2059 static void
2060 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2061 {
2062   complaint (_("macro debug info contains a "
2063                "malformed macro definition:\n`%s'"),
2064              arg1);
2065 }
2066
2067 static void
2068 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2069 {
2070   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2071              arg1, arg2);
2072 }
2073
2074 /* Hash function for line_header_hash.  */
2075
2076 static hashval_t
2077 line_header_hash (const struct line_header *ofs)
2078 {
2079   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2080 }
2081
2082 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2083
2084 static hashval_t
2085 line_header_hash_voidp (const void *item)
2086 {
2087   const struct line_header *ofs = (const struct line_header *) item;
2088
2089   return line_header_hash (ofs);
2090 }
2091
2092 /* Equality function for line_header_hash.  */
2093
2094 static int
2095 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2096 {
2097   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2098   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2099
2100   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2101           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2102 }
2103
2104 \f
2105
2106 /* Read the given attribute value as an address, taking the attribute's
2107    form into account.  */
2108
2109 static CORE_ADDR
2110 attr_value_as_address (struct attribute *attr)
2111 {
2112   CORE_ADDR addr;
2113
2114   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_addrx
2115       && attr->form != DW_FORM_GNU_addr_index)
2116     {
2117       /* Aside from a few clearly defined exceptions, attributes that
2118          contain an address must always be in DW_FORM_addr form.
2119          Unfortunately, some compilers happen to be violating this
2120          requirement by encoding addresses using other forms, such
2121          as DW_FORM_data4 for example.  For those broken compilers,
2122          we try to do our best, without any guarantee of success,
2123          to interpret the address correctly.  It would also be nice
2124          to generate a complaint, but that would require us to maintain
2125          a list of legitimate cases where a non-address form is allowed,
2126          as well as update callers to pass in at least the CU's DWARF
2127          version.  This is more overhead than what we're willing to
2128          expand for a pretty rare case.  */
2129       addr = DW_UNSND (attr);
2130     }
2131   else
2132     addr = DW_ADDR (attr);
2133
2134   return addr;
2135 }
2136
2137 /* See declaration.  */
2138
2139 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2140                                         const dwarf2_debug_sections *names)
2141   : objfile (objfile_)
2142 {
2143   if (names == NULL)
2144     names = &dwarf2_elf_names;
2145
2146   bfd *obfd = objfile->obfd;
2147
2148   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2149     locate_sections (obfd, sec, *names);
2150 }
2151
2152 dwarf2_per_objfile::~dwarf2_per_objfile ()
2153 {
2154   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2155   free_cached_comp_units ();
2156
2157   if (quick_file_names_table)
2158     htab_delete (quick_file_names_table);
2159
2160   if (line_header_hash)
2161     htab_delete (line_header_hash);
2162
2163   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2164     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2165
2166   for (signatured_type *sig_type : all_type_units)
2167     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2168
2169   /* Everything else should be on the objfile obstack.  */
2170 }
2171
2172 /* See declaration.  */
2173
2174 void
2175 dwarf2_per_objfile::free_cached_comp_units ()
2176 {
2177   dwarf2_per_cu_data *per_cu = read_in_chain;
2178   dwarf2_per_cu_data **last_chain = &read_in_chain;
2179   while (per_cu != NULL)
2180     {
2181       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2182
2183       delete per_cu->cu;
2184       *last_chain = next_cu;
2185       per_cu = next_cu;
2186     }
2187 }
2188
2189 /* A helper class that calls free_cached_comp_units on
2190    destruction.  */
2191
2192 class free_cached_comp_units
2193 {
2194 public:
2195
2196   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2197     : m_per_objfile (per_objfile)
2198   {
2199   }
2200
2201   ~free_cached_comp_units ()
2202   {
2203     m_per_objfile->free_cached_comp_units ();
2204   }
2205
2206   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2207
2208 private:
2209
2210   dwarf2_per_objfile *m_per_objfile;
2211 };
2212
2213 /* Try to locate the sections we need for DWARF 2 debugging
2214    information and return true if we have enough to do something.
2215    NAMES points to the dwarf2 section names, or is NULL if the standard
2216    ELF names are used.  */
2217
2218 int
2219 dwarf2_has_info (struct objfile *objfile,
2220                  const struct dwarf2_debug_sections *names)
2221 {
2222   if (objfile->flags & OBJF_READNEVER)
2223     return 0;
2224
2225   struct dwarf2_per_objfile *dwarf2_per_objfile
2226     = get_dwarf2_per_objfile (objfile);
2227
2228   if (dwarf2_per_objfile == NULL)
2229     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
2230                                                           names);
2231
2232   return (!dwarf2_per_objfile->info.is_virtual
2233           && dwarf2_per_objfile->info.s.section != NULL
2234           && !dwarf2_per_objfile->abbrev.is_virtual
2235           && dwarf2_per_objfile->abbrev.s.section != NULL);
2236 }
2237
2238 /* Return the containing section of virtual section SECTION.  */
2239
2240 static struct dwarf2_section_info *
2241 get_containing_section (const struct dwarf2_section_info *section)
2242 {
2243   gdb_assert (section->is_virtual);
2244   return section->s.containing_section;
2245 }
2246
2247 /* Return the bfd owner of SECTION.  */
2248
2249 static struct bfd *
2250 get_section_bfd_owner (const struct dwarf2_section_info *section)
2251 {
2252   if (section->is_virtual)
2253     {
2254       section = get_containing_section (section);
2255       gdb_assert (!section->is_virtual);
2256     }
2257   return section->s.section->owner;
2258 }
2259
2260 /* Return the bfd section of SECTION.
2261    Returns NULL if the section is not present.  */
2262
2263 static asection *
2264 get_section_bfd_section (const struct dwarf2_section_info *section)
2265 {
2266   if (section->is_virtual)
2267     {
2268       section = get_containing_section (section);
2269       gdb_assert (!section->is_virtual);
2270     }
2271   return section->s.section;
2272 }
2273
2274 /* Return the name of SECTION.  */
2275
2276 static const char *
2277 get_section_name (const struct dwarf2_section_info *section)
2278 {
2279   asection *sectp = get_section_bfd_section (section);
2280
2281   gdb_assert (sectp != NULL);
2282   return bfd_section_name (get_section_bfd_owner (section), sectp);
2283 }
2284
2285 /* Return the name of the file SECTION is in.  */
2286
2287 static const char *
2288 get_section_file_name (const struct dwarf2_section_info *section)
2289 {
2290   bfd *abfd = get_section_bfd_owner (section);
2291
2292   return bfd_get_filename (abfd);
2293 }
2294
2295 /* Return the id of SECTION.
2296    Returns 0 if SECTION doesn't exist.  */
2297
2298 static int
2299 get_section_id (const struct dwarf2_section_info *section)
2300 {
2301   asection *sectp = get_section_bfd_section (section);
2302
2303   if (sectp == NULL)
2304     return 0;
2305   return sectp->id;
2306 }
2307
2308 /* Return the flags of SECTION.
2309    SECTION (or containing section if this is a virtual section) must exist.  */
2310
2311 static int
2312 get_section_flags (const struct dwarf2_section_info *section)
2313 {
2314   asection *sectp = get_section_bfd_section (section);
2315
2316   gdb_assert (sectp != NULL);
2317   return bfd_get_section_flags (sectp->owner, sectp);
2318 }
2319
2320 /* When loading sections, we look either for uncompressed section or for
2321    compressed section names.  */
2322
2323 static int
2324 section_is_p (const char *section_name,
2325               const struct dwarf2_section_names *names)
2326 {
2327   if (names->normal != NULL
2328       && strcmp (section_name, names->normal) == 0)
2329     return 1;
2330   if (names->compressed != NULL
2331       && strcmp (section_name, names->compressed) == 0)
2332     return 1;
2333   return 0;
2334 }
2335
2336 /* See declaration.  */
2337
2338 void
2339 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2340                                      const dwarf2_debug_sections &names)
2341 {
2342   flagword aflag = bfd_get_section_flags (abfd, sectp);
2343
2344   if ((aflag & SEC_HAS_CONTENTS) == 0)
2345     {
2346     }
2347   else if (section_is_p (sectp->name, &names.info))
2348     {
2349       this->info.s.section = sectp;
2350       this->info.size = bfd_get_section_size (sectp);
2351     }
2352   else if (section_is_p (sectp->name, &names.abbrev))
2353     {
2354       this->abbrev.s.section = sectp;
2355       this->abbrev.size = bfd_get_section_size (sectp);
2356     }
2357   else if (section_is_p (sectp->name, &names.line))
2358     {
2359       this->line.s.section = sectp;
2360       this->line.size = bfd_get_section_size (sectp);
2361     }
2362   else if (section_is_p (sectp->name, &names.loc))
2363     {
2364       this->loc.s.section = sectp;
2365       this->loc.size = bfd_get_section_size (sectp);
2366     }
2367   else if (section_is_p (sectp->name, &names.loclists))
2368     {
2369       this->loclists.s.section = sectp;
2370       this->loclists.size = bfd_get_section_size (sectp);
2371     }
2372   else if (section_is_p (sectp->name, &names.macinfo))
2373     {
2374       this->macinfo.s.section = sectp;
2375       this->macinfo.size = bfd_get_section_size (sectp);
2376     }
2377   else if (section_is_p (sectp->name, &names.macro))
2378     {
2379       this->macro.s.section = sectp;
2380       this->macro.size = bfd_get_section_size (sectp);
2381     }
2382   else if (section_is_p (sectp->name, &names.str))
2383     {
2384       this->str.s.section = sectp;
2385       this->str.size = bfd_get_section_size (sectp);
2386     }
2387   else if (section_is_p (sectp->name, &names.line_str))
2388     {
2389       this->line_str.s.section = sectp;
2390       this->line_str.size = bfd_get_section_size (sectp);
2391     }
2392   else if (section_is_p (sectp->name, &names.addr))
2393     {
2394       this->addr.s.section = sectp;
2395       this->addr.size = bfd_get_section_size (sectp);
2396     }
2397   else if (section_is_p (sectp->name, &names.frame))
2398     {
2399       this->frame.s.section = sectp;
2400       this->frame.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.eh_frame))
2403     {
2404       this->eh_frame.s.section = sectp;
2405       this->eh_frame.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.ranges))
2408     {
2409       this->ranges.s.section = sectp;
2410       this->ranges.size = bfd_get_section_size (sectp);
2411     }
2412   else if (section_is_p (sectp->name, &names.rnglists))
2413     {
2414       this->rnglists.s.section = sectp;
2415       this->rnglists.size = bfd_get_section_size (sectp);
2416     }
2417   else if (section_is_p (sectp->name, &names.types))
2418     {
2419       struct dwarf2_section_info type_section;
2420
2421       memset (&type_section, 0, sizeof (type_section));
2422       type_section.s.section = sectp;
2423       type_section.size = bfd_get_section_size (sectp);
2424
2425       this->types.push_back (type_section);
2426     }
2427   else if (section_is_p (sectp->name, &names.gdb_index))
2428     {
2429       this->gdb_index.s.section = sectp;
2430       this->gdb_index.size = bfd_get_section_size (sectp);
2431     }
2432   else if (section_is_p (sectp->name, &names.debug_names))
2433     {
2434       this->debug_names.s.section = sectp;
2435       this->debug_names.size = bfd_get_section_size (sectp);
2436     }
2437   else if (section_is_p (sectp->name, &names.debug_aranges))
2438     {
2439       this->debug_aranges.s.section = sectp;
2440       this->debug_aranges.size = bfd_get_section_size (sectp);
2441     }
2442
2443   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2444       && bfd_section_vma (abfd, sectp) == 0)
2445     this->has_section_at_zero = true;
2446 }
2447
2448 /* A helper function that decides whether a section is empty,
2449    or not present.  */
2450
2451 static int
2452 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2453 {
2454   if (section->is_virtual)
2455     return section->size == 0;
2456   return section->s.section == NULL || section->size == 0;
2457 }
2458
2459 /* See dwarf2read.h.  */
2460
2461 void
2462 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2463 {
2464   asection *sectp;
2465   bfd *abfd;
2466   gdb_byte *buf, *retbuf;
2467
2468   if (info->readin)
2469     return;
2470   info->buffer = NULL;
2471   info->readin = true;
2472
2473   if (dwarf2_section_empty_p (info))
2474     return;
2475
2476   sectp = get_section_bfd_section (info);
2477
2478   /* If this is a virtual section we need to read in the real one first.  */
2479   if (info->is_virtual)
2480     {
2481       struct dwarf2_section_info *containing_section =
2482         get_containing_section (info);
2483
2484       gdb_assert (sectp != NULL);
2485       if ((sectp->flags & SEC_RELOC) != 0)
2486         {
2487           error (_("Dwarf Error: DWP format V2 with relocations is not"
2488                    " supported in section %s [in module %s]"),
2489                  get_section_name (info), get_section_file_name (info));
2490         }
2491       dwarf2_read_section (objfile, containing_section);
2492       /* Other code should have already caught virtual sections that don't
2493          fit.  */
2494       gdb_assert (info->virtual_offset + info->size
2495                   <= containing_section->size);
2496       /* If the real section is empty or there was a problem reading the
2497          section we shouldn't get here.  */
2498       gdb_assert (containing_section->buffer != NULL);
2499       info->buffer = containing_section->buffer + info->virtual_offset;
2500       return;
2501     }
2502
2503   /* If the section has relocations, we must read it ourselves.
2504      Otherwise we attach it to the BFD.  */
2505   if ((sectp->flags & SEC_RELOC) == 0)
2506     {
2507       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2508       return;
2509     }
2510
2511   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2512   info->buffer = buf;
2513
2514   /* When debugging .o files, we may need to apply relocations; see
2515      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2516      We never compress sections in .o files, so we only need to
2517      try this when the section is not compressed.  */
2518   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2519   if (retbuf != NULL)
2520     {
2521       info->buffer = retbuf;
2522       return;
2523     }
2524
2525   abfd = get_section_bfd_owner (info);
2526   gdb_assert (abfd != NULL);
2527
2528   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2529       || bfd_bread (buf, info->size, abfd) != info->size)
2530     {
2531       error (_("Dwarf Error: Can't read DWARF data"
2532                " in section %s [in module %s]"),
2533              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2534     }
2535 }
2536
2537 /* A helper function that returns the size of a section in a safe way.
2538    If you are positive that the section has been read before using the
2539    size, then it is safe to refer to the dwarf2_section_info object's
2540    "size" field directly.  In other cases, you must call this
2541    function, because for compressed sections the size field is not set
2542    correctly until the section has been read.  */
2543
2544 static bfd_size_type
2545 dwarf2_section_size (struct objfile *objfile,
2546                      struct dwarf2_section_info *info)
2547 {
2548   if (!info->readin)
2549     dwarf2_read_section (objfile, info);
2550   return info->size;
2551 }
2552
2553 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2554    SECTION_NAME.  */
2555
2556 void
2557 dwarf2_get_section_info (struct objfile *objfile,
2558                          enum dwarf2_section_enum sect,
2559                          asection **sectp, const gdb_byte **bufp,
2560                          bfd_size_type *sizep)
2561 {
2562   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2563   struct dwarf2_section_info *info;
2564
2565   /* We may see an objfile without any DWARF, in which case we just
2566      return nothing.  */
2567   if (data == NULL)
2568     {
2569       *sectp = NULL;
2570       *bufp = NULL;
2571       *sizep = 0;
2572       return;
2573     }
2574   switch (sect)
2575     {
2576     case DWARF2_DEBUG_FRAME:
2577       info = &data->frame;
2578       break;
2579     case DWARF2_EH_FRAME:
2580       info = &data->eh_frame;
2581       break;
2582     default:
2583       gdb_assert_not_reached ("unexpected section");
2584     }
2585
2586   dwarf2_read_section (objfile, info);
2587
2588   *sectp = get_section_bfd_section (info);
2589   *bufp = info->buffer;
2590   *sizep = info->size;
2591 }
2592
2593 /* A helper function to find the sections for a .dwz file.  */
2594
2595 static void
2596 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2597 {
2598   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2599
2600   /* Note that we only support the standard ELF names, because .dwz
2601      is ELF-only (at the time of writing).  */
2602   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2603     {
2604       dwz_file->abbrev.s.section = sectp;
2605       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2606     }
2607   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2608     {
2609       dwz_file->info.s.section = sectp;
2610       dwz_file->info.size = bfd_get_section_size (sectp);
2611     }
2612   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2613     {
2614       dwz_file->str.s.section = sectp;
2615       dwz_file->str.size = bfd_get_section_size (sectp);
2616     }
2617   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2618     {
2619       dwz_file->line.s.section = sectp;
2620       dwz_file->line.size = bfd_get_section_size (sectp);
2621     }
2622   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2623     {
2624       dwz_file->macro.s.section = sectp;
2625       dwz_file->macro.size = bfd_get_section_size (sectp);
2626     }
2627   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2628     {
2629       dwz_file->gdb_index.s.section = sectp;
2630       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2631     }
2632   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2633     {
2634       dwz_file->debug_names.s.section = sectp;
2635       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2636     }
2637 }
2638
2639 /* See dwarf2read.h.  */
2640
2641 struct dwz_file *
2642 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2643 {
2644   const char *filename;
2645   bfd_size_type buildid_len_arg;
2646   size_t buildid_len;
2647   bfd_byte *buildid;
2648
2649   if (dwarf2_per_objfile->dwz_file != NULL)
2650     return dwarf2_per_objfile->dwz_file.get ();
2651
2652   bfd_set_error (bfd_error_no_error);
2653   gdb::unique_xmalloc_ptr<char> data
2654     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2655                                   &buildid_len_arg, &buildid));
2656   if (data == NULL)
2657     {
2658       if (bfd_get_error () == bfd_error_no_error)
2659         return NULL;
2660       error (_("could not read '.gnu_debugaltlink' section: %s"),
2661              bfd_errmsg (bfd_get_error ()));
2662     }
2663
2664   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2665
2666   buildid_len = (size_t) buildid_len_arg;
2667
2668   filename = data.get ();
2669
2670   std::string abs_storage;
2671   if (!IS_ABSOLUTE_PATH (filename))
2672     {
2673       gdb::unique_xmalloc_ptr<char> abs
2674         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2675
2676       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2677       filename = abs_storage.c_str ();
2678     }
2679
2680   /* First try the file name given in the section.  If that doesn't
2681      work, try to use the build-id instead.  */
2682   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2683   if (dwz_bfd != NULL)
2684     {
2685       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2686         dwz_bfd.reset (nullptr);
2687     }
2688
2689   if (dwz_bfd == NULL)
2690     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2691
2692   if (dwz_bfd == NULL)
2693     error (_("could not find '.gnu_debugaltlink' file for %s"),
2694            objfile_name (dwarf2_per_objfile->objfile));
2695
2696   std::unique_ptr<struct dwz_file> result
2697     (new struct dwz_file (std::move (dwz_bfd)));
2698
2699   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2700                          result.get ());
2701
2702   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2703                             result->dwz_bfd.get ());
2704   dwarf2_per_objfile->dwz_file = std::move (result);
2705   return dwarf2_per_objfile->dwz_file.get ();
2706 }
2707 \f
2708 /* DWARF quick_symbols_functions support.  */
2709
2710 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2711    unique line tables, so we maintain a separate table of all .debug_line
2712    derived entries to support the sharing.
2713    All the quick functions need is the list of file names.  We discard the
2714    line_header when we're done and don't need to record it here.  */
2715 struct quick_file_names
2716 {
2717   /* The data used to construct the hash key.  */
2718   struct stmt_list_hash hash;
2719
2720   /* The number of entries in file_names, real_names.  */
2721   unsigned int num_file_names;
2722
2723   /* The file names from the line table, after being run through
2724      file_full_name.  */
2725   const char **file_names;
2726
2727   /* The file names from the line table after being run through
2728      gdb_realpath.  These are computed lazily.  */
2729   const char **real_names;
2730 };
2731
2732 /* When using the index (and thus not using psymtabs), each CU has an
2733    object of this type.  This is used to hold information needed by
2734    the various "quick" methods.  */
2735 struct dwarf2_per_cu_quick_data
2736 {
2737   /* The file table.  This can be NULL if there was no file table
2738      or it's currently not read in.
2739      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2740   struct quick_file_names *file_names;
2741
2742   /* The corresponding symbol table.  This is NULL if symbols for this
2743      CU have not yet been read.  */
2744   struct compunit_symtab *compunit_symtab;
2745
2746   /* A temporary mark bit used when iterating over all CUs in
2747      expand_symtabs_matching.  */
2748   unsigned int mark : 1;
2749
2750   /* True if we've tried to read the file table and found there isn't one.
2751      There will be no point in trying to read it again next time.  */
2752   unsigned int no_file_data : 1;
2753 };
2754
2755 /* Utility hash function for a stmt_list_hash.  */
2756
2757 static hashval_t
2758 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2759 {
2760   hashval_t v = 0;
2761
2762   if (stmt_list_hash->dwo_unit != NULL)
2763     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2764   v += to_underlying (stmt_list_hash->line_sect_off);
2765   return v;
2766 }
2767
2768 /* Utility equality function for a stmt_list_hash.  */
2769
2770 static int
2771 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2772                     const struct stmt_list_hash *rhs)
2773 {
2774   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2775     return 0;
2776   if (lhs->dwo_unit != NULL
2777       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2778     return 0;
2779
2780   return lhs->line_sect_off == rhs->line_sect_off;
2781 }
2782
2783 /* Hash function for a quick_file_names.  */
2784
2785 static hashval_t
2786 hash_file_name_entry (const void *e)
2787 {
2788   const struct quick_file_names *file_data
2789     = (const struct quick_file_names *) e;
2790
2791   return hash_stmt_list_entry (&file_data->hash);
2792 }
2793
2794 /* Equality function for a quick_file_names.  */
2795
2796 static int
2797 eq_file_name_entry (const void *a, const void *b)
2798 {
2799   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2800   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2801
2802   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2803 }
2804
2805 /* Delete function for a quick_file_names.  */
2806
2807 static void
2808 delete_file_name_entry (void *e)
2809 {
2810   struct quick_file_names *file_data = (struct quick_file_names *) e;
2811   int i;
2812
2813   for (i = 0; i < file_data->num_file_names; ++i)
2814     {
2815       xfree ((void*) file_data->file_names[i]);
2816       if (file_data->real_names)
2817         xfree ((void*) file_data->real_names[i]);
2818     }
2819
2820   /* The space for the struct itself lives on objfile_obstack,
2821      so we don't free it here.  */
2822 }
2823
2824 /* Create a quick_file_names hash table.  */
2825
2826 static htab_t
2827 create_quick_file_names_table (unsigned int nr_initial_entries)
2828 {
2829   return htab_create_alloc (nr_initial_entries,
2830                             hash_file_name_entry, eq_file_name_entry,
2831                             delete_file_name_entry, xcalloc, xfree);
2832 }
2833
2834 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2835    have to be created afterwards.  You should call age_cached_comp_units after
2836    processing PER_CU->CU.  dw2_setup must have been already called.  */
2837
2838 static void
2839 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2840 {
2841   if (per_cu->is_debug_types)
2842     load_full_type_unit (per_cu);
2843   else
2844     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2845
2846   if (per_cu->cu == NULL)
2847     return;  /* Dummy CU.  */
2848
2849   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2850 }
2851
2852 /* Read in the symbols for PER_CU.  */
2853
2854 static void
2855 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2856 {
2857   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2858
2859   /* Skip type_unit_groups, reading the type units they contain
2860      is handled elsewhere.  */
2861   if (IS_TYPE_UNIT_GROUP (per_cu))
2862     return;
2863
2864   /* The destructor of dwarf2_queue_guard frees any entries left on
2865      the queue.  After this point we're guaranteed to leave this function
2866      with the dwarf queue empty.  */
2867   dwarf2_queue_guard q_guard;
2868
2869   if (dwarf2_per_objfile->using_index
2870       ? per_cu->v.quick->compunit_symtab == NULL
2871       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2872     {
2873       queue_comp_unit (per_cu, language_minimal);
2874       load_cu (per_cu, skip_partial);
2875
2876       /* If we just loaded a CU from a DWO, and we're working with an index
2877          that may badly handle TUs, load all the TUs in that DWO as well.
2878          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2879       if (!per_cu->is_debug_types
2880           && per_cu->cu != NULL
2881           && per_cu->cu->dwo_unit != NULL
2882           && dwarf2_per_objfile->index_table != NULL
2883           && dwarf2_per_objfile->index_table->version <= 7
2884           /* DWP files aren't supported yet.  */
2885           && get_dwp_file (dwarf2_per_objfile) == NULL)
2886         queue_and_load_all_dwo_tus (per_cu);
2887     }
2888
2889   process_queue (dwarf2_per_objfile);
2890
2891   /* Age the cache, releasing compilation units that have not
2892      been used recently.  */
2893   age_cached_comp_units (dwarf2_per_objfile);
2894 }
2895
2896 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2897    the objfile from which this CU came.  Returns the resulting symbol
2898    table.  */
2899
2900 static struct compunit_symtab *
2901 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2902 {
2903   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2904
2905   gdb_assert (dwarf2_per_objfile->using_index);
2906   if (!per_cu->v.quick->compunit_symtab)
2907     {
2908       free_cached_comp_units freer (dwarf2_per_objfile);
2909       scoped_restore decrementer = increment_reading_symtab ();
2910       dw2_do_instantiate_symtab (per_cu, skip_partial);
2911       process_cu_includes (dwarf2_per_objfile);
2912     }
2913
2914   return per_cu->v.quick->compunit_symtab;
2915 }
2916
2917 /* See declaration.  */
2918
2919 dwarf2_per_cu_data *
2920 dwarf2_per_objfile::get_cutu (int index)
2921 {
2922   if (index >= this->all_comp_units.size ())
2923     {
2924       index -= this->all_comp_units.size ();
2925       gdb_assert (index < this->all_type_units.size ());
2926       return &this->all_type_units[index]->per_cu;
2927     }
2928
2929   return this->all_comp_units[index];
2930 }
2931
2932 /* See declaration.  */
2933
2934 dwarf2_per_cu_data *
2935 dwarf2_per_objfile::get_cu (int index)
2936 {
2937   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2938
2939   return this->all_comp_units[index];
2940 }
2941
2942 /* See declaration.  */
2943
2944 signatured_type *
2945 dwarf2_per_objfile::get_tu (int index)
2946 {
2947   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2948
2949   return this->all_type_units[index];
2950 }
2951
2952 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2953    objfile_obstack, and constructed with the specified field
2954    values.  */
2955
2956 static dwarf2_per_cu_data *
2957 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2958                           struct dwarf2_section_info *section,
2959                           int is_dwz,
2960                           sect_offset sect_off, ULONGEST length)
2961 {
2962   struct objfile *objfile = dwarf2_per_objfile->objfile;
2963   dwarf2_per_cu_data *the_cu
2964     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2965                      struct dwarf2_per_cu_data);
2966   the_cu->sect_off = sect_off;
2967   the_cu->length = length;
2968   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2969   the_cu->section = section;
2970   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2971                                    struct dwarf2_per_cu_quick_data);
2972   the_cu->is_dwz = is_dwz;
2973   return the_cu;
2974 }
2975
2976 /* A helper for create_cus_from_index that handles a given list of
2977    CUs.  */
2978
2979 static void
2980 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2981                             const gdb_byte *cu_list, offset_type n_elements,
2982                             struct dwarf2_section_info *section,
2983                             int is_dwz)
2984 {
2985   for (offset_type i = 0; i < n_elements; i += 2)
2986     {
2987       gdb_static_assert (sizeof (ULONGEST) >= 8);
2988
2989       sect_offset sect_off
2990         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2991       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2992       cu_list += 2 * 8;
2993
2994       dwarf2_per_cu_data *per_cu
2995         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2996                                      sect_off, length);
2997       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2998     }
2999 }
3000
3001 /* Read the CU list from the mapped index, and use it to create all
3002    the CU objects for this objfile.  */
3003
3004 static void
3005 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3006                        const gdb_byte *cu_list, offset_type cu_list_elements,
3007                        const gdb_byte *dwz_list, offset_type dwz_elements)
3008 {
3009   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3010   dwarf2_per_objfile->all_comp_units.reserve
3011     ((cu_list_elements + dwz_elements) / 2);
3012
3013   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3014                               &dwarf2_per_objfile->info, 0);
3015
3016   if (dwz_elements == 0)
3017     return;
3018
3019   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3020   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3021                               &dwz->info, 1);
3022 }
3023
3024 /* Create the signatured type hash table from the index.  */
3025
3026 static void
3027 create_signatured_type_table_from_index
3028   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3029    struct dwarf2_section_info *section,
3030    const gdb_byte *bytes,
3031    offset_type elements)
3032 {
3033   struct objfile *objfile = dwarf2_per_objfile->objfile;
3034
3035   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3036   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3037
3038   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3039
3040   for (offset_type i = 0; i < elements; i += 3)
3041     {
3042       struct signatured_type *sig_type;
3043       ULONGEST signature;
3044       void **slot;
3045       cu_offset type_offset_in_tu;
3046
3047       gdb_static_assert (sizeof (ULONGEST) >= 8);
3048       sect_offset sect_off
3049         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3050       type_offset_in_tu
3051         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3052                                                 BFD_ENDIAN_LITTLE);
3053       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3054       bytes += 3 * 8;
3055
3056       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3057                                  struct signatured_type);
3058       sig_type->signature = signature;
3059       sig_type->type_offset_in_tu = type_offset_in_tu;
3060       sig_type->per_cu.is_debug_types = 1;
3061       sig_type->per_cu.section = section;
3062       sig_type->per_cu.sect_off = sect_off;
3063       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3064       sig_type->per_cu.v.quick
3065         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3066                           struct dwarf2_per_cu_quick_data);
3067
3068       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3069       *slot = sig_type;
3070
3071       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3072     }
3073
3074   dwarf2_per_objfile->signatured_types = sig_types_hash;
3075 }
3076
3077 /* Create the signatured type hash table from .debug_names.  */
3078
3079 static void
3080 create_signatured_type_table_from_debug_names
3081   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3082    const mapped_debug_names &map,
3083    struct dwarf2_section_info *section,
3084    struct dwarf2_section_info *abbrev_section)
3085 {
3086   struct objfile *objfile = dwarf2_per_objfile->objfile;
3087
3088   dwarf2_read_section (objfile, section);
3089   dwarf2_read_section (objfile, abbrev_section);
3090
3091   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3092   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3093
3094   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3095
3096   for (uint32_t i = 0; i < map.tu_count; ++i)
3097     {
3098       struct signatured_type *sig_type;
3099       void **slot;
3100
3101       sect_offset sect_off
3102         = (sect_offset) (extract_unsigned_integer
3103                          (map.tu_table_reordered + i * map.offset_size,
3104                           map.offset_size,
3105                           map.dwarf5_byte_order));
3106
3107       comp_unit_head cu_header;
3108       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3109                                      abbrev_section,
3110                                      section->buffer + to_underlying (sect_off),
3111                                      rcuh_kind::TYPE);
3112
3113       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3114                                  struct signatured_type);
3115       sig_type->signature = cu_header.signature;
3116       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3117       sig_type->per_cu.is_debug_types = 1;
3118       sig_type->per_cu.section = section;
3119       sig_type->per_cu.sect_off = sect_off;
3120       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3121       sig_type->per_cu.v.quick
3122         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3123                           struct dwarf2_per_cu_quick_data);
3124
3125       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3126       *slot = sig_type;
3127
3128       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3129     }
3130
3131   dwarf2_per_objfile->signatured_types = sig_types_hash;
3132 }
3133
3134 /* Read the address map data from the mapped index, and use it to
3135    populate the objfile's psymtabs_addrmap.  */
3136
3137 static void
3138 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3139                            struct mapped_index *index)
3140 {
3141   struct objfile *objfile = dwarf2_per_objfile->objfile;
3142   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3143   const gdb_byte *iter, *end;
3144   struct addrmap *mutable_map;
3145   CORE_ADDR baseaddr;
3146
3147   auto_obstack temp_obstack;
3148
3149   mutable_map = addrmap_create_mutable (&temp_obstack);
3150
3151   iter = index->address_table.data ();
3152   end = iter + index->address_table.size ();
3153
3154   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3155
3156   while (iter < end)
3157     {
3158       ULONGEST hi, lo, cu_index;
3159       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3160       iter += 8;
3161       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3162       iter += 8;
3163       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3164       iter += 4;
3165
3166       if (lo > hi)
3167         {
3168           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3169                      hex_string (lo), hex_string (hi));
3170           continue;
3171         }
3172
3173       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3174         {
3175           complaint (_(".gdb_index address table has invalid CU number %u"),
3176                      (unsigned) cu_index);
3177           continue;
3178         }
3179
3180       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
3181       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
3182       addrmap_set_empty (mutable_map, lo, hi - 1,
3183                          dwarf2_per_objfile->get_cu (cu_index));
3184     }
3185
3186   objfile->partial_symtabs->psymtabs_addrmap
3187     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3188 }
3189
3190 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3191    populate the objfile's psymtabs_addrmap.  */
3192
3193 static void
3194 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3195                              struct dwarf2_section_info *section)
3196 {
3197   struct objfile *objfile = dwarf2_per_objfile->objfile;
3198   bfd *abfd = objfile->obfd;
3199   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3200   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3201                                        SECT_OFF_TEXT (objfile));
3202
3203   auto_obstack temp_obstack;
3204   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3205
3206   std::unordered_map<sect_offset,
3207                      dwarf2_per_cu_data *,
3208                      gdb::hash_enum<sect_offset>>
3209     debug_info_offset_to_per_cu;
3210   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3211     {
3212       const auto insertpair
3213         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3214       if (!insertpair.second)
3215         {
3216           warning (_("Section .debug_aranges in %s has duplicate "
3217                      "debug_info_offset %s, ignoring .debug_aranges."),
3218                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3219           return;
3220         }
3221     }
3222
3223   dwarf2_read_section (objfile, section);
3224
3225   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3226
3227   const gdb_byte *addr = section->buffer;
3228
3229   while (addr < section->buffer + section->size)
3230     {
3231       const gdb_byte *const entry_addr = addr;
3232       unsigned int bytes_read;
3233
3234       const LONGEST entry_length = read_initial_length (abfd, addr,
3235                                                         &bytes_read);
3236       addr += bytes_read;
3237
3238       const gdb_byte *const entry_end = addr + entry_length;
3239       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3240       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3241       if (addr + entry_length > section->buffer + section->size)
3242         {
3243           warning (_("Section .debug_aranges in %s entry at offset %s "
3244                      "length %s exceeds section length %s, "
3245                      "ignoring .debug_aranges."),
3246                    objfile_name (objfile),
3247                    plongest (entry_addr - section->buffer),
3248                    plongest (bytes_read + entry_length),
3249                    pulongest (section->size));
3250           return;
3251         }
3252
3253       /* The version number.  */
3254       const uint16_t version = read_2_bytes (abfd, addr);
3255       addr += 2;
3256       if (version != 2)
3257         {
3258           warning (_("Section .debug_aranges in %s entry at offset %s "
3259                      "has unsupported version %d, ignoring .debug_aranges."),
3260                    objfile_name (objfile),
3261                    plongest (entry_addr - section->buffer), version);
3262           return;
3263         }
3264
3265       const uint64_t debug_info_offset
3266         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3267       addr += offset_size;
3268       const auto per_cu_it
3269         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3270       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3271         {
3272           warning (_("Section .debug_aranges in %s entry at offset %s "
3273                      "debug_info_offset %s does not exists, "
3274                      "ignoring .debug_aranges."),
3275                    objfile_name (objfile),
3276                    plongest (entry_addr - section->buffer),
3277                    pulongest (debug_info_offset));
3278           return;
3279         }
3280       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3281
3282       const uint8_t address_size = *addr++;
3283       if (address_size < 1 || address_size > 8)
3284         {
3285           warning (_("Section .debug_aranges in %s entry at offset %s "
3286                      "address_size %u is invalid, ignoring .debug_aranges."),
3287                    objfile_name (objfile),
3288                    plongest (entry_addr - section->buffer), address_size);
3289           return;
3290         }
3291
3292       const uint8_t segment_selector_size = *addr++;
3293       if (segment_selector_size != 0)
3294         {
3295           warning (_("Section .debug_aranges in %s entry at offset %s "
3296                      "segment_selector_size %u is not supported, "
3297                      "ignoring .debug_aranges."),
3298                    objfile_name (objfile),
3299                    plongest (entry_addr - section->buffer),
3300                    segment_selector_size);
3301           return;
3302         }
3303
3304       /* Must pad to an alignment boundary that is twice the address
3305          size.  It is undocumented by the DWARF standard but GCC does
3306          use it.  */
3307       for (size_t padding = ((-(addr - section->buffer))
3308                              & (2 * address_size - 1));
3309            padding > 0; padding--)
3310         if (*addr++ != 0)
3311           {
3312             warning (_("Section .debug_aranges in %s entry at offset %s "
3313                        "padding is not zero, ignoring .debug_aranges."),
3314                      objfile_name (objfile),
3315                      plongest (entry_addr - section->buffer));
3316             return;
3317           }
3318
3319       for (;;)
3320         {
3321           if (addr + 2 * address_size > entry_end)
3322             {
3323               warning (_("Section .debug_aranges in %s entry at offset %s "
3324                          "address list is not properly terminated, "
3325                          "ignoring .debug_aranges."),
3326                        objfile_name (objfile),
3327                        plongest (entry_addr - section->buffer));
3328               return;
3329             }
3330           ULONGEST start = extract_unsigned_integer (addr, address_size,
3331                                                      dwarf5_byte_order);
3332           addr += address_size;
3333           ULONGEST length = extract_unsigned_integer (addr, address_size,
3334                                                       dwarf5_byte_order);
3335           addr += address_size;
3336           if (start == 0 && length == 0)
3337             break;
3338           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3339             {
3340               /* Symbol was eliminated due to a COMDAT group.  */
3341               continue;
3342             }
3343           ULONGEST end = start + length;
3344           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3345                    - baseaddr);
3346           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3347                  - baseaddr);
3348           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3349         }
3350     }
3351
3352   objfile->partial_symtabs->psymtabs_addrmap
3353     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3354 }
3355
3356 /* Find a slot in the mapped index INDEX for the object named NAME.
3357    If NAME is found, set *VEC_OUT to point to the CU vector in the
3358    constant pool and return true.  If NAME cannot be found, return
3359    false.  */
3360
3361 static bool
3362 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3363                           offset_type **vec_out)
3364 {
3365   offset_type hash;
3366   offset_type slot, step;
3367   int (*cmp) (const char *, const char *);
3368
3369   gdb::unique_xmalloc_ptr<char> without_params;
3370   if (current_language->la_language == language_cplus
3371       || current_language->la_language == language_fortran
3372       || current_language->la_language == language_d)
3373     {
3374       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3375          not contain any.  */
3376
3377       if (strchr (name, '(') != NULL)
3378         {
3379           without_params = cp_remove_params (name);
3380
3381           if (without_params != NULL)
3382             name = without_params.get ();
3383         }
3384     }
3385
3386   /* Index version 4 did not support case insensitive searches.  But the
3387      indices for case insensitive languages are built in lowercase, therefore
3388      simulate our NAME being searched is also lowercased.  */
3389   hash = mapped_index_string_hash ((index->version == 4
3390                                     && case_sensitivity == case_sensitive_off
3391                                     ? 5 : index->version),
3392                                    name);
3393
3394   slot = hash & (index->symbol_table.size () - 1);
3395   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3396   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3397
3398   for (;;)
3399     {
3400       const char *str;
3401
3402       const auto &bucket = index->symbol_table[slot];
3403       if (bucket.name == 0 && bucket.vec == 0)
3404         return false;
3405
3406       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3407       if (!cmp (name, str))
3408         {
3409           *vec_out = (offset_type *) (index->constant_pool
3410                                       + MAYBE_SWAP (bucket.vec));
3411           return true;
3412         }
3413
3414       slot = (slot + step) & (index->symbol_table.size () - 1);
3415     }
3416 }
3417
3418 /* A helper function that reads the .gdb_index from BUFFER and fills
3419    in MAP.  FILENAME is the name of the file containing the data;
3420    it is used for error reporting.  DEPRECATED_OK is true if it is
3421    ok to use deprecated sections.
3422
3423    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3424    out parameters that are filled in with information about the CU and
3425    TU lists in the section.
3426
3427    Returns true if all went well, false otherwise.  */
3428
3429 static bool
3430 read_gdb_index_from_buffer (struct objfile *objfile,
3431                             const char *filename,
3432                             bool deprecated_ok,
3433                             gdb::array_view<const gdb_byte> buffer,
3434                             struct mapped_index *map,
3435                             const gdb_byte **cu_list,
3436                             offset_type *cu_list_elements,
3437                             const gdb_byte **types_list,
3438                             offset_type *types_list_elements)
3439 {
3440   const gdb_byte *addr = &buffer[0];
3441
3442   /* Version check.  */
3443   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3444   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3445      causes the index to behave very poorly for certain requests.  Version 3
3446      contained incomplete addrmap.  So, it seems better to just ignore such
3447      indices.  */
3448   if (version < 4)
3449     {
3450       static int warning_printed = 0;
3451       if (!warning_printed)
3452         {
3453           warning (_("Skipping obsolete .gdb_index section in %s."),
3454                    filename);
3455           warning_printed = 1;
3456         }
3457       return 0;
3458     }
3459   /* Index version 4 uses a different hash function than index version
3460      5 and later.
3461
3462      Versions earlier than 6 did not emit psymbols for inlined
3463      functions.  Using these files will cause GDB not to be able to
3464      set breakpoints on inlined functions by name, so we ignore these
3465      indices unless the user has done
3466      "set use-deprecated-index-sections on".  */
3467   if (version < 6 && !deprecated_ok)
3468     {
3469       static int warning_printed = 0;
3470       if (!warning_printed)
3471         {
3472           warning (_("\
3473 Skipping deprecated .gdb_index section in %s.\n\
3474 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3475 to use the section anyway."),
3476                    filename);
3477           warning_printed = 1;
3478         }
3479       return 0;
3480     }
3481   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3482      of the TU (for symbols coming from TUs),
3483      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3484      Plus gold-generated indices can have duplicate entries for global symbols,
3485      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3486      These are just performance bugs, and we can't distinguish gdb-generated
3487      indices from gold-generated ones, so issue no warning here.  */
3488
3489   /* Indexes with higher version than the one supported by GDB may be no
3490      longer backward compatible.  */
3491   if (version > 8)
3492     return 0;
3493
3494   map->version = version;
3495
3496   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3497
3498   int i = 0;
3499   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3500   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3501                        / 8);
3502   ++i;
3503
3504   *types_list = addr + MAYBE_SWAP (metadata[i]);
3505   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3506                            - MAYBE_SWAP (metadata[i]))
3507                           / 8);
3508   ++i;
3509
3510   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3511   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3512   map->address_table
3513     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3514   ++i;
3515
3516   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3517   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3518   map->symbol_table
3519     = gdb::array_view<mapped_index::symbol_table_slot>
3520        ((mapped_index::symbol_table_slot *) symbol_table,
3521         (mapped_index::symbol_table_slot *) symbol_table_end);
3522
3523   ++i;
3524   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3525
3526   return 1;
3527 }
3528
3529 /* Callback types for dwarf2_read_gdb_index.  */
3530
3531 typedef gdb::function_view
3532     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3533     get_gdb_index_contents_ftype;
3534 typedef gdb::function_view
3535     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3536     get_gdb_index_contents_dwz_ftype;
3537
3538 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3539    elements of all the CUs and return 1.  Otherwise, return 0.  */
3540
3541 static int
3542 dwarf2_read_gdb_index
3543   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3544    get_gdb_index_contents_ftype get_gdb_index_contents,
3545    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3546 {
3547   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3548   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3549   struct dwz_file *dwz;
3550   struct objfile *objfile = dwarf2_per_objfile->objfile;
3551
3552   gdb::array_view<const gdb_byte> main_index_contents
3553     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3554
3555   if (main_index_contents.empty ())
3556     return 0;
3557
3558   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3559   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3560                                    use_deprecated_index_sections,
3561                                    main_index_contents, map.get (), &cu_list,
3562                                    &cu_list_elements, &types_list,
3563                                    &types_list_elements))
3564     return 0;
3565
3566   /* Don't use the index if it's empty.  */
3567   if (map->symbol_table.empty ())
3568     return 0;
3569
3570   /* If there is a .dwz file, read it so we can get its CU list as
3571      well.  */
3572   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3573   if (dwz != NULL)
3574     {
3575       struct mapped_index dwz_map;
3576       const gdb_byte *dwz_types_ignore;
3577       offset_type dwz_types_elements_ignore;
3578
3579       gdb::array_view<const gdb_byte> dwz_index_content
3580         = get_gdb_index_contents_dwz (objfile, dwz);
3581
3582       if (dwz_index_content.empty ())
3583         return 0;
3584
3585       if (!read_gdb_index_from_buffer (objfile,
3586                                        bfd_get_filename (dwz->dwz_bfd), 1,
3587                                        dwz_index_content, &dwz_map,
3588                                        &dwz_list, &dwz_list_elements,
3589                                        &dwz_types_ignore,
3590                                        &dwz_types_elements_ignore))
3591         {
3592           warning (_("could not read '.gdb_index' section from %s; skipping"),
3593                    bfd_get_filename (dwz->dwz_bfd));
3594           return 0;
3595         }
3596     }
3597
3598   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3599                          dwz_list, dwz_list_elements);
3600
3601   if (types_list_elements)
3602     {
3603       /* We can only handle a single .debug_types when we have an
3604          index.  */
3605       if (dwarf2_per_objfile->types.size () != 1)
3606         return 0;
3607
3608       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
3609
3610       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3611                                                types_list, types_list_elements);
3612     }
3613
3614   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3615
3616   dwarf2_per_objfile->index_table = std::move (map);
3617   dwarf2_per_objfile->using_index = 1;
3618   dwarf2_per_objfile->quick_file_names_table =
3619     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3620
3621   return 1;
3622 }
3623
3624 /* die_reader_func for dw2_get_file_names.  */
3625
3626 static void
3627 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3628                            const gdb_byte *info_ptr,
3629                            struct die_info *comp_unit_die,
3630                            int has_children,
3631                            void *data)
3632 {
3633   struct dwarf2_cu *cu = reader->cu;
3634   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3635   struct dwarf2_per_objfile *dwarf2_per_objfile
3636     = cu->per_cu->dwarf2_per_objfile;
3637   struct objfile *objfile = dwarf2_per_objfile->objfile;
3638   struct dwarf2_per_cu_data *lh_cu;
3639   struct attribute *attr;
3640   int i;
3641   void **slot;
3642   struct quick_file_names *qfn;
3643
3644   gdb_assert (! this_cu->is_debug_types);
3645
3646   /* Our callers never want to match partial units -- instead they
3647      will match the enclosing full CU.  */
3648   if (comp_unit_die->tag == DW_TAG_partial_unit)
3649     {
3650       this_cu->v.quick->no_file_data = 1;
3651       return;
3652     }
3653
3654   lh_cu = this_cu;
3655   slot = NULL;
3656
3657   line_header_up lh;
3658   sect_offset line_offset {};
3659
3660   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3661   if (attr)
3662     {
3663       struct quick_file_names find_entry;
3664
3665       line_offset = (sect_offset) DW_UNSND (attr);
3666
3667       /* We may have already read in this line header (TU line header sharing).
3668          If we have we're done.  */
3669       find_entry.hash.dwo_unit = cu->dwo_unit;
3670       find_entry.hash.line_sect_off = line_offset;
3671       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3672                              &find_entry, INSERT);
3673       if (*slot != NULL)
3674         {
3675           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3676           return;
3677         }
3678
3679       lh = dwarf_decode_line_header (line_offset, cu);
3680     }
3681   if (lh == NULL)
3682     {
3683       lh_cu->v.quick->no_file_data = 1;
3684       return;
3685     }
3686
3687   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3688   qfn->hash.dwo_unit = cu->dwo_unit;
3689   qfn->hash.line_sect_off = line_offset;
3690   gdb_assert (slot != NULL);
3691   *slot = qfn;
3692
3693   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3694
3695   qfn->num_file_names = lh->file_names.size ();
3696   qfn->file_names =
3697     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3698   for (i = 0; i < lh->file_names.size (); ++i)
3699     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3700   qfn->real_names = NULL;
3701
3702   lh_cu->v.quick->file_names = qfn;
3703 }
3704
3705 /* A helper for the "quick" functions which attempts to read the line
3706    table for THIS_CU.  */
3707
3708 static struct quick_file_names *
3709 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3710 {
3711   /* This should never be called for TUs.  */
3712   gdb_assert (! this_cu->is_debug_types);
3713   /* Nor type unit groups.  */
3714   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3715
3716   if (this_cu->v.quick->file_names != NULL)
3717     return this_cu->v.quick->file_names;
3718   /* If we know there is no line data, no point in looking again.  */
3719   if (this_cu->v.quick->no_file_data)
3720     return NULL;
3721
3722   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3723
3724   if (this_cu->v.quick->no_file_data)
3725     return NULL;
3726   return this_cu->v.quick->file_names;
3727 }
3728
3729 /* A helper for the "quick" functions which computes and caches the
3730    real path for a given file name from the line table.  */
3731
3732 static const char *
3733 dw2_get_real_path (struct objfile *objfile,
3734                    struct quick_file_names *qfn, int index)
3735 {
3736   if (qfn->real_names == NULL)
3737     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3738                                       qfn->num_file_names, const char *);
3739
3740   if (qfn->real_names[index] == NULL)
3741     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3742
3743   return qfn->real_names[index];
3744 }
3745
3746 static struct symtab *
3747 dw2_find_last_source_symtab (struct objfile *objfile)
3748 {
3749   struct dwarf2_per_objfile *dwarf2_per_objfile
3750     = get_dwarf2_per_objfile (objfile);
3751   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3752   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3753
3754   if (cust == NULL)
3755     return NULL;
3756
3757   return compunit_primary_filetab (cust);
3758 }
3759
3760 /* Traversal function for dw2_forget_cached_source_info.  */
3761
3762 static int
3763 dw2_free_cached_file_names (void **slot, void *info)
3764 {
3765   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3766
3767   if (file_data->real_names)
3768     {
3769       int i;
3770
3771       for (i = 0; i < file_data->num_file_names; ++i)
3772         {
3773           xfree ((void*) file_data->real_names[i]);
3774           file_data->real_names[i] = NULL;
3775         }
3776     }
3777
3778   return 1;
3779 }
3780
3781 static void
3782 dw2_forget_cached_source_info (struct objfile *objfile)
3783 {
3784   struct dwarf2_per_objfile *dwarf2_per_objfile
3785     = get_dwarf2_per_objfile (objfile);
3786
3787   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3788                           dw2_free_cached_file_names, NULL);
3789 }
3790
3791 /* Helper function for dw2_map_symtabs_matching_filename that expands
3792    the symtabs and calls the iterator.  */
3793
3794 static int
3795 dw2_map_expand_apply (struct objfile *objfile,
3796                       struct dwarf2_per_cu_data *per_cu,
3797                       const char *name, const char *real_path,
3798                       gdb::function_view<bool (symtab *)> callback)
3799 {
3800   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3801
3802   /* Don't visit already-expanded CUs.  */
3803   if (per_cu->v.quick->compunit_symtab)
3804     return 0;
3805
3806   /* This may expand more than one symtab, and we want to iterate over
3807      all of them.  */
3808   dw2_instantiate_symtab (per_cu, false);
3809
3810   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3811                                     last_made, callback);
3812 }
3813
3814 /* Implementation of the map_symtabs_matching_filename method.  */
3815
3816 static bool
3817 dw2_map_symtabs_matching_filename
3818   (struct objfile *objfile, const char *name, const char *real_path,
3819    gdb::function_view<bool (symtab *)> callback)
3820 {
3821   const char *name_basename = lbasename (name);
3822   struct dwarf2_per_objfile *dwarf2_per_objfile
3823     = get_dwarf2_per_objfile (objfile);
3824
3825   /* The rule is CUs specify all the files, including those used by
3826      any TU, so there's no need to scan TUs here.  */
3827
3828   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3829     {
3830       /* We only need to look at symtabs not already expanded.  */
3831       if (per_cu->v.quick->compunit_symtab)
3832         continue;
3833
3834       quick_file_names *file_data = dw2_get_file_names (per_cu);
3835       if (file_data == NULL)
3836         continue;
3837
3838       for (int j = 0; j < file_data->num_file_names; ++j)
3839         {
3840           const char *this_name = file_data->file_names[j];
3841           const char *this_real_name;
3842
3843           if (compare_filenames_for_search (this_name, name))
3844             {
3845               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3846                                         callback))
3847                 return true;
3848               continue;
3849             }
3850
3851           /* Before we invoke realpath, which can get expensive when many
3852              files are involved, do a quick comparison of the basenames.  */
3853           if (! basenames_may_differ
3854               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3855             continue;
3856
3857           this_real_name = dw2_get_real_path (objfile, file_data, j);
3858           if (compare_filenames_for_search (this_real_name, name))
3859             {
3860               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3861                                         callback))
3862                 return true;
3863               continue;
3864             }
3865
3866           if (real_path != NULL)
3867             {
3868               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3869               gdb_assert (IS_ABSOLUTE_PATH (name));
3870               if (this_real_name != NULL
3871                   && FILENAME_CMP (real_path, this_real_name) == 0)
3872                 {
3873                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3874                                             callback))
3875                     return true;
3876                   continue;
3877                 }
3878             }
3879         }
3880     }
3881
3882   return false;
3883 }
3884
3885 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3886
3887 struct dw2_symtab_iterator
3888 {
3889   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3890   struct dwarf2_per_objfile *dwarf2_per_objfile;
3891   /* If set, only look for symbols that match that block.  Valid values are
3892      GLOBAL_BLOCK and STATIC_BLOCK.  */
3893   gdb::optional<block_enum> block_index;
3894   /* The kind of symbol we're looking for.  */
3895   domain_enum domain;
3896   /* The list of CUs from the index entry of the symbol,
3897      or NULL if not found.  */
3898   offset_type *vec;
3899   /* The next element in VEC to look at.  */
3900   int next;
3901   /* The number of elements in VEC, or zero if there is no match.  */
3902   int length;
3903   /* Have we seen a global version of the symbol?
3904      If so we can ignore all further global instances.
3905      This is to work around gold/15646, inefficient gold-generated
3906      indices.  */
3907   int global_seen;
3908 };
3909
3910 /* Initialize the index symtab iterator ITER.  */
3911
3912 static void
3913 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3914                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3915                       gdb::optional<block_enum> block_index,
3916                       domain_enum domain,
3917                       const char *name)
3918 {
3919   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3920   iter->block_index = block_index;
3921   iter->domain = domain;
3922   iter->next = 0;
3923   iter->global_seen = 0;
3924
3925   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3926
3927   /* index is NULL if OBJF_READNOW.  */
3928   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3929     iter->length = MAYBE_SWAP (*iter->vec);
3930   else
3931     {
3932       iter->vec = NULL;
3933       iter->length = 0;
3934     }
3935 }
3936
3937 /* Return the next matching CU or NULL if there are no more.  */
3938
3939 static struct dwarf2_per_cu_data *
3940 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3941 {
3942   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3943
3944   for ( ; iter->next < iter->length; ++iter->next)
3945     {
3946       offset_type cu_index_and_attrs =
3947         MAYBE_SWAP (iter->vec[iter->next + 1]);
3948       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3949       gdb_index_symbol_kind symbol_kind =
3950         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3951       /* Only check the symbol attributes if they're present.
3952          Indices prior to version 7 don't record them,
3953          and indices >= 7 may elide them for certain symbols
3954          (gold does this).  */
3955       int attrs_valid =
3956         (dwarf2_per_objfile->index_table->version >= 7
3957          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3958
3959       /* Don't crash on bad data.  */
3960       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3961                        + dwarf2_per_objfile->all_type_units.size ()))
3962         {
3963           complaint (_(".gdb_index entry has bad CU index"
3964                        " [in module %s]"),
3965                      objfile_name (dwarf2_per_objfile->objfile));
3966           continue;
3967         }
3968
3969       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3970
3971       /* Skip if already read in.  */
3972       if (per_cu->v.quick->compunit_symtab)
3973         continue;
3974
3975       /* Check static vs global.  */
3976       if (attrs_valid)
3977         {
3978           bool is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3979
3980           if (iter->block_index.has_value ())
3981             {
3982               bool want_static = *iter->block_index == STATIC_BLOCK;
3983
3984               if (is_static != want_static)
3985                 continue;
3986             }
3987
3988           /* Work around gold/15646.  */
3989           if (!is_static && iter->global_seen)
3990             continue;
3991           if (!is_static)
3992             iter->global_seen = 1;
3993         }
3994
3995       /* Only check the symbol's kind if it has one.  */
3996       if (attrs_valid)
3997         {
3998           switch (iter->domain)
3999             {
4000             case VAR_DOMAIN:
4001               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4002                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4003                   /* Some types are also in VAR_DOMAIN.  */
4004                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4005                 continue;
4006               break;
4007             case STRUCT_DOMAIN:
4008               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4009                 continue;
4010               break;
4011             case LABEL_DOMAIN:
4012               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4013                 continue;
4014               break;
4015             default:
4016               break;
4017             }
4018         }
4019
4020       ++iter->next;
4021       return per_cu;
4022     }
4023
4024   return NULL;
4025 }
4026
4027 static struct compunit_symtab *
4028 dw2_lookup_symbol (struct objfile *objfile, block_enum block_index,
4029                    const char *name, domain_enum domain)
4030 {
4031   struct compunit_symtab *stab_best = NULL;
4032   struct dwarf2_per_objfile *dwarf2_per_objfile
4033     = get_dwarf2_per_objfile (objfile);
4034
4035   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4036
4037   struct dw2_symtab_iterator iter;
4038   struct dwarf2_per_cu_data *per_cu;
4039
4040   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, block_index, domain, name);
4041
4042   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4043     {
4044       struct symbol *sym, *with_opaque = NULL;
4045       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4046       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4047       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4048
4049       sym = block_find_symbol (block, name, domain,
4050                                block_find_non_opaque_type_preferred,
4051                                &with_opaque);
4052
4053       /* Some caution must be observed with overloaded functions
4054          and methods, since the index will not contain any overload
4055          information (but NAME might contain it).  */
4056
4057       if (sym != NULL
4058           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4059         return stab;
4060       if (with_opaque != NULL
4061           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4062         stab_best = stab;
4063
4064       /* Keep looking through other CUs.  */
4065     }
4066
4067   return stab_best;
4068 }
4069
4070 static void
4071 dw2_print_stats (struct objfile *objfile)
4072 {
4073   struct dwarf2_per_objfile *dwarf2_per_objfile
4074     = get_dwarf2_per_objfile (objfile);
4075   int total = (dwarf2_per_objfile->all_comp_units.size ()
4076                + dwarf2_per_objfile->all_type_units.size ());
4077   int count = 0;
4078
4079   for (int i = 0; i < total; ++i)
4080     {
4081       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4082
4083       if (!per_cu->v.quick->compunit_symtab)
4084         ++count;
4085     }
4086   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4087   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4088 }
4089
4090 /* This dumps minimal information about the index.
4091    It is called via "mt print objfiles".
4092    One use is to verify .gdb_index has been loaded by the
4093    gdb.dwarf2/gdb-index.exp testcase.  */
4094
4095 static void
4096 dw2_dump (struct objfile *objfile)
4097 {
4098   struct dwarf2_per_objfile *dwarf2_per_objfile
4099     = get_dwarf2_per_objfile (objfile);
4100
4101   gdb_assert (dwarf2_per_objfile->using_index);
4102   printf_filtered (".gdb_index:");
4103   if (dwarf2_per_objfile->index_table != NULL)
4104     {
4105       printf_filtered (" version %d\n",
4106                        dwarf2_per_objfile->index_table->version);
4107     }
4108   else
4109     printf_filtered (" faked for \"readnow\"\n");
4110   printf_filtered ("\n");
4111 }
4112
4113 static void
4114 dw2_expand_symtabs_for_function (struct objfile *objfile,
4115                                  const char *func_name)
4116 {
4117   struct dwarf2_per_objfile *dwarf2_per_objfile
4118     = get_dwarf2_per_objfile (objfile);
4119
4120   struct dw2_symtab_iterator iter;
4121   struct dwarf2_per_cu_data *per_cu;
4122
4123   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, {}, VAR_DOMAIN, func_name);
4124
4125   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4126     dw2_instantiate_symtab (per_cu, false);
4127
4128 }
4129
4130 static void
4131 dw2_expand_all_symtabs (struct objfile *objfile)
4132 {
4133   struct dwarf2_per_objfile *dwarf2_per_objfile
4134     = get_dwarf2_per_objfile (objfile);
4135   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4136                      + dwarf2_per_objfile->all_type_units.size ());
4137
4138   for (int i = 0; i < total_units; ++i)
4139     {
4140       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4141
4142       /* We don't want to directly expand a partial CU, because if we
4143          read it with the wrong language, then assertion failures can
4144          be triggered later on.  See PR symtab/23010.  So, tell
4145          dw2_instantiate_symtab to skip partial CUs -- any important
4146          partial CU will be read via DW_TAG_imported_unit anyway.  */
4147       dw2_instantiate_symtab (per_cu, true);
4148     }
4149 }
4150
4151 static void
4152 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4153                                   const char *fullname)
4154 {
4155   struct dwarf2_per_objfile *dwarf2_per_objfile
4156     = get_dwarf2_per_objfile (objfile);
4157
4158   /* We don't need to consider type units here.
4159      This is only called for examining code, e.g. expand_line_sal.
4160      There can be an order of magnitude (or more) more type units
4161      than comp units, and we avoid them if we can.  */
4162
4163   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4164     {
4165       /* We only need to look at symtabs not already expanded.  */
4166       if (per_cu->v.quick->compunit_symtab)
4167         continue;
4168
4169       quick_file_names *file_data = dw2_get_file_names (per_cu);
4170       if (file_data == NULL)
4171         continue;
4172
4173       for (int j = 0; j < file_data->num_file_names; ++j)
4174         {
4175           const char *this_fullname = file_data->file_names[j];
4176
4177           if (filename_cmp (this_fullname, fullname) == 0)
4178             {
4179               dw2_instantiate_symtab (per_cu, false);
4180               break;
4181             }
4182         }
4183     }
4184 }
4185
4186 static void
4187 dw2_map_matching_symbols
4188   (struct objfile *objfile,
4189    const char * name, domain_enum domain,
4190    int global,
4191    gdb::function_view<symbol_found_callback_ftype> callback,
4192    symbol_name_match_type match,
4193    symbol_compare_ftype *ordered_compare)
4194 {
4195   /* Currently unimplemented; used for Ada.  The function can be called if the
4196      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4197      does not look for non-Ada symbols this function should just return.  */
4198 }
4199
4200 /* Symbol name matcher for .gdb_index names.
4201
4202    Symbol names in .gdb_index have a few particularities:
4203
4204    - There's no indication of which is the language of each symbol.
4205
4206      Since each language has its own symbol name matching algorithm,
4207      and we don't know which language is the right one, we must match
4208      each symbol against all languages.  This would be a potential
4209      performance problem if it were not mitigated by the
4210      mapped_index::name_components lookup table, which significantly
4211      reduces the number of times we need to call into this matcher,
4212      making it a non-issue.
4213
4214    - Symbol names in the index have no overload (parameter)
4215      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4216      appear as "foo" in the index, for example.
4217
4218      This means that the lookup names passed to the symbol name
4219      matcher functions must have no parameter information either
4220      because (e.g.) symbol search name "foo" does not match
4221      lookup-name "foo(int)" [while swapping search name for lookup
4222      name would match].
4223 */
4224 class gdb_index_symbol_name_matcher
4225 {
4226 public:
4227   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4228   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4229
4230   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4231      Returns true if any matcher matches.  */
4232   bool matches (const char *symbol_name);
4233
4234 private:
4235   /* A reference to the lookup name we're matching against.  */
4236   const lookup_name_info &m_lookup_name;
4237
4238   /* A vector holding all the different symbol name matchers, for all
4239      languages.  */
4240   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4241 };
4242
4243 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4244   (const lookup_name_info &lookup_name)
4245     : m_lookup_name (lookup_name)
4246 {
4247   /* Prepare the vector of comparison functions upfront, to avoid
4248      doing the same work for each symbol.  Care is taken to avoid
4249      matching with the same matcher more than once if/when multiple
4250      languages use the same matcher function.  */
4251   auto &matchers = m_symbol_name_matcher_funcs;
4252   matchers.reserve (nr_languages);
4253
4254   matchers.push_back (default_symbol_name_matcher);
4255
4256   for (int i = 0; i < nr_languages; i++)
4257     {
4258       const language_defn *lang = language_def ((enum language) i);
4259       symbol_name_matcher_ftype *name_matcher
4260         = get_symbol_name_matcher (lang, m_lookup_name);
4261
4262       /* Don't insert the same comparison routine more than once.
4263          Note that we do this linear walk instead of a seemingly
4264          cheaper sorted insert, or use a std::set or something like
4265          that, because relative order of function addresses is not
4266          stable.  This is not a problem in practice because the number
4267          of supported languages is low, and the cost here is tiny
4268          compared to the number of searches we'll do afterwards using
4269          this object.  */
4270       if (name_matcher != default_symbol_name_matcher
4271           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4272               == matchers.end ()))
4273         matchers.push_back (name_matcher);
4274     }
4275 }
4276
4277 bool
4278 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4279 {
4280   for (auto matches_name : m_symbol_name_matcher_funcs)
4281     if (matches_name (symbol_name, m_lookup_name, NULL))
4282       return true;
4283
4284   return false;
4285 }
4286
4287 /* Starting from a search name, return the string that finds the upper
4288    bound of all strings that start with SEARCH_NAME in a sorted name
4289    list.  Returns the empty string to indicate that the upper bound is
4290    the end of the list.  */
4291
4292 static std::string
4293 make_sort_after_prefix_name (const char *search_name)
4294 {
4295   /* When looking to complete "func", we find the upper bound of all
4296      symbols that start with "func" by looking for where we'd insert
4297      the closest string that would follow "func" in lexicographical
4298      order.  Usually, that's "func"-with-last-character-incremented,
4299      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4300      will be UTF-8 multi-byte sequences, but we can't be certain.
4301      Especially mind the 0xff character, which is a valid character in
4302      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4303      rule out compilers allowing it in identifiers.  Note that
4304      conveniently, strcmp/strcasecmp are specified to compare
4305      characters interpreted as unsigned char.  So what we do is treat
4306      the whole string as a base 256 number composed of a sequence of
4307      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4308      to 0, and carries 1 to the following more-significant position.
4309      If the very first character in SEARCH_NAME ends up incremented
4310      and carries/overflows, then the upper bound is the end of the
4311      list.  The string after the empty string is also the empty
4312      string.
4313
4314      Some examples of this operation:
4315
4316        SEARCH_NAME  => "+1" RESULT
4317
4318        "abc"              => "abd"
4319        "ab\xff"           => "ac"
4320        "\xff" "a" "\xff"  => "\xff" "b"
4321        "\xff"             => ""
4322        "\xff\xff"         => ""
4323        ""                 => ""
4324
4325      Then, with these symbols for example:
4326
4327       func
4328       func1
4329       fund
4330
4331      completing "func" looks for symbols between "func" and
4332      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4333      which finds "func" and "func1", but not "fund".
4334
4335      And with:
4336
4337       funcÿ     (Latin1 'ÿ' [0xff])
4338       funcÿ1
4339       fund
4340
4341      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4342      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4343
4344      And with:
4345
4346       ÿÿ        (Latin1 'ÿ' [0xff])
4347       ÿÿ1
4348
4349      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4350      the end of the list.
4351   */
4352   std::string after = search_name;
4353   while (!after.empty () && (unsigned char) after.back () == 0xff)
4354     after.pop_back ();
4355   if (!after.empty ())
4356     after.back () = (unsigned char) after.back () + 1;
4357   return after;
4358 }
4359
4360 /* See declaration.  */
4361
4362 std::pair<std::vector<name_component>::const_iterator,
4363           std::vector<name_component>::const_iterator>
4364 mapped_index_base::find_name_components_bounds
4365   (const lookup_name_info &lookup_name_without_params) const
4366 {
4367   auto *name_cmp
4368     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4369
4370   const char *cplus
4371     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4372
4373   /* Comparison function object for lower_bound that matches against a
4374      given symbol name.  */
4375   auto lookup_compare_lower = [&] (const name_component &elem,
4376                                    const char *name)
4377     {
4378       const char *elem_qualified = this->symbol_name_at (elem.idx);
4379       const char *elem_name = elem_qualified + elem.name_offset;
4380       return name_cmp (elem_name, name) < 0;
4381     };
4382
4383   /* Comparison function object for upper_bound that matches against a
4384      given symbol name.  */
4385   auto lookup_compare_upper = [&] (const char *name,
4386                                    const name_component &elem)
4387     {
4388       const char *elem_qualified = this->symbol_name_at (elem.idx);
4389       const char *elem_name = elem_qualified + elem.name_offset;
4390       return name_cmp (name, elem_name) < 0;
4391     };
4392
4393   auto begin = this->name_components.begin ();
4394   auto end = this->name_components.end ();
4395
4396   /* Find the lower bound.  */
4397   auto lower = [&] ()
4398     {
4399       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4400         return begin;
4401       else
4402         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4403     } ();
4404
4405   /* Find the upper bound.  */
4406   auto upper = [&] ()
4407     {
4408       if (lookup_name_without_params.completion_mode ())
4409         {
4410           /* In completion mode, we want UPPER to point past all
4411              symbols names that have the same prefix.  I.e., with
4412              these symbols, and completing "func":
4413
4414               function        << lower bound
4415               function1
4416               other_function  << upper bound
4417
4418              We find the upper bound by looking for the insertion
4419              point of "func"-with-last-character-incremented,
4420              i.e. "fund".  */
4421           std::string after = make_sort_after_prefix_name (cplus);
4422           if (after.empty ())
4423             return end;
4424           return std::lower_bound (lower, end, after.c_str (),
4425                                    lookup_compare_lower);
4426         }
4427       else
4428         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4429     } ();
4430
4431   return {lower, upper};
4432 }
4433
4434 /* See declaration.  */
4435
4436 void
4437 mapped_index_base::build_name_components ()
4438 {
4439   if (!this->name_components.empty ())
4440     return;
4441
4442   this->name_components_casing = case_sensitivity;
4443   auto *name_cmp
4444     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4445
4446   /* The code below only knows how to break apart components of C++
4447      symbol names (and other languages that use '::' as
4448      namespace/module separator).  If we add support for wild matching
4449      to some language that uses some other operator (E.g., Ada, Go and
4450      D use '.'), then we'll need to try splitting the symbol name
4451      according to that language too.  Note that Ada does support wild
4452      matching, but doesn't currently support .gdb_index.  */
4453   auto count = this->symbol_name_count ();
4454   for (offset_type idx = 0; idx < count; idx++)
4455     {
4456       if (this->symbol_name_slot_invalid (idx))
4457         continue;
4458
4459       const char *name = this->symbol_name_at (idx);
4460
4461       /* Add each name component to the name component table.  */
4462       unsigned int previous_len = 0;
4463       for (unsigned int current_len = cp_find_first_component (name);
4464            name[current_len] != '\0';
4465            current_len += cp_find_first_component (name + current_len))
4466         {
4467           gdb_assert (name[current_len] == ':');
4468           this->name_components.push_back ({previous_len, idx});
4469           /* Skip the '::'.  */
4470           current_len += 2;
4471           previous_len = current_len;
4472         }
4473       this->name_components.push_back ({previous_len, idx});
4474     }
4475
4476   /* Sort name_components elements by name.  */
4477   auto name_comp_compare = [&] (const name_component &left,
4478                                 const name_component &right)
4479     {
4480       const char *left_qualified = this->symbol_name_at (left.idx);
4481       const char *right_qualified = this->symbol_name_at (right.idx);
4482
4483       const char *left_name = left_qualified + left.name_offset;
4484       const char *right_name = right_qualified + right.name_offset;
4485
4486       return name_cmp (left_name, right_name) < 0;
4487     };
4488
4489   std::sort (this->name_components.begin (),
4490              this->name_components.end (),
4491              name_comp_compare);
4492 }
4493
4494 /* Helper for dw2_expand_symtabs_matching that works with a
4495    mapped_index_base instead of the containing objfile.  This is split
4496    to a separate function in order to be able to unit test the
4497    name_components matching using a mock mapped_index_base.  For each
4498    symbol name that matches, calls MATCH_CALLBACK, passing it the
4499    symbol's index in the mapped_index_base symbol table.  */
4500
4501 static void
4502 dw2_expand_symtabs_matching_symbol
4503   (mapped_index_base &index,
4504    const lookup_name_info &lookup_name_in,
4505    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4506    enum search_domain kind,
4507    gdb::function_view<void (offset_type)> match_callback)
4508 {
4509   lookup_name_info lookup_name_without_params
4510     = lookup_name_in.make_ignore_params ();
4511   gdb_index_symbol_name_matcher lookup_name_matcher
4512     (lookup_name_without_params);
4513
4514   /* Build the symbol name component sorted vector, if we haven't
4515      yet.  */
4516   index.build_name_components ();
4517
4518   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4519
4520   /* Now for each symbol name in range, check to see if we have a name
4521      match, and if so, call the MATCH_CALLBACK callback.  */
4522
4523   /* The same symbol may appear more than once in the range though.
4524      E.g., if we're looking for symbols that complete "w", and we have
4525      a symbol named "w1::w2", we'll find the two name components for
4526      that same symbol in the range.  To be sure we only call the
4527      callback once per symbol, we first collect the symbol name
4528      indexes that matched in a temporary vector and ignore
4529      duplicates.  */
4530   std::vector<offset_type> matches;
4531   matches.reserve (std::distance (bounds.first, bounds.second));
4532
4533   for (; bounds.first != bounds.second; ++bounds.first)
4534     {
4535       const char *qualified = index.symbol_name_at (bounds.first->idx);
4536
4537       if (!lookup_name_matcher.matches (qualified)
4538           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4539         continue;
4540
4541       matches.push_back (bounds.first->idx);
4542     }
4543
4544   std::sort (matches.begin (), matches.end ());
4545
4546   /* Finally call the callback, once per match.  */
4547   ULONGEST prev = -1;
4548   for (offset_type idx : matches)
4549     {
4550       if (prev != idx)
4551         {
4552           match_callback (idx);
4553           prev = idx;
4554         }
4555     }
4556
4557   /* Above we use a type wider than idx's for 'prev', since 0 and
4558      (offset_type)-1 are both possible values.  */
4559   static_assert (sizeof (prev) > sizeof (offset_type), "");
4560 }
4561
4562 #if GDB_SELF_TEST
4563
4564 namespace selftests { namespace dw2_expand_symtabs_matching {
4565
4566 /* A mock .gdb_index/.debug_names-like name index table, enough to
4567    exercise dw2_expand_symtabs_matching_symbol, which works with the
4568    mapped_index_base interface.  Builds an index from the symbol list
4569    passed as parameter to the constructor.  */
4570 class mock_mapped_index : public mapped_index_base
4571 {
4572 public:
4573   mock_mapped_index (gdb::array_view<const char *> symbols)
4574     : m_symbol_table (symbols)
4575   {}
4576
4577   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4578
4579   /* Return the number of names in the symbol table.  */
4580   size_t symbol_name_count () const override
4581   {
4582     return m_symbol_table.size ();
4583   }
4584
4585   /* Get the name of the symbol at IDX in the symbol table.  */
4586   const char *symbol_name_at (offset_type idx) const override
4587   {
4588     return m_symbol_table[idx];
4589   }
4590
4591 private:
4592   gdb::array_view<const char *> m_symbol_table;
4593 };
4594
4595 /* Convenience function that converts a NULL pointer to a "<null>"
4596    string, to pass to print routines.  */
4597
4598 static const char *
4599 string_or_null (const char *str)
4600 {
4601   return str != NULL ? str : "<null>";
4602 }
4603
4604 /* Check if a lookup_name_info built from
4605    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4606    index.  EXPECTED_LIST is the list of expected matches, in expected
4607    matching order.  If no match expected, then an empty list is
4608    specified.  Returns true on success.  On failure prints a warning
4609    indicating the file:line that failed, and returns false.  */
4610
4611 static bool
4612 check_match (const char *file, int line,
4613              mock_mapped_index &mock_index,
4614              const char *name, symbol_name_match_type match_type,
4615              bool completion_mode,
4616              std::initializer_list<const char *> expected_list)
4617 {
4618   lookup_name_info lookup_name (name, match_type, completion_mode);
4619
4620   bool matched = true;
4621
4622   auto mismatch = [&] (const char *expected_str,
4623                        const char *got)
4624   {
4625     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4626                "expected=\"%s\", got=\"%s\"\n"),
4627              file, line,
4628              (match_type == symbol_name_match_type::FULL
4629               ? "FULL" : "WILD"),
4630              name, string_or_null (expected_str), string_or_null (got));
4631     matched = false;
4632   };
4633
4634   auto expected_it = expected_list.begin ();
4635   auto expected_end = expected_list.end ();
4636
4637   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4638                                       NULL, ALL_DOMAIN,
4639                                       [&] (offset_type idx)
4640   {
4641     const char *matched_name = mock_index.symbol_name_at (idx);
4642     const char *expected_str
4643       = expected_it == expected_end ? NULL : *expected_it++;
4644
4645     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4646       mismatch (expected_str, matched_name);
4647   });
4648
4649   const char *expected_str
4650   = expected_it == expected_end ? NULL : *expected_it++;
4651   if (expected_str != NULL)
4652     mismatch (expected_str, NULL);
4653
4654   return matched;
4655 }
4656
4657 /* The symbols added to the mock mapped_index for testing (in
4658    canonical form).  */
4659 static const char *test_symbols[] = {
4660   "function",
4661   "std::bar",
4662   "std::zfunction",
4663   "std::zfunction2",
4664   "w1::w2",
4665   "ns::foo<char*>",
4666   "ns::foo<int>",
4667   "ns::foo<long>",
4668   "ns2::tmpl<int>::foo2",
4669   "(anonymous namespace)::A::B::C",
4670
4671   /* These are used to check that the increment-last-char in the
4672      matching algorithm for completion doesn't match "t1_fund" when
4673      completing "t1_func".  */
4674   "t1_func",
4675   "t1_func1",
4676   "t1_fund",
4677   "t1_fund1",
4678
4679   /* A UTF-8 name with multi-byte sequences to make sure that
4680      cp-name-parser understands this as a single identifier ("função"
4681      is "function" in PT).  */
4682   u8"u8função",
4683
4684   /* \377 (0xff) is Latin1 'ÿ'.  */
4685   "yfunc\377",
4686
4687   /* \377 (0xff) is Latin1 'ÿ'.  */
4688   "\377",
4689   "\377\377123",
4690
4691   /* A name with all sorts of complications.  Starts with "z" to make
4692      it easier for the completion tests below.  */
4693 #define Z_SYM_NAME \
4694   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4695     "::tuple<(anonymous namespace)::ui*, " \
4696     "std::default_delete<(anonymous namespace)::ui>, void>"
4697
4698   Z_SYM_NAME
4699 };
4700
4701 /* Returns true if the mapped_index_base::find_name_component_bounds
4702    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4703    in completion mode.  */
4704
4705 static bool
4706 check_find_bounds_finds (mapped_index_base &index,
4707                          const char *search_name,
4708                          gdb::array_view<const char *> expected_syms)
4709 {
4710   lookup_name_info lookup_name (search_name,
4711                                 symbol_name_match_type::FULL, true);
4712
4713   auto bounds = index.find_name_components_bounds (lookup_name);
4714
4715   size_t distance = std::distance (bounds.first, bounds.second);
4716   if (distance != expected_syms.size ())
4717     return false;
4718
4719   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4720     {
4721       auto nc_elem = bounds.first + exp_elem;
4722       const char *qualified = index.symbol_name_at (nc_elem->idx);
4723       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4724         return false;
4725     }
4726
4727   return true;
4728 }
4729
4730 /* Test the lower-level mapped_index::find_name_component_bounds
4731    method.  */
4732
4733 static void
4734 test_mapped_index_find_name_component_bounds ()
4735 {
4736   mock_mapped_index mock_index (test_symbols);
4737
4738   mock_index.build_name_components ();
4739
4740   /* Test the lower-level mapped_index::find_name_component_bounds
4741      method in completion mode.  */
4742   {
4743     static const char *expected_syms[] = {
4744       "t1_func",
4745       "t1_func1",
4746     };
4747
4748     SELF_CHECK (check_find_bounds_finds (mock_index,
4749                                          "t1_func", expected_syms));
4750   }
4751
4752   /* Check that the increment-last-char in the name matching algorithm
4753      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4754   {
4755     static const char *expected_syms1[] = {
4756       "\377",
4757       "\377\377123",
4758     };
4759     SELF_CHECK (check_find_bounds_finds (mock_index,
4760                                          "\377", expected_syms1));
4761
4762     static const char *expected_syms2[] = {
4763       "\377\377123",
4764     };
4765     SELF_CHECK (check_find_bounds_finds (mock_index,
4766                                          "\377\377", expected_syms2));
4767   }
4768 }
4769
4770 /* Test dw2_expand_symtabs_matching_symbol.  */
4771
4772 static void
4773 test_dw2_expand_symtabs_matching_symbol ()
4774 {
4775   mock_mapped_index mock_index (test_symbols);
4776
4777   /* We let all tests run until the end even if some fails, for debug
4778      convenience.  */
4779   bool any_mismatch = false;
4780
4781   /* Create the expected symbols list (an initializer_list).  Needed
4782      because lists have commas, and we need to pass them to CHECK,
4783      which is a macro.  */
4784 #define EXPECT(...) { __VA_ARGS__ }
4785
4786   /* Wrapper for check_match that passes down the current
4787      __FILE__/__LINE__.  */
4788 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4789   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4790                                 mock_index,                             \
4791                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4792                                 EXPECTED_LIST)
4793
4794   /* Identity checks.  */
4795   for (const char *sym : test_symbols)
4796     {
4797       /* Should be able to match all existing symbols.  */
4798       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4799                    EXPECT (sym));
4800
4801       /* Should be able to match all existing symbols with
4802          parameters.  */
4803       std::string with_params = std::string (sym) + "(int)";
4804       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4805                    EXPECT (sym));
4806
4807       /* Should be able to match all existing symbols with
4808          parameters and qualifiers.  */
4809       with_params = std::string (sym) + " ( int ) const";
4810       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4811                    EXPECT (sym));
4812
4813       /* This should really find sym, but cp-name-parser.y doesn't
4814          know about lvalue/rvalue qualifiers yet.  */
4815       with_params = std::string (sym) + " ( int ) &&";
4816       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4817                    {});
4818     }
4819
4820   /* Check that the name matching algorithm for completion doesn't get
4821      confused with Latin1 'ÿ' / 0xff.  */
4822   {
4823     static const char str[] = "\377";
4824     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4825                  EXPECT ("\377", "\377\377123"));
4826   }
4827
4828   /* Check that the increment-last-char in the matching algorithm for
4829      completion doesn't match "t1_fund" when completing "t1_func".  */
4830   {
4831     static const char str[] = "t1_func";
4832     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4833                  EXPECT ("t1_func", "t1_func1"));
4834   }
4835
4836   /* Check that completion mode works at each prefix of the expected
4837      symbol name.  */
4838   {
4839     static const char str[] = "function(int)";
4840     size_t len = strlen (str);
4841     std::string lookup;
4842
4843     for (size_t i = 1; i < len; i++)
4844       {
4845         lookup.assign (str, i);
4846         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4847                      EXPECT ("function"));
4848       }
4849   }
4850
4851   /* While "w" is a prefix of both components, the match function
4852      should still only be called once.  */
4853   {
4854     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4855                  EXPECT ("w1::w2"));
4856     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4857                  EXPECT ("w1::w2"));
4858   }
4859
4860   /* Same, with a "complicated" symbol.  */
4861   {
4862     static const char str[] = Z_SYM_NAME;
4863     size_t len = strlen (str);
4864     std::string lookup;
4865
4866     for (size_t i = 1; i < len; i++)
4867       {
4868         lookup.assign (str, i);
4869         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4870                      EXPECT (Z_SYM_NAME));
4871       }
4872   }
4873
4874   /* In FULL mode, an incomplete symbol doesn't match.  */
4875   {
4876     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4877                  {});
4878   }
4879
4880   /* A complete symbol with parameters matches any overload, since the
4881      index has no overload info.  */
4882   {
4883     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4884                  EXPECT ("std::zfunction", "std::zfunction2"));
4885     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4886                  EXPECT ("std::zfunction", "std::zfunction2"));
4887     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4888                  EXPECT ("std::zfunction", "std::zfunction2"));
4889   }
4890
4891   /* Check that whitespace is ignored appropriately.  A symbol with a
4892      template argument list. */
4893   {
4894     static const char expected[] = "ns::foo<int>";
4895     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4896                  EXPECT (expected));
4897     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4898                  EXPECT (expected));
4899   }
4900
4901   /* Check that whitespace is ignored appropriately.  A symbol with a
4902      template argument list that includes a pointer.  */
4903   {
4904     static const char expected[] = "ns::foo<char*>";
4905     /* Try both completion and non-completion modes.  */
4906     static const bool completion_mode[2] = {false, true};
4907     for (size_t i = 0; i < 2; i++)
4908       {
4909         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4910                      completion_mode[i], EXPECT (expected));
4911         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4912                      completion_mode[i], EXPECT (expected));
4913
4914         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4915                      completion_mode[i], EXPECT (expected));
4916         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4917                      completion_mode[i], EXPECT (expected));
4918       }
4919   }
4920
4921   {
4922     /* Check method qualifiers are ignored.  */
4923     static const char expected[] = "ns::foo<char*>";
4924     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4925                  symbol_name_match_type::FULL, true, EXPECT (expected));
4926     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4927                  symbol_name_match_type::FULL, true, EXPECT (expected));
4928     CHECK_MATCH ("foo < char * >  ( int ) const",
4929                  symbol_name_match_type::WILD, true, EXPECT (expected));
4930     CHECK_MATCH ("foo < char * >  ( int ) &&",
4931                  symbol_name_match_type::WILD, true, EXPECT (expected));
4932   }
4933
4934   /* Test lookup names that don't match anything.  */
4935   {
4936     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4937                  {});
4938
4939     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4940                  {});
4941   }
4942
4943   /* Some wild matching tests, exercising "(anonymous namespace)",
4944      which should not be confused with a parameter list.  */
4945   {
4946     static const char *syms[] = {
4947       "A::B::C",
4948       "B::C",
4949       "C",
4950       "A :: B :: C ( int )",
4951       "B :: C ( int )",
4952       "C ( int )",
4953     };
4954
4955     for (const char *s : syms)
4956       {
4957         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4958                      EXPECT ("(anonymous namespace)::A::B::C"));
4959       }
4960   }
4961
4962   {
4963     static const char expected[] = "ns2::tmpl<int>::foo2";
4964     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4965                  EXPECT (expected));
4966     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4967                  EXPECT (expected));
4968   }
4969
4970   SELF_CHECK (!any_mismatch);
4971
4972 #undef EXPECT
4973 #undef CHECK_MATCH
4974 }
4975
4976 static void
4977 run_test ()
4978 {
4979   test_mapped_index_find_name_component_bounds ();
4980   test_dw2_expand_symtabs_matching_symbol ();
4981 }
4982
4983 }} // namespace selftests::dw2_expand_symtabs_matching
4984
4985 #endif /* GDB_SELF_TEST */
4986
4987 /* If FILE_MATCHER is NULL or if PER_CU has
4988    dwarf2_per_cu_quick_data::MARK set (see
4989    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4990    EXPANSION_NOTIFY on it.  */
4991
4992 static void
4993 dw2_expand_symtabs_matching_one
4994   (struct dwarf2_per_cu_data *per_cu,
4995    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4996    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4997 {
4998   if (file_matcher == NULL || per_cu->v.quick->mark)
4999     {
5000       bool symtab_was_null
5001         = (per_cu->v.quick->compunit_symtab == NULL);
5002
5003       dw2_instantiate_symtab (per_cu, false);
5004
5005       if (expansion_notify != NULL
5006           && symtab_was_null
5007           && per_cu->v.quick->compunit_symtab != NULL)
5008         expansion_notify (per_cu->v.quick->compunit_symtab);
5009     }
5010 }
5011
5012 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5013    matched, to expand corresponding CUs that were marked.  IDX is the
5014    index of the symbol name that matched.  */
5015
5016 static void
5017 dw2_expand_marked_cus
5018   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5019    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5020    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5021    search_domain kind)
5022 {
5023   offset_type *vec, vec_len, vec_idx;
5024   bool global_seen = false;
5025   mapped_index &index = *dwarf2_per_objfile->index_table;
5026
5027   vec = (offset_type *) (index.constant_pool
5028                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5029   vec_len = MAYBE_SWAP (vec[0]);
5030   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5031     {
5032       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5033       /* This value is only valid for index versions >= 7.  */
5034       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5035       gdb_index_symbol_kind symbol_kind =
5036         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5037       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5038       /* Only check the symbol attributes if they're present.
5039          Indices prior to version 7 don't record them,
5040          and indices >= 7 may elide them for certain symbols
5041          (gold does this).  */
5042       int attrs_valid =
5043         (index.version >= 7
5044          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5045
5046       /* Work around gold/15646.  */
5047       if (attrs_valid)
5048         {
5049           if (!is_static && global_seen)
5050             continue;
5051           if (!is_static)
5052             global_seen = true;
5053         }
5054
5055       /* Only check the symbol's kind if it has one.  */
5056       if (attrs_valid)
5057         {
5058           switch (kind)
5059             {
5060             case VARIABLES_DOMAIN:
5061               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5062                 continue;
5063               break;
5064             case FUNCTIONS_DOMAIN:
5065               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5066                 continue;
5067               break;
5068             case TYPES_DOMAIN:
5069               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5070                 continue;
5071               break;
5072             default:
5073               break;
5074             }
5075         }
5076
5077       /* Don't crash on bad data.  */
5078       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5079                        + dwarf2_per_objfile->all_type_units.size ()))
5080         {
5081           complaint (_(".gdb_index entry has bad CU index"
5082                        " [in module %s]"),
5083                        objfile_name (dwarf2_per_objfile->objfile));
5084           continue;
5085         }
5086
5087       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5088       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5089                                        expansion_notify);
5090     }
5091 }
5092
5093 /* If FILE_MATCHER is non-NULL, set all the
5094    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5095    that match FILE_MATCHER.  */
5096
5097 static void
5098 dw_expand_symtabs_matching_file_matcher
5099   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5100    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5101 {
5102   if (file_matcher == NULL)
5103     return;
5104
5105   objfile *const objfile = dwarf2_per_objfile->objfile;
5106
5107   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5108                                             htab_eq_pointer,
5109                                             NULL, xcalloc, xfree));
5110   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5111                                                 htab_eq_pointer,
5112                                                 NULL, xcalloc, xfree));
5113
5114   /* The rule is CUs specify all the files, including those used by
5115      any TU, so there's no need to scan TUs here.  */
5116
5117   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5118     {
5119       QUIT;
5120
5121       per_cu->v.quick->mark = 0;
5122
5123       /* We only need to look at symtabs not already expanded.  */
5124       if (per_cu->v.quick->compunit_symtab)
5125         continue;
5126
5127       quick_file_names *file_data = dw2_get_file_names (per_cu);
5128       if (file_data == NULL)
5129         continue;
5130
5131       if (htab_find (visited_not_found.get (), file_data) != NULL)
5132         continue;
5133       else if (htab_find (visited_found.get (), file_data) != NULL)
5134         {
5135           per_cu->v.quick->mark = 1;
5136           continue;
5137         }
5138
5139       for (int j = 0; j < file_data->num_file_names; ++j)
5140         {
5141           const char *this_real_name;
5142
5143           if (file_matcher (file_data->file_names[j], false))
5144             {
5145               per_cu->v.quick->mark = 1;
5146               break;
5147             }
5148
5149           /* Before we invoke realpath, which can get expensive when many
5150              files are involved, do a quick comparison of the basenames.  */
5151           if (!basenames_may_differ
5152               && !file_matcher (lbasename (file_data->file_names[j]),
5153                                 true))
5154             continue;
5155
5156           this_real_name = dw2_get_real_path (objfile, file_data, j);
5157           if (file_matcher (this_real_name, false))
5158             {
5159               per_cu->v.quick->mark = 1;
5160               break;
5161             }
5162         }
5163
5164       void **slot = htab_find_slot (per_cu->v.quick->mark
5165                                     ? visited_found.get ()
5166                                     : visited_not_found.get (),
5167                                     file_data, INSERT);
5168       *slot = file_data;
5169     }
5170 }
5171
5172 static void
5173 dw2_expand_symtabs_matching
5174   (struct objfile *objfile,
5175    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5176    const lookup_name_info &lookup_name,
5177    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5178    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5179    enum search_domain kind)
5180 {
5181   struct dwarf2_per_objfile *dwarf2_per_objfile
5182     = get_dwarf2_per_objfile (objfile);
5183
5184   /* index_table is NULL if OBJF_READNOW.  */
5185   if (!dwarf2_per_objfile->index_table)
5186     return;
5187
5188   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5189
5190   mapped_index &index = *dwarf2_per_objfile->index_table;
5191
5192   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5193                                       symbol_matcher,
5194                                       kind, [&] (offset_type idx)
5195     {
5196       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5197                              expansion_notify, kind);
5198     });
5199 }
5200
5201 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5202    symtab.  */
5203
5204 static struct compunit_symtab *
5205 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5206                                           CORE_ADDR pc)
5207 {
5208   int i;
5209
5210   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5211       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5212     return cust;
5213
5214   if (cust->includes == NULL)
5215     return NULL;
5216
5217   for (i = 0; cust->includes[i]; ++i)
5218     {
5219       struct compunit_symtab *s = cust->includes[i];
5220
5221       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5222       if (s != NULL)
5223         return s;
5224     }
5225
5226   return NULL;
5227 }
5228
5229 static struct compunit_symtab *
5230 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5231                                   struct bound_minimal_symbol msymbol,
5232                                   CORE_ADDR pc,
5233                                   struct obj_section *section,
5234                                   int warn_if_readin)
5235 {
5236   struct dwarf2_per_cu_data *data;
5237   struct compunit_symtab *result;
5238
5239   if (!objfile->partial_symtabs->psymtabs_addrmap)
5240     return NULL;
5241
5242   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5243                                  SECT_OFF_TEXT (objfile));
5244   data = (struct dwarf2_per_cu_data *) addrmap_find
5245     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
5246   if (!data)
5247     return NULL;
5248
5249   if (warn_if_readin && data->v.quick->compunit_symtab)
5250     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5251              paddress (get_objfile_arch (objfile), pc));
5252
5253   result
5254     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5255                                                                         false),
5256                                                 pc);
5257   gdb_assert (result != NULL);
5258   return result;
5259 }
5260
5261 static void
5262 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5263                           void *data, int need_fullname)
5264 {
5265   struct dwarf2_per_objfile *dwarf2_per_objfile
5266     = get_dwarf2_per_objfile (objfile);
5267
5268   if (!dwarf2_per_objfile->filenames_cache)
5269     {
5270       dwarf2_per_objfile->filenames_cache.emplace ();
5271
5272       htab_up visited (htab_create_alloc (10,
5273                                           htab_hash_pointer, htab_eq_pointer,
5274                                           NULL, xcalloc, xfree));
5275
5276       /* The rule is CUs specify all the files, including those used
5277          by any TU, so there's no need to scan TUs here.  We can
5278          ignore file names coming from already-expanded CUs.  */
5279
5280       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5281         {
5282           if (per_cu->v.quick->compunit_symtab)
5283             {
5284               void **slot = htab_find_slot (visited.get (),
5285                                             per_cu->v.quick->file_names,
5286                                             INSERT);
5287
5288               *slot = per_cu->v.quick->file_names;
5289             }
5290         }
5291
5292       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5293         {
5294           /* We only need to look at symtabs not already expanded.  */
5295           if (per_cu->v.quick->compunit_symtab)
5296             continue;
5297
5298           quick_file_names *file_data = dw2_get_file_names (per_cu);
5299           if (file_data == NULL)
5300             continue;
5301
5302           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5303           if (*slot)
5304             {
5305               /* Already visited.  */
5306               continue;
5307             }
5308           *slot = file_data;
5309
5310           for (int j = 0; j < file_data->num_file_names; ++j)
5311             {
5312               const char *filename = file_data->file_names[j];
5313               dwarf2_per_objfile->filenames_cache->seen (filename);
5314             }
5315         }
5316     }
5317
5318   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5319     {
5320       gdb::unique_xmalloc_ptr<char> this_real_name;
5321
5322       if (need_fullname)
5323         this_real_name = gdb_realpath (filename);
5324       (*fun) (filename, this_real_name.get (), data);
5325     });
5326 }
5327
5328 static int
5329 dw2_has_symbols (struct objfile *objfile)
5330 {
5331   return 1;
5332 }
5333
5334 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5335 {
5336   dw2_has_symbols,
5337   dw2_find_last_source_symtab,
5338   dw2_forget_cached_source_info,
5339   dw2_map_symtabs_matching_filename,
5340   dw2_lookup_symbol,
5341   dw2_print_stats,
5342   dw2_dump,
5343   dw2_expand_symtabs_for_function,
5344   dw2_expand_all_symtabs,
5345   dw2_expand_symtabs_with_fullname,
5346   dw2_map_matching_symbols,
5347   dw2_expand_symtabs_matching,
5348   dw2_find_pc_sect_compunit_symtab,
5349   NULL,
5350   dw2_map_symbol_filenames
5351 };
5352
5353 /* DWARF-5 debug_names reader.  */
5354
5355 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5356 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5357
5358 /* A helper function that reads the .debug_names section in SECTION
5359    and fills in MAP.  FILENAME is the name of the file containing the
5360    section; it is used for error reporting.
5361
5362    Returns true if all went well, false otherwise.  */
5363
5364 static bool
5365 read_debug_names_from_section (struct objfile *objfile,
5366                                const char *filename,
5367                                struct dwarf2_section_info *section,
5368                                mapped_debug_names &map)
5369 {
5370   if (dwarf2_section_empty_p (section))
5371     return false;
5372
5373   /* Older elfutils strip versions could keep the section in the main
5374      executable while splitting it for the separate debug info file.  */
5375   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5376     return false;
5377
5378   dwarf2_read_section (objfile, section);
5379
5380   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5381
5382   const gdb_byte *addr = section->buffer;
5383
5384   bfd *const abfd = get_section_bfd_owner (section);
5385
5386   unsigned int bytes_read;
5387   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5388   addr += bytes_read;
5389
5390   map.dwarf5_is_dwarf64 = bytes_read != 4;
5391   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5392   if (bytes_read + length != section->size)
5393     {
5394       /* There may be multiple per-CU indices.  */
5395       warning (_("Section .debug_names in %s length %s does not match "
5396                  "section length %s, ignoring .debug_names."),
5397                filename, plongest (bytes_read + length),
5398                pulongest (section->size));
5399       return false;
5400     }
5401
5402   /* The version number.  */
5403   uint16_t version = read_2_bytes (abfd, addr);
5404   addr += 2;
5405   if (version != 5)
5406     {
5407       warning (_("Section .debug_names in %s has unsupported version %d, "
5408                  "ignoring .debug_names."),
5409                filename, version);
5410       return false;
5411     }
5412
5413   /* Padding.  */
5414   uint16_t padding = read_2_bytes (abfd, addr);
5415   addr += 2;
5416   if (padding != 0)
5417     {
5418       warning (_("Section .debug_names in %s has unsupported padding %d, "
5419                  "ignoring .debug_names."),
5420                filename, padding);
5421       return false;
5422     }
5423
5424   /* comp_unit_count - The number of CUs in the CU list.  */
5425   map.cu_count = read_4_bytes (abfd, addr);
5426   addr += 4;
5427
5428   /* local_type_unit_count - The number of TUs in the local TU
5429      list.  */
5430   map.tu_count = read_4_bytes (abfd, addr);
5431   addr += 4;
5432
5433   /* foreign_type_unit_count - The number of TUs in the foreign TU
5434      list.  */
5435   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5436   addr += 4;
5437   if (foreign_tu_count != 0)
5438     {
5439       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5440                  "ignoring .debug_names."),
5441                filename, static_cast<unsigned long> (foreign_tu_count));
5442       return false;
5443     }
5444
5445   /* bucket_count - The number of hash buckets in the hash lookup
5446      table.  */
5447   map.bucket_count = read_4_bytes (abfd, addr);
5448   addr += 4;
5449
5450   /* name_count - The number of unique names in the index.  */
5451   map.name_count = read_4_bytes (abfd, addr);
5452   addr += 4;
5453
5454   /* abbrev_table_size - The size in bytes of the abbreviations
5455      table.  */
5456   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5457   addr += 4;
5458
5459   /* augmentation_string_size - The size in bytes of the augmentation
5460      string.  This value is rounded up to a multiple of 4.  */
5461   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5462   addr += 4;
5463   map.augmentation_is_gdb = ((augmentation_string_size
5464                               == sizeof (dwarf5_augmentation))
5465                              && memcmp (addr, dwarf5_augmentation,
5466                                         sizeof (dwarf5_augmentation)) == 0);
5467   augmentation_string_size += (-augmentation_string_size) & 3;
5468   addr += augmentation_string_size;
5469
5470   /* List of CUs */
5471   map.cu_table_reordered = addr;
5472   addr += map.cu_count * map.offset_size;
5473
5474   /* List of Local TUs */
5475   map.tu_table_reordered = addr;
5476   addr += map.tu_count * map.offset_size;
5477
5478   /* Hash Lookup Table */
5479   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5480   addr += map.bucket_count * 4;
5481   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5482   addr += map.name_count * 4;
5483
5484   /* Name Table */
5485   map.name_table_string_offs_reordered = addr;
5486   addr += map.name_count * map.offset_size;
5487   map.name_table_entry_offs_reordered = addr;
5488   addr += map.name_count * map.offset_size;
5489
5490   const gdb_byte *abbrev_table_start = addr;
5491   for (;;)
5492     {
5493       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5494       addr += bytes_read;
5495       if (index_num == 0)
5496         break;
5497
5498       const auto insertpair
5499         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5500       if (!insertpair.second)
5501         {
5502           warning (_("Section .debug_names in %s has duplicate index %s, "
5503                      "ignoring .debug_names."),
5504                    filename, pulongest (index_num));
5505           return false;
5506         }
5507       mapped_debug_names::index_val &indexval = insertpair.first->second;
5508       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5509       addr += bytes_read;
5510
5511       for (;;)
5512         {
5513           mapped_debug_names::index_val::attr attr;
5514           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5515           addr += bytes_read;
5516           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5517           addr += bytes_read;
5518           if (attr.form == DW_FORM_implicit_const)
5519             {
5520               attr.implicit_const = read_signed_leb128 (abfd, addr,
5521                                                         &bytes_read);
5522               addr += bytes_read;
5523             }
5524           if (attr.dw_idx == 0 && attr.form == 0)
5525             break;
5526           indexval.attr_vec.push_back (std::move (attr));
5527         }
5528     }
5529   if (addr != abbrev_table_start + abbrev_table_size)
5530     {
5531       warning (_("Section .debug_names in %s has abbreviation_table "
5532                  "of size %s vs. written as %u, ignoring .debug_names."),
5533                filename, plongest (addr - abbrev_table_start),
5534                abbrev_table_size);
5535       return false;
5536     }
5537   map.entry_pool = addr;
5538
5539   return true;
5540 }
5541
5542 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5543    list.  */
5544
5545 static void
5546 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5547                                   const mapped_debug_names &map,
5548                                   dwarf2_section_info &section,
5549                                   bool is_dwz)
5550 {
5551   sect_offset sect_off_prev;
5552   for (uint32_t i = 0; i <= map.cu_count; ++i)
5553     {
5554       sect_offset sect_off_next;
5555       if (i < map.cu_count)
5556         {
5557           sect_off_next
5558             = (sect_offset) (extract_unsigned_integer
5559                              (map.cu_table_reordered + i * map.offset_size,
5560                               map.offset_size,
5561                               map.dwarf5_byte_order));
5562         }
5563       else
5564         sect_off_next = (sect_offset) section.size;
5565       if (i >= 1)
5566         {
5567           const ULONGEST length = sect_off_next - sect_off_prev;
5568           dwarf2_per_cu_data *per_cu
5569             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5570                                          sect_off_prev, length);
5571           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5572         }
5573       sect_off_prev = sect_off_next;
5574     }
5575 }
5576
5577 /* Read the CU list from the mapped index, and use it to create all
5578    the CU objects for this dwarf2_per_objfile.  */
5579
5580 static void
5581 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5582                              const mapped_debug_names &map,
5583                              const mapped_debug_names &dwz_map)
5584 {
5585   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5586   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5587
5588   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5589                                     dwarf2_per_objfile->info,
5590                                     false /* is_dwz */);
5591
5592   if (dwz_map.cu_count == 0)
5593     return;
5594
5595   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5596   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5597                                     true /* is_dwz */);
5598 }
5599
5600 /* Read .debug_names.  If everything went ok, initialize the "quick"
5601    elements of all the CUs and return true.  Otherwise, return false.  */
5602
5603 static bool
5604 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5605 {
5606   std::unique_ptr<mapped_debug_names> map
5607     (new mapped_debug_names (dwarf2_per_objfile));
5608   mapped_debug_names dwz_map (dwarf2_per_objfile);
5609   struct objfile *objfile = dwarf2_per_objfile->objfile;
5610
5611   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5612                                       &dwarf2_per_objfile->debug_names,
5613                                       *map))
5614     return false;
5615
5616   /* Don't use the index if it's empty.  */
5617   if (map->name_count == 0)
5618     return false;
5619
5620   /* If there is a .dwz file, read it so we can get its CU list as
5621      well.  */
5622   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5623   if (dwz != NULL)
5624     {
5625       if (!read_debug_names_from_section (objfile,
5626                                           bfd_get_filename (dwz->dwz_bfd),
5627                                           &dwz->debug_names, dwz_map))
5628         {
5629           warning (_("could not read '.debug_names' section from %s; skipping"),
5630                    bfd_get_filename (dwz->dwz_bfd));
5631           return false;
5632         }
5633     }
5634
5635   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5636
5637   if (map->tu_count != 0)
5638     {
5639       /* We can only handle a single .debug_types when we have an
5640          index.  */
5641       if (dwarf2_per_objfile->types.size () != 1)
5642         return false;
5643
5644       dwarf2_section_info *section = &dwarf2_per_objfile->types[0];
5645
5646       create_signatured_type_table_from_debug_names
5647         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5648     }
5649
5650   create_addrmap_from_aranges (dwarf2_per_objfile,
5651                                &dwarf2_per_objfile->debug_aranges);
5652
5653   dwarf2_per_objfile->debug_names_table = std::move (map);
5654   dwarf2_per_objfile->using_index = 1;
5655   dwarf2_per_objfile->quick_file_names_table =
5656     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5657
5658   return true;
5659 }
5660
5661 /* Type used to manage iterating over all CUs looking for a symbol for
5662    .debug_names.  */
5663
5664 class dw2_debug_names_iterator
5665 {
5666 public:
5667   dw2_debug_names_iterator (const mapped_debug_names &map,
5668                             gdb::optional<block_enum> block_index,
5669                             domain_enum domain,
5670                             const char *name)
5671     : m_map (map), m_block_index (block_index), m_domain (domain),
5672       m_addr (find_vec_in_debug_names (map, name))
5673   {}
5674
5675   dw2_debug_names_iterator (const mapped_debug_names &map,
5676                             search_domain search, uint32_t namei)
5677     : m_map (map),
5678       m_search (search),
5679       m_addr (find_vec_in_debug_names (map, namei))
5680   {}
5681
5682   /* Return the next matching CU or NULL if there are no more.  */
5683   dwarf2_per_cu_data *next ();
5684
5685 private:
5686   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5687                                                   const char *name);
5688   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5689                                                   uint32_t namei);
5690
5691   /* The internalized form of .debug_names.  */
5692   const mapped_debug_names &m_map;
5693
5694   /* If set, only look for symbols that match that block.  Valid values are
5695      GLOBAL_BLOCK and STATIC_BLOCK.  */
5696   const gdb::optional<block_enum> m_block_index;
5697
5698   /* The kind of symbol we're looking for.  */
5699   const domain_enum m_domain = UNDEF_DOMAIN;
5700   const search_domain m_search = ALL_DOMAIN;
5701
5702   /* The list of CUs from the index entry of the symbol, or NULL if
5703      not found.  */
5704   const gdb_byte *m_addr;
5705 };
5706
5707 const char *
5708 mapped_debug_names::namei_to_name (uint32_t namei) const
5709 {
5710   const ULONGEST namei_string_offs
5711     = extract_unsigned_integer ((name_table_string_offs_reordered
5712                                  + namei * offset_size),
5713                                 offset_size,
5714                                 dwarf5_byte_order);
5715   return read_indirect_string_at_offset
5716     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5717 }
5718
5719 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5720    found, return pointer to its pool data.  If NAME cannot be found,
5721    return NULL.  */
5722
5723 const gdb_byte *
5724 dw2_debug_names_iterator::find_vec_in_debug_names
5725   (const mapped_debug_names &map, const char *name)
5726 {
5727   int (*cmp) (const char *, const char *);
5728
5729   gdb::unique_xmalloc_ptr<char> without_params;
5730   if (current_language->la_language == language_cplus
5731       || current_language->la_language == language_fortran
5732       || current_language->la_language == language_d)
5733     {
5734       /* NAME is already canonical.  Drop any qualifiers as
5735          .debug_names does not contain any.  */
5736
5737       if (strchr (name, '(') != NULL)
5738         {
5739           without_params = cp_remove_params (name);
5740           if (without_params != NULL)
5741             name = without_params.get ();
5742         }
5743     }
5744
5745   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5746
5747   const uint32_t full_hash = dwarf5_djb_hash (name);
5748   uint32_t namei
5749     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5750                                 (map.bucket_table_reordered
5751                                  + (full_hash % map.bucket_count)), 4,
5752                                 map.dwarf5_byte_order);
5753   if (namei == 0)
5754     return NULL;
5755   --namei;
5756   if (namei >= map.name_count)
5757     {
5758       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5759                    "[in module %s]"),
5760                  namei, map.name_count,
5761                  objfile_name (map.dwarf2_per_objfile->objfile));
5762       return NULL;
5763     }
5764
5765   for (;;)
5766     {
5767       const uint32_t namei_full_hash
5768         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5769                                     (map.hash_table_reordered + namei), 4,
5770                                     map.dwarf5_byte_order);
5771       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5772         return NULL;
5773
5774       if (full_hash == namei_full_hash)
5775         {
5776           const char *const namei_string = map.namei_to_name (namei);
5777
5778 #if 0 /* An expensive sanity check.  */
5779           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5780             {
5781               complaint (_("Wrong .debug_names hash for string at index %u "
5782                            "[in module %s]"),
5783                          namei, objfile_name (dwarf2_per_objfile->objfile));
5784               return NULL;
5785             }
5786 #endif
5787
5788           if (cmp (namei_string, name) == 0)
5789             {
5790               const ULONGEST namei_entry_offs
5791                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5792                                              + namei * map.offset_size),
5793                                             map.offset_size, map.dwarf5_byte_order);
5794               return map.entry_pool + namei_entry_offs;
5795             }
5796         }
5797
5798       ++namei;
5799       if (namei >= map.name_count)
5800         return NULL;
5801     }
5802 }
5803
5804 const gdb_byte *
5805 dw2_debug_names_iterator::find_vec_in_debug_names
5806   (const mapped_debug_names &map, uint32_t namei)
5807 {
5808   if (namei >= map.name_count)
5809     {
5810       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5811                    "[in module %s]"),
5812                  namei, map.name_count,
5813                  objfile_name (map.dwarf2_per_objfile->objfile));
5814       return NULL;
5815     }
5816
5817   const ULONGEST namei_entry_offs
5818     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5819                                  + namei * map.offset_size),
5820                                 map.offset_size, map.dwarf5_byte_order);
5821   return map.entry_pool + namei_entry_offs;
5822 }
5823
5824 /* See dw2_debug_names_iterator.  */
5825
5826 dwarf2_per_cu_data *
5827 dw2_debug_names_iterator::next ()
5828 {
5829   if (m_addr == NULL)
5830     return NULL;
5831
5832   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5833   struct objfile *objfile = dwarf2_per_objfile->objfile;
5834   bfd *const abfd = objfile->obfd;
5835
5836  again:
5837
5838   unsigned int bytes_read;
5839   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5840   m_addr += bytes_read;
5841   if (abbrev == 0)
5842     return NULL;
5843
5844   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5845   if (indexval_it == m_map.abbrev_map.cend ())
5846     {
5847       complaint (_("Wrong .debug_names undefined abbrev code %s "
5848                    "[in module %s]"),
5849                  pulongest (abbrev), objfile_name (objfile));
5850       return NULL;
5851     }
5852   const mapped_debug_names::index_val &indexval = indexval_it->second;
5853   enum class symbol_linkage {
5854     unknown,
5855     static_,
5856     extern_,
5857   } symbol_linkage_ = symbol_linkage::unknown;
5858   dwarf2_per_cu_data *per_cu = NULL;
5859   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5860     {
5861       ULONGEST ull;
5862       switch (attr.form)
5863         {
5864         case DW_FORM_implicit_const:
5865           ull = attr.implicit_const;
5866           break;
5867         case DW_FORM_flag_present:
5868           ull = 1;
5869           break;
5870         case DW_FORM_udata:
5871           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5872           m_addr += bytes_read;
5873           break;
5874         default:
5875           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5876                      dwarf_form_name (attr.form),
5877                      objfile_name (objfile));
5878           return NULL;
5879         }
5880       switch (attr.dw_idx)
5881         {
5882         case DW_IDX_compile_unit:
5883           /* Don't crash on bad data.  */
5884           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5885             {
5886               complaint (_(".debug_names entry has bad CU index %s"
5887                            " [in module %s]"),
5888                          pulongest (ull),
5889                          objfile_name (dwarf2_per_objfile->objfile));
5890               continue;
5891             }
5892           per_cu = dwarf2_per_objfile->get_cutu (ull);
5893           break;
5894         case DW_IDX_type_unit:
5895           /* Don't crash on bad data.  */
5896           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5897             {
5898               complaint (_(".debug_names entry has bad TU index %s"
5899                            " [in module %s]"),
5900                          pulongest (ull),
5901                          objfile_name (dwarf2_per_objfile->objfile));
5902               continue;
5903             }
5904           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5905           break;
5906         case DW_IDX_GNU_internal:
5907           if (!m_map.augmentation_is_gdb)
5908             break;
5909           symbol_linkage_ = symbol_linkage::static_;
5910           break;
5911         case DW_IDX_GNU_external:
5912           if (!m_map.augmentation_is_gdb)
5913             break;
5914           symbol_linkage_ = symbol_linkage::extern_;
5915           break;
5916         }
5917     }
5918
5919   /* Skip if already read in.  */
5920   if (per_cu->v.quick->compunit_symtab)
5921     goto again;
5922
5923   /* Check static vs global.  */
5924   if (symbol_linkage_ != symbol_linkage::unknown && m_block_index.has_value ())
5925     {
5926         const bool want_static = *m_block_index == STATIC_BLOCK;
5927         const bool symbol_is_static =
5928           symbol_linkage_ == symbol_linkage::static_;
5929         if (want_static != symbol_is_static)
5930           goto again;
5931     }
5932
5933   /* Match dw2_symtab_iter_next, symbol_kind
5934      and debug_names::psymbol_tag.  */
5935   switch (m_domain)
5936     {
5937     case VAR_DOMAIN:
5938       switch (indexval.dwarf_tag)
5939         {
5940         case DW_TAG_variable:
5941         case DW_TAG_subprogram:
5942         /* Some types are also in VAR_DOMAIN.  */
5943         case DW_TAG_typedef:
5944         case DW_TAG_structure_type:
5945           break;
5946         default:
5947           goto again;
5948         }
5949       break;
5950     case STRUCT_DOMAIN:
5951       switch (indexval.dwarf_tag)
5952         {
5953         case DW_TAG_typedef:
5954         case DW_TAG_structure_type:
5955           break;
5956         default:
5957           goto again;
5958         }
5959       break;
5960     case LABEL_DOMAIN:
5961       switch (indexval.dwarf_tag)
5962         {
5963         case 0:
5964         case DW_TAG_variable:
5965           break;
5966         default:
5967           goto again;
5968         }
5969       break;
5970     default:
5971       break;
5972     }
5973
5974   /* Match dw2_expand_symtabs_matching, symbol_kind and
5975      debug_names::psymbol_tag.  */
5976   switch (m_search)
5977     {
5978     case VARIABLES_DOMAIN:
5979       switch (indexval.dwarf_tag)
5980         {
5981         case DW_TAG_variable:
5982           break;
5983         default:
5984           goto again;
5985         }
5986       break;
5987     case FUNCTIONS_DOMAIN:
5988       switch (indexval.dwarf_tag)
5989         {
5990         case DW_TAG_subprogram:
5991           break;
5992         default:
5993           goto again;
5994         }
5995       break;
5996     case TYPES_DOMAIN:
5997       switch (indexval.dwarf_tag)
5998         {
5999         case DW_TAG_typedef:
6000         case DW_TAG_structure_type:
6001           break;
6002         default:
6003           goto again;
6004         }
6005       break;
6006     default:
6007       break;
6008     }
6009
6010   return per_cu;
6011 }
6012
6013 static struct compunit_symtab *
6014 dw2_debug_names_lookup_symbol (struct objfile *objfile, block_enum block_index,
6015                                const char *name, domain_enum domain)
6016 {
6017   struct dwarf2_per_objfile *dwarf2_per_objfile
6018     = get_dwarf2_per_objfile (objfile);
6019
6020   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6021   if (!mapp)
6022     {
6023       /* index is NULL if OBJF_READNOW.  */
6024       return NULL;
6025     }
6026   const auto &map = *mapp;
6027
6028   dw2_debug_names_iterator iter (map, block_index, domain, name);
6029
6030   struct compunit_symtab *stab_best = NULL;
6031   struct dwarf2_per_cu_data *per_cu;
6032   while ((per_cu = iter.next ()) != NULL)
6033     {
6034       struct symbol *sym, *with_opaque = NULL;
6035       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6036       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6037       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6038
6039       sym = block_find_symbol (block, name, domain,
6040                                block_find_non_opaque_type_preferred,
6041                                &with_opaque);
6042
6043       /* Some caution must be observed with overloaded functions and
6044          methods, since the index will not contain any overload
6045          information (but NAME might contain it).  */
6046
6047       if (sym != NULL
6048           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6049         return stab;
6050       if (with_opaque != NULL
6051           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6052         stab_best = stab;
6053
6054       /* Keep looking through other CUs.  */
6055     }
6056
6057   return stab_best;
6058 }
6059
6060 /* This dumps minimal information about .debug_names.  It is called
6061    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6062    uses this to verify that .debug_names has been loaded.  */
6063
6064 static void
6065 dw2_debug_names_dump (struct objfile *objfile)
6066 {
6067   struct dwarf2_per_objfile *dwarf2_per_objfile
6068     = get_dwarf2_per_objfile (objfile);
6069
6070   gdb_assert (dwarf2_per_objfile->using_index);
6071   printf_filtered (".debug_names:");
6072   if (dwarf2_per_objfile->debug_names_table)
6073     printf_filtered (" exists\n");
6074   else
6075     printf_filtered (" faked for \"readnow\"\n");
6076   printf_filtered ("\n");
6077 }
6078
6079 static void
6080 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6081                                              const char *func_name)
6082 {
6083   struct dwarf2_per_objfile *dwarf2_per_objfile
6084     = get_dwarf2_per_objfile (objfile);
6085
6086   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6087   if (dwarf2_per_objfile->debug_names_table)
6088     {
6089       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6090
6091       dw2_debug_names_iterator iter (map, {}, VAR_DOMAIN, func_name);
6092
6093       struct dwarf2_per_cu_data *per_cu;
6094       while ((per_cu = iter.next ()) != NULL)
6095         dw2_instantiate_symtab (per_cu, false);
6096     }
6097 }
6098
6099 static void
6100 dw2_debug_names_expand_symtabs_matching
6101   (struct objfile *objfile,
6102    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6103    const lookup_name_info &lookup_name,
6104    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6105    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6106    enum search_domain kind)
6107 {
6108   struct dwarf2_per_objfile *dwarf2_per_objfile
6109     = get_dwarf2_per_objfile (objfile);
6110
6111   /* debug_names_table is NULL if OBJF_READNOW.  */
6112   if (!dwarf2_per_objfile->debug_names_table)
6113     return;
6114
6115   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6116
6117   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6118
6119   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6120                                       symbol_matcher,
6121                                       kind, [&] (offset_type namei)
6122     {
6123       /* The name was matched, now expand corresponding CUs that were
6124          marked.  */
6125       dw2_debug_names_iterator iter (map, kind, namei);
6126
6127       struct dwarf2_per_cu_data *per_cu;
6128       while ((per_cu = iter.next ()) != NULL)
6129         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6130                                          expansion_notify);
6131     });
6132 }
6133
6134 const struct quick_symbol_functions dwarf2_debug_names_functions =
6135 {
6136   dw2_has_symbols,
6137   dw2_find_last_source_symtab,
6138   dw2_forget_cached_source_info,
6139   dw2_map_symtabs_matching_filename,
6140   dw2_debug_names_lookup_symbol,
6141   dw2_print_stats,
6142   dw2_debug_names_dump,
6143   dw2_debug_names_expand_symtabs_for_function,
6144   dw2_expand_all_symtabs,
6145   dw2_expand_symtabs_with_fullname,
6146   dw2_map_matching_symbols,
6147   dw2_debug_names_expand_symtabs_matching,
6148   dw2_find_pc_sect_compunit_symtab,
6149   NULL,
6150   dw2_map_symbol_filenames
6151 };
6152
6153 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
6154    to either a dwarf2_per_objfile or dwz_file object.  */
6155
6156 template <typename T>
6157 static gdb::array_view<const gdb_byte>
6158 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
6159 {
6160   dwarf2_section_info *section = &section_owner->gdb_index;
6161
6162   if (dwarf2_section_empty_p (section))
6163     return {};
6164
6165   /* Older elfutils strip versions could keep the section in the main
6166      executable while splitting it for the separate debug info file.  */
6167   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
6168     return {};
6169
6170   dwarf2_read_section (obj, section);
6171
6172   /* dwarf2_section_info::size is a bfd_size_type, while
6173      gdb::array_view works with size_t.  On 32-bit hosts, with
6174      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
6175      is 32-bit.  So we need an explicit narrowing conversion here.
6176      This is fine, because it's impossible to allocate or mmap an
6177      array/buffer larger than what size_t can represent.  */
6178   return gdb::make_array_view (section->buffer, section->size);
6179 }
6180
6181 /* Lookup the index cache for the contents of the index associated to
6182    DWARF2_OBJ.  */
6183
6184 static gdb::array_view<const gdb_byte>
6185 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
6186 {
6187   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
6188   if (build_id == nullptr)
6189     return {};
6190
6191   return global_index_cache.lookup_gdb_index (build_id,
6192                                               &dwarf2_obj->index_cache_res);
6193 }
6194
6195 /* Same as the above, but for DWZ.  */
6196
6197 static gdb::array_view<const gdb_byte>
6198 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
6199 {
6200   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
6201   if (build_id == nullptr)
6202     return {};
6203
6204   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
6205 }
6206
6207 /* See symfile.h.  */
6208
6209 bool
6210 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6211 {
6212   struct dwarf2_per_objfile *dwarf2_per_objfile
6213     = get_dwarf2_per_objfile (objfile);
6214
6215   /* If we're about to read full symbols, don't bother with the
6216      indices.  In this case we also don't care if some other debug
6217      format is making psymtabs, because they are all about to be
6218      expanded anyway.  */
6219   if ((objfile->flags & OBJF_READNOW))
6220     {
6221       dwarf2_per_objfile->using_index = 1;
6222       create_all_comp_units (dwarf2_per_objfile);
6223       create_all_type_units (dwarf2_per_objfile);
6224       dwarf2_per_objfile->quick_file_names_table
6225         = create_quick_file_names_table
6226             (dwarf2_per_objfile->all_comp_units.size ());
6227
6228       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6229                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6230         {
6231           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6232
6233           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6234                                             struct dwarf2_per_cu_quick_data);
6235         }
6236
6237       /* Return 1 so that gdb sees the "quick" functions.  However,
6238          these functions will be no-ops because we will have expanded
6239          all symtabs.  */
6240       *index_kind = dw_index_kind::GDB_INDEX;
6241       return true;
6242     }
6243
6244   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6245     {
6246       *index_kind = dw_index_kind::DEBUG_NAMES;
6247       return true;
6248     }
6249
6250   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6251                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6252                              get_gdb_index_contents_from_section<dwz_file>))
6253     {
6254       *index_kind = dw_index_kind::GDB_INDEX;
6255       return true;
6256     }
6257
6258   /* ... otherwise, try to find the index in the index cache.  */
6259   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6260                              get_gdb_index_contents_from_cache,
6261                              get_gdb_index_contents_from_cache_dwz))
6262     {
6263       global_index_cache.hit ();
6264       *index_kind = dw_index_kind::GDB_INDEX;
6265       return true;
6266     }
6267
6268   global_index_cache.miss ();
6269   return false;
6270 }
6271
6272 \f
6273
6274 /* Build a partial symbol table.  */
6275
6276 void
6277 dwarf2_build_psymtabs (struct objfile *objfile)
6278 {
6279   struct dwarf2_per_objfile *dwarf2_per_objfile
6280     = get_dwarf2_per_objfile (objfile);
6281
6282   init_psymbol_list (objfile, 1024);
6283
6284   try
6285     {
6286       /* This isn't really ideal: all the data we allocate on the
6287          objfile's obstack is still uselessly kept around.  However,
6288          freeing it seems unsafe.  */
6289       psymtab_discarder psymtabs (objfile);
6290       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6291       psymtabs.keep ();
6292
6293       /* (maybe) store an index in the cache.  */
6294       global_index_cache.store (dwarf2_per_objfile);
6295     }
6296   catch (const gdb_exception_error &except)
6297     {
6298       exception_print (gdb_stderr, except);
6299     }
6300 }
6301
6302 /* Return the total length of the CU described by HEADER.  */
6303
6304 static unsigned int
6305 get_cu_length (const struct comp_unit_head *header)
6306 {
6307   return header->initial_length_size + header->length;
6308 }
6309
6310 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6311
6312 static inline bool
6313 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6314 {
6315   sect_offset bottom = cu_header->sect_off;
6316   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6317
6318   return sect_off >= bottom && sect_off < top;
6319 }
6320
6321 /* Find the base address of the compilation unit for range lists and
6322    location lists.  It will normally be specified by DW_AT_low_pc.
6323    In DWARF-3 draft 4, the base address could be overridden by
6324    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6325    compilation units with discontinuous ranges.  */
6326
6327 static void
6328 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6329 {
6330   struct attribute *attr;
6331
6332   cu->base_known = 0;
6333   cu->base_address = 0;
6334
6335   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6336   if (attr)
6337     {
6338       cu->base_address = attr_value_as_address (attr);
6339       cu->base_known = 1;
6340     }
6341   else
6342     {
6343       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6344       if (attr)
6345         {
6346           cu->base_address = attr_value_as_address (attr);
6347           cu->base_known = 1;
6348         }
6349     }
6350 }
6351
6352 /* Read in the comp unit header information from the debug_info at info_ptr.
6353    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6354    NOTE: This leaves members offset, first_die_offset to be filled in
6355    by the caller.  */
6356
6357 static const gdb_byte *
6358 read_comp_unit_head (struct comp_unit_head *cu_header,
6359                      const gdb_byte *info_ptr,
6360                      struct dwarf2_section_info *section,
6361                      rcuh_kind section_kind)
6362 {
6363   int signed_addr;
6364   unsigned int bytes_read;
6365   const char *filename = get_section_file_name (section);
6366   bfd *abfd = get_section_bfd_owner (section);
6367
6368   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6369   cu_header->initial_length_size = bytes_read;
6370   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6371   info_ptr += bytes_read;
6372   cu_header->version = read_2_bytes (abfd, info_ptr);
6373   if (cu_header->version < 2 || cu_header->version > 5)
6374     error (_("Dwarf Error: wrong version in compilation unit header "
6375            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6376            cu_header->version, filename);
6377   info_ptr += 2;
6378   if (cu_header->version < 5)
6379     switch (section_kind)
6380       {
6381       case rcuh_kind::COMPILE:
6382         cu_header->unit_type = DW_UT_compile;
6383         break;
6384       case rcuh_kind::TYPE:
6385         cu_header->unit_type = DW_UT_type;
6386         break;
6387       default:
6388         internal_error (__FILE__, __LINE__,
6389                         _("read_comp_unit_head: invalid section_kind"));
6390       }
6391   else
6392     {
6393       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6394                                                  (read_1_byte (abfd, info_ptr));
6395       info_ptr += 1;
6396       switch (cu_header->unit_type)
6397         {
6398         case DW_UT_compile:
6399         case DW_UT_partial:
6400         case DW_UT_skeleton:
6401         case DW_UT_split_compile:
6402           if (section_kind != rcuh_kind::COMPILE)
6403             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6404                    "(is %s, should be %s) [in module %s]"),
6405                    dwarf_unit_type_name (cu_header->unit_type),
6406                    dwarf_unit_type_name (DW_UT_type), filename);
6407           break;
6408         case DW_UT_type:
6409         case DW_UT_split_type:
6410           section_kind = rcuh_kind::TYPE;
6411           break;
6412         default:
6413           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6414                  "(is %#04x, should be one of: %s, %s, %s, %s or %s) "
6415                  "[in module %s]"), cu_header->unit_type,
6416                  dwarf_unit_type_name (DW_UT_compile),
6417                  dwarf_unit_type_name (DW_UT_skeleton),
6418                  dwarf_unit_type_name (DW_UT_split_compile),
6419                  dwarf_unit_type_name (DW_UT_type),
6420                  dwarf_unit_type_name (DW_UT_split_type), filename);
6421         }
6422
6423       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6424       info_ptr += 1;
6425     }
6426   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6427                                                           cu_header,
6428                                                           &bytes_read);
6429   info_ptr += bytes_read;
6430   if (cu_header->version < 5)
6431     {
6432       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6433       info_ptr += 1;
6434     }
6435   signed_addr = bfd_get_sign_extend_vma (abfd);
6436   if (signed_addr < 0)
6437     internal_error (__FILE__, __LINE__,
6438                     _("read_comp_unit_head: dwarf from non elf file"));
6439   cu_header->signed_addr_p = signed_addr;
6440
6441   bool header_has_signature = section_kind == rcuh_kind::TYPE
6442     || cu_header->unit_type == DW_UT_skeleton
6443     || cu_header->unit_type == DW_UT_split_compile;
6444
6445   if (header_has_signature)
6446     {
6447       cu_header->signature = read_8_bytes (abfd, info_ptr);
6448       info_ptr += 8;
6449     }
6450
6451   if (section_kind == rcuh_kind::TYPE)
6452     {
6453       LONGEST type_offset;
6454       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6455       info_ptr += bytes_read;
6456       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6457       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6458         error (_("Dwarf Error: Too big type_offset in compilation unit "
6459                "header (is %s) [in module %s]"), plongest (type_offset),
6460                filename);
6461     }
6462
6463   return info_ptr;
6464 }
6465
6466 /* Helper function that returns the proper abbrev section for
6467    THIS_CU.  */
6468
6469 static struct dwarf2_section_info *
6470 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6471 {
6472   struct dwarf2_section_info *abbrev;
6473   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6474
6475   if (this_cu->is_dwz)
6476     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6477   else
6478     abbrev = &dwarf2_per_objfile->abbrev;
6479
6480   return abbrev;
6481 }
6482
6483 /* Subroutine of read_and_check_comp_unit_head and
6484    read_and_check_type_unit_head to simplify them.
6485    Perform various error checking on the header.  */
6486
6487 static void
6488 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6489                             struct comp_unit_head *header,
6490                             struct dwarf2_section_info *section,
6491                             struct dwarf2_section_info *abbrev_section)
6492 {
6493   const char *filename = get_section_file_name (section);
6494
6495   if (to_underlying (header->abbrev_sect_off)
6496       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6497     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6498            "(offset %s + 6) [in module %s]"),
6499            sect_offset_str (header->abbrev_sect_off),
6500            sect_offset_str (header->sect_off),
6501            filename);
6502
6503   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6504      avoid potential 32-bit overflow.  */
6505   if (((ULONGEST) header->sect_off + get_cu_length (header))
6506       > section->size)
6507     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6508            "(offset %s + 0) [in module %s]"),
6509            header->length, sect_offset_str (header->sect_off),
6510            filename);
6511 }
6512
6513 /* Read in a CU/TU header and perform some basic error checking.
6514    The contents of the header are stored in HEADER.
6515    The result is a pointer to the start of the first DIE.  */
6516
6517 static const gdb_byte *
6518 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6519                                struct comp_unit_head *header,
6520                                struct dwarf2_section_info *section,
6521                                struct dwarf2_section_info *abbrev_section,
6522                                const gdb_byte *info_ptr,
6523                                rcuh_kind section_kind)
6524 {
6525   const gdb_byte *beg_of_comp_unit = info_ptr;
6526
6527   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6528
6529   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6530
6531   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6532
6533   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6534                               abbrev_section);
6535
6536   return info_ptr;
6537 }
6538
6539 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6540
6541 static sect_offset
6542 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6543                     struct dwarf2_section_info *section,
6544                     sect_offset sect_off)
6545 {
6546   bfd *abfd = get_section_bfd_owner (section);
6547   const gdb_byte *info_ptr;
6548   unsigned int initial_length_size, offset_size;
6549   uint16_t version;
6550
6551   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6552   info_ptr = section->buffer + to_underlying (sect_off);
6553   read_initial_length (abfd, info_ptr, &initial_length_size);
6554   offset_size = initial_length_size == 4 ? 4 : 8;
6555   info_ptr += initial_length_size;
6556
6557   version = read_2_bytes (abfd, info_ptr);
6558   info_ptr += 2;
6559   if (version >= 5)
6560     {
6561       /* Skip unit type and address size.  */
6562       info_ptr += 2;
6563     }
6564
6565   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6566 }
6567
6568 /* Allocate a new partial symtab for file named NAME and mark this new
6569    partial symtab as being an include of PST.  */
6570
6571 static void
6572 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6573                                struct objfile *objfile)
6574 {
6575   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6576
6577   if (!IS_ABSOLUTE_PATH (subpst->filename))
6578     {
6579       /* It shares objfile->objfile_obstack.  */
6580       subpst->dirname = pst->dirname;
6581     }
6582
6583   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
6584   subpst->dependencies[0] = pst;
6585   subpst->number_of_dependencies = 1;
6586
6587   subpst->read_symtab = pst->read_symtab;
6588
6589   /* No private part is necessary for include psymtabs.  This property
6590      can be used to differentiate between such include psymtabs and
6591      the regular ones.  */
6592   subpst->read_symtab_private = NULL;
6593 }
6594
6595 /* Read the Line Number Program data and extract the list of files
6596    included by the source file represented by PST.  Build an include
6597    partial symtab for each of these included files.  */
6598
6599 static void
6600 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6601                                struct die_info *die,
6602                                struct partial_symtab *pst)
6603 {
6604   line_header_up lh;
6605   struct attribute *attr;
6606
6607   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6608   if (attr)
6609     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6610   if (lh == NULL)
6611     return;  /* No linetable, so no includes.  */
6612
6613   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6614      that we pass in the raw text_low here; that is ok because we're
6615      only decoding the line table to make include partial symtabs, and
6616      so the addresses aren't really used.  */
6617   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6618                       pst->raw_text_low (), 1);
6619 }
6620
6621 static hashval_t
6622 hash_signatured_type (const void *item)
6623 {
6624   const struct signatured_type *sig_type
6625     = (const struct signatured_type *) item;
6626
6627   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6628   return sig_type->signature;
6629 }
6630
6631 static int
6632 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6633 {
6634   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6635   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6636
6637   return lhs->signature == rhs->signature;
6638 }
6639
6640 /* Allocate a hash table for signatured types.  */
6641
6642 static htab_t
6643 allocate_signatured_type_table (struct objfile *objfile)
6644 {
6645   return htab_create_alloc_ex (41,
6646                                hash_signatured_type,
6647                                eq_signatured_type,
6648                                NULL,
6649                                &objfile->objfile_obstack,
6650                                hashtab_obstack_allocate,
6651                                dummy_obstack_deallocate);
6652 }
6653
6654 /* A helper function to add a signatured type CU to a table.  */
6655
6656 static int
6657 add_signatured_type_cu_to_table (void **slot, void *datum)
6658 {
6659   struct signatured_type *sigt = (struct signatured_type *) *slot;
6660   std::vector<signatured_type *> *all_type_units
6661     = (std::vector<signatured_type *> *) datum;
6662
6663   all_type_units->push_back (sigt);
6664
6665   return 1;
6666 }
6667
6668 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6669    and fill them into TYPES_HTAB.  It will process only type units,
6670    therefore DW_UT_type.  */
6671
6672 static void
6673 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6674                               struct dwo_file *dwo_file,
6675                               dwarf2_section_info *section, htab_t &types_htab,
6676                               rcuh_kind section_kind)
6677 {
6678   struct objfile *objfile = dwarf2_per_objfile->objfile;
6679   struct dwarf2_section_info *abbrev_section;
6680   bfd *abfd;
6681   const gdb_byte *info_ptr, *end_ptr;
6682
6683   abbrev_section = (dwo_file != NULL
6684                     ? &dwo_file->sections.abbrev
6685                     : &dwarf2_per_objfile->abbrev);
6686
6687   if (dwarf_read_debug)
6688     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6689                         get_section_name (section),
6690                         get_section_file_name (abbrev_section));
6691
6692   dwarf2_read_section (objfile, section);
6693   info_ptr = section->buffer;
6694
6695   if (info_ptr == NULL)
6696     return;
6697
6698   /* We can't set abfd until now because the section may be empty or
6699      not present, in which case the bfd is unknown.  */
6700   abfd = get_section_bfd_owner (section);
6701
6702   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6703      because we don't need to read any dies: the signature is in the
6704      header.  */
6705
6706   end_ptr = info_ptr + section->size;
6707   while (info_ptr < end_ptr)
6708     {
6709       struct signatured_type *sig_type;
6710       struct dwo_unit *dwo_tu;
6711       void **slot;
6712       const gdb_byte *ptr = info_ptr;
6713       struct comp_unit_head header;
6714       unsigned int length;
6715
6716       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6717
6718       /* Initialize it due to a false compiler warning.  */
6719       header.signature = -1;
6720       header.type_cu_offset_in_tu = (cu_offset) -1;
6721
6722       /* We need to read the type's signature in order to build the hash
6723          table, but we don't need anything else just yet.  */
6724
6725       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6726                                            abbrev_section, ptr, section_kind);
6727
6728       length = get_cu_length (&header);
6729
6730       /* Skip dummy type units.  */
6731       if (ptr >= info_ptr + length
6732           || peek_abbrev_code (abfd, ptr) == 0
6733           || header.unit_type != DW_UT_type)
6734         {
6735           info_ptr += length;
6736           continue;
6737         }
6738
6739       if (types_htab == NULL)
6740         {
6741           if (dwo_file)
6742             types_htab = allocate_dwo_unit_table (objfile);
6743           else
6744             types_htab = allocate_signatured_type_table (objfile);
6745         }
6746
6747       if (dwo_file)
6748         {
6749           sig_type = NULL;
6750           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6751                                    struct dwo_unit);
6752           dwo_tu->dwo_file = dwo_file;
6753           dwo_tu->signature = header.signature;
6754           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6755           dwo_tu->section = section;
6756           dwo_tu->sect_off = sect_off;
6757           dwo_tu->length = length;
6758         }
6759       else
6760         {
6761           /* N.B.: type_offset is not usable if this type uses a DWO file.
6762              The real type_offset is in the DWO file.  */
6763           dwo_tu = NULL;
6764           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6765                                      struct signatured_type);
6766           sig_type->signature = header.signature;
6767           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6768           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6769           sig_type->per_cu.is_debug_types = 1;
6770           sig_type->per_cu.section = section;
6771           sig_type->per_cu.sect_off = sect_off;
6772           sig_type->per_cu.length = length;
6773         }
6774
6775       slot = htab_find_slot (types_htab,
6776                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6777                              INSERT);
6778       gdb_assert (slot != NULL);
6779       if (*slot != NULL)
6780         {
6781           sect_offset dup_sect_off;
6782
6783           if (dwo_file)
6784             {
6785               const struct dwo_unit *dup_tu
6786                 = (const struct dwo_unit *) *slot;
6787
6788               dup_sect_off = dup_tu->sect_off;
6789             }
6790           else
6791             {
6792               const struct signatured_type *dup_tu
6793                 = (const struct signatured_type *) *slot;
6794
6795               dup_sect_off = dup_tu->per_cu.sect_off;
6796             }
6797
6798           complaint (_("debug type entry at offset %s is duplicate to"
6799                        " the entry at offset %s, signature %s"),
6800                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6801                      hex_string (header.signature));
6802         }
6803       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6804
6805       if (dwarf_read_debug > 1)
6806         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6807                             sect_offset_str (sect_off),
6808                             hex_string (header.signature));
6809
6810       info_ptr += length;
6811     }
6812 }
6813
6814 /* Create the hash table of all entries in the .debug_types
6815    (or .debug_types.dwo) section(s).
6816    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6817    otherwise it is NULL.
6818
6819    The result is a pointer to the hash table or NULL if there are no types.
6820
6821    Note: This function processes DWO files only, not DWP files.  */
6822
6823 static void
6824 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6825                                struct dwo_file *dwo_file,
6826                                gdb::array_view<dwarf2_section_info> type_sections,
6827                                htab_t &types_htab)
6828 {
6829   for (dwarf2_section_info &section : type_sections)
6830     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, &section,
6831                                   types_htab, rcuh_kind::TYPE);
6832 }
6833
6834 /* Create the hash table of all entries in the .debug_types section,
6835    and initialize all_type_units.
6836    The result is zero if there is an error (e.g. missing .debug_types section),
6837    otherwise non-zero.  */
6838
6839 static int
6840 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6841 {
6842   htab_t types_htab = NULL;
6843
6844   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6845                                 &dwarf2_per_objfile->info, types_htab,
6846                                 rcuh_kind::COMPILE);
6847   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6848                                  dwarf2_per_objfile->types, types_htab);
6849   if (types_htab == NULL)
6850     {
6851       dwarf2_per_objfile->signatured_types = NULL;
6852       return 0;
6853     }
6854
6855   dwarf2_per_objfile->signatured_types = types_htab;
6856
6857   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6858   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6859
6860   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6861                           &dwarf2_per_objfile->all_type_units);
6862
6863   return 1;
6864 }
6865
6866 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6867    If SLOT is non-NULL, it is the entry to use in the hash table.
6868    Otherwise we find one.  */
6869
6870 static struct signatured_type *
6871 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6872                void **slot)
6873 {
6874   struct objfile *objfile = dwarf2_per_objfile->objfile;
6875
6876   if (dwarf2_per_objfile->all_type_units.size ()
6877       == dwarf2_per_objfile->all_type_units.capacity ())
6878     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6879
6880   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6881                                               struct signatured_type);
6882
6883   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6884   sig_type->signature = sig;
6885   sig_type->per_cu.is_debug_types = 1;
6886   if (dwarf2_per_objfile->using_index)
6887     {
6888       sig_type->per_cu.v.quick =
6889         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6890                         struct dwarf2_per_cu_quick_data);
6891     }
6892
6893   if (slot == NULL)
6894     {
6895       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6896                              sig_type, INSERT);
6897     }
6898   gdb_assert (*slot == NULL);
6899   *slot = sig_type;
6900   /* The rest of sig_type must be filled in by the caller.  */
6901   return sig_type;
6902 }
6903
6904 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6905    Fill in SIG_ENTRY with DWO_ENTRY.  */
6906
6907 static void
6908 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6909                                   struct signatured_type *sig_entry,
6910                                   struct dwo_unit *dwo_entry)
6911 {
6912   /* Make sure we're not clobbering something we don't expect to.  */
6913   gdb_assert (! sig_entry->per_cu.queued);
6914   gdb_assert (sig_entry->per_cu.cu == NULL);
6915   if (dwarf2_per_objfile->using_index)
6916     {
6917       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6918       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6919     }
6920   else
6921       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6922   gdb_assert (sig_entry->signature == dwo_entry->signature);
6923   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6924   gdb_assert (sig_entry->type_unit_group == NULL);
6925   gdb_assert (sig_entry->dwo_unit == NULL);
6926
6927   sig_entry->per_cu.section = dwo_entry->section;
6928   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6929   sig_entry->per_cu.length = dwo_entry->length;
6930   sig_entry->per_cu.reading_dwo_directly = 1;
6931   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6932   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6933   sig_entry->dwo_unit = dwo_entry;
6934 }
6935
6936 /* Subroutine of lookup_signatured_type.
6937    If we haven't read the TU yet, create the signatured_type data structure
6938    for a TU to be read in directly from a DWO file, bypassing the stub.
6939    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6940    using .gdb_index, then when reading a CU we want to stay in the DWO file
6941    containing that CU.  Otherwise we could end up reading several other DWO
6942    files (due to comdat folding) to process the transitive closure of all the
6943    mentioned TUs, and that can be slow.  The current DWO file will have every
6944    type signature that it needs.
6945    We only do this for .gdb_index because in the psymtab case we already have
6946    to read all the DWOs to build the type unit groups.  */
6947
6948 static struct signatured_type *
6949 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6950 {
6951   struct dwarf2_per_objfile *dwarf2_per_objfile
6952     = cu->per_cu->dwarf2_per_objfile;
6953   struct objfile *objfile = dwarf2_per_objfile->objfile;
6954   struct dwo_file *dwo_file;
6955   struct dwo_unit find_dwo_entry, *dwo_entry;
6956   struct signatured_type find_sig_entry, *sig_entry;
6957   void **slot;
6958
6959   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6960
6961   /* If TU skeletons have been removed then we may not have read in any
6962      TUs yet.  */
6963   if (dwarf2_per_objfile->signatured_types == NULL)
6964     {
6965       dwarf2_per_objfile->signatured_types
6966         = allocate_signatured_type_table (objfile);
6967     }
6968
6969   /* We only ever need to read in one copy of a signatured type.
6970      Use the global signatured_types array to do our own comdat-folding
6971      of types.  If this is the first time we're reading this TU, and
6972      the TU has an entry in .gdb_index, replace the recorded data from
6973      .gdb_index with this TU.  */
6974
6975   find_sig_entry.signature = sig;
6976   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6977                          &find_sig_entry, INSERT);
6978   sig_entry = (struct signatured_type *) *slot;
6979
6980   /* We can get here with the TU already read, *or* in the process of being
6981      read.  Don't reassign the global entry to point to this DWO if that's
6982      the case.  Also note that if the TU is already being read, it may not
6983      have come from a DWO, the program may be a mix of Fission-compiled
6984      code and non-Fission-compiled code.  */
6985
6986   /* Have we already tried to read this TU?
6987      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6988      needn't exist in the global table yet).  */
6989   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6990     return sig_entry;
6991
6992   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6993      dwo_unit of the TU itself.  */
6994   dwo_file = cu->dwo_unit->dwo_file;
6995
6996   /* Ok, this is the first time we're reading this TU.  */
6997   if (dwo_file->tus == NULL)
6998     return NULL;
6999   find_dwo_entry.signature = sig;
7000   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7001   if (dwo_entry == NULL)
7002     return NULL;
7003
7004   /* If the global table doesn't have an entry for this TU, add one.  */
7005   if (sig_entry == NULL)
7006     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7007
7008   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7009   sig_entry->per_cu.tu_read = 1;
7010   return sig_entry;
7011 }
7012
7013 /* Subroutine of lookup_signatured_type.
7014    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7015    then try the DWP file.  If the TU stub (skeleton) has been removed then
7016    it won't be in .gdb_index.  */
7017
7018 static struct signatured_type *
7019 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7020 {
7021   struct dwarf2_per_objfile *dwarf2_per_objfile
7022     = cu->per_cu->dwarf2_per_objfile;
7023   struct objfile *objfile = dwarf2_per_objfile->objfile;
7024   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7025   struct dwo_unit *dwo_entry;
7026   struct signatured_type find_sig_entry, *sig_entry;
7027   void **slot;
7028
7029   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7030   gdb_assert (dwp_file != NULL);
7031
7032   /* If TU skeletons have been removed then we may not have read in any
7033      TUs yet.  */
7034   if (dwarf2_per_objfile->signatured_types == NULL)
7035     {
7036       dwarf2_per_objfile->signatured_types
7037         = allocate_signatured_type_table (objfile);
7038     }
7039
7040   find_sig_entry.signature = sig;
7041   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7042                          &find_sig_entry, INSERT);
7043   sig_entry = (struct signatured_type *) *slot;
7044
7045   /* Have we already tried to read this TU?
7046      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7047      needn't exist in the global table yet).  */
7048   if (sig_entry != NULL)
7049     return sig_entry;
7050
7051   if (dwp_file->tus == NULL)
7052     return NULL;
7053   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7054                                       sig, 1 /* is_debug_types */);
7055   if (dwo_entry == NULL)
7056     return NULL;
7057
7058   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7059   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7060
7061   return sig_entry;
7062 }
7063
7064 /* Lookup a signature based type for DW_FORM_ref_sig8.
7065    Returns NULL if signature SIG is not present in the table.
7066    It is up to the caller to complain about this.  */
7067
7068 static struct signatured_type *
7069 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7070 {
7071   struct dwarf2_per_objfile *dwarf2_per_objfile
7072     = cu->per_cu->dwarf2_per_objfile;
7073
7074   if (cu->dwo_unit
7075       && dwarf2_per_objfile->using_index)
7076     {
7077       /* We're in a DWO/DWP file, and we're using .gdb_index.
7078          These cases require special processing.  */
7079       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7080         return lookup_dwo_signatured_type (cu, sig);
7081       else
7082         return lookup_dwp_signatured_type (cu, sig);
7083     }
7084   else
7085     {
7086       struct signatured_type find_entry, *entry;
7087
7088       if (dwarf2_per_objfile->signatured_types == NULL)
7089         return NULL;
7090       find_entry.signature = sig;
7091       entry = ((struct signatured_type *)
7092                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7093       return entry;
7094     }
7095 }
7096 \f
7097 /* Low level DIE reading support.  */
7098
7099 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7100
7101 static void
7102 init_cu_die_reader (struct die_reader_specs *reader,
7103                     struct dwarf2_cu *cu,
7104                     struct dwarf2_section_info *section,
7105                     struct dwo_file *dwo_file,
7106                     struct abbrev_table *abbrev_table)
7107 {
7108   gdb_assert (section->readin && section->buffer != NULL);
7109   reader->abfd = get_section_bfd_owner (section);
7110   reader->cu = cu;
7111   reader->dwo_file = dwo_file;
7112   reader->die_section = section;
7113   reader->buffer = section->buffer;
7114   reader->buffer_end = section->buffer + section->size;
7115   reader->comp_dir = NULL;
7116   reader->abbrev_table = abbrev_table;
7117 }
7118
7119 /* Subroutine of init_cutu_and_read_dies to simplify it.
7120    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7121    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7122    already.
7123
7124    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7125    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7126    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7127    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7128    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7129    STUB_COMP_DIR may be non-NULL.
7130    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7131    are filled in with the info of the DIE from the DWO file.
7132    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7133    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7134    kept around for at least as long as *RESULT_READER.
7135
7136    The result is non-zero if a valid (non-dummy) DIE was found.  */
7137
7138 static int
7139 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7140                         struct dwo_unit *dwo_unit,
7141                         struct die_info *stub_comp_unit_die,
7142                         const char *stub_comp_dir,
7143                         struct die_reader_specs *result_reader,
7144                         const gdb_byte **result_info_ptr,
7145                         struct die_info **result_comp_unit_die,
7146                         int *result_has_children,
7147                         abbrev_table_up *result_dwo_abbrev_table)
7148 {
7149   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7150   struct objfile *objfile = dwarf2_per_objfile->objfile;
7151   struct dwarf2_cu *cu = this_cu->cu;
7152   bfd *abfd;
7153   const gdb_byte *begin_info_ptr, *info_ptr;
7154   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7155   int i,num_extra_attrs;
7156   struct dwarf2_section_info *dwo_abbrev_section;
7157   struct attribute *attr;
7158   struct die_info *comp_unit_die;
7159
7160   /* At most one of these may be provided.  */
7161   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7162
7163   /* These attributes aren't processed until later:
7164      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7165      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7166      referenced later.  However, these attributes are found in the stub
7167      which we won't have later.  In order to not impose this complication
7168      on the rest of the code, we read them here and copy them to the
7169      DWO CU/TU die.  */
7170
7171   stmt_list = NULL;
7172   low_pc = NULL;
7173   high_pc = NULL;
7174   ranges = NULL;
7175   comp_dir = NULL;
7176
7177   if (stub_comp_unit_die != NULL)
7178     {
7179       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7180          DWO file.  */
7181       if (! this_cu->is_debug_types)
7182         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7183       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7184       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7185       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7186       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7187
7188       /* There should be a DW_AT_addr_base attribute here (if needed).
7189          We need the value before we can process DW_FORM_GNU_addr_index
7190          or DW_FORM_addrx.  */
7191       cu->addr_base = 0;
7192       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7193       if (attr)
7194         cu->addr_base = DW_UNSND (attr);
7195
7196       /* There should be a DW_AT_ranges_base attribute here (if needed).
7197          We need the value before we can process DW_AT_ranges.  */
7198       cu->ranges_base = 0;
7199       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7200       if (attr)
7201         cu->ranges_base = DW_UNSND (attr);
7202     }
7203   else if (stub_comp_dir != NULL)
7204     {
7205       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7206       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7207       comp_dir->name = DW_AT_comp_dir;
7208       comp_dir->form = DW_FORM_string;
7209       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7210       DW_STRING (comp_dir) = stub_comp_dir;
7211     }
7212
7213   /* Set up for reading the DWO CU/TU.  */
7214   cu->dwo_unit = dwo_unit;
7215   dwarf2_section_info *section = dwo_unit->section;
7216   dwarf2_read_section (objfile, section);
7217   abfd = get_section_bfd_owner (section);
7218   begin_info_ptr = info_ptr = (section->buffer
7219                                + to_underlying (dwo_unit->sect_off));
7220   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7221
7222   if (this_cu->is_debug_types)
7223     {
7224       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7225
7226       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7227                                                 &cu->header, section,
7228                                                 dwo_abbrev_section,
7229                                                 info_ptr, rcuh_kind::TYPE);
7230       /* This is not an assert because it can be caused by bad debug info.  */
7231       if (sig_type->signature != cu->header.signature)
7232         {
7233           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7234                    " TU at offset %s [in module %s]"),
7235                  hex_string (sig_type->signature),
7236                  hex_string (cu->header.signature),
7237                  sect_offset_str (dwo_unit->sect_off),
7238                  bfd_get_filename (abfd));
7239         }
7240       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7241       /* For DWOs coming from DWP files, we don't know the CU length
7242          nor the type's offset in the TU until now.  */
7243       dwo_unit->length = get_cu_length (&cu->header);
7244       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7245
7246       /* Establish the type offset that can be used to lookup the type.
7247          For DWO files, we don't know it until now.  */
7248       sig_type->type_offset_in_section
7249         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7250     }
7251   else
7252     {
7253       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7254                                                 &cu->header, section,
7255                                                 dwo_abbrev_section,
7256                                                 info_ptr, rcuh_kind::COMPILE);
7257       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7258       /* For DWOs coming from DWP files, we don't know the CU length
7259          until now.  */
7260       dwo_unit->length = get_cu_length (&cu->header);
7261     }
7262
7263   *result_dwo_abbrev_table
7264     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7265                                cu->header.abbrev_sect_off);
7266   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7267                       result_dwo_abbrev_table->get ());
7268
7269   /* Read in the die, but leave space to copy over the attributes
7270      from the stub.  This has the benefit of simplifying the rest of
7271      the code - all the work to maintain the illusion of a single
7272      DW_TAG_{compile,type}_unit DIE is done here.  */
7273   num_extra_attrs = ((stmt_list != NULL)
7274                      + (low_pc != NULL)
7275                      + (high_pc != NULL)
7276                      + (ranges != NULL)
7277                      + (comp_dir != NULL));
7278   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7279                               result_has_children, num_extra_attrs);
7280
7281   /* Copy over the attributes from the stub to the DIE we just read in.  */
7282   comp_unit_die = *result_comp_unit_die;
7283   i = comp_unit_die->num_attrs;
7284   if (stmt_list != NULL)
7285     comp_unit_die->attrs[i++] = *stmt_list;
7286   if (low_pc != NULL)
7287     comp_unit_die->attrs[i++] = *low_pc;
7288   if (high_pc != NULL)
7289     comp_unit_die->attrs[i++] = *high_pc;
7290   if (ranges != NULL)
7291     comp_unit_die->attrs[i++] = *ranges;
7292   if (comp_dir != NULL)
7293     comp_unit_die->attrs[i++] = *comp_dir;
7294   comp_unit_die->num_attrs += num_extra_attrs;
7295
7296   if (dwarf_die_debug)
7297     {
7298       fprintf_unfiltered (gdb_stdlog,
7299                           "Read die from %s@0x%x of %s:\n",
7300                           get_section_name (section),
7301                           (unsigned) (begin_info_ptr - section->buffer),
7302                           bfd_get_filename (abfd));
7303       dump_die (comp_unit_die, dwarf_die_debug);
7304     }
7305
7306   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7307      TUs by skipping the stub and going directly to the entry in the DWO file.
7308      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7309      to get it via circuitous means.  Blech.  */
7310   if (comp_dir != NULL)
7311     result_reader->comp_dir = DW_STRING (comp_dir);
7312
7313   /* Skip dummy compilation units.  */
7314   if (info_ptr >= begin_info_ptr + dwo_unit->length
7315       || peek_abbrev_code (abfd, info_ptr) == 0)
7316     return 0;
7317
7318   *result_info_ptr = info_ptr;
7319   return 1;
7320 }
7321
7322 /* Return the signature of the compile unit, if found. In DWARF 4 and before,
7323    the signature is in the DW_AT_GNU_dwo_id attribute. In DWARF 5 and later, the
7324    signature is part of the header.  */
7325 static gdb::optional<ULONGEST>
7326 lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die)
7327 {
7328   if (cu->header.version >= 5)
7329     return cu->header.signature;
7330   struct attribute *attr;
7331   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7332   if (attr == nullptr)
7333     return gdb::optional<ULONGEST> ();
7334   return DW_UNSND (attr);
7335 }
7336
7337 /* Subroutine of init_cutu_and_read_dies to simplify it.
7338    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7339    Returns NULL if the specified DWO unit cannot be found.  */
7340
7341 static struct dwo_unit *
7342 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7343                  struct die_info *comp_unit_die)
7344 {
7345   struct dwarf2_cu *cu = this_cu->cu;
7346   struct dwo_unit *dwo_unit;
7347   const char *comp_dir, *dwo_name;
7348
7349   gdb_assert (cu != NULL);
7350
7351   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7352   dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7353   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7354
7355   if (this_cu->is_debug_types)
7356     {
7357       struct signatured_type *sig_type;
7358
7359       /* Since this_cu is the first member of struct signatured_type,
7360          we can go from a pointer to one to a pointer to the other.  */
7361       sig_type = (struct signatured_type *) this_cu;
7362       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7363     }
7364   else
7365     {
7366       gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
7367       if (!signature.has_value ())
7368         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7369                  " [in module %s]"),
7370                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7371       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7372                                        *signature);
7373     }
7374
7375   return dwo_unit;
7376 }
7377
7378 /* Subroutine of init_cutu_and_read_dies to simplify it.
7379    See it for a description of the parameters.
7380    Read a TU directly from a DWO file, bypassing the stub.  */
7381
7382 static void
7383 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7384                            int use_existing_cu, int keep,
7385                            die_reader_func_ftype *die_reader_func,
7386                            void *data)
7387 {
7388   std::unique_ptr<dwarf2_cu> new_cu;
7389   struct signatured_type *sig_type;
7390   struct die_reader_specs reader;
7391   const gdb_byte *info_ptr;
7392   struct die_info *comp_unit_die;
7393   int has_children;
7394   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7395
7396   /* Verify we can do the following downcast, and that we have the
7397      data we need.  */
7398   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7399   sig_type = (struct signatured_type *) this_cu;
7400   gdb_assert (sig_type->dwo_unit != NULL);
7401
7402   if (use_existing_cu && this_cu->cu != NULL)
7403     {
7404       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7405       /* There's no need to do the rereading_dwo_cu handling that
7406          init_cutu_and_read_dies does since we don't read the stub.  */
7407     }
7408   else
7409     {
7410       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7411       gdb_assert (this_cu->cu == NULL);
7412       new_cu.reset (new dwarf2_cu (this_cu));
7413     }
7414
7415   /* A future optimization, if needed, would be to use an existing
7416      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7417      could share abbrev tables.  */
7418
7419   /* The abbreviation table used by READER, this must live at least as long as
7420      READER.  */
7421   abbrev_table_up dwo_abbrev_table;
7422
7423   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7424                               NULL /* stub_comp_unit_die */,
7425                               sig_type->dwo_unit->dwo_file->comp_dir,
7426                               &reader, &info_ptr,
7427                               &comp_unit_die, &has_children,
7428                               &dwo_abbrev_table) == 0)
7429     {
7430       /* Dummy die.  */
7431       return;
7432     }
7433
7434   /* All the "real" work is done here.  */
7435   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7436
7437   /* This duplicates the code in init_cutu_and_read_dies,
7438      but the alternative is making the latter more complex.
7439      This function is only for the special case of using DWO files directly:
7440      no point in overly complicating the general case just to handle this.  */
7441   if (new_cu != NULL && keep)
7442     {
7443       /* Link this CU into read_in_chain.  */
7444       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7445       dwarf2_per_objfile->read_in_chain = this_cu;
7446       /* The chain owns it now.  */
7447       new_cu.release ();
7448     }
7449 }
7450
7451 /* Initialize a CU (or TU) and read its DIEs.
7452    If the CU defers to a DWO file, read the DWO file as well.
7453
7454    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7455    Otherwise the table specified in the comp unit header is read in and used.
7456    This is an optimization for when we already have the abbrev table.
7457
7458    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7459    Otherwise, a new CU is allocated with xmalloc.
7460
7461    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7462    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7463
7464    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7465    linker) then DIE_READER_FUNC will not get called.  */
7466
7467 static void
7468 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7469                          struct abbrev_table *abbrev_table,
7470                          int use_existing_cu, int keep,
7471                          bool skip_partial,
7472                          die_reader_func_ftype *die_reader_func,
7473                          void *data)
7474 {
7475   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7476   struct objfile *objfile = dwarf2_per_objfile->objfile;
7477   struct dwarf2_section_info *section = this_cu->section;
7478   bfd *abfd = get_section_bfd_owner (section);
7479   struct dwarf2_cu *cu;
7480   const gdb_byte *begin_info_ptr, *info_ptr;
7481   struct die_reader_specs reader;
7482   struct die_info *comp_unit_die;
7483   int has_children;
7484   struct signatured_type *sig_type = NULL;
7485   struct dwarf2_section_info *abbrev_section;
7486   /* Non-zero if CU currently points to a DWO file and we need to
7487      reread it.  When this happens we need to reread the skeleton die
7488      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7489   int rereading_dwo_cu = 0;
7490
7491   if (dwarf_die_debug)
7492     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7493                         this_cu->is_debug_types ? "type" : "comp",
7494                         sect_offset_str (this_cu->sect_off));
7495
7496   if (use_existing_cu)
7497     gdb_assert (keep);
7498
7499   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7500      file (instead of going through the stub), short-circuit all of this.  */
7501   if (this_cu->reading_dwo_directly)
7502     {
7503       /* Narrow down the scope of possibilities to have to understand.  */
7504       gdb_assert (this_cu->is_debug_types);
7505       gdb_assert (abbrev_table == NULL);
7506       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7507                                  die_reader_func, data);
7508       return;
7509     }
7510
7511   /* This is cheap if the section is already read in.  */
7512   dwarf2_read_section (objfile, section);
7513
7514   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7515
7516   abbrev_section = get_abbrev_section_for_cu (this_cu);
7517
7518   std::unique_ptr<dwarf2_cu> new_cu;
7519   if (use_existing_cu && this_cu->cu != NULL)
7520     {
7521       cu = this_cu->cu;
7522       /* If this CU is from a DWO file we need to start over, we need to
7523          refetch the attributes from the skeleton CU.
7524          This could be optimized by retrieving those attributes from when we
7525          were here the first time: the previous comp_unit_die was stored in
7526          comp_unit_obstack.  But there's no data yet that we need this
7527          optimization.  */
7528       if (cu->dwo_unit != NULL)
7529         rereading_dwo_cu = 1;
7530     }
7531   else
7532     {
7533       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7534       gdb_assert (this_cu->cu == NULL);
7535       new_cu.reset (new dwarf2_cu (this_cu));
7536       cu = new_cu.get ();
7537     }
7538
7539   /* Get the header.  */
7540   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7541     {
7542       /* We already have the header, there's no need to read it in again.  */
7543       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7544     }
7545   else
7546     {
7547       if (this_cu->is_debug_types)
7548         {
7549           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7550                                                     &cu->header, section,
7551                                                     abbrev_section, info_ptr,
7552                                                     rcuh_kind::TYPE);
7553
7554           /* Since per_cu is the first member of struct signatured_type,
7555              we can go from a pointer to one to a pointer to the other.  */
7556           sig_type = (struct signatured_type *) this_cu;
7557           gdb_assert (sig_type->signature == cu->header.signature);
7558           gdb_assert (sig_type->type_offset_in_tu
7559                       == cu->header.type_cu_offset_in_tu);
7560           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7561
7562           /* LENGTH has not been set yet for type units if we're
7563              using .gdb_index.  */
7564           this_cu->length = get_cu_length (&cu->header);
7565
7566           /* Establish the type offset that can be used to lookup the type.  */
7567           sig_type->type_offset_in_section =
7568             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7569
7570           this_cu->dwarf_version = cu->header.version;
7571         }
7572       else
7573         {
7574           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7575                                                     &cu->header, section,
7576                                                     abbrev_section,
7577                                                     info_ptr,
7578                                                     rcuh_kind::COMPILE);
7579
7580           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7581           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7582           this_cu->dwarf_version = cu->header.version;
7583         }
7584     }
7585
7586   /* Skip dummy compilation units.  */
7587   if (info_ptr >= begin_info_ptr + this_cu->length
7588       || peek_abbrev_code (abfd, info_ptr) == 0)
7589     return;
7590
7591   /* If we don't have them yet, read the abbrevs for this compilation unit.
7592      And if we need to read them now, make sure they're freed when we're
7593      done (own the table through ABBREV_TABLE_HOLDER).  */
7594   abbrev_table_up abbrev_table_holder;
7595   if (abbrev_table != NULL)
7596     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7597   else
7598     {
7599       abbrev_table_holder
7600         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7601                                    cu->header.abbrev_sect_off);
7602       abbrev_table = abbrev_table_holder.get ();
7603     }
7604
7605   /* Read the top level CU/TU die.  */
7606   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7607   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7608
7609   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7610     return;
7611
7612   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7613      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7614      table from the DWO file and pass the ownership over to us.  It will be
7615      referenced from READER, so we must make sure to free it after we're done
7616      with READER.
7617
7618      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7619      DWO CU, that this test will fail (the attribute will not be present).  */
7620   const char *dwo_name = dwarf2_dwo_name (comp_unit_die, cu);
7621   abbrev_table_up dwo_abbrev_table;
7622   if (dwo_name != nullptr)
7623     {
7624       struct dwo_unit *dwo_unit;
7625       struct die_info *dwo_comp_unit_die;
7626
7627       if (has_children)
7628         {
7629           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7630                        " has children (offset %s) [in module %s]"),
7631                      sect_offset_str (this_cu->sect_off),
7632                      bfd_get_filename (abfd));
7633         }
7634       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7635       if (dwo_unit != NULL)
7636         {
7637           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7638                                       comp_unit_die, NULL,
7639                                       &reader, &info_ptr,
7640                                       &dwo_comp_unit_die, &has_children,
7641                                       &dwo_abbrev_table) == 0)
7642             {
7643               /* Dummy die.  */
7644               return;
7645             }
7646           comp_unit_die = dwo_comp_unit_die;
7647         }
7648       else
7649         {
7650           /* Yikes, we couldn't find the rest of the DIE, we only have
7651              the stub.  A complaint has already been logged.  There's
7652              not much more we can do except pass on the stub DIE to
7653              die_reader_func.  We don't want to throw an error on bad
7654              debug info.  */
7655         }
7656     }
7657
7658   /* All of the above is setup for this call.  Yikes.  */
7659   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7660
7661   /* Done, clean up.  */
7662   if (new_cu != NULL && keep)
7663     {
7664       /* Link this CU into read_in_chain.  */
7665       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7666       dwarf2_per_objfile->read_in_chain = this_cu;
7667       /* The chain owns it now.  */
7668       new_cu.release ();
7669     }
7670 }
7671
7672 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7673    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7674    to have already done the lookup to find the DWO file).
7675
7676    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7677    THIS_CU->is_debug_types, but nothing else.
7678
7679    We fill in THIS_CU->length.
7680
7681    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7682    linker) then DIE_READER_FUNC will not get called.
7683
7684    THIS_CU->cu is always freed when done.
7685    This is done in order to not leave THIS_CU->cu in a state where we have
7686    to care whether it refers to the "main" CU or the DWO CU.  */
7687
7688 static void
7689 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7690                                    struct dwo_file *dwo_file,
7691                                    die_reader_func_ftype *die_reader_func,
7692                                    void *data)
7693 {
7694   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7695   struct objfile *objfile = dwarf2_per_objfile->objfile;
7696   struct dwarf2_section_info *section = this_cu->section;
7697   bfd *abfd = get_section_bfd_owner (section);
7698   struct dwarf2_section_info *abbrev_section;
7699   const gdb_byte *begin_info_ptr, *info_ptr;
7700   struct die_reader_specs reader;
7701   struct die_info *comp_unit_die;
7702   int has_children;
7703
7704   if (dwarf_die_debug)
7705     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7706                         this_cu->is_debug_types ? "type" : "comp",
7707                         sect_offset_str (this_cu->sect_off));
7708
7709   gdb_assert (this_cu->cu == NULL);
7710
7711   abbrev_section = (dwo_file != NULL
7712                     ? &dwo_file->sections.abbrev
7713                     : get_abbrev_section_for_cu (this_cu));
7714
7715   /* This is cheap if the section is already read in.  */
7716   dwarf2_read_section (objfile, section);
7717
7718   struct dwarf2_cu cu (this_cu);
7719
7720   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7721   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7722                                             &cu.header, section,
7723                                             abbrev_section, info_ptr,
7724                                             (this_cu->is_debug_types
7725                                              ? rcuh_kind::TYPE
7726                                              : rcuh_kind::COMPILE));
7727
7728   this_cu->length = get_cu_length (&cu.header);
7729
7730   /* Skip dummy compilation units.  */
7731   if (info_ptr >= begin_info_ptr + this_cu->length
7732       || peek_abbrev_code (abfd, info_ptr) == 0)
7733     return;
7734
7735   abbrev_table_up abbrev_table
7736     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7737                                cu.header.abbrev_sect_off);
7738
7739   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7740   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7741
7742   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7743 }
7744
7745 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7746    does not lookup the specified DWO file.
7747    This cannot be used to read DWO files.
7748
7749    THIS_CU->cu is always freed when done.
7750    This is done in order to not leave THIS_CU->cu in a state where we have
7751    to care whether it refers to the "main" CU or the DWO CU.
7752    We can revisit this if the data shows there's a performance issue.  */
7753
7754 static void
7755 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7756                                 die_reader_func_ftype *die_reader_func,
7757                                 void *data)
7758 {
7759   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7760 }
7761 \f
7762 /* Type Unit Groups.
7763
7764    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7765    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7766    so that all types coming from the same compilation (.o file) are grouped
7767    together.  A future step could be to put the types in the same symtab as
7768    the CU the types ultimately came from.  */
7769
7770 static hashval_t
7771 hash_type_unit_group (const void *item)
7772 {
7773   const struct type_unit_group *tu_group
7774     = (const struct type_unit_group *) item;
7775
7776   return hash_stmt_list_entry (&tu_group->hash);
7777 }
7778
7779 static int
7780 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7781 {
7782   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7783   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7784
7785   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7786 }
7787
7788 /* Allocate a hash table for type unit groups.  */
7789
7790 static htab_t
7791 allocate_type_unit_groups_table (struct objfile *objfile)
7792 {
7793   return htab_create_alloc_ex (3,
7794                                hash_type_unit_group,
7795                                eq_type_unit_group,
7796                                NULL,
7797                                &objfile->objfile_obstack,
7798                                hashtab_obstack_allocate,
7799                                dummy_obstack_deallocate);
7800 }
7801
7802 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7803    partial symtabs.  We combine several TUs per psymtab to not let the size
7804    of any one psymtab grow too big.  */
7805 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7806 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7807
7808 /* Helper routine for get_type_unit_group.
7809    Create the type_unit_group object used to hold one or more TUs.  */
7810
7811 static struct type_unit_group *
7812 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7813 {
7814   struct dwarf2_per_objfile *dwarf2_per_objfile
7815     = cu->per_cu->dwarf2_per_objfile;
7816   struct objfile *objfile = dwarf2_per_objfile->objfile;
7817   struct dwarf2_per_cu_data *per_cu;
7818   struct type_unit_group *tu_group;
7819
7820   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7821                              struct type_unit_group);
7822   per_cu = &tu_group->per_cu;
7823   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7824
7825   if (dwarf2_per_objfile->using_index)
7826     {
7827       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7828                                         struct dwarf2_per_cu_quick_data);
7829     }
7830   else
7831     {
7832       unsigned int line_offset = to_underlying (line_offset_struct);
7833       struct partial_symtab *pst;
7834       std::string name;
7835
7836       /* Give the symtab a useful name for debug purposes.  */
7837       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7838         name = string_printf ("<type_units_%d>",
7839                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7840       else
7841         name = string_printf ("<type_units_at_0x%x>", line_offset);
7842
7843       pst = create_partial_symtab (per_cu, name.c_str ());
7844       pst->anonymous = 1;
7845     }
7846
7847   tu_group->hash.dwo_unit = cu->dwo_unit;
7848   tu_group->hash.line_sect_off = line_offset_struct;
7849
7850   return tu_group;
7851 }
7852
7853 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7854    STMT_LIST is a DW_AT_stmt_list attribute.  */
7855
7856 static struct type_unit_group *
7857 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7858 {
7859   struct dwarf2_per_objfile *dwarf2_per_objfile
7860     = cu->per_cu->dwarf2_per_objfile;
7861   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7862   struct type_unit_group *tu_group;
7863   void **slot;
7864   unsigned int line_offset;
7865   struct type_unit_group type_unit_group_for_lookup;
7866
7867   if (dwarf2_per_objfile->type_unit_groups == NULL)
7868     {
7869       dwarf2_per_objfile->type_unit_groups =
7870         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7871     }
7872
7873   /* Do we need to create a new group, or can we use an existing one?  */
7874
7875   if (stmt_list)
7876     {
7877       line_offset = DW_UNSND (stmt_list);
7878       ++tu_stats->nr_symtab_sharers;
7879     }
7880   else
7881     {
7882       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7883          We can do various things here like create one group per TU or
7884          spread them over multiple groups to split up the expansion work.
7885          To avoid worst case scenarios (too many groups or too large groups)
7886          we, umm, group them in bunches.  */
7887       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7888                      | (tu_stats->nr_stmt_less_type_units
7889                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7890       ++tu_stats->nr_stmt_less_type_units;
7891     }
7892
7893   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7894   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7895   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7896                          &type_unit_group_for_lookup, INSERT);
7897   if (*slot != NULL)
7898     {
7899       tu_group = (struct type_unit_group *) *slot;
7900       gdb_assert (tu_group != NULL);
7901     }
7902   else
7903     {
7904       sect_offset line_offset_struct = (sect_offset) line_offset;
7905       tu_group = create_type_unit_group (cu, line_offset_struct);
7906       *slot = tu_group;
7907       ++tu_stats->nr_symtabs;
7908     }
7909
7910   return tu_group;
7911 }
7912 \f
7913 /* Partial symbol tables.  */
7914
7915 /* Create a psymtab named NAME and assign it to PER_CU.
7916
7917    The caller must fill in the following details:
7918    dirname, textlow, texthigh.  */
7919
7920 static struct partial_symtab *
7921 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7922 {
7923   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7924   struct partial_symtab *pst;
7925
7926   pst = start_psymtab_common (objfile, name, 0);
7927
7928   pst->psymtabs_addrmap_supported = 1;
7929
7930   /* This is the glue that links PST into GDB's symbol API.  */
7931   pst->read_symtab_private = per_cu;
7932   pst->read_symtab = dwarf2_read_symtab;
7933   per_cu->v.psymtab = pst;
7934
7935   return pst;
7936 }
7937
7938 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7939    type.  */
7940
7941 struct process_psymtab_comp_unit_data
7942 {
7943   /* True if we are reading a DW_TAG_partial_unit.  */
7944
7945   int want_partial_unit;
7946
7947   /* The "pretend" language that is used if the CU doesn't declare a
7948      language.  */
7949
7950   enum language pretend_language;
7951 };
7952
7953 /* die_reader_func for process_psymtab_comp_unit.  */
7954
7955 static void
7956 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7957                                   const gdb_byte *info_ptr,
7958                                   struct die_info *comp_unit_die,
7959                                   int has_children,
7960                                   void *data)
7961 {
7962   struct dwarf2_cu *cu = reader->cu;
7963   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7964   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7965   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7966   CORE_ADDR baseaddr;
7967   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7968   struct partial_symtab *pst;
7969   enum pc_bounds_kind cu_bounds_kind;
7970   const char *filename;
7971   struct process_psymtab_comp_unit_data *info
7972     = (struct process_psymtab_comp_unit_data *) data;
7973
7974   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7975     return;
7976
7977   gdb_assert (! per_cu->is_debug_types);
7978
7979   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7980
7981   /* Allocate a new partial symbol table structure.  */
7982   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7983   if (filename == NULL)
7984     filename = "";
7985
7986   pst = create_partial_symtab (per_cu, filename);
7987
7988   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7989   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7990
7991   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7992
7993   dwarf2_find_base_address (comp_unit_die, cu);
7994
7995   /* Possibly set the default values of LOWPC and HIGHPC from
7996      `DW_AT_ranges'.  */
7997   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7998                                          &best_highpc, cu, pst);
7999   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8000     {
8001       CORE_ADDR low
8002         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
8003            - baseaddr);
8004       CORE_ADDR high
8005         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
8006            - baseaddr - 1);
8007       /* Store the contiguous range if it is not empty; it can be
8008          empty for CUs with no code.  */
8009       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8010                          low, high, pst);
8011     }
8012
8013   /* Check if comp unit has_children.
8014      If so, read the rest of the partial symbols from this comp unit.
8015      If not, there's no more debug_info for this comp unit.  */
8016   if (has_children)
8017     {
8018       struct partial_die_info *first_die;
8019       CORE_ADDR lowpc, highpc;
8020
8021       lowpc = ((CORE_ADDR) -1);
8022       highpc = ((CORE_ADDR) 0);
8023
8024       first_die = load_partial_dies (reader, info_ptr, 1);
8025
8026       scan_partial_symbols (first_die, &lowpc, &highpc,
8027                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8028
8029       /* If we didn't find a lowpc, set it to highpc to avoid
8030          complaints from `maint check'.  */
8031       if (lowpc == ((CORE_ADDR) -1))
8032         lowpc = highpc;
8033
8034       /* If the compilation unit didn't have an explicit address range,
8035          then use the information extracted from its child dies.  */
8036       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8037         {
8038           best_lowpc = lowpc;
8039           best_highpc = highpc;
8040         }
8041     }
8042   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
8043                                                  best_lowpc + baseaddr)
8044                      - baseaddr);
8045   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
8046                                                   best_highpc + baseaddr)
8047                       - baseaddr);
8048
8049   end_psymtab_common (objfile, pst);
8050
8051   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8052     {
8053       int i;
8054       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8055       struct dwarf2_per_cu_data *iter;
8056
8057       /* Fill in 'dependencies' here; we fill in 'users' in a
8058          post-pass.  */
8059       pst->number_of_dependencies = len;
8060       pst->dependencies
8061         = objfile->partial_symtabs->allocate_dependencies (len);
8062       for (i = 0;
8063            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8064                         i, iter);
8065            ++i)
8066         pst->dependencies[i] = iter->v.psymtab;
8067
8068       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8069     }
8070
8071   /* Get the list of files included in the current compilation unit,
8072      and build a psymtab for each of them.  */
8073   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8074
8075   if (dwarf_read_debug)
8076     fprintf_unfiltered (gdb_stdlog,
8077                         "Psymtab for %s unit @%s: %s - %s"
8078                         ", %d global, %d static syms\n",
8079                         per_cu->is_debug_types ? "type" : "comp",
8080                         sect_offset_str (per_cu->sect_off),
8081                         paddress (gdbarch, pst->text_low (objfile)),
8082                         paddress (gdbarch, pst->text_high (objfile)),
8083                         pst->n_global_syms, pst->n_static_syms);
8084 }
8085
8086 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8087    Process compilation unit THIS_CU for a psymtab.  */
8088
8089 static void
8090 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8091                            int want_partial_unit,
8092                            enum language pretend_language)
8093 {
8094   /* If this compilation unit was already read in, free the
8095      cached copy in order to read it in again.  This is
8096      necessary because we skipped some symbols when we first
8097      read in the compilation unit (see load_partial_dies).
8098      This problem could be avoided, but the benefit is unclear.  */
8099   if (this_cu->cu != NULL)
8100     free_one_cached_comp_unit (this_cu);
8101
8102   if (this_cu->is_debug_types)
8103     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8104                              build_type_psymtabs_reader, NULL);
8105   else
8106     {
8107       process_psymtab_comp_unit_data info;
8108       info.want_partial_unit = want_partial_unit;
8109       info.pretend_language = pretend_language;
8110       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8111                                process_psymtab_comp_unit_reader, &info);
8112     }
8113
8114   /* Age out any secondary CUs.  */
8115   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8116 }
8117
8118 /* Reader function for build_type_psymtabs.  */
8119
8120 static void
8121 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8122                             const gdb_byte *info_ptr,
8123                             struct die_info *type_unit_die,
8124                             int has_children,
8125                             void *data)
8126 {
8127   struct dwarf2_per_objfile *dwarf2_per_objfile
8128     = reader->cu->per_cu->dwarf2_per_objfile;
8129   struct objfile *objfile = dwarf2_per_objfile->objfile;
8130   struct dwarf2_cu *cu = reader->cu;
8131   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8132   struct signatured_type *sig_type;
8133   struct type_unit_group *tu_group;
8134   struct attribute *attr;
8135   struct partial_die_info *first_die;
8136   CORE_ADDR lowpc, highpc;
8137   struct partial_symtab *pst;
8138
8139   gdb_assert (data == NULL);
8140   gdb_assert (per_cu->is_debug_types);
8141   sig_type = (struct signatured_type *) per_cu;
8142
8143   if (! has_children)
8144     return;
8145
8146   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8147   tu_group = get_type_unit_group (cu, attr);
8148
8149   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8150
8151   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8152   pst = create_partial_symtab (per_cu, "");
8153   pst->anonymous = 1;
8154
8155   first_die = load_partial_dies (reader, info_ptr, 1);
8156
8157   lowpc = (CORE_ADDR) -1;
8158   highpc = (CORE_ADDR) 0;
8159   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8160
8161   end_psymtab_common (objfile, pst);
8162 }
8163
8164 /* Struct used to sort TUs by their abbreviation table offset.  */
8165
8166 struct tu_abbrev_offset
8167 {
8168   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8169   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8170   {}
8171
8172   signatured_type *sig_type;
8173   sect_offset abbrev_offset;
8174 };
8175
8176 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8177
8178 static bool
8179 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8180                           const struct tu_abbrev_offset &b)
8181 {
8182   return a.abbrev_offset < b.abbrev_offset;
8183 }
8184
8185 /* Efficiently read all the type units.
8186    This does the bulk of the work for build_type_psymtabs.
8187
8188    The efficiency is because we sort TUs by the abbrev table they use and
8189    only read each abbrev table once.  In one program there are 200K TUs
8190    sharing 8K abbrev tables.
8191
8192    The main purpose of this function is to support building the
8193    dwarf2_per_objfile->type_unit_groups table.
8194    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8195    can collapse the search space by grouping them by stmt_list.
8196    The savings can be significant, in the same program from above the 200K TUs
8197    share 8K stmt_list tables.
8198
8199    FUNC is expected to call get_type_unit_group, which will create the
8200    struct type_unit_group if necessary and add it to
8201    dwarf2_per_objfile->type_unit_groups.  */
8202
8203 static void
8204 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8205 {
8206   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8207   abbrev_table_up abbrev_table;
8208   sect_offset abbrev_offset;
8209
8210   /* It's up to the caller to not call us multiple times.  */
8211   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8212
8213   if (dwarf2_per_objfile->all_type_units.empty ())
8214     return;
8215
8216   /* TUs typically share abbrev tables, and there can be way more TUs than
8217      abbrev tables.  Sort by abbrev table to reduce the number of times we
8218      read each abbrev table in.
8219      Alternatives are to punt or to maintain a cache of abbrev tables.
8220      This is simpler and efficient enough for now.
8221
8222      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8223      symtab to use).  Typically TUs with the same abbrev offset have the same
8224      stmt_list value too so in practice this should work well.
8225
8226      The basic algorithm here is:
8227
8228       sort TUs by abbrev table
8229       for each TU with same abbrev table:
8230         read abbrev table if first user
8231         read TU top level DIE
8232           [IWBN if DWO skeletons had DW_AT_stmt_list]
8233         call FUNC  */
8234
8235   if (dwarf_read_debug)
8236     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8237
8238   /* Sort in a separate table to maintain the order of all_type_units
8239      for .gdb_index: TU indices directly index all_type_units.  */
8240   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8241   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8242
8243   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8244     sorted_by_abbrev.emplace_back
8245       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8246                                      sig_type->per_cu.section,
8247                                      sig_type->per_cu.sect_off));
8248
8249   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8250              sort_tu_by_abbrev_offset);
8251
8252   abbrev_offset = (sect_offset) ~(unsigned) 0;
8253
8254   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8255     {
8256       /* Switch to the next abbrev table if necessary.  */
8257       if (abbrev_table == NULL
8258           || tu.abbrev_offset != abbrev_offset)
8259         {
8260           abbrev_offset = tu.abbrev_offset;
8261           abbrev_table =
8262             abbrev_table_read_table (dwarf2_per_objfile,
8263                                      &dwarf2_per_objfile->abbrev,
8264                                      abbrev_offset);
8265           ++tu_stats->nr_uniq_abbrev_tables;
8266         }
8267
8268       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8269                                0, 0, false, build_type_psymtabs_reader, NULL);
8270     }
8271 }
8272
8273 /* Print collected type unit statistics.  */
8274
8275 static void
8276 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8277 {
8278   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8279
8280   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8281   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8282                       dwarf2_per_objfile->all_type_units.size ());
8283   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8284                       tu_stats->nr_uniq_abbrev_tables);
8285   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8286                       tu_stats->nr_symtabs);
8287   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8288                       tu_stats->nr_symtab_sharers);
8289   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8290                       tu_stats->nr_stmt_less_type_units);
8291   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8292                       tu_stats->nr_all_type_units_reallocs);
8293 }
8294
8295 /* Traversal function for build_type_psymtabs.  */
8296
8297 static int
8298 build_type_psymtab_dependencies (void **slot, void *info)
8299 {
8300   struct dwarf2_per_objfile *dwarf2_per_objfile
8301     = (struct dwarf2_per_objfile *) info;
8302   struct objfile *objfile = dwarf2_per_objfile->objfile;
8303   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8304   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8305   struct partial_symtab *pst = per_cu->v.psymtab;
8306   int len = VEC_length (sig_type_ptr, tu_group->tus);
8307   struct signatured_type *iter;
8308   int i;
8309
8310   gdb_assert (len > 0);
8311   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8312
8313   pst->number_of_dependencies = len;
8314   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
8315   for (i = 0;
8316        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8317        ++i)
8318     {
8319       gdb_assert (iter->per_cu.is_debug_types);
8320       pst->dependencies[i] = iter->per_cu.v.psymtab;
8321       iter->type_unit_group = tu_group;
8322     }
8323
8324   VEC_free (sig_type_ptr, tu_group->tus);
8325
8326   return 1;
8327 }
8328
8329 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8330    Build partial symbol tables for the .debug_types comp-units.  */
8331
8332 static void
8333 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8334 {
8335   if (! create_all_type_units (dwarf2_per_objfile))
8336     return;
8337
8338   build_type_psymtabs_1 (dwarf2_per_objfile);
8339 }
8340
8341 /* Traversal function for process_skeletonless_type_unit.
8342    Read a TU in a DWO file and build partial symbols for it.  */
8343
8344 static int
8345 process_skeletonless_type_unit (void **slot, void *info)
8346 {
8347   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8348   struct dwarf2_per_objfile *dwarf2_per_objfile
8349     = (struct dwarf2_per_objfile *) info;
8350   struct signatured_type find_entry, *entry;
8351
8352   /* If this TU doesn't exist in the global table, add it and read it in.  */
8353
8354   if (dwarf2_per_objfile->signatured_types == NULL)
8355     {
8356       dwarf2_per_objfile->signatured_types
8357         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8358     }
8359
8360   find_entry.signature = dwo_unit->signature;
8361   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8362                          INSERT);
8363   /* If we've already seen this type there's nothing to do.  What's happening
8364      is we're doing our own version of comdat-folding here.  */
8365   if (*slot != NULL)
8366     return 1;
8367
8368   /* This does the job that create_all_type_units would have done for
8369      this TU.  */
8370   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8371   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8372   *slot = entry;
8373
8374   /* This does the job that build_type_psymtabs_1 would have done.  */
8375   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8376                            build_type_psymtabs_reader, NULL);
8377
8378   return 1;
8379 }
8380
8381 /* Traversal function for process_skeletonless_type_units.  */
8382
8383 static int
8384 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8385 {
8386   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8387
8388   if (dwo_file->tus != NULL)
8389     {
8390       htab_traverse_noresize (dwo_file->tus,
8391                               process_skeletonless_type_unit, info);
8392     }
8393
8394   return 1;
8395 }
8396
8397 /* Scan all TUs of DWO files, verifying we've processed them.
8398    This is needed in case a TU was emitted without its skeleton.
8399    Note: This can't be done until we know what all the DWO files are.  */
8400
8401 static void
8402 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8403 {
8404   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8405   if (get_dwp_file (dwarf2_per_objfile) == NULL
8406       && dwarf2_per_objfile->dwo_files != NULL)
8407     {
8408       htab_traverse_noresize (dwarf2_per_objfile->dwo_files.get (),
8409                               process_dwo_file_for_skeletonless_type_units,
8410                               dwarf2_per_objfile);
8411     }
8412 }
8413
8414 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8415
8416 static void
8417 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8418 {
8419   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8420     {
8421       struct partial_symtab *pst = per_cu->v.psymtab;
8422
8423       if (pst == NULL)
8424         continue;
8425
8426       for (int j = 0; j < pst->number_of_dependencies; ++j)
8427         {
8428           /* Set the 'user' field only if it is not already set.  */
8429           if (pst->dependencies[j]->user == NULL)
8430             pst->dependencies[j]->user = pst;
8431         }
8432     }
8433 }
8434
8435 /* Build the partial symbol table by doing a quick pass through the
8436    .debug_info and .debug_abbrev sections.  */
8437
8438 static void
8439 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8440 {
8441   struct objfile *objfile = dwarf2_per_objfile->objfile;
8442
8443   if (dwarf_read_debug)
8444     {
8445       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8446                           objfile_name (objfile));
8447     }
8448
8449   dwarf2_per_objfile->reading_partial_symbols = 1;
8450
8451   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8452
8453   /* Any cached compilation units will be linked by the per-objfile
8454      read_in_chain.  Make sure to free them when we're done.  */
8455   free_cached_comp_units freer (dwarf2_per_objfile);
8456
8457   build_type_psymtabs (dwarf2_per_objfile);
8458
8459   create_all_comp_units (dwarf2_per_objfile);
8460
8461   /* Create a temporary address map on a temporary obstack.  We later
8462      copy this to the final obstack.  */
8463   auto_obstack temp_obstack;
8464
8465   scoped_restore save_psymtabs_addrmap
8466     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
8467                            addrmap_create_mutable (&temp_obstack));
8468
8469   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8470     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8471
8472   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8473   process_skeletonless_type_units (dwarf2_per_objfile);
8474
8475   /* Now that all TUs have been processed we can fill in the dependencies.  */
8476   if (dwarf2_per_objfile->type_unit_groups != NULL)
8477     {
8478       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8479                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8480     }
8481
8482   if (dwarf_read_debug)
8483     print_tu_stats (dwarf2_per_objfile);
8484
8485   set_partial_user (dwarf2_per_objfile);
8486
8487   objfile->partial_symtabs->psymtabs_addrmap
8488     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
8489                             objfile->partial_symtabs->obstack ());
8490   /* At this point we want to keep the address map.  */
8491   save_psymtabs_addrmap.release ();
8492
8493   if (dwarf_read_debug)
8494     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8495                         objfile_name (objfile));
8496 }
8497
8498 /* die_reader_func for load_partial_comp_unit.  */
8499
8500 static void
8501 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8502                                const gdb_byte *info_ptr,
8503                                struct die_info *comp_unit_die,
8504                                int has_children,
8505                                void *data)
8506 {
8507   struct dwarf2_cu *cu = reader->cu;
8508
8509   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8510
8511   /* Check if comp unit has_children.
8512      If so, read the rest of the partial symbols from this comp unit.
8513      If not, there's no more debug_info for this comp unit.  */
8514   if (has_children)
8515     load_partial_dies (reader, info_ptr, 0);
8516 }
8517
8518 /* Load the partial DIEs for a secondary CU into memory.
8519    This is also used when rereading a primary CU with load_all_dies.  */
8520
8521 static void
8522 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8523 {
8524   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8525                            load_partial_comp_unit_reader, NULL);
8526 }
8527
8528 static void
8529 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8530                               struct dwarf2_section_info *section,
8531                               struct dwarf2_section_info *abbrev_section,
8532                               unsigned int is_dwz)
8533 {
8534   const gdb_byte *info_ptr;
8535   struct objfile *objfile = dwarf2_per_objfile->objfile;
8536
8537   if (dwarf_read_debug)
8538     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8539                         get_section_name (section),
8540                         get_section_file_name (section));
8541
8542   dwarf2_read_section (objfile, section);
8543
8544   info_ptr = section->buffer;
8545
8546   while (info_ptr < section->buffer + section->size)
8547     {
8548       struct dwarf2_per_cu_data *this_cu;
8549
8550       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8551
8552       comp_unit_head cu_header;
8553       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8554                                      abbrev_section, info_ptr,
8555                                      rcuh_kind::COMPILE);
8556
8557       /* Save the compilation unit for later lookup.  */
8558       if (cu_header.unit_type != DW_UT_type)
8559         {
8560           this_cu = XOBNEW (&objfile->objfile_obstack,
8561                             struct dwarf2_per_cu_data);
8562           memset (this_cu, 0, sizeof (*this_cu));
8563         }
8564       else
8565         {
8566           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8567                                   struct signatured_type);
8568           memset (sig_type, 0, sizeof (*sig_type));
8569           sig_type->signature = cu_header.signature;
8570           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8571           this_cu = &sig_type->per_cu;
8572         }
8573       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8574       this_cu->sect_off = sect_off;
8575       this_cu->length = cu_header.length + cu_header.initial_length_size;
8576       this_cu->is_dwz = is_dwz;
8577       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8578       this_cu->section = section;
8579
8580       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8581
8582       info_ptr = info_ptr + this_cu->length;
8583     }
8584 }
8585
8586 /* Create a list of all compilation units in OBJFILE.
8587    This is only done for -readnow and building partial symtabs.  */
8588
8589 static void
8590 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8591 {
8592   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8593   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8594                                 &dwarf2_per_objfile->abbrev, 0);
8595
8596   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8597   if (dwz != NULL)
8598     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8599                                   1);
8600 }
8601
8602 /* Process all loaded DIEs for compilation unit CU, starting at
8603    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8604    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8605    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8606    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8607
8608 static void
8609 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8610                       CORE_ADDR *highpc, int set_addrmap,
8611                       struct dwarf2_cu *cu)
8612 {
8613   struct partial_die_info *pdi;
8614
8615   /* Now, march along the PDI's, descending into ones which have
8616      interesting children but skipping the children of the other ones,
8617      until we reach the end of the compilation unit.  */
8618
8619   pdi = first_die;
8620
8621   while (pdi != NULL)
8622     {
8623       pdi->fixup (cu);
8624
8625       /* Anonymous namespaces or modules have no name but have interesting
8626          children, so we need to look at them.  Ditto for anonymous
8627          enums.  */
8628
8629       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8630           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8631           || pdi->tag == DW_TAG_imported_unit
8632           || pdi->tag == DW_TAG_inlined_subroutine)
8633         {
8634           switch (pdi->tag)
8635             {
8636             case DW_TAG_subprogram:
8637             case DW_TAG_inlined_subroutine:
8638               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8639               break;
8640             case DW_TAG_constant:
8641             case DW_TAG_variable:
8642             case DW_TAG_typedef:
8643             case DW_TAG_union_type:
8644               if (!pdi->is_declaration)
8645                 {
8646                   add_partial_symbol (pdi, cu);
8647                 }
8648               break;
8649             case DW_TAG_class_type:
8650             case DW_TAG_interface_type:
8651             case DW_TAG_structure_type:
8652               if (!pdi->is_declaration)
8653                 {
8654                   add_partial_symbol (pdi, cu);
8655                 }
8656               if ((cu->language == language_rust
8657                    || cu->language == language_cplus) && pdi->has_children)
8658                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8659                                       set_addrmap, cu);
8660               break;
8661             case DW_TAG_enumeration_type:
8662               if (!pdi->is_declaration)
8663                 add_partial_enumeration (pdi, cu);
8664               break;
8665             case DW_TAG_base_type:
8666             case DW_TAG_subrange_type:
8667               /* File scope base type definitions are added to the partial
8668                  symbol table.  */
8669               add_partial_symbol (pdi, cu);
8670               break;
8671             case DW_TAG_namespace:
8672               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8673               break;
8674             case DW_TAG_module:
8675               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8676               break;
8677             case DW_TAG_imported_unit:
8678               {
8679                 struct dwarf2_per_cu_data *per_cu;
8680
8681                 /* For now we don't handle imported units in type units.  */
8682                 if (cu->per_cu->is_debug_types)
8683                   {
8684                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8685                              " supported in type units [in module %s]"),
8686                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8687                   }
8688
8689                 per_cu = dwarf2_find_containing_comp_unit
8690                            (pdi->d.sect_off, pdi->is_dwz,
8691                             cu->per_cu->dwarf2_per_objfile);
8692
8693                 /* Go read the partial unit, if needed.  */
8694                 if (per_cu->v.psymtab == NULL)
8695                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8696
8697                 VEC_safe_push (dwarf2_per_cu_ptr,
8698                                cu->per_cu->imported_symtabs, per_cu);
8699               }
8700               break;
8701             case DW_TAG_imported_declaration:
8702               add_partial_symbol (pdi, cu);
8703               break;
8704             default:
8705               break;
8706             }
8707         }
8708
8709       /* If the die has a sibling, skip to the sibling.  */
8710
8711       pdi = pdi->die_sibling;
8712     }
8713 }
8714
8715 /* Functions used to compute the fully scoped name of a partial DIE.
8716
8717    Normally, this is simple.  For C++, the parent DIE's fully scoped
8718    name is concatenated with "::" and the partial DIE's name.
8719    Enumerators are an exception; they use the scope of their parent
8720    enumeration type, i.e. the name of the enumeration type is not
8721    prepended to the enumerator.
8722
8723    There are two complexities.  One is DW_AT_specification; in this
8724    case "parent" means the parent of the target of the specification,
8725    instead of the direct parent of the DIE.  The other is compilers
8726    which do not emit DW_TAG_namespace; in this case we try to guess
8727    the fully qualified name of structure types from their members'
8728    linkage names.  This must be done using the DIE's children rather
8729    than the children of any DW_AT_specification target.  We only need
8730    to do this for structures at the top level, i.e. if the target of
8731    any DW_AT_specification (if any; otherwise the DIE itself) does not
8732    have a parent.  */
8733
8734 /* Compute the scope prefix associated with PDI's parent, in
8735    compilation unit CU.  The result will be allocated on CU's
8736    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8737    field.  NULL is returned if no prefix is necessary.  */
8738 static const char *
8739 partial_die_parent_scope (struct partial_die_info *pdi,
8740                           struct dwarf2_cu *cu)
8741 {
8742   const char *grandparent_scope;
8743   struct partial_die_info *parent, *real_pdi;
8744
8745   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8746      then this means the parent of the specification DIE.  */
8747
8748   real_pdi = pdi;
8749   while (real_pdi->has_specification)
8750     {
8751       auto res = find_partial_die (real_pdi->spec_offset,
8752                                    real_pdi->spec_is_dwz, cu);
8753       real_pdi = res.pdi;
8754       cu = res.cu;
8755     }
8756
8757   parent = real_pdi->die_parent;
8758   if (parent == NULL)
8759     return NULL;
8760
8761   if (parent->scope_set)
8762     return parent->scope;
8763
8764   parent->fixup (cu);
8765
8766   grandparent_scope = partial_die_parent_scope (parent, cu);
8767
8768   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8769      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8770      Work around this problem here.  */
8771   if (cu->language == language_cplus
8772       && parent->tag == DW_TAG_namespace
8773       && strcmp (parent->name, "::") == 0
8774       && grandparent_scope == NULL)
8775     {
8776       parent->scope = NULL;
8777       parent->scope_set = 1;
8778       return NULL;
8779     }
8780
8781   if (pdi->tag == DW_TAG_enumerator)
8782     /* Enumerators should not get the name of the enumeration as a prefix.  */
8783     parent->scope = grandparent_scope;
8784   else if (parent->tag == DW_TAG_namespace
8785       || parent->tag == DW_TAG_module
8786       || parent->tag == DW_TAG_structure_type
8787       || parent->tag == DW_TAG_class_type
8788       || parent->tag == DW_TAG_interface_type
8789       || parent->tag == DW_TAG_union_type
8790       || parent->tag == DW_TAG_enumeration_type)
8791     {
8792       if (grandparent_scope == NULL)
8793         parent->scope = parent->name;
8794       else
8795         parent->scope = typename_concat (&cu->comp_unit_obstack,
8796                                          grandparent_scope,
8797                                          parent->name, 0, cu);
8798     }
8799   else
8800     {
8801       /* FIXME drow/2004-04-01: What should we be doing with
8802          function-local names?  For partial symbols, we should probably be
8803          ignoring them.  */
8804       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8805                  dwarf_tag_name (parent->tag),
8806                  sect_offset_str (pdi->sect_off));
8807       parent->scope = grandparent_scope;
8808     }
8809
8810   parent->scope_set = 1;
8811   return parent->scope;
8812 }
8813
8814 /* Return the fully scoped name associated with PDI, from compilation unit
8815    CU.  The result will be allocated with malloc.  */
8816
8817 static char *
8818 partial_die_full_name (struct partial_die_info *pdi,
8819                        struct dwarf2_cu *cu)
8820 {
8821   const char *parent_scope;
8822
8823   /* If this is a template instantiation, we can not work out the
8824      template arguments from partial DIEs.  So, unfortunately, we have
8825      to go through the full DIEs.  At least any work we do building
8826      types here will be reused if full symbols are loaded later.  */
8827   if (pdi->has_template_arguments)
8828     {
8829       pdi->fixup (cu);
8830
8831       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8832         {
8833           struct die_info *die;
8834           struct attribute attr;
8835           struct dwarf2_cu *ref_cu = cu;
8836
8837           /* DW_FORM_ref_addr is using section offset.  */
8838           attr.name = (enum dwarf_attribute) 0;
8839           attr.form = DW_FORM_ref_addr;
8840           attr.u.unsnd = to_underlying (pdi->sect_off);
8841           die = follow_die_ref (NULL, &attr, &ref_cu);
8842
8843           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8844         }
8845     }
8846
8847   parent_scope = partial_die_parent_scope (pdi, cu);
8848   if (parent_scope == NULL)
8849     return NULL;
8850   else
8851     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8852 }
8853
8854 static void
8855 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8856 {
8857   struct dwarf2_per_objfile *dwarf2_per_objfile
8858     = cu->per_cu->dwarf2_per_objfile;
8859   struct objfile *objfile = dwarf2_per_objfile->objfile;
8860   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8861   CORE_ADDR addr = 0;
8862   const char *actual_name = NULL;
8863   CORE_ADDR baseaddr;
8864   char *built_actual_name;
8865
8866   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8867
8868   built_actual_name = partial_die_full_name (pdi, cu);
8869   if (built_actual_name != NULL)
8870     actual_name = built_actual_name;
8871
8872   if (actual_name == NULL)
8873     actual_name = pdi->name;
8874
8875   switch (pdi->tag)
8876     {
8877     case DW_TAG_inlined_subroutine:
8878     case DW_TAG_subprogram:
8879       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8880               - baseaddr);
8881       if (pdi->is_external || cu->language == language_ada)
8882         {
8883           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8884              of the global scope.  But in Ada, we want to be able to access
8885              nested procedures globally.  So all Ada subprograms are stored
8886              in the global scope.  */
8887           add_psymbol_to_list (actual_name, strlen (actual_name),
8888                                built_actual_name != NULL,
8889                                VAR_DOMAIN, LOC_BLOCK,
8890                                SECT_OFF_TEXT (objfile),
8891                                psymbol_placement::GLOBAL,
8892                                addr,
8893                                cu->language, objfile);
8894         }
8895       else
8896         {
8897           add_psymbol_to_list (actual_name, strlen (actual_name),
8898                                built_actual_name != NULL,
8899                                VAR_DOMAIN, LOC_BLOCK,
8900                                SECT_OFF_TEXT (objfile),
8901                                psymbol_placement::STATIC,
8902                                addr, cu->language, objfile);
8903         }
8904
8905       if (pdi->main_subprogram && actual_name != NULL)
8906         set_objfile_main_name (objfile, actual_name, cu->language);
8907       break;
8908     case DW_TAG_constant:
8909       add_psymbol_to_list (actual_name, strlen (actual_name),
8910                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8911                            -1, (pdi->is_external
8912                                 ? psymbol_placement::GLOBAL
8913                                 : psymbol_placement::STATIC),
8914                            0, cu->language, objfile);
8915       break;
8916     case DW_TAG_variable:
8917       if (pdi->d.locdesc)
8918         addr = decode_locdesc (pdi->d.locdesc, cu);
8919
8920       if (pdi->d.locdesc
8921           && addr == 0
8922           && !dwarf2_per_objfile->has_section_at_zero)
8923         {
8924           /* A global or static variable may also have been stripped
8925              out by the linker if unused, in which case its address
8926              will be nullified; do not add such variables into partial
8927              symbol table then.  */
8928         }
8929       else if (pdi->is_external)
8930         {
8931           /* Global Variable.
8932              Don't enter into the minimal symbol tables as there is
8933              a minimal symbol table entry from the ELF symbols already.
8934              Enter into partial symbol table if it has a location
8935              descriptor or a type.
8936              If the location descriptor is missing, new_symbol will create
8937              a LOC_UNRESOLVED symbol, the address of the variable will then
8938              be determined from the minimal symbol table whenever the variable
8939              is referenced.
8940              The address for the partial symbol table entry is not
8941              used by GDB, but it comes in handy for debugging partial symbol
8942              table building.  */
8943
8944           if (pdi->d.locdesc || pdi->has_type)
8945             add_psymbol_to_list (actual_name, strlen (actual_name),
8946                                  built_actual_name != NULL,
8947                                  VAR_DOMAIN, LOC_STATIC,
8948                                  SECT_OFF_TEXT (objfile),
8949                                  psymbol_placement::GLOBAL,
8950                                  addr, cu->language, objfile);
8951         }
8952       else
8953         {
8954           int has_loc = pdi->d.locdesc != NULL;
8955
8956           /* Static Variable.  Skip symbols whose value we cannot know (those
8957              without location descriptors or constant values).  */
8958           if (!has_loc && !pdi->has_const_value)
8959             {
8960               xfree (built_actual_name);
8961               return;
8962             }
8963
8964           add_psymbol_to_list (actual_name, strlen (actual_name),
8965                                built_actual_name != NULL,
8966                                VAR_DOMAIN, LOC_STATIC,
8967                                SECT_OFF_TEXT (objfile),
8968                                psymbol_placement::STATIC,
8969                                has_loc ? addr : 0,
8970                                cu->language, objfile);
8971         }
8972       break;
8973     case DW_TAG_typedef:
8974     case DW_TAG_base_type:
8975     case DW_TAG_subrange_type:
8976       add_psymbol_to_list (actual_name, strlen (actual_name),
8977                            built_actual_name != NULL,
8978                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8979                            psymbol_placement::STATIC,
8980                            0, cu->language, objfile);
8981       break;
8982     case DW_TAG_imported_declaration:
8983     case DW_TAG_namespace:
8984       add_psymbol_to_list (actual_name, strlen (actual_name),
8985                            built_actual_name != NULL,
8986                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8987                            psymbol_placement::GLOBAL,
8988                            0, cu->language, objfile);
8989       break;
8990     case DW_TAG_module:
8991       /* With Fortran 77 there might be a "BLOCK DATA" module
8992          available without any name.  If so, we skip the module as it
8993          doesn't bring any value.  */
8994       if (actual_name != nullptr)
8995         add_psymbol_to_list (actual_name, strlen (actual_name),
8996                              built_actual_name != NULL,
8997                              MODULE_DOMAIN, LOC_TYPEDEF, -1,
8998                              psymbol_placement::GLOBAL,
8999                              0, cu->language, objfile);
9000       break;
9001     case DW_TAG_class_type:
9002     case DW_TAG_interface_type:
9003     case DW_TAG_structure_type:
9004     case DW_TAG_union_type:
9005     case DW_TAG_enumeration_type:
9006       /* Skip external references.  The DWARF standard says in the section
9007          about "Structure, Union, and Class Type Entries": "An incomplete
9008          structure, union or class type is represented by a structure,
9009          union or class entry that does not have a byte size attribute
9010          and that has a DW_AT_declaration attribute."  */
9011       if (!pdi->has_byte_size && pdi->is_declaration)
9012         {
9013           xfree (built_actual_name);
9014           return;
9015         }
9016
9017       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9018          static vs. global.  */
9019       add_psymbol_to_list (actual_name, strlen (actual_name),
9020                            built_actual_name != NULL,
9021                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
9022                            cu->language == language_cplus
9023                            ? psymbol_placement::GLOBAL
9024                            : psymbol_placement::STATIC,
9025                            0, cu->language, objfile);
9026
9027       break;
9028     case DW_TAG_enumerator:
9029       add_psymbol_to_list (actual_name, strlen (actual_name),
9030                            built_actual_name != NULL,
9031                            VAR_DOMAIN, LOC_CONST, -1,
9032                            cu->language == language_cplus
9033                            ? psymbol_placement::GLOBAL
9034                            : psymbol_placement::STATIC,
9035                            0, cu->language, objfile);
9036       break;
9037     default:
9038       break;
9039     }
9040
9041   xfree (built_actual_name);
9042 }
9043
9044 /* Read a partial die corresponding to a namespace; also, add a symbol
9045    corresponding to that namespace to the symbol table.  NAMESPACE is
9046    the name of the enclosing namespace.  */
9047
9048 static void
9049 add_partial_namespace (struct partial_die_info *pdi,
9050                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9051                        int set_addrmap, struct dwarf2_cu *cu)
9052 {
9053   /* Add a symbol for the namespace.  */
9054
9055   add_partial_symbol (pdi, cu);
9056
9057   /* Now scan partial symbols in that namespace.  */
9058
9059   if (pdi->has_children)
9060     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9061 }
9062
9063 /* Read a partial die corresponding to a Fortran module.  */
9064
9065 static void
9066 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9067                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9068 {
9069   /* Add a symbol for the namespace.  */
9070
9071   add_partial_symbol (pdi, cu);
9072
9073   /* Now scan partial symbols in that module.  */
9074
9075   if (pdi->has_children)
9076     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9077 }
9078
9079 /* Read a partial die corresponding to a subprogram or an inlined
9080    subprogram and create a partial symbol for that subprogram.
9081    When the CU language allows it, this routine also defines a partial
9082    symbol for each nested subprogram that this subprogram contains.
9083    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9084    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9085
9086    PDI may also be a lexical block, in which case we simply search
9087    recursively for subprograms defined inside that lexical block.
9088    Again, this is only performed when the CU language allows this
9089    type of definitions.  */
9090
9091 static void
9092 add_partial_subprogram (struct partial_die_info *pdi,
9093                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9094                         int set_addrmap, struct dwarf2_cu *cu)
9095 {
9096   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9097     {
9098       if (pdi->has_pc_info)
9099         {
9100           if (pdi->lowpc < *lowpc)
9101             *lowpc = pdi->lowpc;
9102           if (pdi->highpc > *highpc)
9103             *highpc = pdi->highpc;
9104           if (set_addrmap)
9105             {
9106               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9107               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9108               CORE_ADDR baseaddr;
9109               CORE_ADDR this_highpc;
9110               CORE_ADDR this_lowpc;
9111
9112               baseaddr = ANOFFSET (objfile->section_offsets,
9113                                    SECT_OFF_TEXT (objfile));
9114               this_lowpc
9115                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9116                                                pdi->lowpc + baseaddr)
9117                    - baseaddr);
9118               this_highpc
9119                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9120                                                pdi->highpc + baseaddr)
9121                    - baseaddr);
9122               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
9123                                  this_lowpc, this_highpc - 1,
9124                                  cu->per_cu->v.psymtab);
9125             }
9126         }
9127
9128       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9129         {
9130           if (!pdi->is_declaration)
9131             /* Ignore subprogram DIEs that do not have a name, they are
9132                illegal.  Do not emit a complaint at this point, we will
9133                do so when we convert this psymtab into a symtab.  */
9134             if (pdi->name)
9135               add_partial_symbol (pdi, cu);
9136         }
9137     }
9138
9139   if (! pdi->has_children)
9140     return;
9141
9142   if (cu->language == language_ada)
9143     {
9144       pdi = pdi->die_child;
9145       while (pdi != NULL)
9146         {
9147           pdi->fixup (cu);
9148           if (pdi->tag == DW_TAG_subprogram
9149               || pdi->tag == DW_TAG_inlined_subroutine
9150               || pdi->tag == DW_TAG_lexical_block)
9151             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9152           pdi = pdi->die_sibling;
9153         }
9154     }
9155 }
9156
9157 /* Read a partial die corresponding to an enumeration type.  */
9158
9159 static void
9160 add_partial_enumeration (struct partial_die_info *enum_pdi,
9161                          struct dwarf2_cu *cu)
9162 {
9163   struct partial_die_info *pdi;
9164
9165   if (enum_pdi->name != NULL)
9166     add_partial_symbol (enum_pdi, cu);
9167
9168   pdi = enum_pdi->die_child;
9169   while (pdi)
9170     {
9171       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9172         complaint (_("malformed enumerator DIE ignored"));
9173       else
9174         add_partial_symbol (pdi, cu);
9175       pdi = pdi->die_sibling;
9176     }
9177 }
9178
9179 /* Return the initial uleb128 in the die at INFO_PTR.  */
9180
9181 static unsigned int
9182 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9183 {
9184   unsigned int bytes_read;
9185
9186   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9187 }
9188
9189 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9190    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9191
9192    Return the corresponding abbrev, or NULL if the number is zero (indicating
9193    an empty DIE).  In either case *BYTES_READ will be set to the length of
9194    the initial number.  */
9195
9196 static struct abbrev_info *
9197 peek_die_abbrev (const die_reader_specs &reader,
9198                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9199 {
9200   dwarf2_cu *cu = reader.cu;
9201   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9202   unsigned int abbrev_number
9203     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9204
9205   if (abbrev_number == 0)
9206     return NULL;
9207
9208   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9209   if (!abbrev)
9210     {
9211       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9212                " at offset %s [in module %s]"),
9213              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9214              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9215     }
9216
9217   return abbrev;
9218 }
9219
9220 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9221    Returns a pointer to the end of a series of DIEs, terminated by an empty
9222    DIE.  Any children of the skipped DIEs will also be skipped.  */
9223
9224 static const gdb_byte *
9225 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9226 {
9227   while (1)
9228     {
9229       unsigned int bytes_read;
9230       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9231
9232       if (abbrev == NULL)
9233         return info_ptr + bytes_read;
9234       else
9235         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9236     }
9237 }
9238
9239 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9240    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9241    abbrev corresponding to that skipped uleb128 should be passed in
9242    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9243    children.  */
9244
9245 static const gdb_byte *
9246 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9247               struct abbrev_info *abbrev)
9248 {
9249   unsigned int bytes_read;
9250   struct attribute attr;
9251   bfd *abfd = reader->abfd;
9252   struct dwarf2_cu *cu = reader->cu;
9253   const gdb_byte *buffer = reader->buffer;
9254   const gdb_byte *buffer_end = reader->buffer_end;
9255   unsigned int form, i;
9256
9257   for (i = 0; i < abbrev->num_attrs; i++)
9258     {
9259       /* The only abbrev we care about is DW_AT_sibling.  */
9260       if (abbrev->attrs[i].name == DW_AT_sibling)
9261         {
9262           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9263           if (attr.form == DW_FORM_ref_addr)
9264             complaint (_("ignoring absolute DW_AT_sibling"));
9265           else
9266             {
9267               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9268               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9269
9270               if (sibling_ptr < info_ptr)
9271                 complaint (_("DW_AT_sibling points backwards"));
9272               else if (sibling_ptr > reader->buffer_end)
9273                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9274               else
9275                 return sibling_ptr;
9276             }
9277         }
9278
9279       /* If it isn't DW_AT_sibling, skip this attribute.  */
9280       form = abbrev->attrs[i].form;
9281     skip_attribute:
9282       switch (form)
9283         {
9284         case DW_FORM_ref_addr:
9285           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9286              and later it is offset sized.  */
9287           if (cu->header.version == 2)
9288             info_ptr += cu->header.addr_size;
9289           else
9290             info_ptr += cu->header.offset_size;
9291           break;
9292         case DW_FORM_GNU_ref_alt:
9293           info_ptr += cu->header.offset_size;
9294           break;
9295         case DW_FORM_addr:
9296           info_ptr += cu->header.addr_size;
9297           break;
9298         case DW_FORM_data1:
9299         case DW_FORM_ref1:
9300         case DW_FORM_flag:
9301           info_ptr += 1;
9302           break;
9303         case DW_FORM_flag_present:
9304         case DW_FORM_implicit_const:
9305           break;
9306         case DW_FORM_data2:
9307         case DW_FORM_ref2:
9308           info_ptr += 2;
9309           break;
9310         case DW_FORM_data4:
9311         case DW_FORM_ref4:
9312           info_ptr += 4;
9313           break;
9314         case DW_FORM_data8:
9315         case DW_FORM_ref8:
9316         case DW_FORM_ref_sig8:
9317           info_ptr += 8;
9318           break;
9319         case DW_FORM_data16:
9320           info_ptr += 16;
9321           break;
9322         case DW_FORM_string:
9323           read_direct_string (abfd, info_ptr, &bytes_read);
9324           info_ptr += bytes_read;
9325           break;
9326         case DW_FORM_sec_offset:
9327         case DW_FORM_strp:
9328         case DW_FORM_GNU_strp_alt:
9329           info_ptr += cu->header.offset_size;
9330           break;
9331         case DW_FORM_exprloc:
9332         case DW_FORM_block:
9333           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9334           info_ptr += bytes_read;
9335           break;
9336         case DW_FORM_block1:
9337           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9338           break;
9339         case DW_FORM_block2:
9340           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9341           break;
9342         case DW_FORM_block4:
9343           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9344           break;
9345         case DW_FORM_addrx:
9346         case DW_FORM_strx:
9347         case DW_FORM_sdata:
9348         case DW_FORM_udata:
9349         case DW_FORM_ref_udata:
9350         case DW_FORM_GNU_addr_index:
9351         case DW_FORM_GNU_str_index:
9352           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9353           break;
9354         case DW_FORM_indirect:
9355           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9356           info_ptr += bytes_read;
9357           /* We need to continue parsing from here, so just go back to
9358              the top.  */
9359           goto skip_attribute;
9360
9361         default:
9362           error (_("Dwarf Error: Cannot handle %s "
9363                    "in DWARF reader [in module %s]"),
9364                  dwarf_form_name (form),
9365                  bfd_get_filename (abfd));
9366         }
9367     }
9368
9369   if (abbrev->has_children)
9370     return skip_children (reader, info_ptr);
9371   else
9372     return info_ptr;
9373 }
9374
9375 /* Locate ORIG_PDI's sibling.
9376    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9377
9378 static const gdb_byte *
9379 locate_pdi_sibling (const struct die_reader_specs *reader,
9380                     struct partial_die_info *orig_pdi,
9381                     const gdb_byte *info_ptr)
9382 {
9383   /* Do we know the sibling already?  */
9384
9385   if (orig_pdi->sibling)
9386     return orig_pdi->sibling;
9387
9388   /* Are there any children to deal with?  */
9389
9390   if (!orig_pdi->has_children)
9391     return info_ptr;
9392
9393   /* Skip the children the long way.  */
9394
9395   return skip_children (reader, info_ptr);
9396 }
9397
9398 /* Expand this partial symbol table into a full symbol table.  SELF is
9399    not NULL.  */
9400
9401 static void
9402 dwarf2_read_symtab (struct partial_symtab *self,
9403                     struct objfile *objfile)
9404 {
9405   struct dwarf2_per_objfile *dwarf2_per_objfile
9406     = get_dwarf2_per_objfile (objfile);
9407
9408   if (self->readin)
9409     {
9410       warning (_("bug: psymtab for %s is already read in."),
9411                self->filename);
9412     }
9413   else
9414     {
9415       if (info_verbose)
9416         {
9417           printf_filtered (_("Reading in symbols for %s..."),
9418                            self->filename);
9419           gdb_flush (gdb_stdout);
9420         }
9421
9422       /* If this psymtab is constructed from a debug-only objfile, the
9423          has_section_at_zero flag will not necessarily be correct.  We
9424          can get the correct value for this flag by looking at the data
9425          associated with the (presumably stripped) associated objfile.  */
9426       if (objfile->separate_debug_objfile_backlink)
9427         {
9428           struct dwarf2_per_objfile *dpo_backlink
9429             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9430
9431           dwarf2_per_objfile->has_section_at_zero
9432             = dpo_backlink->has_section_at_zero;
9433         }
9434
9435       dwarf2_per_objfile->reading_partial_symbols = 0;
9436
9437       psymtab_to_symtab_1 (self);
9438
9439       /* Finish up the debug error message.  */
9440       if (info_verbose)
9441         printf_filtered (_("done.\n"));
9442     }
9443
9444   process_cu_includes (dwarf2_per_objfile);
9445 }
9446 \f
9447 /* Reading in full CUs.  */
9448
9449 /* Add PER_CU to the queue.  */
9450
9451 static void
9452 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9453                  enum language pretend_language)
9454 {
9455   struct dwarf2_queue_item *item;
9456
9457   per_cu->queued = 1;
9458   item = XNEW (struct dwarf2_queue_item);
9459   item->per_cu = per_cu;
9460   item->pretend_language = pretend_language;
9461   item->next = NULL;
9462
9463   if (dwarf2_queue == NULL)
9464     dwarf2_queue = item;
9465   else
9466     dwarf2_queue_tail->next = item;
9467
9468   dwarf2_queue_tail = item;
9469 }
9470
9471 /* If PER_CU is not yet queued, add it to the queue.
9472    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9473    dependency.
9474    The result is non-zero if PER_CU was queued, otherwise the result is zero
9475    meaning either PER_CU is already queued or it is already loaded.
9476
9477    N.B. There is an invariant here that if a CU is queued then it is loaded.
9478    The caller is required to load PER_CU if we return non-zero.  */
9479
9480 static int
9481 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9482                        struct dwarf2_per_cu_data *per_cu,
9483                        enum language pretend_language)
9484 {
9485   /* We may arrive here during partial symbol reading, if we need full
9486      DIEs to process an unusual case (e.g. template arguments).  Do
9487      not queue PER_CU, just tell our caller to load its DIEs.  */
9488   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9489     {
9490       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9491         return 1;
9492       return 0;
9493     }
9494
9495   /* Mark the dependence relation so that we don't flush PER_CU
9496      too early.  */
9497   if (dependent_cu != NULL)
9498     dwarf2_add_dependence (dependent_cu, per_cu);
9499
9500   /* If it's already on the queue, we have nothing to do.  */
9501   if (per_cu->queued)
9502     return 0;
9503
9504   /* If the compilation unit is already loaded, just mark it as
9505      used.  */
9506   if (per_cu->cu != NULL)
9507     {
9508       per_cu->cu->last_used = 0;
9509       return 0;
9510     }
9511
9512   /* Add it to the queue.  */
9513   queue_comp_unit (per_cu, pretend_language);
9514
9515   return 1;
9516 }
9517
9518 /* Process the queue.  */
9519
9520 static void
9521 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9522 {
9523   struct dwarf2_queue_item *item, *next_item;
9524
9525   if (dwarf_read_debug)
9526     {
9527       fprintf_unfiltered (gdb_stdlog,
9528                           "Expanding one or more symtabs of objfile %s ...\n",
9529                           objfile_name (dwarf2_per_objfile->objfile));
9530     }
9531
9532   /* The queue starts out with one item, but following a DIE reference
9533      may load a new CU, adding it to the end of the queue.  */
9534   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9535     {
9536       if ((dwarf2_per_objfile->using_index
9537            ? !item->per_cu->v.quick->compunit_symtab
9538            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9539           /* Skip dummy CUs.  */
9540           && item->per_cu->cu != NULL)
9541         {
9542           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9543           unsigned int debug_print_threshold;
9544           char buf[100];
9545
9546           if (per_cu->is_debug_types)
9547             {
9548               struct signatured_type *sig_type =
9549                 (struct signatured_type *) per_cu;
9550
9551               sprintf (buf, "TU %s at offset %s",
9552                        hex_string (sig_type->signature),
9553                        sect_offset_str (per_cu->sect_off));
9554               /* There can be 100s of TUs.
9555                  Only print them in verbose mode.  */
9556               debug_print_threshold = 2;
9557             }
9558           else
9559             {
9560               sprintf (buf, "CU at offset %s",
9561                        sect_offset_str (per_cu->sect_off));
9562               debug_print_threshold = 1;
9563             }
9564
9565           if (dwarf_read_debug >= debug_print_threshold)
9566             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9567
9568           if (per_cu->is_debug_types)
9569             process_full_type_unit (per_cu, item->pretend_language);
9570           else
9571             process_full_comp_unit (per_cu, item->pretend_language);
9572
9573           if (dwarf_read_debug >= debug_print_threshold)
9574             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9575         }
9576
9577       item->per_cu->queued = 0;
9578       next_item = item->next;
9579       xfree (item);
9580     }
9581
9582   dwarf2_queue_tail = NULL;
9583
9584   if (dwarf_read_debug)
9585     {
9586       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9587                           objfile_name (dwarf2_per_objfile->objfile));
9588     }
9589 }
9590
9591 /* Read in full symbols for PST, and anything it depends on.  */
9592
9593 static void
9594 psymtab_to_symtab_1 (struct partial_symtab *pst)
9595 {
9596   struct dwarf2_per_cu_data *per_cu;
9597   int i;
9598
9599   if (pst->readin)
9600     return;
9601
9602   for (i = 0; i < pst->number_of_dependencies; i++)
9603     if (!pst->dependencies[i]->readin
9604         && pst->dependencies[i]->user == NULL)
9605       {
9606         /* Inform about additional files that need to be read in.  */
9607         if (info_verbose)
9608           {
9609             /* FIXME: i18n: Need to make this a single string.  */
9610             fputs_filtered (" ", gdb_stdout);
9611             wrap_here ("");
9612             fputs_filtered ("and ", gdb_stdout);
9613             wrap_here ("");
9614             printf_filtered ("%s...", pst->dependencies[i]->filename);
9615             wrap_here ("");     /* Flush output.  */
9616             gdb_flush (gdb_stdout);
9617           }
9618         psymtab_to_symtab_1 (pst->dependencies[i]);
9619       }
9620
9621   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9622
9623   if (per_cu == NULL)
9624     {
9625       /* It's an include file, no symbols to read for it.
9626          Everything is in the parent symtab.  */
9627       pst->readin = 1;
9628       return;
9629     }
9630
9631   dw2_do_instantiate_symtab (per_cu, false);
9632 }
9633
9634 /* Trivial hash function for die_info: the hash value of a DIE
9635    is its offset in .debug_info for this objfile.  */
9636
9637 static hashval_t
9638 die_hash (const void *item)
9639 {
9640   const struct die_info *die = (const struct die_info *) item;
9641
9642   return to_underlying (die->sect_off);
9643 }
9644
9645 /* Trivial comparison function for die_info structures: two DIEs
9646    are equal if they have the same offset.  */
9647
9648 static int
9649 die_eq (const void *item_lhs, const void *item_rhs)
9650 {
9651   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9652   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9653
9654   return die_lhs->sect_off == die_rhs->sect_off;
9655 }
9656
9657 /* die_reader_func for load_full_comp_unit.
9658    This is identical to read_signatured_type_reader,
9659    but is kept separate for now.  */
9660
9661 static void
9662 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9663                             const gdb_byte *info_ptr,
9664                             struct die_info *comp_unit_die,
9665                             int has_children,
9666                             void *data)
9667 {
9668   struct dwarf2_cu *cu = reader->cu;
9669   enum language *language_ptr = (enum language *) data;
9670
9671   gdb_assert (cu->die_hash == NULL);
9672   cu->die_hash =
9673     htab_create_alloc_ex (cu->header.length / 12,
9674                           die_hash,
9675                           die_eq,
9676                           NULL,
9677                           &cu->comp_unit_obstack,
9678                           hashtab_obstack_allocate,
9679                           dummy_obstack_deallocate);
9680
9681   if (has_children)
9682     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9683                                                   &info_ptr, comp_unit_die);
9684   cu->dies = comp_unit_die;
9685   /* comp_unit_die is not stored in die_hash, no need.  */
9686
9687   /* We try not to read any attributes in this function, because not
9688      all CUs needed for references have been loaded yet, and symbol
9689      table processing isn't initialized.  But we have to set the CU language,
9690      or we won't be able to build types correctly.
9691      Similarly, if we do not read the producer, we can not apply
9692      producer-specific interpretation.  */
9693   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9694 }
9695
9696 /* Load the DIEs associated with PER_CU into memory.  */
9697
9698 static void
9699 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9700                      bool skip_partial,
9701                      enum language pretend_language)
9702 {
9703   gdb_assert (! this_cu->is_debug_types);
9704
9705   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9706                            load_full_comp_unit_reader, &pretend_language);
9707 }
9708
9709 /* Add a DIE to the delayed physname list.  */
9710
9711 static void
9712 add_to_method_list (struct type *type, int fnfield_index, int index,
9713                     const char *name, struct die_info *die,
9714                     struct dwarf2_cu *cu)
9715 {
9716   struct delayed_method_info mi;
9717   mi.type = type;
9718   mi.fnfield_index = fnfield_index;
9719   mi.index = index;
9720   mi.name = name;
9721   mi.die = die;
9722   cu->method_list.push_back (mi);
9723 }
9724
9725 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9726    "const" / "volatile".  If so, decrements LEN by the length of the
9727    modifier and return true.  Otherwise return false.  */
9728
9729 template<size_t N>
9730 static bool
9731 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9732 {
9733   size_t mod_len = sizeof (mod) - 1;
9734   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9735     {
9736       len -= mod_len;
9737       return true;
9738     }
9739   return false;
9740 }
9741
9742 /* Compute the physnames of any methods on the CU's method list.
9743
9744    The computation of method physnames is delayed in order to avoid the
9745    (bad) condition that one of the method's formal parameters is of an as yet
9746    incomplete type.  */
9747
9748 static void
9749 compute_delayed_physnames (struct dwarf2_cu *cu)
9750 {
9751   /* Only C++ delays computing physnames.  */
9752   if (cu->method_list.empty ())
9753     return;
9754   gdb_assert (cu->language == language_cplus);
9755
9756   for (const delayed_method_info &mi : cu->method_list)
9757     {
9758       const char *physname;
9759       struct fn_fieldlist *fn_flp
9760         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9761       physname = dwarf2_physname (mi.name, mi.die, cu);
9762       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9763         = physname ? physname : "";
9764
9765       /* Since there's no tag to indicate whether a method is a
9766          const/volatile overload, extract that information out of the
9767          demangled name.  */
9768       if (physname != NULL)
9769         {
9770           size_t len = strlen (physname);
9771
9772           while (1)
9773             {
9774               if (physname[len] == ')') /* shortcut */
9775                 break;
9776               else if (check_modifier (physname, len, " const"))
9777                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9778               else if (check_modifier (physname, len, " volatile"))
9779                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9780               else
9781                 break;
9782             }
9783         }
9784     }
9785
9786   /* The list is no longer needed.  */
9787   cu->method_list.clear ();
9788 }
9789
9790 /* Go objects should be embedded in a DW_TAG_module DIE,
9791    and it's not clear if/how imported objects will appear.
9792    To keep Go support simple until that's worked out,
9793    go back through what we've read and create something usable.
9794    We could do this while processing each DIE, and feels kinda cleaner,
9795    but that way is more invasive.
9796    This is to, for example, allow the user to type "p var" or "b main"
9797    without having to specify the package name, and allow lookups
9798    of module.object to work in contexts that use the expression
9799    parser.  */
9800
9801 static void
9802 fixup_go_packaging (struct dwarf2_cu *cu)
9803 {
9804   char *package_name = NULL;
9805   struct pending *list;
9806   int i;
9807
9808   for (list = *cu->get_builder ()->get_global_symbols ();
9809        list != NULL;
9810        list = list->next)
9811     {
9812       for (i = 0; i < list->nsyms; ++i)
9813         {
9814           struct symbol *sym = list->symbol[i];
9815
9816           if (SYMBOL_LANGUAGE (sym) == language_go
9817               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9818             {
9819               char *this_package_name = go_symbol_package_name (sym);
9820
9821               if (this_package_name == NULL)
9822                 continue;
9823               if (package_name == NULL)
9824                 package_name = this_package_name;
9825               else
9826                 {
9827                   struct objfile *objfile
9828                     = cu->per_cu->dwarf2_per_objfile->objfile;
9829                   if (strcmp (package_name, this_package_name) != 0)
9830                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9831                                (symbol_symtab (sym) != NULL
9832                                 ? symtab_to_filename_for_display
9833                                     (symbol_symtab (sym))
9834                                 : objfile_name (objfile)),
9835                                this_package_name, package_name);
9836                   xfree (this_package_name);
9837                 }
9838             }
9839         }
9840     }
9841
9842   if (package_name != NULL)
9843     {
9844       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9845       const char *saved_package_name
9846         = obstack_strdup (&objfile->per_bfd->storage_obstack, package_name);
9847       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9848                                      saved_package_name);
9849       struct symbol *sym;
9850
9851       sym = allocate_symbol (objfile);
9852       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9853       SYMBOL_SET_NAMES (sym, saved_package_name,
9854                         strlen (saved_package_name), 0, objfile);
9855       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9856          e.g., "main" finds the "main" module and not C's main().  */
9857       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9858       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9859       SYMBOL_TYPE (sym) = type;
9860
9861       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9862
9863       xfree (package_name);
9864     }
9865 }
9866
9867 /* Allocate a fully-qualified name consisting of the two parts on the
9868    obstack.  */
9869
9870 static const char *
9871 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9872 {
9873   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9874 }
9875
9876 /* A helper that allocates a struct discriminant_info to attach to a
9877    union type.  */
9878
9879 static struct discriminant_info *
9880 alloc_discriminant_info (struct type *type, int discriminant_index,
9881                          int default_index)
9882 {
9883   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9884   gdb_assert (discriminant_index == -1
9885               || (discriminant_index >= 0
9886                   && discriminant_index < TYPE_NFIELDS (type)));
9887   gdb_assert (default_index == -1
9888               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9889
9890   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9891
9892   struct discriminant_info *disc
9893     = ((struct discriminant_info *)
9894        TYPE_ZALLOC (type,
9895                     offsetof (struct discriminant_info, discriminants)
9896                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9897   disc->default_index = default_index;
9898   disc->discriminant_index = discriminant_index;
9899
9900   struct dynamic_prop prop;
9901   prop.kind = PROP_UNDEFINED;
9902   prop.data.baton = disc;
9903
9904   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9905
9906   return disc;
9907 }
9908
9909 /* Some versions of rustc emitted enums in an unusual way.
9910
9911    Ordinary enums were emitted as unions.  The first element of each
9912    structure in the union was named "RUST$ENUM$DISR".  This element
9913    held the discriminant.
9914
9915    These versions of Rust also implemented the "non-zero"
9916    optimization.  When the enum had two values, and one is empty and
9917    the other holds a pointer that cannot be zero, the pointer is used
9918    as the discriminant, with a zero value meaning the empty variant.
9919    Here, the union's first member is of the form
9920    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9921    where the fieldnos are the indices of the fields that should be
9922    traversed in order to find the field (which may be several fields deep)
9923    and the variantname is the name of the variant of the case when the
9924    field is zero.
9925
9926    This function recognizes whether TYPE is of one of these forms,
9927    and, if so, smashes it to be a variant type.  */
9928
9929 static void
9930 quirk_rust_enum (struct type *type, struct objfile *objfile)
9931 {
9932   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9933
9934   /* We don't need to deal with empty enums.  */
9935   if (TYPE_NFIELDS (type) == 0)
9936     return;
9937
9938 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9939   if (TYPE_NFIELDS (type) == 1
9940       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9941     {
9942       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9943
9944       /* Decode the field name to find the offset of the
9945          discriminant.  */
9946       ULONGEST bit_offset = 0;
9947       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9948       while (name[0] >= '0' && name[0] <= '9')
9949         {
9950           char *tail;
9951           unsigned long index = strtoul (name, &tail, 10);
9952           name = tail;
9953           if (*name != '$'
9954               || index >= TYPE_NFIELDS (field_type)
9955               || (TYPE_FIELD_LOC_KIND (field_type, index)
9956                   != FIELD_LOC_KIND_BITPOS))
9957             {
9958               complaint (_("Could not parse Rust enum encoding string \"%s\""
9959                            "[in module %s]"),
9960                          TYPE_FIELD_NAME (type, 0),
9961                          objfile_name (objfile));
9962               return;
9963             }
9964           ++name;
9965
9966           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9967           field_type = TYPE_FIELD_TYPE (field_type, index);
9968         }
9969
9970       /* Make a union to hold the variants.  */
9971       struct type *union_type = alloc_type (objfile);
9972       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9973       TYPE_NFIELDS (union_type) = 3;
9974       TYPE_FIELDS (union_type)
9975         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9976       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9977       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9978
9979       /* Put the discriminant must at index 0.  */
9980       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9981       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9982       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9983       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9984
9985       /* The order of fields doesn't really matter, so put the real
9986          field at index 1 and the data-less field at index 2.  */
9987       struct discriminant_info *disc
9988         = alloc_discriminant_info (union_type, 0, 1);
9989       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9990       TYPE_FIELD_NAME (union_type, 1)
9991         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9992       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9993         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9994                               TYPE_FIELD_NAME (union_type, 1));
9995
9996       const char *dataless_name
9997         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9998                               name);
9999       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10000                                               dataless_name);
10001       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10002       /* NAME points into the original discriminant name, which
10003          already has the correct lifetime.  */
10004       TYPE_FIELD_NAME (union_type, 2) = name;
10005       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10006       disc->discriminants[2] = 0;
10007
10008       /* Smash this type to be a structure type.  We have to do this
10009          because the type has already been recorded.  */
10010       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10011       TYPE_NFIELDS (type) = 1;
10012       TYPE_FIELDS (type)
10013         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10014
10015       /* Install the variant part.  */
10016       TYPE_FIELD_TYPE (type, 0) = union_type;
10017       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10018       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10019     }
10020   else if (TYPE_NFIELDS (type) == 1)
10021     {
10022       /* We assume that a union with a single field is a univariant
10023          enum.  */
10024       /* Smash this type to be a structure type.  We have to do this
10025          because the type has already been recorded.  */
10026       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10027
10028       /* Make a union to hold the variants.  */
10029       struct type *union_type = alloc_type (objfile);
10030       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10031       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10032       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10033       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10034       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10035
10036       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10037       const char *variant_name
10038         = rust_last_path_segment (TYPE_NAME (field_type));
10039       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10040       TYPE_NAME (field_type)
10041         = rust_fully_qualify (&objfile->objfile_obstack,
10042                               TYPE_NAME (type), variant_name);
10043
10044       /* Install the union in the outer struct type.  */
10045       TYPE_NFIELDS (type) = 1;
10046       TYPE_FIELDS (type)
10047         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10048       TYPE_FIELD_TYPE (type, 0) = union_type;
10049       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10050       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10051
10052       alloc_discriminant_info (union_type, -1, 0);
10053     }
10054   else
10055     {
10056       struct type *disr_type = nullptr;
10057       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10058         {
10059           disr_type = TYPE_FIELD_TYPE (type, i);
10060
10061           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10062             {
10063               /* All fields of a true enum will be structs.  */
10064               return;
10065             }
10066           else if (TYPE_NFIELDS (disr_type) == 0)
10067             {
10068               /* Could be data-less variant, so keep going.  */
10069               disr_type = nullptr;
10070             }
10071           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10072                            "RUST$ENUM$DISR") != 0)
10073             {
10074               /* Not a Rust enum.  */
10075               return;
10076             }
10077           else
10078             {
10079               /* Found one.  */
10080               break;
10081             }
10082         }
10083
10084       /* If we got here without a discriminant, then it's probably
10085          just a union.  */
10086       if (disr_type == nullptr)
10087         return;
10088
10089       /* Smash this type to be a structure type.  We have to do this
10090          because the type has already been recorded.  */
10091       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10092
10093       /* Make a union to hold the variants.  */
10094       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10095       struct type *union_type = alloc_type (objfile);
10096       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10097       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10098       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10099       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10100       TYPE_FIELDS (union_type)
10101         = (struct field *) TYPE_ZALLOC (union_type,
10102                                         (TYPE_NFIELDS (union_type)
10103                                          * sizeof (struct field)));
10104
10105       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10106               TYPE_NFIELDS (type) * sizeof (struct field));
10107
10108       /* Install the discriminant at index 0 in the union.  */
10109       TYPE_FIELD (union_type, 0) = *disr_field;
10110       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10111       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10112
10113       /* Install the union in the outer struct type.  */
10114       TYPE_FIELD_TYPE (type, 0) = union_type;
10115       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10116       TYPE_NFIELDS (type) = 1;
10117
10118       /* Set the size and offset of the union type.  */
10119       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10120
10121       /* We need a way to find the correct discriminant given a
10122          variant name.  For convenience we build a map here.  */
10123       struct type *enum_type = FIELD_TYPE (*disr_field);
10124       std::unordered_map<std::string, ULONGEST> discriminant_map;
10125       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10126         {
10127           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10128             {
10129               const char *name
10130                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10131               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10132             }
10133         }
10134
10135       int n_fields = TYPE_NFIELDS (union_type);
10136       struct discriminant_info *disc
10137         = alloc_discriminant_info (union_type, 0, -1);
10138       /* Skip the discriminant here.  */
10139       for (int i = 1; i < n_fields; ++i)
10140         {
10141           /* Find the final word in the name of this variant's type.
10142              That name can be used to look up the correct
10143              discriminant.  */
10144           const char *variant_name
10145             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10146                                                                   i)));
10147
10148           auto iter = discriminant_map.find (variant_name);
10149           if (iter != discriminant_map.end ())
10150             disc->discriminants[i] = iter->second;
10151
10152           /* Remove the discriminant field, if it exists.  */
10153           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10154           if (TYPE_NFIELDS (sub_type) > 0)
10155             {
10156               --TYPE_NFIELDS (sub_type);
10157               ++TYPE_FIELDS (sub_type);
10158             }
10159           TYPE_FIELD_NAME (union_type, i) = variant_name;
10160           TYPE_NAME (sub_type)
10161             = rust_fully_qualify (&objfile->objfile_obstack,
10162                                   TYPE_NAME (type), variant_name);
10163         }
10164     }
10165 }
10166
10167 /* Rewrite some Rust unions to be structures with variants parts.  */
10168
10169 static void
10170 rust_union_quirks (struct dwarf2_cu *cu)
10171 {
10172   gdb_assert (cu->language == language_rust);
10173   for (type *type_ : cu->rust_unions)
10174     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10175   /* We don't need this any more.  */
10176   cu->rust_unions.clear ();
10177 }
10178
10179 /* Return the symtab for PER_CU.  This works properly regardless of
10180    whether we're using the index or psymtabs.  */
10181
10182 static struct compunit_symtab *
10183 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10184 {
10185   return (per_cu->dwarf2_per_objfile->using_index
10186           ? per_cu->v.quick->compunit_symtab
10187           : per_cu->v.psymtab->compunit_symtab);
10188 }
10189
10190 /* A helper function for computing the list of all symbol tables
10191    included by PER_CU.  */
10192
10193 static void
10194 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
10195                                 htab_t all_children, htab_t all_type_symtabs,
10196                                 struct dwarf2_per_cu_data *per_cu,
10197                                 struct compunit_symtab *immediate_parent)
10198 {
10199   void **slot;
10200   int ix;
10201   struct compunit_symtab *cust;
10202   struct dwarf2_per_cu_data *iter;
10203
10204   slot = htab_find_slot (all_children, per_cu, INSERT);
10205   if (*slot != NULL)
10206     {
10207       /* This inclusion and its children have been processed.  */
10208       return;
10209     }
10210
10211   *slot = per_cu;
10212   /* Only add a CU if it has a symbol table.  */
10213   cust = get_compunit_symtab (per_cu);
10214   if (cust != NULL)
10215     {
10216       /* If this is a type unit only add its symbol table if we haven't
10217          seen it yet (type unit per_cu's can share symtabs).  */
10218       if (per_cu->is_debug_types)
10219         {
10220           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10221           if (*slot == NULL)
10222             {
10223               *slot = cust;
10224               result->push_back (cust);
10225               if (cust->user == NULL)
10226                 cust->user = immediate_parent;
10227             }
10228         }
10229       else
10230         {
10231           result->push_back (cust);
10232           if (cust->user == NULL)
10233             cust->user = immediate_parent;
10234         }
10235     }
10236
10237   for (ix = 0;
10238        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10239        ++ix)
10240     {
10241       recursively_compute_inclusions (result, all_children,
10242                                       all_type_symtabs, iter, cust);
10243     }
10244 }
10245
10246 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10247    PER_CU.  */
10248
10249 static void
10250 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10251 {
10252   gdb_assert (! per_cu->is_debug_types);
10253
10254   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10255     {
10256       int ix, len;
10257       struct dwarf2_per_cu_data *per_cu_iter;
10258       std::vector<compunit_symtab *> result_symtabs;
10259       htab_t all_children, all_type_symtabs;
10260       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10261
10262       /* If we don't have a symtab, we can just skip this case.  */
10263       if (cust == NULL)
10264         return;
10265
10266       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10267                                         NULL, xcalloc, xfree);
10268       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10269                                             NULL, xcalloc, xfree);
10270
10271       for (ix = 0;
10272            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10273                         ix, per_cu_iter);
10274            ++ix)
10275         {
10276           recursively_compute_inclusions (&result_symtabs, all_children,
10277                                           all_type_symtabs, per_cu_iter,
10278                                           cust);
10279         }
10280
10281       /* Now we have a transitive closure of all the included symtabs.  */
10282       len = result_symtabs.size ();
10283       cust->includes
10284         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10285                      struct compunit_symtab *, len + 1);
10286       memcpy (cust->includes, result_symtabs.data (),
10287               len * sizeof (compunit_symtab *));
10288       cust->includes[len] = NULL;
10289
10290       htab_delete (all_children);
10291       htab_delete (all_type_symtabs);
10292     }
10293 }
10294
10295 /* Compute the 'includes' field for the symtabs of all the CUs we just
10296    read.  */
10297
10298 static void
10299 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10300 {
10301   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10302     {
10303       if (! iter->is_debug_types)
10304         compute_compunit_symtab_includes (iter);
10305     }
10306
10307   dwarf2_per_objfile->just_read_cus.clear ();
10308 }
10309
10310 /* Generate full symbol information for PER_CU, whose DIEs have
10311    already been loaded into memory.  */
10312
10313 static void
10314 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10315                         enum language pretend_language)
10316 {
10317   struct dwarf2_cu *cu = per_cu->cu;
10318   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10319   struct objfile *objfile = dwarf2_per_objfile->objfile;
10320   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10321   CORE_ADDR lowpc, highpc;
10322   struct compunit_symtab *cust;
10323   CORE_ADDR baseaddr;
10324   struct block *static_block;
10325   CORE_ADDR addr;
10326
10327   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10328
10329   /* Clear the list here in case something was left over.  */
10330   cu->method_list.clear ();
10331
10332   cu->language = pretend_language;
10333   cu->language_defn = language_def (cu->language);
10334
10335   /* Do line number decoding in read_file_scope () */
10336   process_die (cu->dies, cu);
10337
10338   /* For now fudge the Go package.  */
10339   if (cu->language == language_go)
10340     fixup_go_packaging (cu);
10341
10342   /* Now that we have processed all the DIEs in the CU, all the types 
10343      should be complete, and it should now be safe to compute all of the
10344      physnames.  */
10345   compute_delayed_physnames (cu);
10346
10347   if (cu->language == language_rust)
10348     rust_union_quirks (cu);
10349
10350   /* Some compilers don't define a DW_AT_high_pc attribute for the
10351      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10352      it, by scanning the DIE's below the compilation unit.  */
10353   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10354
10355   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10356   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
10357
10358   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10359      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10360      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10361      addrmap to help ensure it has an accurate map of pc values belonging to
10362      this comp unit.  */
10363   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10364
10365   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10366                                                     SECT_OFF_TEXT (objfile),
10367                                                     0);
10368
10369   if (cust != NULL)
10370     {
10371       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10372
10373       /* Set symtab language to language from DW_AT_language.  If the
10374          compilation is from a C file generated by language preprocessors, do
10375          not set the language if it was already deduced by start_subfile.  */
10376       if (!(cu->language == language_c
10377             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10378         COMPUNIT_FILETABS (cust)->language = cu->language;
10379
10380       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10381          produce DW_AT_location with location lists but it can be possibly
10382          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10383          there were bugs in prologue debug info, fixed later in GCC-4.5
10384          by "unwind info for epilogues" patch (which is not directly related).
10385
10386          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10387          needed, it would be wrong due to missing DW_AT_producer there.
10388
10389          Still one can confuse GDB by using non-standard GCC compilation
10390          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10391          */ 
10392       if (cu->has_loclist && gcc_4_minor >= 5)
10393         cust->locations_valid = 1;
10394
10395       if (gcc_4_minor >= 5)
10396         cust->epilogue_unwind_valid = 1;
10397
10398       cust->call_site_htab = cu->call_site_htab;
10399     }
10400
10401   if (dwarf2_per_objfile->using_index)
10402     per_cu->v.quick->compunit_symtab = cust;
10403   else
10404     {
10405       struct partial_symtab *pst = per_cu->v.psymtab;
10406       pst->compunit_symtab = cust;
10407       pst->readin = 1;
10408     }
10409
10410   /* Push it for inclusion processing later.  */
10411   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10412
10413   /* Not needed any more.  */
10414   cu->reset_builder ();
10415 }
10416
10417 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10418    already been loaded into memory.  */
10419
10420 static void
10421 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10422                         enum language pretend_language)
10423 {
10424   struct dwarf2_cu *cu = per_cu->cu;
10425   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10426   struct objfile *objfile = dwarf2_per_objfile->objfile;
10427   struct compunit_symtab *cust;
10428   struct signatured_type *sig_type;
10429
10430   gdb_assert (per_cu->is_debug_types);
10431   sig_type = (struct signatured_type *) per_cu;
10432
10433   /* Clear the list here in case something was left over.  */
10434   cu->method_list.clear ();
10435
10436   cu->language = pretend_language;
10437   cu->language_defn = language_def (cu->language);
10438
10439   /* The symbol tables are set up in read_type_unit_scope.  */
10440   process_die (cu->dies, cu);
10441
10442   /* For now fudge the Go package.  */
10443   if (cu->language == language_go)
10444     fixup_go_packaging (cu);
10445
10446   /* Now that we have processed all the DIEs in the CU, all the types 
10447      should be complete, and it should now be safe to compute all of the
10448      physnames.  */
10449   compute_delayed_physnames (cu);
10450
10451   if (cu->language == language_rust)
10452     rust_union_quirks (cu);
10453
10454   /* TUs share symbol tables.
10455      If this is the first TU to use this symtab, complete the construction
10456      of it with end_expandable_symtab.  Otherwise, complete the addition of
10457      this TU's symbols to the existing symtab.  */
10458   if (sig_type->type_unit_group->compunit_symtab == NULL)
10459     {
10460       buildsym_compunit *builder = cu->get_builder ();
10461       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10462       sig_type->type_unit_group->compunit_symtab = cust;
10463
10464       if (cust != NULL)
10465         {
10466           /* Set symtab language to language from DW_AT_language.  If the
10467              compilation is from a C file generated by language preprocessors,
10468              do not set the language if it was already deduced by
10469              start_subfile.  */
10470           if (!(cu->language == language_c
10471                 && COMPUNIT_FILETABS (cust)->language != language_c))
10472             COMPUNIT_FILETABS (cust)->language = cu->language;
10473         }
10474     }
10475   else
10476     {
10477       cu->get_builder ()->augment_type_symtab ();
10478       cust = sig_type->type_unit_group->compunit_symtab;
10479     }
10480
10481   if (dwarf2_per_objfile->using_index)
10482     per_cu->v.quick->compunit_symtab = cust;
10483   else
10484     {
10485       struct partial_symtab *pst = per_cu->v.psymtab;
10486       pst->compunit_symtab = cust;
10487       pst->readin = 1;
10488     }
10489
10490   /* Not needed any more.  */
10491   cu->reset_builder ();
10492 }
10493
10494 /* Process an imported unit DIE.  */
10495
10496 static void
10497 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10498 {
10499   struct attribute *attr;
10500
10501   /* For now we don't handle imported units in type units.  */
10502   if (cu->per_cu->is_debug_types)
10503     {
10504       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10505                " supported in type units [in module %s]"),
10506              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10507     }
10508
10509   attr = dwarf2_attr (die, DW_AT_import, cu);
10510   if (attr != NULL)
10511     {
10512       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10513       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10514       dwarf2_per_cu_data *per_cu
10515         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10516                                             cu->per_cu->dwarf2_per_objfile);
10517
10518       /* If necessary, add it to the queue and load its DIEs.  */
10519       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10520         load_full_comp_unit (per_cu, false, cu->language);
10521
10522       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10523                      per_cu);
10524     }
10525 }
10526
10527 /* RAII object that represents a process_die scope: i.e.,
10528    starts/finishes processing a DIE.  */
10529 class process_die_scope
10530 {
10531 public:
10532   process_die_scope (die_info *die, dwarf2_cu *cu)
10533     : m_die (die), m_cu (cu)
10534   {
10535     /* We should only be processing DIEs not already in process.  */
10536     gdb_assert (!m_die->in_process);
10537     m_die->in_process = true;
10538   }
10539
10540   ~process_die_scope ()
10541   {
10542     m_die->in_process = false;
10543
10544     /* If we're done processing the DIE for the CU that owns the line
10545        header, we don't need the line header anymore.  */
10546     if (m_cu->line_header_die_owner == m_die)
10547       {
10548         delete m_cu->line_header;
10549         m_cu->line_header = NULL;
10550         m_cu->line_header_die_owner = NULL;
10551       }
10552   }
10553
10554 private:
10555   die_info *m_die;
10556   dwarf2_cu *m_cu;
10557 };
10558
10559 /* Process a die and its children.  */
10560
10561 static void
10562 process_die (struct die_info *die, struct dwarf2_cu *cu)
10563 {
10564   process_die_scope scope (die, cu);
10565
10566   switch (die->tag)
10567     {
10568     case DW_TAG_padding:
10569       break;
10570     case DW_TAG_compile_unit:
10571     case DW_TAG_partial_unit:
10572       read_file_scope (die, cu);
10573       break;
10574     case DW_TAG_type_unit:
10575       read_type_unit_scope (die, cu);
10576       break;
10577     case DW_TAG_subprogram:
10578     case DW_TAG_inlined_subroutine:
10579       read_func_scope (die, cu);
10580       break;
10581     case DW_TAG_lexical_block:
10582     case DW_TAG_try_block:
10583     case DW_TAG_catch_block:
10584       read_lexical_block_scope (die, cu);
10585       break;
10586     case DW_TAG_call_site:
10587     case DW_TAG_GNU_call_site:
10588       read_call_site_scope (die, cu);
10589       break;
10590     case DW_TAG_class_type:
10591     case DW_TAG_interface_type:
10592     case DW_TAG_structure_type:
10593     case DW_TAG_union_type:
10594       process_structure_scope (die, cu);
10595       break;
10596     case DW_TAG_enumeration_type:
10597       process_enumeration_scope (die, cu);
10598       break;
10599
10600     /* These dies have a type, but processing them does not create
10601        a symbol or recurse to process the children.  Therefore we can
10602        read them on-demand through read_type_die.  */
10603     case DW_TAG_subroutine_type:
10604     case DW_TAG_set_type:
10605     case DW_TAG_array_type:
10606     case DW_TAG_pointer_type:
10607     case DW_TAG_ptr_to_member_type:
10608     case DW_TAG_reference_type:
10609     case DW_TAG_rvalue_reference_type:
10610     case DW_TAG_string_type:
10611       break;
10612
10613     case DW_TAG_base_type:
10614     case DW_TAG_subrange_type:
10615     case DW_TAG_typedef:
10616       /* Add a typedef symbol for the type definition, if it has a
10617          DW_AT_name.  */
10618       new_symbol (die, read_type_die (die, cu), cu);
10619       break;
10620     case DW_TAG_common_block:
10621       read_common_block (die, cu);
10622       break;
10623     case DW_TAG_common_inclusion:
10624       break;
10625     case DW_TAG_namespace:
10626       cu->processing_has_namespace_info = true;
10627       read_namespace (die, cu);
10628       break;
10629     case DW_TAG_module:
10630       cu->processing_has_namespace_info = true;
10631       read_module (die, cu);
10632       break;
10633     case DW_TAG_imported_declaration:
10634       cu->processing_has_namespace_info = true;
10635       if (read_namespace_alias (die, cu))
10636         break;
10637       /* The declaration is not a global namespace alias.  */
10638       /* Fall through.  */
10639     case DW_TAG_imported_module:
10640       cu->processing_has_namespace_info = true;
10641       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10642                                  || cu->language != language_fortran))
10643         complaint (_("Tag '%s' has unexpected children"),
10644                    dwarf_tag_name (die->tag));
10645       read_import_statement (die, cu);
10646       break;
10647
10648     case DW_TAG_imported_unit:
10649       process_imported_unit_die (die, cu);
10650       break;
10651
10652     case DW_TAG_variable:
10653       read_variable (die, cu);
10654       break;
10655
10656     default:
10657       new_symbol (die, NULL, cu);
10658       break;
10659     }
10660 }
10661 \f
10662 /* DWARF name computation.  */
10663
10664 /* A helper function for dwarf2_compute_name which determines whether DIE
10665    needs to have the name of the scope prepended to the name listed in the
10666    die.  */
10667
10668 static int
10669 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10670 {
10671   struct attribute *attr;
10672
10673   switch (die->tag)
10674     {
10675     case DW_TAG_namespace:
10676     case DW_TAG_typedef:
10677     case DW_TAG_class_type:
10678     case DW_TAG_interface_type:
10679     case DW_TAG_structure_type:
10680     case DW_TAG_union_type:
10681     case DW_TAG_enumeration_type:
10682     case DW_TAG_enumerator:
10683     case DW_TAG_subprogram:
10684     case DW_TAG_inlined_subroutine:
10685     case DW_TAG_member:
10686     case DW_TAG_imported_declaration:
10687       return 1;
10688
10689     case DW_TAG_variable:
10690     case DW_TAG_constant:
10691       /* We only need to prefix "globally" visible variables.  These include
10692          any variable marked with DW_AT_external or any variable that
10693          lives in a namespace.  [Variables in anonymous namespaces
10694          require prefixing, but they are not DW_AT_external.]  */
10695
10696       if (dwarf2_attr (die, DW_AT_specification, cu))
10697         {
10698           struct dwarf2_cu *spec_cu = cu;
10699
10700           return die_needs_namespace (die_specification (die, &spec_cu),
10701                                       spec_cu);
10702         }
10703
10704       attr = dwarf2_attr (die, DW_AT_external, cu);
10705       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10706           && die->parent->tag != DW_TAG_module)
10707         return 0;
10708       /* A variable in a lexical block of some kind does not need a
10709          namespace, even though in C++ such variables may be external
10710          and have a mangled name.  */
10711       if (die->parent->tag ==  DW_TAG_lexical_block
10712           || die->parent->tag ==  DW_TAG_try_block
10713           || die->parent->tag ==  DW_TAG_catch_block
10714           || die->parent->tag == DW_TAG_subprogram)
10715         return 0;
10716       return 1;
10717
10718     default:
10719       return 0;
10720     }
10721 }
10722
10723 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10724    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10725    defined for the given DIE.  */
10726
10727 static struct attribute *
10728 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10729 {
10730   struct attribute *attr;
10731
10732   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10733   if (attr == NULL)
10734     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10735
10736   return attr;
10737 }
10738
10739 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10740    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10741    defined for the given DIE.  */
10742
10743 static const char *
10744 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10745 {
10746   const char *linkage_name;
10747
10748   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10749   if (linkage_name == NULL)
10750     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10751
10752   return linkage_name;
10753 }
10754
10755 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10756    compute the physname for the object, which include a method's:
10757    - formal parameters (C++),
10758    - receiver type (Go),
10759
10760    The term "physname" is a bit confusing.
10761    For C++, for example, it is the demangled name.
10762    For Go, for example, it's the mangled name.
10763
10764    For Ada, return the DIE's linkage name rather than the fully qualified
10765    name.  PHYSNAME is ignored..
10766
10767    The result is allocated on the objfile_obstack and canonicalized.  */
10768
10769 static const char *
10770 dwarf2_compute_name (const char *name,
10771                      struct die_info *die, struct dwarf2_cu *cu,
10772                      int physname)
10773 {
10774   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10775
10776   if (name == NULL)
10777     name = dwarf2_name (die, cu);
10778
10779   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10780      but otherwise compute it by typename_concat inside GDB.
10781      FIXME: Actually this is not really true, or at least not always true.
10782      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10783      Fortran names because there is no mangling standard.  So new_symbol
10784      will set the demangled name to the result of dwarf2_full_name, and it is
10785      the demangled name that GDB uses if it exists.  */
10786   if (cu->language == language_ada
10787       || (cu->language == language_fortran && physname))
10788     {
10789       /* For Ada unit, we prefer the linkage name over the name, as
10790          the former contains the exported name, which the user expects
10791          to be able to reference.  Ideally, we want the user to be able
10792          to reference this entity using either natural or linkage name,
10793          but we haven't started looking at this enhancement yet.  */
10794       const char *linkage_name = dw2_linkage_name (die, cu);
10795
10796       if (linkage_name != NULL)
10797         return linkage_name;
10798     }
10799
10800   /* These are the only languages we know how to qualify names in.  */
10801   if (name != NULL
10802       && (cu->language == language_cplus
10803           || cu->language == language_fortran || cu->language == language_d
10804           || cu->language == language_rust))
10805     {
10806       if (die_needs_namespace (die, cu))
10807         {
10808           const char *prefix;
10809           const char *canonical_name = NULL;
10810
10811           string_file buf;
10812
10813           prefix = determine_prefix (die, cu);
10814           if (*prefix != '\0')
10815             {
10816               char *prefixed_name = typename_concat (NULL, prefix, name,
10817                                                      physname, cu);
10818
10819               buf.puts (prefixed_name);
10820               xfree (prefixed_name);
10821             }
10822           else
10823             buf.puts (name);
10824
10825           /* Template parameters may be specified in the DIE's DW_AT_name, or
10826              as children with DW_TAG_template_type_param or
10827              DW_TAG_value_type_param.  If the latter, add them to the name
10828              here.  If the name already has template parameters, then
10829              skip this step; some versions of GCC emit both, and
10830              it is more efficient to use the pre-computed name.
10831
10832              Something to keep in mind about this process: it is very
10833              unlikely, or in some cases downright impossible, to produce
10834              something that will match the mangled name of a function.
10835              If the definition of the function has the same debug info,
10836              we should be able to match up with it anyway.  But fallbacks
10837              using the minimal symbol, for instance to find a method
10838              implemented in a stripped copy of libstdc++, will not work.
10839              If we do not have debug info for the definition, we will have to
10840              match them up some other way.
10841
10842              When we do name matching there is a related problem with function
10843              templates; two instantiated function templates are allowed to
10844              differ only by their return types, which we do not add here.  */
10845
10846           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10847             {
10848               struct attribute *attr;
10849               struct die_info *child;
10850               int first = 1;
10851
10852               die->building_fullname = 1;
10853
10854               for (child = die->child; child != NULL; child = child->sibling)
10855                 {
10856                   struct type *type;
10857                   LONGEST value;
10858                   const gdb_byte *bytes;
10859                   struct dwarf2_locexpr_baton *baton;
10860                   struct value *v;
10861
10862                   if (child->tag != DW_TAG_template_type_param
10863                       && child->tag != DW_TAG_template_value_param)
10864                     continue;
10865
10866                   if (first)
10867                     {
10868                       buf.puts ("<");
10869                       first = 0;
10870                     }
10871                   else
10872                     buf.puts (", ");
10873
10874                   attr = dwarf2_attr (child, DW_AT_type, cu);
10875                   if (attr == NULL)
10876                     {
10877                       complaint (_("template parameter missing DW_AT_type"));
10878                       buf.puts ("UNKNOWN_TYPE");
10879                       continue;
10880                     }
10881                   type = die_type (child, cu);
10882
10883                   if (child->tag == DW_TAG_template_type_param)
10884                     {
10885                       c_print_type (type, "", &buf, -1, 0, cu->language,
10886                                     &type_print_raw_options);
10887                       continue;
10888                     }
10889
10890                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10891                   if (attr == NULL)
10892                     {
10893                       complaint (_("template parameter missing "
10894                                    "DW_AT_const_value"));
10895                       buf.puts ("UNKNOWN_VALUE");
10896                       continue;
10897                     }
10898
10899                   dwarf2_const_value_attr (attr, type, name,
10900                                            &cu->comp_unit_obstack, cu,
10901                                            &value, &bytes, &baton);
10902
10903                   if (TYPE_NOSIGN (type))
10904                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10905                        changed, this can use value_print instead.  */
10906                     c_printchar (value, type, &buf);
10907                   else
10908                     {
10909                       struct value_print_options opts;
10910
10911                       if (baton != NULL)
10912                         v = dwarf2_evaluate_loc_desc (type, NULL,
10913                                                       baton->data,
10914                                                       baton->size,
10915                                                       baton->per_cu);
10916                       else if (bytes != NULL)
10917                         {
10918                           v = allocate_value (type);
10919                           memcpy (value_contents_writeable (v), bytes,
10920                                   TYPE_LENGTH (type));
10921                         }
10922                       else
10923                         v = value_from_longest (type, value);
10924
10925                       /* Specify decimal so that we do not depend on
10926                          the radix.  */
10927                       get_formatted_print_options (&opts, 'd');
10928                       opts.raw = 1;
10929                       value_print (v, &buf, &opts);
10930                       release_value (v);
10931                     }
10932                 }
10933
10934               die->building_fullname = 0;
10935
10936               if (!first)
10937                 {
10938                   /* Close the argument list, with a space if necessary
10939                      (nested templates).  */
10940                   if (!buf.empty () && buf.string ().back () == '>')
10941                     buf.puts (" >");
10942                   else
10943                     buf.puts (">");
10944                 }
10945             }
10946
10947           /* For C++ methods, append formal parameter type
10948              information, if PHYSNAME.  */
10949
10950           if (physname && die->tag == DW_TAG_subprogram
10951               && cu->language == language_cplus)
10952             {
10953               struct type *type = read_type_die (die, cu);
10954
10955               c_type_print_args (type, &buf, 1, cu->language,
10956                                  &type_print_raw_options);
10957
10958               if (cu->language == language_cplus)
10959                 {
10960                   /* Assume that an artificial first parameter is
10961                      "this", but do not crash if it is not.  RealView
10962                      marks unnamed (and thus unused) parameters as
10963                      artificial; there is no way to differentiate
10964                      the two cases.  */
10965                   if (TYPE_NFIELDS (type) > 0
10966                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10967                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10968                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10969                                                                         0))))
10970                     buf.puts (" const");
10971                 }
10972             }
10973
10974           const std::string &intermediate_name = buf.string ();
10975
10976           if (cu->language == language_cplus)
10977             canonical_name
10978               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10979                                           &objfile->per_bfd->storage_obstack);
10980
10981           /* If we only computed INTERMEDIATE_NAME, or if
10982              INTERMEDIATE_NAME is already canonical, then we need to
10983              copy it to the appropriate obstack.  */
10984           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10985             name = obstack_strdup (&objfile->per_bfd->storage_obstack,
10986                                    intermediate_name);
10987           else
10988             name = canonical_name;
10989         }
10990     }
10991
10992   return name;
10993 }
10994
10995 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10996    If scope qualifiers are appropriate they will be added.  The result
10997    will be allocated on the storage_obstack, or NULL if the DIE does
10998    not have a name.  NAME may either be from a previous call to
10999    dwarf2_name or NULL.
11000
11001    The output string will be canonicalized (if C++).  */
11002
11003 static const char *
11004 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11005 {
11006   return dwarf2_compute_name (name, die, cu, 0);
11007 }
11008
11009 /* Construct a physname for the given DIE in CU.  NAME may either be
11010    from a previous call to dwarf2_name or NULL.  The result will be
11011    allocated on the objfile_objstack or NULL if the DIE does not have a
11012    name.
11013
11014    The output string will be canonicalized (if C++).  */
11015
11016 static const char *
11017 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11018 {
11019   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11020   const char *retval, *mangled = NULL, *canon = NULL;
11021   int need_copy = 1;
11022
11023   /* In this case dwarf2_compute_name is just a shortcut not building anything
11024      on its own.  */
11025   if (!die_needs_namespace (die, cu))
11026     return dwarf2_compute_name (name, die, cu, 1);
11027
11028   mangled = dw2_linkage_name (die, cu);
11029
11030   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11031      See https://github.com/rust-lang/rust/issues/32925.  */
11032   if (cu->language == language_rust && mangled != NULL
11033       && strchr (mangled, '{') != NULL)
11034     mangled = NULL;
11035
11036   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11037      has computed.  */
11038   gdb::unique_xmalloc_ptr<char> demangled;
11039   if (mangled != NULL)
11040     {
11041
11042       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11043         {
11044           /* Do nothing (do not demangle the symbol name).  */
11045         }
11046       else if (cu->language == language_go)
11047         {
11048           /* This is a lie, but we already lie to the caller new_symbol.
11049              new_symbol assumes we return the mangled name.
11050              This just undoes that lie until things are cleaned up.  */
11051         }
11052       else
11053         {
11054           /* Use DMGL_RET_DROP for C++ template functions to suppress
11055              their return type.  It is easier for GDB users to search
11056              for such functions as `name(params)' than `long name(params)'.
11057              In such case the minimal symbol names do not match the full
11058              symbol names but for template functions there is never a need
11059              to look up their definition from their declaration so
11060              the only disadvantage remains the minimal symbol variant
11061              `long name(params)' does not have the proper inferior type.  */
11062           demangled.reset (gdb_demangle (mangled,
11063                                          (DMGL_PARAMS | DMGL_ANSI
11064                                           | DMGL_RET_DROP)));
11065         }
11066       if (demangled)
11067         canon = demangled.get ();
11068       else
11069         {
11070           canon = mangled;
11071           need_copy = 0;
11072         }
11073     }
11074
11075   if (canon == NULL || check_physname)
11076     {
11077       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11078
11079       if (canon != NULL && strcmp (physname, canon) != 0)
11080         {
11081           /* It may not mean a bug in GDB.  The compiler could also
11082              compute DW_AT_linkage_name incorrectly.  But in such case
11083              GDB would need to be bug-to-bug compatible.  */
11084
11085           complaint (_("Computed physname <%s> does not match demangled <%s> "
11086                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11087                      physname, canon, mangled, sect_offset_str (die->sect_off),
11088                      objfile_name (objfile));
11089
11090           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11091              is available here - over computed PHYSNAME.  It is safer
11092              against both buggy GDB and buggy compilers.  */
11093
11094           retval = canon;
11095         }
11096       else
11097         {
11098           retval = physname;
11099           need_copy = 0;
11100         }
11101     }
11102   else
11103     retval = canon;
11104
11105   if (need_copy)
11106     retval = obstack_strdup (&objfile->per_bfd->storage_obstack, retval);
11107
11108   return retval;
11109 }
11110
11111 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11112    a new symbol for it.
11113
11114    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11115
11116 static int
11117 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11118 {
11119   struct attribute *attr;
11120
11121   /* If the die does not have a name, this is not a namespace
11122      alias.  */
11123   attr = dwarf2_attr (die, DW_AT_name, cu);
11124   if (attr != NULL)
11125     {
11126       int num;
11127       struct die_info *d = die;
11128       struct dwarf2_cu *imported_cu = cu;
11129
11130       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11131          keep inspecting DIEs until we hit the underlying import.  */
11132 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11133       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11134         {
11135           attr = dwarf2_attr (d, DW_AT_import, cu);
11136           if (attr == NULL)
11137             break;
11138
11139           d = follow_die_ref (d, attr, &imported_cu);
11140           if (d->tag != DW_TAG_imported_declaration)
11141             break;
11142         }
11143
11144       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11145         {
11146           complaint (_("DIE at %s has too many recursively imported "
11147                        "declarations"), sect_offset_str (d->sect_off));
11148           return 0;
11149         }
11150
11151       if (attr != NULL)
11152         {
11153           struct type *type;
11154           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11155
11156           type = get_die_type_at_offset (sect_off, cu->per_cu);
11157           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11158             {
11159               /* This declaration is a global namespace alias.  Add
11160                  a symbol for it whose type is the aliased namespace.  */
11161               new_symbol (die, type, cu);
11162               return 1;
11163             }
11164         }
11165     }
11166
11167   return 0;
11168 }
11169
11170 /* Return the using directives repository (global or local?) to use in the
11171    current context for CU.
11172
11173    For Ada, imported declarations can materialize renamings, which *may* be
11174    global.  However it is impossible (for now?) in DWARF to distinguish
11175    "external" imported declarations and "static" ones.  As all imported
11176    declarations seem to be static in all other languages, make them all CU-wide
11177    global only in Ada.  */
11178
11179 static struct using_direct **
11180 using_directives (struct dwarf2_cu *cu)
11181 {
11182   if (cu->language == language_ada
11183       && cu->get_builder ()->outermost_context_p ())
11184     return cu->get_builder ()->get_global_using_directives ();
11185   else
11186     return cu->get_builder ()->get_local_using_directives ();
11187 }
11188
11189 /* Read the import statement specified by the given die and record it.  */
11190
11191 static void
11192 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11193 {
11194   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11195   struct attribute *import_attr;
11196   struct die_info *imported_die, *child_die;
11197   struct dwarf2_cu *imported_cu;
11198   const char *imported_name;
11199   const char *imported_name_prefix;
11200   const char *canonical_name;
11201   const char *import_alias;
11202   const char *imported_declaration = NULL;
11203   const char *import_prefix;
11204   std::vector<const char *> excludes;
11205
11206   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11207   if (import_attr == NULL)
11208     {
11209       complaint (_("Tag '%s' has no DW_AT_import"),
11210                  dwarf_tag_name (die->tag));
11211       return;
11212     }
11213
11214   imported_cu = cu;
11215   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11216   imported_name = dwarf2_name (imported_die, imported_cu);
11217   if (imported_name == NULL)
11218     {
11219       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11220
11221         The import in the following code:
11222         namespace A
11223           {
11224             typedef int B;
11225           }
11226
11227         int main ()
11228           {
11229             using A::B;
11230             B b;
11231             return b;
11232           }
11233
11234         ...
11235          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11236             <52>   DW_AT_decl_file   : 1
11237             <53>   DW_AT_decl_line   : 6
11238             <54>   DW_AT_import      : <0x75>
11239          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11240             <59>   DW_AT_name        : B
11241             <5b>   DW_AT_decl_file   : 1
11242             <5c>   DW_AT_decl_line   : 2
11243             <5d>   DW_AT_type        : <0x6e>
11244         ...
11245          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11246             <76>   DW_AT_byte_size   : 4
11247             <77>   DW_AT_encoding    : 5        (signed)
11248
11249         imports the wrong die ( 0x75 instead of 0x58 ).
11250         This case will be ignored until the gcc bug is fixed.  */
11251       return;
11252     }
11253
11254   /* Figure out the local name after import.  */
11255   import_alias = dwarf2_name (die, cu);
11256
11257   /* Figure out where the statement is being imported to.  */
11258   import_prefix = determine_prefix (die, cu);
11259
11260   /* Figure out what the scope of the imported die is and prepend it
11261      to the name of the imported die.  */
11262   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11263
11264   if (imported_die->tag != DW_TAG_namespace
11265       && imported_die->tag != DW_TAG_module)
11266     {
11267       imported_declaration = imported_name;
11268       canonical_name = imported_name_prefix;
11269     }
11270   else if (strlen (imported_name_prefix) > 0)
11271     canonical_name = obconcat (&objfile->objfile_obstack,
11272                                imported_name_prefix,
11273                                (cu->language == language_d ? "." : "::"),
11274                                imported_name, (char *) NULL);
11275   else
11276     canonical_name = imported_name;
11277
11278   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11279     for (child_die = die->child; child_die && child_die->tag;
11280          child_die = sibling_die (child_die))
11281       {
11282         /* DWARF-4: A Fortran use statement with a “rename list” may be
11283            represented by an imported module entry with an import attribute
11284            referring to the module and owned entries corresponding to those
11285            entities that are renamed as part of being imported.  */
11286
11287         if (child_die->tag != DW_TAG_imported_declaration)
11288           {
11289             complaint (_("child DW_TAG_imported_declaration expected "
11290                          "- DIE at %s [in module %s]"),
11291                        sect_offset_str (child_die->sect_off),
11292                        objfile_name (objfile));
11293             continue;
11294           }
11295
11296         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11297         if (import_attr == NULL)
11298           {
11299             complaint (_("Tag '%s' has no DW_AT_import"),
11300                        dwarf_tag_name (child_die->tag));
11301             continue;
11302           }
11303
11304         imported_cu = cu;
11305         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11306                                               &imported_cu);
11307         imported_name = dwarf2_name (imported_die, imported_cu);
11308         if (imported_name == NULL)
11309           {
11310             complaint (_("child DW_TAG_imported_declaration has unknown "
11311                          "imported name - DIE at %s [in module %s]"),
11312                        sect_offset_str (child_die->sect_off),
11313                        objfile_name (objfile));
11314             continue;
11315           }
11316
11317         excludes.push_back (imported_name);
11318
11319         process_die (child_die, cu);
11320       }
11321
11322   add_using_directive (using_directives (cu),
11323                        import_prefix,
11324                        canonical_name,
11325                        import_alias,
11326                        imported_declaration,
11327                        excludes,
11328                        0,
11329                        &objfile->objfile_obstack);
11330 }
11331
11332 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11333    types, but gives them a size of zero.  Starting with version 14,
11334    ICC is compatible with GCC.  */
11335
11336 static bool
11337 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11338 {
11339   if (!cu->checked_producer)
11340     check_producer (cu);
11341
11342   return cu->producer_is_icc_lt_14;
11343 }
11344
11345 /* ICC generates a DW_AT_type for C void functions.  This was observed on
11346    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
11347    which says that void functions should not have a DW_AT_type.  */
11348
11349 static bool
11350 producer_is_icc (struct dwarf2_cu *cu)
11351 {
11352   if (!cu->checked_producer)
11353     check_producer (cu);
11354
11355   return cu->producer_is_icc;
11356 }
11357
11358 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11359    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11360    this, it was first present in GCC release 4.3.0.  */
11361
11362 static bool
11363 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11364 {
11365   if (!cu->checked_producer)
11366     check_producer (cu);
11367
11368   return cu->producer_is_gcc_lt_4_3;
11369 }
11370
11371 static file_and_directory
11372 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11373 {
11374   file_and_directory res;
11375
11376   /* Find the filename.  Do not use dwarf2_name here, since the filename
11377      is not a source language identifier.  */
11378   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11379   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11380
11381   if (res.comp_dir == NULL
11382       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11383       && IS_ABSOLUTE_PATH (res.name))
11384     {
11385       res.comp_dir_storage = ldirname (res.name);
11386       if (!res.comp_dir_storage.empty ())
11387         res.comp_dir = res.comp_dir_storage.c_str ();
11388     }
11389   if (res.comp_dir != NULL)
11390     {
11391       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11392          directory, get rid of it.  */
11393       const char *cp = strchr (res.comp_dir, ':');
11394
11395       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11396         res.comp_dir = cp + 1;
11397     }
11398
11399   if (res.name == NULL)
11400     res.name = "<unknown>";
11401
11402   return res;
11403 }
11404
11405 /* Handle DW_AT_stmt_list for a compilation unit.
11406    DIE is the DW_TAG_compile_unit die for CU.
11407    COMP_DIR is the compilation directory.  LOWPC is passed to
11408    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11409
11410 static void
11411 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11412                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11413 {
11414   struct dwarf2_per_objfile *dwarf2_per_objfile
11415     = cu->per_cu->dwarf2_per_objfile;
11416   struct objfile *objfile = dwarf2_per_objfile->objfile;
11417   struct attribute *attr;
11418   struct line_header line_header_local;
11419   hashval_t line_header_local_hash;
11420   void **slot;
11421   int decode_mapping;
11422
11423   gdb_assert (! cu->per_cu->is_debug_types);
11424
11425   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11426   if (attr == NULL)
11427     return;
11428
11429   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11430
11431   /* The line header hash table is only created if needed (it exists to
11432      prevent redundant reading of the line table for partial_units).
11433      If we're given a partial_unit, we'll need it.  If we're given a
11434      compile_unit, then use the line header hash table if it's already
11435      created, but don't create one just yet.  */
11436
11437   if (dwarf2_per_objfile->line_header_hash == NULL
11438       && die->tag == DW_TAG_partial_unit)
11439     {
11440       dwarf2_per_objfile->line_header_hash
11441         = htab_create_alloc_ex (127, line_header_hash_voidp,
11442                                 line_header_eq_voidp,
11443                                 free_line_header_voidp,
11444                                 &objfile->objfile_obstack,
11445                                 hashtab_obstack_allocate,
11446                                 dummy_obstack_deallocate);
11447     }
11448
11449   line_header_local.sect_off = line_offset;
11450   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11451   line_header_local_hash = line_header_hash (&line_header_local);
11452   if (dwarf2_per_objfile->line_header_hash != NULL)
11453     {
11454       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11455                                        &line_header_local,
11456                                        line_header_local_hash, NO_INSERT);
11457
11458       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11459          is not present in *SLOT (since if there is something in *SLOT then
11460          it will be for a partial_unit).  */
11461       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11462         {
11463           gdb_assert (*slot != NULL);
11464           cu->line_header = (struct line_header *) *slot;
11465           return;
11466         }
11467     }
11468
11469   /* dwarf_decode_line_header does not yet provide sufficient information.
11470      We always have to call also dwarf_decode_lines for it.  */
11471   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11472   if (lh == NULL)
11473     return;
11474
11475   cu->line_header = lh.release ();
11476   cu->line_header_die_owner = die;
11477
11478   if (dwarf2_per_objfile->line_header_hash == NULL)
11479     slot = NULL;
11480   else
11481     {
11482       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11483                                        &line_header_local,
11484                                        line_header_local_hash, INSERT);
11485       gdb_assert (slot != NULL);
11486     }
11487   if (slot != NULL && *slot == NULL)
11488     {
11489       /* This newly decoded line number information unit will be owned
11490          by line_header_hash hash table.  */
11491       *slot = cu->line_header;
11492       cu->line_header_die_owner = NULL;
11493     }
11494   else
11495     {
11496       /* We cannot free any current entry in (*slot) as that struct line_header
11497          may be already used by multiple CUs.  Create only temporary decoded
11498          line_header for this CU - it may happen at most once for each line
11499          number information unit.  And if we're not using line_header_hash
11500          then this is what we want as well.  */
11501       gdb_assert (die->tag != DW_TAG_partial_unit);
11502     }
11503   decode_mapping = (die->tag != DW_TAG_partial_unit);
11504   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11505                       decode_mapping);
11506
11507 }
11508
11509 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11510
11511 static void
11512 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11513 {
11514   struct dwarf2_per_objfile *dwarf2_per_objfile
11515     = cu->per_cu->dwarf2_per_objfile;
11516   struct objfile *objfile = dwarf2_per_objfile->objfile;
11517   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11518   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11519   CORE_ADDR highpc = ((CORE_ADDR) 0);
11520   struct attribute *attr;
11521   struct die_info *child_die;
11522   CORE_ADDR baseaddr;
11523
11524   prepare_one_comp_unit (cu, die, cu->language);
11525   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11526
11527   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11528
11529   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11530      from finish_block.  */
11531   if (lowpc == ((CORE_ADDR) -1))
11532     lowpc = highpc;
11533   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11534
11535   file_and_directory fnd = find_file_and_directory (die, cu);
11536
11537   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11538      standardised yet.  As a workaround for the language detection we fall
11539      back to the DW_AT_producer string.  */
11540   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11541     cu->language = language_opencl;
11542
11543   /* Similar hack for Go.  */
11544   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11545     set_cu_language (DW_LANG_Go, cu);
11546
11547   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11548
11549   /* Decode line number information if present.  We do this before
11550      processing child DIEs, so that the line header table is available
11551      for DW_AT_decl_file.  */
11552   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11553
11554   /* Process all dies in compilation unit.  */
11555   if (die->child != NULL)
11556     {
11557       child_die = die->child;
11558       while (child_die && child_die->tag)
11559         {
11560           process_die (child_die, cu);
11561           child_die = sibling_die (child_die);
11562         }
11563     }
11564
11565   /* Decode macro information, if present.  Dwarf 2 macro information
11566      refers to information in the line number info statement program
11567      header, so we can only read it if we've read the header
11568      successfully.  */
11569   attr = dwarf2_attr (die, DW_AT_macros, cu);
11570   if (attr == NULL)
11571     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11572   if (attr && cu->line_header)
11573     {
11574       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11575         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11576
11577       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11578     }
11579   else
11580     {
11581       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11582       if (attr && cu->line_header)
11583         {
11584           unsigned int macro_offset = DW_UNSND (attr);
11585
11586           dwarf_decode_macros (cu, macro_offset, 0);
11587         }
11588     }
11589 }
11590
11591 void
11592 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11593 {
11594   struct type_unit_group *tu_group;
11595   int first_time;
11596   struct attribute *attr;
11597   unsigned int i;
11598   struct signatured_type *sig_type;
11599
11600   gdb_assert (per_cu->is_debug_types);
11601   sig_type = (struct signatured_type *) per_cu;
11602
11603   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11604
11605   /* If we're using .gdb_index (includes -readnow) then
11606      per_cu->type_unit_group may not have been set up yet.  */
11607   if (sig_type->type_unit_group == NULL)
11608     sig_type->type_unit_group = get_type_unit_group (this, attr);
11609   tu_group = sig_type->type_unit_group;
11610
11611   /* If we've already processed this stmt_list there's no real need to
11612      do it again, we could fake it and just recreate the part we need
11613      (file name,index -> symtab mapping).  If data shows this optimization
11614      is useful we can do it then.  */
11615   first_time = tu_group->compunit_symtab == NULL;
11616
11617   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11618      debug info.  */
11619   line_header_up lh;
11620   if (attr != NULL)
11621     {
11622       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11623       lh = dwarf_decode_line_header (line_offset, this);
11624     }
11625   if (lh == NULL)
11626     {
11627       if (first_time)
11628         start_symtab ("", NULL, 0);
11629       else
11630         {
11631           gdb_assert (tu_group->symtabs == NULL);
11632           gdb_assert (m_builder == nullptr);
11633           struct compunit_symtab *cust = tu_group->compunit_symtab;
11634           m_builder.reset (new struct buildsym_compunit
11635                            (COMPUNIT_OBJFILE (cust), "",
11636                             COMPUNIT_DIRNAME (cust),
11637                             compunit_language (cust),
11638                             0, cust));
11639         }
11640       return;
11641     }
11642
11643   line_header = lh.release ();
11644   line_header_die_owner = die;
11645
11646   if (first_time)
11647     {
11648       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11649
11650       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11651          still initializing it, and our caller (a few levels up)
11652          process_full_type_unit still needs to know if this is the first
11653          time.  */
11654
11655       tu_group->num_symtabs = line_header->file_names.size ();
11656       tu_group->symtabs = XNEWVEC (struct symtab *,
11657                                    line_header->file_names.size ());
11658
11659       for (i = 0; i < line_header->file_names.size (); ++i)
11660         {
11661           file_entry &fe = line_header->file_names[i];
11662
11663           dwarf2_start_subfile (this, fe.name,
11664                                 fe.include_dir (line_header));
11665           buildsym_compunit *b = get_builder ();
11666           if (b->get_current_subfile ()->symtab == NULL)
11667             {
11668               /* NOTE: start_subfile will recognize when it's been
11669                  passed a file it has already seen.  So we can't
11670                  assume there's a simple mapping from
11671                  cu->line_header->file_names to subfiles, plus
11672                  cu->line_header->file_names may contain dups.  */
11673               b->get_current_subfile ()->symtab
11674                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11675             }
11676
11677           fe.symtab = b->get_current_subfile ()->symtab;
11678           tu_group->symtabs[i] = fe.symtab;
11679         }
11680     }
11681   else
11682     {
11683       gdb_assert (m_builder == nullptr);
11684       struct compunit_symtab *cust = tu_group->compunit_symtab;
11685       m_builder.reset (new struct buildsym_compunit
11686                        (COMPUNIT_OBJFILE (cust), "",
11687                         COMPUNIT_DIRNAME (cust),
11688                         compunit_language (cust),
11689                         0, cust));
11690
11691       for (i = 0; i < line_header->file_names.size (); ++i)
11692         {
11693           file_entry &fe = line_header->file_names[i];
11694
11695           fe.symtab = tu_group->symtabs[i];
11696         }
11697     }
11698
11699   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11700      so they don't have a "real" (so to speak) symtab anyway.
11701      There is later code that will assign the main symtab to all symbols
11702      that don't have one.  We need to handle the case of a symbol with a
11703      missing symtab (DW_AT_decl_file) anyway.  */
11704 }
11705
11706 /* Process DW_TAG_type_unit.
11707    For TUs we want to skip the first top level sibling if it's not the
11708    actual type being defined by this TU.  In this case the first top
11709    level sibling is there to provide context only.  */
11710
11711 static void
11712 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11713 {
11714   struct die_info *child_die;
11715
11716   prepare_one_comp_unit (cu, die, language_minimal);
11717
11718   /* Initialize (or reinitialize) the machinery for building symtabs.
11719      We do this before processing child DIEs, so that the line header table
11720      is available for DW_AT_decl_file.  */
11721   cu->setup_type_unit_groups (die);
11722
11723   if (die->child != NULL)
11724     {
11725       child_die = die->child;
11726       while (child_die && child_die->tag)
11727         {
11728           process_die (child_die, cu);
11729           child_die = sibling_die (child_die);
11730         }
11731     }
11732 }
11733 \f
11734 /* DWO/DWP files.
11735
11736    http://gcc.gnu.org/wiki/DebugFission
11737    http://gcc.gnu.org/wiki/DebugFissionDWP
11738
11739    To simplify handling of both DWO files ("object" files with the DWARF info)
11740    and DWP files (a file with the DWOs packaged up into one file), we treat
11741    DWP files as having a collection of virtual DWO files.  */
11742
11743 static hashval_t
11744 hash_dwo_file (const void *item)
11745 {
11746   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11747   hashval_t hash;
11748
11749   hash = htab_hash_string (dwo_file->dwo_name);
11750   if (dwo_file->comp_dir != NULL)
11751     hash += htab_hash_string (dwo_file->comp_dir);
11752   return hash;
11753 }
11754
11755 static int
11756 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11757 {
11758   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11759   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11760
11761   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11762     return 0;
11763   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11764     return lhs->comp_dir == rhs->comp_dir;
11765   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11766 }
11767
11768 /* Allocate a hash table for DWO files.  */
11769
11770 static htab_up
11771 allocate_dwo_file_hash_table (struct objfile *objfile)
11772 {
11773   auto delete_dwo_file = [] (void *item)
11774     {
11775       struct dwo_file *dwo_file = (struct dwo_file *) item;
11776
11777       delete dwo_file;
11778     };
11779
11780   return htab_up (htab_create_alloc_ex (41,
11781                                         hash_dwo_file,
11782                                         eq_dwo_file,
11783                                         delete_dwo_file,
11784                                         &objfile->objfile_obstack,
11785                                         hashtab_obstack_allocate,
11786                                         dummy_obstack_deallocate));
11787 }
11788
11789 /* Lookup DWO file DWO_NAME.  */
11790
11791 static void **
11792 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11793                       const char *dwo_name,
11794                       const char *comp_dir)
11795 {
11796   struct dwo_file find_entry;
11797   void **slot;
11798
11799   if (dwarf2_per_objfile->dwo_files == NULL)
11800     dwarf2_per_objfile->dwo_files
11801       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11802
11803   find_entry.dwo_name = dwo_name;
11804   find_entry.comp_dir = comp_dir;
11805   slot = htab_find_slot (dwarf2_per_objfile->dwo_files.get (), &find_entry,
11806                          INSERT);
11807
11808   return slot;
11809 }
11810
11811 static hashval_t
11812 hash_dwo_unit (const void *item)
11813 {
11814   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11815
11816   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11817   return dwo_unit->signature;
11818 }
11819
11820 static int
11821 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11822 {
11823   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11824   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11825
11826   /* The signature is assumed to be unique within the DWO file.
11827      So while object file CU dwo_id's always have the value zero,
11828      that's OK, assuming each object file DWO file has only one CU,
11829      and that's the rule for now.  */
11830   return lhs->signature == rhs->signature;
11831 }
11832
11833 /* Allocate a hash table for DWO CUs,TUs.
11834    There is one of these tables for each of CUs,TUs for each DWO file.  */
11835
11836 static htab_t
11837 allocate_dwo_unit_table (struct objfile *objfile)
11838 {
11839   /* Start out with a pretty small number.
11840      Generally DWO files contain only one CU and maybe some TUs.  */
11841   return htab_create_alloc_ex (3,
11842                                hash_dwo_unit,
11843                                eq_dwo_unit,
11844                                NULL,
11845                                &objfile->objfile_obstack,
11846                                hashtab_obstack_allocate,
11847                                dummy_obstack_deallocate);
11848 }
11849
11850 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11851
11852 struct create_dwo_cu_data
11853 {
11854   struct dwo_file *dwo_file;
11855   struct dwo_unit dwo_unit;
11856 };
11857
11858 /* die_reader_func for create_dwo_cu.  */
11859
11860 static void
11861 create_dwo_cu_reader (const struct die_reader_specs *reader,
11862                       const gdb_byte *info_ptr,
11863                       struct die_info *comp_unit_die,
11864                       int has_children,
11865                       void *datap)
11866 {
11867   struct dwarf2_cu *cu = reader->cu;
11868   sect_offset sect_off = cu->per_cu->sect_off;
11869   struct dwarf2_section_info *section = cu->per_cu->section;
11870   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11871   struct dwo_file *dwo_file = data->dwo_file;
11872   struct dwo_unit *dwo_unit = &data->dwo_unit;
11873
11874   gdb::optional<ULONGEST> signature = lookup_dwo_id (cu, comp_unit_die);
11875   if (!signature.has_value ())
11876     {
11877       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11878                    " its dwo_id [in module %s]"),
11879                  sect_offset_str (sect_off), dwo_file->dwo_name);
11880       return;
11881     }
11882
11883   dwo_unit->dwo_file = dwo_file;
11884   dwo_unit->signature = *signature;
11885   dwo_unit->section = section;
11886   dwo_unit->sect_off = sect_off;
11887   dwo_unit->length = cu->per_cu->length;
11888
11889   if (dwarf_read_debug)
11890     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11891                         sect_offset_str (sect_off),
11892                         hex_string (dwo_unit->signature));
11893 }
11894
11895 /* Create the dwo_units for the CUs in a DWO_FILE.
11896    Note: This function processes DWO files only, not DWP files.  */
11897
11898 static void
11899 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11900                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11901                        htab_t &cus_htab)
11902 {
11903   struct objfile *objfile = dwarf2_per_objfile->objfile;
11904   const gdb_byte *info_ptr, *end_ptr;
11905
11906   dwarf2_read_section (objfile, &section);
11907   info_ptr = section.buffer;
11908
11909   if (info_ptr == NULL)
11910     return;
11911
11912   if (dwarf_read_debug)
11913     {
11914       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11915                           get_section_name (&section),
11916                           get_section_file_name (&section));
11917     }
11918
11919   end_ptr = info_ptr + section.size;
11920   while (info_ptr < end_ptr)
11921     {
11922       struct dwarf2_per_cu_data per_cu;
11923       struct create_dwo_cu_data create_dwo_cu_data;
11924       struct dwo_unit *dwo_unit;
11925       void **slot;
11926       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11927
11928       memset (&create_dwo_cu_data.dwo_unit, 0,
11929               sizeof (create_dwo_cu_data.dwo_unit));
11930       memset (&per_cu, 0, sizeof (per_cu));
11931       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11932       per_cu.is_debug_types = 0;
11933       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11934       per_cu.section = &section;
11935       create_dwo_cu_data.dwo_file = &dwo_file;
11936
11937       init_cutu_and_read_dies_no_follow (
11938           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11939       info_ptr += per_cu.length;
11940
11941       // If the unit could not be parsed, skip it.
11942       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11943         continue;
11944
11945       if (cus_htab == NULL)
11946         cus_htab = allocate_dwo_unit_table (objfile);
11947
11948       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11949       *dwo_unit = create_dwo_cu_data.dwo_unit;
11950       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11951       gdb_assert (slot != NULL);
11952       if (*slot != NULL)
11953         {
11954           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11955           sect_offset dup_sect_off = dup_cu->sect_off;
11956
11957           complaint (_("debug cu entry at offset %s is duplicate to"
11958                        " the entry at offset %s, signature %s"),
11959                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11960                      hex_string (dwo_unit->signature));
11961         }
11962       *slot = (void *)dwo_unit;
11963     }
11964 }
11965
11966 /* DWP file .debug_{cu,tu}_index section format:
11967    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11968
11969    DWP Version 1:
11970
11971    Both index sections have the same format, and serve to map a 64-bit
11972    signature to a set of section numbers.  Each section begins with a header,
11973    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11974    indexes, and a pool of 32-bit section numbers.  The index sections will be
11975    aligned at 8-byte boundaries in the file.
11976
11977    The index section header consists of:
11978
11979     V, 32 bit version number
11980     -, 32 bits unused
11981     N, 32 bit number of compilation units or type units in the index
11982     M, 32 bit number of slots in the hash table
11983
11984    Numbers are recorded using the byte order of the application binary.
11985
11986    The hash table begins at offset 16 in the section, and consists of an array
11987    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11988    order of the application binary).  Unused slots in the hash table are 0.
11989    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11990
11991    The parallel table begins immediately after the hash table
11992    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11993    array of 32-bit indexes (using the byte order of the application binary),
11994    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11995    table contains a 32-bit index into the pool of section numbers.  For unused
11996    hash table slots, the corresponding entry in the parallel table will be 0.
11997
11998    The pool of section numbers begins immediately following the hash table
11999    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12000    section numbers consists of an array of 32-bit words (using the byte order
12001    of the application binary).  Each item in the array is indexed starting
12002    from 0.  The hash table entry provides the index of the first section
12003    number in the set.  Additional section numbers in the set follow, and the
12004    set is terminated by a 0 entry (section number 0 is not used in ELF).
12005
12006    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12007    section must be the first entry in the set, and the .debug_abbrev.dwo must
12008    be the second entry. Other members of the set may follow in any order.
12009
12010    ---
12011
12012    DWP Version 2:
12013
12014    DWP Version 2 combines all the .debug_info, etc. sections into one,
12015    and the entries in the index tables are now offsets into these sections.
12016    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12017    section.
12018
12019    Index Section Contents:
12020     Header
12021     Hash Table of Signatures   dwp_hash_table.hash_table
12022     Parallel Table of Indices  dwp_hash_table.unit_table
12023     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12024     Table of Section Sizes     dwp_hash_table.v2.sizes
12025
12026    The index section header consists of:
12027
12028     V, 32 bit version number
12029     L, 32 bit number of columns in the table of section offsets
12030     N, 32 bit number of compilation units or type units in the index
12031     M, 32 bit number of slots in the hash table
12032
12033    Numbers are recorded using the byte order of the application binary.
12034
12035    The hash table has the same format as version 1.
12036    The parallel table of indices has the same format as version 1,
12037    except that the entries are origin-1 indices into the table of sections
12038    offsets and the table of section sizes.
12039
12040    The table of offsets begins immediately following the parallel table
12041    (at offset 16 + 12 * M from the beginning of the section).  The table is
12042    a two-dimensional array of 32-bit words (using the byte order of the
12043    application binary), with L columns and N+1 rows, in row-major order.
12044    Each row in the array is indexed starting from 0.  The first row provides
12045    a key to the remaining rows: each column in this row provides an identifier
12046    for a debug section, and the offsets in the same column of subsequent rows
12047    refer to that section.  The section identifiers are:
12048
12049     DW_SECT_INFO         1  .debug_info.dwo
12050     DW_SECT_TYPES        2  .debug_types.dwo
12051     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12052     DW_SECT_LINE         4  .debug_line.dwo
12053     DW_SECT_LOC          5  .debug_loc.dwo
12054     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12055     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12056     DW_SECT_MACRO        8  .debug_macro.dwo
12057
12058    The offsets provided by the CU and TU index sections are the base offsets
12059    for the contributions made by each CU or TU to the corresponding section
12060    in the package file.  Each CU and TU header contains an abbrev_offset
12061    field, used to find the abbreviations table for that CU or TU within the
12062    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12063    be interpreted as relative to the base offset given in the index section.
12064    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12065    should be interpreted as relative to the base offset for .debug_line.dwo,
12066    and offsets into other debug sections obtained from DWARF attributes should
12067    also be interpreted as relative to the corresponding base offset.
12068
12069    The table of sizes begins immediately following the table of offsets.
12070    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12071    with L columns and N rows, in row-major order.  Each row in the array is
12072    indexed starting from 1 (row 0 is shared by the two tables).
12073
12074    ---
12075
12076    Hash table lookup is handled the same in version 1 and 2:
12077
12078    We assume that N and M will not exceed 2^32 - 1.
12079    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12080
12081    Given a 64-bit compilation unit signature or a type signature S, an entry
12082    in the hash table is located as follows:
12083
12084    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12085       the low-order k bits all set to 1.
12086
12087    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12088
12089    3) If the hash table entry at index H matches the signature, use that
12090       entry.  If the hash table entry at index H is unused (all zeroes),
12091       terminate the search: the signature is not present in the table.
12092
12093    4) Let H = (H + H') modulo M. Repeat at Step 3.
12094
12095    Because M > N and H' and M are relatively prime, the search is guaranteed
12096    to stop at an unused slot or find the match.  */
12097
12098 /* Create a hash table to map DWO IDs to their CU/TU entry in
12099    .debug_{info,types}.dwo in DWP_FILE.
12100    Returns NULL if there isn't one.
12101    Note: This function processes DWP files only, not DWO files.  */
12102
12103 static struct dwp_hash_table *
12104 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12105                        struct dwp_file *dwp_file, int is_debug_types)
12106 {
12107   struct objfile *objfile = dwarf2_per_objfile->objfile;
12108   bfd *dbfd = dwp_file->dbfd.get ();
12109   const gdb_byte *index_ptr, *index_end;
12110   struct dwarf2_section_info *index;
12111   uint32_t version, nr_columns, nr_units, nr_slots;
12112   struct dwp_hash_table *htab;
12113
12114   if (is_debug_types)
12115     index = &dwp_file->sections.tu_index;
12116   else
12117     index = &dwp_file->sections.cu_index;
12118
12119   if (dwarf2_section_empty_p (index))
12120     return NULL;
12121   dwarf2_read_section (objfile, index);
12122
12123   index_ptr = index->buffer;
12124   index_end = index_ptr + index->size;
12125
12126   version = read_4_bytes (dbfd, index_ptr);
12127   index_ptr += 4;
12128   if (version == 2)
12129     nr_columns = read_4_bytes (dbfd, index_ptr);
12130   else
12131     nr_columns = 0;
12132   index_ptr += 4;
12133   nr_units = read_4_bytes (dbfd, index_ptr);
12134   index_ptr += 4;
12135   nr_slots = read_4_bytes (dbfd, index_ptr);
12136   index_ptr += 4;
12137
12138   if (version != 1 && version != 2)
12139     {
12140       error (_("Dwarf Error: unsupported DWP file version (%s)"
12141                " [in module %s]"),
12142              pulongest (version), dwp_file->name);
12143     }
12144   if (nr_slots != (nr_slots & -nr_slots))
12145     {
12146       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12147                " is not power of 2 [in module %s]"),
12148              pulongest (nr_slots), dwp_file->name);
12149     }
12150
12151   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12152   htab->version = version;
12153   htab->nr_columns = nr_columns;
12154   htab->nr_units = nr_units;
12155   htab->nr_slots = nr_slots;
12156   htab->hash_table = index_ptr;
12157   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12158
12159   /* Exit early if the table is empty.  */
12160   if (nr_slots == 0 || nr_units == 0
12161       || (version == 2 && nr_columns == 0))
12162     {
12163       /* All must be zero.  */
12164       if (nr_slots != 0 || nr_units != 0
12165           || (version == 2 && nr_columns != 0))
12166         {
12167           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12168                        " all zero [in modules %s]"),
12169                      dwp_file->name);
12170         }
12171       return htab;
12172     }
12173
12174   if (version == 1)
12175     {
12176       htab->section_pool.v1.indices =
12177         htab->unit_table + sizeof (uint32_t) * nr_slots;
12178       /* It's harder to decide whether the section is too small in v1.
12179          V1 is deprecated anyway so we punt.  */
12180     }
12181   else
12182     {
12183       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12184       int *ids = htab->section_pool.v2.section_ids;
12185       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
12186       /* Reverse map for error checking.  */
12187       int ids_seen[DW_SECT_MAX + 1];
12188       int i;
12189
12190       if (nr_columns < 2)
12191         {
12192           error (_("Dwarf Error: bad DWP hash table, too few columns"
12193                    " in section table [in module %s]"),
12194                  dwp_file->name);
12195         }
12196       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12197         {
12198           error (_("Dwarf Error: bad DWP hash table, too many columns"
12199                    " in section table [in module %s]"),
12200                  dwp_file->name);
12201         }
12202       memset (ids, 255, sizeof_ids);
12203       memset (ids_seen, 255, sizeof (ids_seen));
12204       for (i = 0; i < nr_columns; ++i)
12205         {
12206           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12207
12208           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12209             {
12210               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12211                        " in section table [in module %s]"),
12212                      id, dwp_file->name);
12213             }
12214           if (ids_seen[id] != -1)
12215             {
12216               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12217                        " id %d in section table [in module %s]"),
12218                      id, dwp_file->name);
12219             }
12220           ids_seen[id] = i;
12221           ids[i] = id;
12222         }
12223       /* Must have exactly one info or types section.  */
12224       if (((ids_seen[DW_SECT_INFO] != -1)
12225            + (ids_seen[DW_SECT_TYPES] != -1))
12226           != 1)
12227         {
12228           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12229                    " DWO info/types section [in module %s]"),
12230                  dwp_file->name);
12231         }
12232       /* Must have an abbrev section.  */
12233       if (ids_seen[DW_SECT_ABBREV] == -1)
12234         {
12235           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12236                    " section [in module %s]"),
12237                  dwp_file->name);
12238         }
12239       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12240       htab->section_pool.v2.sizes =
12241         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12242                                          * nr_units * nr_columns);
12243       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12244                                           * nr_units * nr_columns))
12245           > index_end)
12246         {
12247           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12248                    " [in module %s]"),
12249                  dwp_file->name);
12250         }
12251     }
12252
12253   return htab;
12254 }
12255
12256 /* Update SECTIONS with the data from SECTP.
12257
12258    This function is like the other "locate" section routines that are
12259    passed to bfd_map_over_sections, but in this context the sections to
12260    read comes from the DWP V1 hash table, not the full ELF section table.
12261
12262    The result is non-zero for success, or zero if an error was found.  */
12263
12264 static int
12265 locate_v1_virtual_dwo_sections (asection *sectp,
12266                                 struct virtual_v1_dwo_sections *sections)
12267 {
12268   const struct dwop_section_names *names = &dwop_section_names;
12269
12270   if (section_is_p (sectp->name, &names->abbrev_dwo))
12271     {
12272       /* There can be only one.  */
12273       if (sections->abbrev.s.section != NULL)
12274         return 0;
12275       sections->abbrev.s.section = sectp;
12276       sections->abbrev.size = bfd_get_section_size (sectp);
12277     }
12278   else if (section_is_p (sectp->name, &names->info_dwo)
12279            || section_is_p (sectp->name, &names->types_dwo))
12280     {
12281       /* There can be only one.  */
12282       if (sections->info_or_types.s.section != NULL)
12283         return 0;
12284       sections->info_or_types.s.section = sectp;
12285       sections->info_or_types.size = bfd_get_section_size (sectp);
12286     }
12287   else if (section_is_p (sectp->name, &names->line_dwo))
12288     {
12289       /* There can be only one.  */
12290       if (sections->line.s.section != NULL)
12291         return 0;
12292       sections->line.s.section = sectp;
12293       sections->line.size = bfd_get_section_size (sectp);
12294     }
12295   else if (section_is_p (sectp->name, &names->loc_dwo))
12296     {
12297       /* There can be only one.  */
12298       if (sections->loc.s.section != NULL)
12299         return 0;
12300       sections->loc.s.section = sectp;
12301       sections->loc.size = bfd_get_section_size (sectp);
12302     }
12303   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12304     {
12305       /* There can be only one.  */
12306       if (sections->macinfo.s.section != NULL)
12307         return 0;
12308       sections->macinfo.s.section = sectp;
12309       sections->macinfo.size = bfd_get_section_size (sectp);
12310     }
12311   else if (section_is_p (sectp->name, &names->macro_dwo))
12312     {
12313       /* There can be only one.  */
12314       if (sections->macro.s.section != NULL)
12315         return 0;
12316       sections->macro.s.section = sectp;
12317       sections->macro.size = bfd_get_section_size (sectp);
12318     }
12319   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12320     {
12321       /* There can be only one.  */
12322       if (sections->str_offsets.s.section != NULL)
12323         return 0;
12324       sections->str_offsets.s.section = sectp;
12325       sections->str_offsets.size = bfd_get_section_size (sectp);
12326     }
12327   else
12328     {
12329       /* No other kind of section is valid.  */
12330       return 0;
12331     }
12332
12333   return 1;
12334 }
12335
12336 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12337    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12338    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12339    This is for DWP version 1 files.  */
12340
12341 static struct dwo_unit *
12342 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12343                            struct dwp_file *dwp_file,
12344                            uint32_t unit_index,
12345                            const char *comp_dir,
12346                            ULONGEST signature, int is_debug_types)
12347 {
12348   struct objfile *objfile = dwarf2_per_objfile->objfile;
12349   const struct dwp_hash_table *dwp_htab =
12350     is_debug_types ? dwp_file->tus : dwp_file->cus;
12351   bfd *dbfd = dwp_file->dbfd.get ();
12352   const char *kind = is_debug_types ? "TU" : "CU";
12353   struct dwo_file *dwo_file;
12354   struct dwo_unit *dwo_unit;
12355   struct virtual_v1_dwo_sections sections;
12356   void **dwo_file_slot;
12357   int i;
12358
12359   gdb_assert (dwp_file->version == 1);
12360
12361   if (dwarf_read_debug)
12362     {
12363       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12364                           kind,
12365                           pulongest (unit_index), hex_string (signature),
12366                           dwp_file->name);
12367     }
12368
12369   /* Fetch the sections of this DWO unit.
12370      Put a limit on the number of sections we look for so that bad data
12371      doesn't cause us to loop forever.  */
12372
12373 #define MAX_NR_V1_DWO_SECTIONS \
12374   (1 /* .debug_info or .debug_types */ \
12375    + 1 /* .debug_abbrev */ \
12376    + 1 /* .debug_line */ \
12377    + 1 /* .debug_loc */ \
12378    + 1 /* .debug_str_offsets */ \
12379    + 1 /* .debug_macro or .debug_macinfo */ \
12380    + 1 /* trailing zero */)
12381
12382   memset (&sections, 0, sizeof (sections));
12383
12384   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12385     {
12386       asection *sectp;
12387       uint32_t section_nr =
12388         read_4_bytes (dbfd,
12389                       dwp_htab->section_pool.v1.indices
12390                       + (unit_index + i) * sizeof (uint32_t));
12391
12392       if (section_nr == 0)
12393         break;
12394       if (section_nr >= dwp_file->num_sections)
12395         {
12396           error (_("Dwarf Error: bad DWP hash table, section number too large"
12397                    " [in module %s]"),
12398                  dwp_file->name);
12399         }
12400
12401       sectp = dwp_file->elf_sections[section_nr];
12402       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12403         {
12404           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12405                    " [in module %s]"),
12406                  dwp_file->name);
12407         }
12408     }
12409
12410   if (i < 2
12411       || dwarf2_section_empty_p (&sections.info_or_types)
12412       || dwarf2_section_empty_p (&sections.abbrev))
12413     {
12414       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12415                " [in module %s]"),
12416              dwp_file->name);
12417     }
12418   if (i == MAX_NR_V1_DWO_SECTIONS)
12419     {
12420       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12421                " [in module %s]"),
12422              dwp_file->name);
12423     }
12424
12425   /* It's easier for the rest of the code if we fake a struct dwo_file and
12426      have dwo_unit "live" in that.  At least for now.
12427
12428      The DWP file can be made up of a random collection of CUs and TUs.
12429      However, for each CU + set of TUs that came from the same original DWO
12430      file, we can combine them back into a virtual DWO file to save space
12431      (fewer struct dwo_file objects to allocate).  Remember that for really
12432      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12433
12434   std::string virtual_dwo_name =
12435     string_printf ("virtual-dwo/%d-%d-%d-%d",
12436                    get_section_id (&sections.abbrev),
12437                    get_section_id (&sections.line),
12438                    get_section_id (&sections.loc),
12439                    get_section_id (&sections.str_offsets));
12440   /* Can we use an existing virtual DWO file?  */
12441   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12442                                         virtual_dwo_name.c_str (),
12443                                         comp_dir);
12444   /* Create one if necessary.  */
12445   if (*dwo_file_slot == NULL)
12446     {
12447       if (dwarf_read_debug)
12448         {
12449           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12450                               virtual_dwo_name.c_str ());
12451         }
12452       dwo_file = new struct dwo_file;
12453       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
12454                                            virtual_dwo_name);
12455       dwo_file->comp_dir = comp_dir;
12456       dwo_file->sections.abbrev = sections.abbrev;
12457       dwo_file->sections.line = sections.line;
12458       dwo_file->sections.loc = sections.loc;
12459       dwo_file->sections.macinfo = sections.macinfo;
12460       dwo_file->sections.macro = sections.macro;
12461       dwo_file->sections.str_offsets = sections.str_offsets;
12462       /* The "str" section is global to the entire DWP file.  */
12463       dwo_file->sections.str = dwp_file->sections.str;
12464       /* The info or types section is assigned below to dwo_unit,
12465          there's no need to record it in dwo_file.
12466          Also, we can't simply record type sections in dwo_file because
12467          we record a pointer into the vector in dwo_unit.  As we collect more
12468          types we'll grow the vector and eventually have to reallocate space
12469          for it, invalidating all copies of pointers into the previous
12470          contents.  */
12471       *dwo_file_slot = dwo_file;
12472     }
12473   else
12474     {
12475       if (dwarf_read_debug)
12476         {
12477           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12478                               virtual_dwo_name.c_str ());
12479         }
12480       dwo_file = (struct dwo_file *) *dwo_file_slot;
12481     }
12482
12483   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12484   dwo_unit->dwo_file = dwo_file;
12485   dwo_unit->signature = signature;
12486   dwo_unit->section =
12487     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12488   *dwo_unit->section = sections.info_or_types;
12489   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12490
12491   return dwo_unit;
12492 }
12493
12494 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12495    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12496    piece within that section used by a TU/CU, return a virtual section
12497    of just that piece.  */
12498
12499 static struct dwarf2_section_info
12500 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12501                        struct dwarf2_section_info *section,
12502                        bfd_size_type offset, bfd_size_type size)
12503 {
12504   struct dwarf2_section_info result;
12505   asection *sectp;
12506
12507   gdb_assert (section != NULL);
12508   gdb_assert (!section->is_virtual);
12509
12510   memset (&result, 0, sizeof (result));
12511   result.s.containing_section = section;
12512   result.is_virtual = true;
12513
12514   if (size == 0)
12515     return result;
12516
12517   sectp = get_section_bfd_section (section);
12518
12519   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12520      bounds of the real section.  This is a pretty-rare event, so just
12521      flag an error (easier) instead of a warning and trying to cope.  */
12522   if (sectp == NULL
12523       || offset + size > bfd_get_section_size (sectp))
12524     {
12525       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12526                " in section %s [in module %s]"),
12527              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12528              objfile_name (dwarf2_per_objfile->objfile));
12529     }
12530
12531   result.virtual_offset = offset;
12532   result.size = size;
12533   return result;
12534 }
12535
12536 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12537    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12538    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12539    This is for DWP version 2 files.  */
12540
12541 static struct dwo_unit *
12542 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12543                            struct dwp_file *dwp_file,
12544                            uint32_t unit_index,
12545                            const char *comp_dir,
12546                            ULONGEST signature, int is_debug_types)
12547 {
12548   struct objfile *objfile = dwarf2_per_objfile->objfile;
12549   const struct dwp_hash_table *dwp_htab =
12550     is_debug_types ? dwp_file->tus : dwp_file->cus;
12551   bfd *dbfd = dwp_file->dbfd.get ();
12552   const char *kind = is_debug_types ? "TU" : "CU";
12553   struct dwo_file *dwo_file;
12554   struct dwo_unit *dwo_unit;
12555   struct virtual_v2_dwo_sections sections;
12556   void **dwo_file_slot;
12557   int i;
12558
12559   gdb_assert (dwp_file->version == 2);
12560
12561   if (dwarf_read_debug)
12562     {
12563       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12564                           kind,
12565                           pulongest (unit_index), hex_string (signature),
12566                           dwp_file->name);
12567     }
12568
12569   /* Fetch the section offsets of this DWO unit.  */
12570
12571   memset (&sections, 0, sizeof (sections));
12572
12573   for (i = 0; i < dwp_htab->nr_columns; ++i)
12574     {
12575       uint32_t offset = read_4_bytes (dbfd,
12576                                       dwp_htab->section_pool.v2.offsets
12577                                       + (((unit_index - 1) * dwp_htab->nr_columns
12578                                           + i)
12579                                          * sizeof (uint32_t)));
12580       uint32_t size = read_4_bytes (dbfd,
12581                                     dwp_htab->section_pool.v2.sizes
12582                                     + (((unit_index - 1) * dwp_htab->nr_columns
12583                                         + i)
12584                                        * sizeof (uint32_t)));
12585
12586       switch (dwp_htab->section_pool.v2.section_ids[i])
12587         {
12588         case DW_SECT_INFO:
12589         case DW_SECT_TYPES:
12590           sections.info_or_types_offset = offset;
12591           sections.info_or_types_size = size;
12592           break;
12593         case DW_SECT_ABBREV:
12594           sections.abbrev_offset = offset;
12595           sections.abbrev_size = size;
12596           break;
12597         case DW_SECT_LINE:
12598           sections.line_offset = offset;
12599           sections.line_size = size;
12600           break;
12601         case DW_SECT_LOC:
12602           sections.loc_offset = offset;
12603           sections.loc_size = size;
12604           break;
12605         case DW_SECT_STR_OFFSETS:
12606           sections.str_offsets_offset = offset;
12607           sections.str_offsets_size = size;
12608           break;
12609         case DW_SECT_MACINFO:
12610           sections.macinfo_offset = offset;
12611           sections.macinfo_size = size;
12612           break;
12613         case DW_SECT_MACRO:
12614           sections.macro_offset = offset;
12615           sections.macro_size = size;
12616           break;
12617         }
12618     }
12619
12620   /* It's easier for the rest of the code if we fake a struct dwo_file and
12621      have dwo_unit "live" in that.  At least for now.
12622
12623      The DWP file can be made up of a random collection of CUs and TUs.
12624      However, for each CU + set of TUs that came from the same original DWO
12625      file, we can combine them back into a virtual DWO file to save space
12626      (fewer struct dwo_file objects to allocate).  Remember that for really
12627      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12628
12629   std::string virtual_dwo_name =
12630     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12631                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12632                    (long) (sections.line_size ? sections.line_offset : 0),
12633                    (long) (sections.loc_size ? sections.loc_offset : 0),
12634                    (long) (sections.str_offsets_size
12635                            ? sections.str_offsets_offset : 0));
12636   /* Can we use an existing virtual DWO file?  */
12637   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12638                                         virtual_dwo_name.c_str (),
12639                                         comp_dir);
12640   /* Create one if necessary.  */
12641   if (*dwo_file_slot == NULL)
12642     {
12643       if (dwarf_read_debug)
12644         {
12645           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12646                               virtual_dwo_name.c_str ());
12647         }
12648       dwo_file = new struct dwo_file;
12649       dwo_file->dwo_name = obstack_strdup (&objfile->objfile_obstack,
12650                                            virtual_dwo_name);
12651       dwo_file->comp_dir = comp_dir;
12652       dwo_file->sections.abbrev =
12653         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12654                                sections.abbrev_offset, sections.abbrev_size);
12655       dwo_file->sections.line =
12656         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12657                                sections.line_offset, sections.line_size);
12658       dwo_file->sections.loc =
12659         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12660                                sections.loc_offset, sections.loc_size);
12661       dwo_file->sections.macinfo =
12662         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12663                                sections.macinfo_offset, sections.macinfo_size);
12664       dwo_file->sections.macro =
12665         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12666                                sections.macro_offset, sections.macro_size);
12667       dwo_file->sections.str_offsets =
12668         create_dwp_v2_section (dwarf2_per_objfile,
12669                                &dwp_file->sections.str_offsets,
12670                                sections.str_offsets_offset,
12671                                sections.str_offsets_size);
12672       /* The "str" section is global to the entire DWP file.  */
12673       dwo_file->sections.str = dwp_file->sections.str;
12674       /* The info or types section is assigned below to dwo_unit,
12675          there's no need to record it in dwo_file.
12676          Also, we can't simply record type sections in dwo_file because
12677          we record a pointer into the vector in dwo_unit.  As we collect more
12678          types we'll grow the vector and eventually have to reallocate space
12679          for it, invalidating all copies of pointers into the previous
12680          contents.  */
12681       *dwo_file_slot = dwo_file;
12682     }
12683   else
12684     {
12685       if (dwarf_read_debug)
12686         {
12687           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12688                               virtual_dwo_name.c_str ());
12689         }
12690       dwo_file = (struct dwo_file *) *dwo_file_slot;
12691     }
12692
12693   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12694   dwo_unit->dwo_file = dwo_file;
12695   dwo_unit->signature = signature;
12696   dwo_unit->section =
12697     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12698   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12699                                               is_debug_types
12700                                               ? &dwp_file->sections.types
12701                                               : &dwp_file->sections.info,
12702                                               sections.info_or_types_offset,
12703                                               sections.info_or_types_size);
12704   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12705
12706   return dwo_unit;
12707 }
12708
12709 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12710    Returns NULL if the signature isn't found.  */
12711
12712 static struct dwo_unit *
12713 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12714                         struct dwp_file *dwp_file, const char *comp_dir,
12715                         ULONGEST signature, int is_debug_types)
12716 {
12717   const struct dwp_hash_table *dwp_htab =
12718     is_debug_types ? dwp_file->tus : dwp_file->cus;
12719   bfd *dbfd = dwp_file->dbfd.get ();
12720   uint32_t mask = dwp_htab->nr_slots - 1;
12721   uint32_t hash = signature & mask;
12722   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12723   unsigned int i;
12724   void **slot;
12725   struct dwo_unit find_dwo_cu;
12726
12727   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12728   find_dwo_cu.signature = signature;
12729   slot = htab_find_slot (is_debug_types
12730                          ? dwp_file->loaded_tus
12731                          : dwp_file->loaded_cus,
12732                          &find_dwo_cu, INSERT);
12733
12734   if (*slot != NULL)
12735     return (struct dwo_unit *) *slot;
12736
12737   /* Use a for loop so that we don't loop forever on bad debug info.  */
12738   for (i = 0; i < dwp_htab->nr_slots; ++i)
12739     {
12740       ULONGEST signature_in_table;
12741
12742       signature_in_table =
12743         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12744       if (signature_in_table == signature)
12745         {
12746           uint32_t unit_index =
12747             read_4_bytes (dbfd,
12748                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12749
12750           if (dwp_file->version == 1)
12751             {
12752               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12753                                                  dwp_file, unit_index,
12754                                                  comp_dir, signature,
12755                                                  is_debug_types);
12756             }
12757           else
12758             {
12759               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12760                                                  dwp_file, unit_index,
12761                                                  comp_dir, signature,
12762                                                  is_debug_types);
12763             }
12764           return (struct dwo_unit *) *slot;
12765         }
12766       if (signature_in_table == 0)
12767         return NULL;
12768       hash = (hash + hash2) & mask;
12769     }
12770
12771   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12772            " [in module %s]"),
12773          dwp_file->name);
12774 }
12775
12776 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12777    Open the file specified by FILE_NAME and hand it off to BFD for
12778    preliminary analysis.  Return a newly initialized bfd *, which
12779    includes a canonicalized copy of FILE_NAME.
12780    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12781    SEARCH_CWD is true if the current directory is to be searched.
12782    It will be searched before debug-file-directory.
12783    If successful, the file is added to the bfd include table of the
12784    objfile's bfd (see gdb_bfd_record_inclusion).
12785    If unable to find/open the file, return NULL.
12786    NOTE: This function is derived from symfile_bfd_open.  */
12787
12788 static gdb_bfd_ref_ptr
12789 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12790                     const char *file_name, int is_dwp, int search_cwd)
12791 {
12792   int desc;
12793   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12794      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12795      to debug_file_directory.  */
12796   const char *search_path;
12797   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12798
12799   gdb::unique_xmalloc_ptr<char> search_path_holder;
12800   if (search_cwd)
12801     {
12802       if (*debug_file_directory != '\0')
12803         {
12804           search_path_holder.reset (concat (".", dirname_separator_string,
12805                                             debug_file_directory,
12806                                             (char *) NULL));
12807           search_path = search_path_holder.get ();
12808         }
12809       else
12810         search_path = ".";
12811     }
12812   else
12813     search_path = debug_file_directory;
12814
12815   openp_flags flags = OPF_RETURN_REALPATH;
12816   if (is_dwp)
12817     flags |= OPF_SEARCH_IN_PATH;
12818
12819   gdb::unique_xmalloc_ptr<char> absolute_name;
12820   desc = openp (search_path, flags, file_name,
12821                 O_RDONLY | O_BINARY, &absolute_name);
12822   if (desc < 0)
12823     return NULL;
12824
12825   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12826                                          gnutarget, desc));
12827   if (sym_bfd == NULL)
12828     return NULL;
12829   bfd_set_cacheable (sym_bfd.get (), 1);
12830
12831   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12832     return NULL;
12833
12834   /* Success.  Record the bfd as having been included by the objfile's bfd.
12835      This is important because things like demangled_names_hash lives in the
12836      objfile's per_bfd space and may have references to things like symbol
12837      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12838   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12839
12840   return sym_bfd;
12841 }
12842
12843 /* Try to open DWO file FILE_NAME.
12844    COMP_DIR is the DW_AT_comp_dir attribute.
12845    The result is the bfd handle of the file.
12846    If there is a problem finding or opening the file, return NULL.
12847    Upon success, the canonicalized path of the file is stored in the bfd,
12848    same as symfile_bfd_open.  */
12849
12850 static gdb_bfd_ref_ptr
12851 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12852                const char *file_name, const char *comp_dir)
12853 {
12854   if (IS_ABSOLUTE_PATH (file_name))
12855     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12856                                0 /*is_dwp*/, 0 /*search_cwd*/);
12857
12858   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12859
12860   if (comp_dir != NULL)
12861     {
12862       char *path_to_try = concat (comp_dir, SLASH_STRING,
12863                                   file_name, (char *) NULL);
12864
12865       /* NOTE: If comp_dir is a relative path, this will also try the
12866          search path, which seems useful.  */
12867       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12868                                                 path_to_try,
12869                                                 0 /*is_dwp*/,
12870                                                 1 /*search_cwd*/));
12871       xfree (path_to_try);
12872       if (abfd != NULL)
12873         return abfd;
12874     }
12875
12876   /* That didn't work, try debug-file-directory, which, despite its name,
12877      is a list of paths.  */
12878
12879   if (*debug_file_directory == '\0')
12880     return NULL;
12881
12882   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12883                              0 /*is_dwp*/, 1 /*search_cwd*/);
12884 }
12885
12886 /* This function is mapped across the sections and remembers the offset and
12887    size of each of the DWO debugging sections we are interested in.  */
12888
12889 static void
12890 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12891 {
12892   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12893   const struct dwop_section_names *names = &dwop_section_names;
12894
12895   if (section_is_p (sectp->name, &names->abbrev_dwo))
12896     {
12897       dwo_sections->abbrev.s.section = sectp;
12898       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12899     }
12900   else if (section_is_p (sectp->name, &names->info_dwo))
12901     {
12902       dwo_sections->info.s.section = sectp;
12903       dwo_sections->info.size = bfd_get_section_size (sectp);
12904     }
12905   else if (section_is_p (sectp->name, &names->line_dwo))
12906     {
12907       dwo_sections->line.s.section = sectp;
12908       dwo_sections->line.size = bfd_get_section_size (sectp);
12909     }
12910   else if (section_is_p (sectp->name, &names->loc_dwo))
12911     {
12912       dwo_sections->loc.s.section = sectp;
12913       dwo_sections->loc.size = bfd_get_section_size (sectp);
12914     }
12915   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12916     {
12917       dwo_sections->macinfo.s.section = sectp;
12918       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12919     }
12920   else if (section_is_p (sectp->name, &names->macro_dwo))
12921     {
12922       dwo_sections->macro.s.section = sectp;
12923       dwo_sections->macro.size = bfd_get_section_size (sectp);
12924     }
12925   else if (section_is_p (sectp->name, &names->str_dwo))
12926     {
12927       dwo_sections->str.s.section = sectp;
12928       dwo_sections->str.size = bfd_get_section_size (sectp);
12929     }
12930   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12931     {
12932       dwo_sections->str_offsets.s.section = sectp;
12933       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12934     }
12935   else if (section_is_p (sectp->name, &names->types_dwo))
12936     {
12937       struct dwarf2_section_info type_section;
12938
12939       memset (&type_section, 0, sizeof (type_section));
12940       type_section.s.section = sectp;
12941       type_section.size = bfd_get_section_size (sectp);
12942       dwo_sections->types.push_back (type_section);
12943     }
12944 }
12945
12946 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12947    by PER_CU.  This is for the non-DWP case.
12948    The result is NULL if DWO_NAME can't be found.  */
12949
12950 static struct dwo_file *
12951 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12952                         const char *dwo_name, const char *comp_dir)
12953 {
12954   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12955
12956   gdb_bfd_ref_ptr dbfd = open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir);
12957   if (dbfd == NULL)
12958     {
12959       if (dwarf_read_debug)
12960         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12961       return NULL;
12962     }
12963
12964   dwo_file_up dwo_file (new struct dwo_file);
12965   dwo_file->dwo_name = dwo_name;
12966   dwo_file->comp_dir = comp_dir;
12967   dwo_file->dbfd = std::move (dbfd);
12968
12969   bfd_map_over_sections (dwo_file->dbfd.get (), dwarf2_locate_dwo_sections,
12970                          &dwo_file->sections);
12971
12972   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12973                          dwo_file->cus);
12974
12975   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12976                                  dwo_file->sections.types, dwo_file->tus);
12977
12978   if (dwarf_read_debug)
12979     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12980
12981   return dwo_file.release ();
12982 }
12983
12984 /* This function is mapped across the sections and remembers the offset and
12985    size of each of the DWP debugging sections common to version 1 and 2 that
12986    we are interested in.  */
12987
12988 static void
12989 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12990                                    void *dwp_file_ptr)
12991 {
12992   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12993   const struct dwop_section_names *names = &dwop_section_names;
12994   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12995
12996   /* Record the ELF section number for later lookup: this is what the
12997      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12998   gdb_assert (elf_section_nr < dwp_file->num_sections);
12999   dwp_file->elf_sections[elf_section_nr] = sectp;
13000
13001   /* Look for specific sections that we need.  */
13002   if (section_is_p (sectp->name, &names->str_dwo))
13003     {
13004       dwp_file->sections.str.s.section = sectp;
13005       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13006     }
13007   else if (section_is_p (sectp->name, &names->cu_index))
13008     {
13009       dwp_file->sections.cu_index.s.section = sectp;
13010       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13011     }
13012   else if (section_is_p (sectp->name, &names->tu_index))
13013     {
13014       dwp_file->sections.tu_index.s.section = sectp;
13015       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13016     }
13017 }
13018
13019 /* This function is mapped across the sections and remembers the offset and
13020    size of each of the DWP version 2 debugging sections that we are interested
13021    in.  This is split into a separate function because we don't know if we
13022    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13023
13024 static void
13025 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13026 {
13027   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13028   const struct dwop_section_names *names = &dwop_section_names;
13029   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13030
13031   /* Record the ELF section number for later lookup: this is what the
13032      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13033   gdb_assert (elf_section_nr < dwp_file->num_sections);
13034   dwp_file->elf_sections[elf_section_nr] = sectp;
13035
13036   /* Look for specific sections that we need.  */
13037   if (section_is_p (sectp->name, &names->abbrev_dwo))
13038     {
13039       dwp_file->sections.abbrev.s.section = sectp;
13040       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13041     }
13042   else if (section_is_p (sectp->name, &names->info_dwo))
13043     {
13044       dwp_file->sections.info.s.section = sectp;
13045       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13046     }
13047   else if (section_is_p (sectp->name, &names->line_dwo))
13048     {
13049       dwp_file->sections.line.s.section = sectp;
13050       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13051     }
13052   else if (section_is_p (sectp->name, &names->loc_dwo))
13053     {
13054       dwp_file->sections.loc.s.section = sectp;
13055       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13056     }
13057   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13058     {
13059       dwp_file->sections.macinfo.s.section = sectp;
13060       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13061     }
13062   else if (section_is_p (sectp->name, &names->macro_dwo))
13063     {
13064       dwp_file->sections.macro.s.section = sectp;
13065       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13066     }
13067   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13068     {
13069       dwp_file->sections.str_offsets.s.section = sectp;
13070       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13071     }
13072   else if (section_is_p (sectp->name, &names->types_dwo))
13073     {
13074       dwp_file->sections.types.s.section = sectp;
13075       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13076     }
13077 }
13078
13079 /* Hash function for dwp_file loaded CUs/TUs.  */
13080
13081 static hashval_t
13082 hash_dwp_loaded_cutus (const void *item)
13083 {
13084   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13085
13086   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13087   return dwo_unit->signature;
13088 }
13089
13090 /* Equality function for dwp_file loaded CUs/TUs.  */
13091
13092 static int
13093 eq_dwp_loaded_cutus (const void *a, const void *b)
13094 {
13095   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13096   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13097
13098   return dua->signature == dub->signature;
13099 }
13100
13101 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13102
13103 static htab_t
13104 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13105 {
13106   return htab_create_alloc_ex (3,
13107                                hash_dwp_loaded_cutus,
13108                                eq_dwp_loaded_cutus,
13109                                NULL,
13110                                &objfile->objfile_obstack,
13111                                hashtab_obstack_allocate,
13112                                dummy_obstack_deallocate);
13113 }
13114
13115 /* Try to open DWP file FILE_NAME.
13116    The result is the bfd handle of the file.
13117    If there is a problem finding or opening the file, return NULL.
13118    Upon success, the canonicalized path of the file is stored in the bfd,
13119    same as symfile_bfd_open.  */
13120
13121 static gdb_bfd_ref_ptr
13122 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13123                const char *file_name)
13124 {
13125   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13126                                             1 /*is_dwp*/,
13127                                             1 /*search_cwd*/));
13128   if (abfd != NULL)
13129     return abfd;
13130
13131   /* Work around upstream bug 15652.
13132      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13133      [Whether that's a "bug" is debatable, but it is getting in our way.]
13134      We have no real idea where the dwp file is, because gdb's realpath-ing
13135      of the executable's path may have discarded the needed info.
13136      [IWBN if the dwp file name was recorded in the executable, akin to
13137      .gnu_debuglink, but that doesn't exist yet.]
13138      Strip the directory from FILE_NAME and search again.  */
13139   if (*debug_file_directory != '\0')
13140     {
13141       /* Don't implicitly search the current directory here.
13142          If the user wants to search "." to handle this case,
13143          it must be added to debug-file-directory.  */
13144       return try_open_dwop_file (dwarf2_per_objfile,
13145                                  lbasename (file_name), 1 /*is_dwp*/,
13146                                  0 /*search_cwd*/);
13147     }
13148
13149   return NULL;
13150 }
13151
13152 /* Initialize the use of the DWP file for the current objfile.
13153    By convention the name of the DWP file is ${objfile}.dwp.
13154    The result is NULL if it can't be found.  */
13155
13156 static std::unique_ptr<struct dwp_file>
13157 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13158 {
13159   struct objfile *objfile = dwarf2_per_objfile->objfile;
13160
13161   /* Try to find first .dwp for the binary file before any symbolic links
13162      resolving.  */
13163
13164   /* If the objfile is a debug file, find the name of the real binary
13165      file and get the name of dwp file from there.  */
13166   std::string dwp_name;
13167   if (objfile->separate_debug_objfile_backlink != NULL)
13168     {
13169       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13170       const char *backlink_basename = lbasename (backlink->original_name);
13171
13172       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13173     }
13174   else
13175     dwp_name = objfile->original_name;
13176
13177   dwp_name += ".dwp";
13178
13179   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13180   if (dbfd == NULL
13181       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13182     {
13183       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13184       dwp_name = objfile_name (objfile);
13185       dwp_name += ".dwp";
13186       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13187     }
13188
13189   if (dbfd == NULL)
13190     {
13191       if (dwarf_read_debug)
13192         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13193       return std::unique_ptr<dwp_file> ();
13194     }
13195
13196   const char *name = bfd_get_filename (dbfd.get ());
13197   std::unique_ptr<struct dwp_file> dwp_file
13198     (new struct dwp_file (name, std::move (dbfd)));
13199
13200   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
13201   dwp_file->elf_sections =
13202     OBSTACK_CALLOC (&objfile->objfile_obstack,
13203                     dwp_file->num_sections, asection *);
13204
13205   bfd_map_over_sections (dwp_file->dbfd.get (),
13206                          dwarf2_locate_common_dwp_sections,
13207                          dwp_file.get ());
13208
13209   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13210                                          0);
13211
13212   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13213                                          1);
13214
13215   /* The DWP file version is stored in the hash table.  Oh well.  */
13216   if (dwp_file->cus && dwp_file->tus
13217       && dwp_file->cus->version != dwp_file->tus->version)
13218     {
13219       /* Technically speaking, we should try to limp along, but this is
13220          pretty bizarre.  We use pulongest here because that's the established
13221          portability solution (e.g, we cannot use %u for uint32_t).  */
13222       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13223                " TU version %s [in DWP file %s]"),
13224              pulongest (dwp_file->cus->version),
13225              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13226     }
13227
13228   if (dwp_file->cus)
13229     dwp_file->version = dwp_file->cus->version;
13230   else if (dwp_file->tus)
13231     dwp_file->version = dwp_file->tus->version;
13232   else
13233     dwp_file->version = 2;
13234
13235   if (dwp_file->version == 2)
13236     bfd_map_over_sections (dwp_file->dbfd.get (),
13237                            dwarf2_locate_v2_dwp_sections,
13238                            dwp_file.get ());
13239
13240   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13241   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13242
13243   if (dwarf_read_debug)
13244     {
13245       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13246       fprintf_unfiltered (gdb_stdlog,
13247                           "    %s CUs, %s TUs\n",
13248                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13249                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13250     }
13251
13252   return dwp_file;
13253 }
13254
13255 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13256
13257 static struct dwp_file *
13258 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13259 {
13260   if (! dwarf2_per_objfile->dwp_checked)
13261     {
13262       dwarf2_per_objfile->dwp_file
13263         = open_and_init_dwp_file (dwarf2_per_objfile);
13264       dwarf2_per_objfile->dwp_checked = 1;
13265     }
13266   return dwarf2_per_objfile->dwp_file.get ();
13267 }
13268
13269 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13270    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13271    or in the DWP file for the objfile, referenced by THIS_UNIT.
13272    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13273    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13274
13275    This is called, for example, when wanting to read a variable with a
13276    complex location.  Therefore we don't want to do file i/o for every call.
13277    Therefore we don't want to look for a DWO file on every call.
13278    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13279    then we check if we've already seen DWO_NAME, and only THEN do we check
13280    for a DWO file.
13281
13282    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13283    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13284
13285 static struct dwo_unit *
13286 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13287                  const char *dwo_name, const char *comp_dir,
13288                  ULONGEST signature, int is_debug_types)
13289 {
13290   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13291   struct objfile *objfile = dwarf2_per_objfile->objfile;
13292   const char *kind = is_debug_types ? "TU" : "CU";
13293   void **dwo_file_slot;
13294   struct dwo_file *dwo_file;
13295   struct dwp_file *dwp_file;
13296
13297   /* First see if there's a DWP file.
13298      If we have a DWP file but didn't find the DWO inside it, don't
13299      look for the original DWO file.  It makes gdb behave differently
13300      depending on whether one is debugging in the build tree.  */
13301
13302   dwp_file = get_dwp_file (dwarf2_per_objfile);
13303   if (dwp_file != NULL)
13304     {
13305       const struct dwp_hash_table *dwp_htab =
13306         is_debug_types ? dwp_file->tus : dwp_file->cus;
13307
13308       if (dwp_htab != NULL)
13309         {
13310           struct dwo_unit *dwo_cutu =
13311             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13312                                     signature, is_debug_types);
13313
13314           if (dwo_cutu != NULL)
13315             {
13316               if (dwarf_read_debug)
13317                 {
13318                   fprintf_unfiltered (gdb_stdlog,
13319                                       "Virtual DWO %s %s found: @%s\n",
13320                                       kind, hex_string (signature),
13321                                       host_address_to_string (dwo_cutu));
13322                 }
13323               return dwo_cutu;
13324             }
13325         }
13326     }
13327   else
13328     {
13329       /* No DWP file, look for the DWO file.  */
13330
13331       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13332                                             dwo_name, comp_dir);
13333       if (*dwo_file_slot == NULL)
13334         {
13335           /* Read in the file and build a table of the CUs/TUs it contains.  */
13336           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13337         }
13338       /* NOTE: This will be NULL if unable to open the file.  */
13339       dwo_file = (struct dwo_file *) *dwo_file_slot;
13340
13341       if (dwo_file != NULL)
13342         {
13343           struct dwo_unit *dwo_cutu = NULL;
13344
13345           if (is_debug_types && dwo_file->tus)
13346             {
13347               struct dwo_unit find_dwo_cutu;
13348
13349               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13350               find_dwo_cutu.signature = signature;
13351               dwo_cutu
13352                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13353             }
13354           else if (!is_debug_types && dwo_file->cus)
13355             {
13356               struct dwo_unit find_dwo_cutu;
13357
13358               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13359               find_dwo_cutu.signature = signature;
13360               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13361                                                        &find_dwo_cutu);
13362             }
13363
13364           if (dwo_cutu != NULL)
13365             {
13366               if (dwarf_read_debug)
13367                 {
13368                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13369                                       kind, dwo_name, hex_string (signature),
13370                                       host_address_to_string (dwo_cutu));
13371                 }
13372               return dwo_cutu;
13373             }
13374         }
13375     }
13376
13377   /* We didn't find it.  This could mean a dwo_id mismatch, or
13378      someone deleted the DWO/DWP file, or the search path isn't set up
13379      correctly to find the file.  */
13380
13381   if (dwarf_read_debug)
13382     {
13383       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13384                           kind, dwo_name, hex_string (signature));
13385     }
13386
13387   /* This is a warning and not a complaint because it can be caused by
13388      pilot error (e.g., user accidentally deleting the DWO).  */
13389   {
13390     /* Print the name of the DWP file if we looked there, helps the user
13391        better diagnose the problem.  */
13392     std::string dwp_text;
13393
13394     if (dwp_file != NULL)
13395       dwp_text = string_printf (" [in DWP file %s]",
13396                                 lbasename (dwp_file->name));
13397
13398     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13399                " [in module %s]"),
13400              kind, dwo_name, hex_string (signature),
13401              dwp_text.c_str (),
13402              this_unit->is_debug_types ? "TU" : "CU",
13403              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13404   }
13405   return NULL;
13406 }
13407
13408 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13409    See lookup_dwo_cutu_unit for details.  */
13410
13411 static struct dwo_unit *
13412 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13413                       const char *dwo_name, const char *comp_dir,
13414                       ULONGEST signature)
13415 {
13416   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13417 }
13418
13419 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13420    See lookup_dwo_cutu_unit for details.  */
13421
13422 static struct dwo_unit *
13423 lookup_dwo_type_unit (struct signatured_type *this_tu,
13424                       const char *dwo_name, const char *comp_dir)
13425 {
13426   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13427 }
13428
13429 /* Traversal function for queue_and_load_all_dwo_tus.  */
13430
13431 static int
13432 queue_and_load_dwo_tu (void **slot, void *info)
13433 {
13434   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13435   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13436   ULONGEST signature = dwo_unit->signature;
13437   struct signatured_type *sig_type =
13438     lookup_dwo_signatured_type (per_cu->cu, signature);
13439
13440   if (sig_type != NULL)
13441     {
13442       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13443
13444       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13445          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13446          while processing PER_CU.  */
13447       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13448         load_full_type_unit (sig_cu);
13449       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13450     }
13451
13452   return 1;
13453 }
13454
13455 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13456    The DWO may have the only definition of the type, though it may not be
13457    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13458    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13459
13460 static void
13461 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13462 {
13463   struct dwo_unit *dwo_unit;
13464   struct dwo_file *dwo_file;
13465
13466   gdb_assert (!per_cu->is_debug_types);
13467   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13468   gdb_assert (per_cu->cu != NULL);
13469
13470   dwo_unit = per_cu->cu->dwo_unit;
13471   gdb_assert (dwo_unit != NULL);
13472
13473   dwo_file = dwo_unit->dwo_file;
13474   if (dwo_file->tus != NULL)
13475     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13476 }
13477
13478 /* Read in various DIEs.  */
13479
13480 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13481    Inherit only the children of the DW_AT_abstract_origin DIE not being
13482    already referenced by DW_AT_abstract_origin from the children of the
13483    current DIE.  */
13484
13485 static void
13486 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13487 {
13488   struct die_info *child_die;
13489   sect_offset *offsetp;
13490   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13491   struct die_info *origin_die;
13492   /* Iterator of the ORIGIN_DIE children.  */
13493   struct die_info *origin_child_die;
13494   struct attribute *attr;
13495   struct dwarf2_cu *origin_cu;
13496   struct pending **origin_previous_list_in_scope;
13497
13498   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13499   if (!attr)
13500     return;
13501
13502   /* Note that following die references may follow to a die in a
13503      different cu.  */
13504
13505   origin_cu = cu;
13506   origin_die = follow_die_ref (die, attr, &origin_cu);
13507
13508   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13509      symbols in.  */
13510   origin_previous_list_in_scope = origin_cu->list_in_scope;
13511   origin_cu->list_in_scope = cu->list_in_scope;
13512
13513   if (die->tag != origin_die->tag
13514       && !(die->tag == DW_TAG_inlined_subroutine
13515            && origin_die->tag == DW_TAG_subprogram))
13516     complaint (_("DIE %s and its abstract origin %s have different tags"),
13517                sect_offset_str (die->sect_off),
13518                sect_offset_str (origin_die->sect_off));
13519
13520   std::vector<sect_offset> offsets;
13521
13522   for (child_die = die->child;
13523        child_die && child_die->tag;
13524        child_die = sibling_die (child_die))
13525     {
13526       struct die_info *child_origin_die;
13527       struct dwarf2_cu *child_origin_cu;
13528
13529       /* We are trying to process concrete instance entries:
13530          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13531          it's not relevant to our analysis here. i.e. detecting DIEs that are
13532          present in the abstract instance but not referenced in the concrete
13533          one.  */
13534       if (child_die->tag == DW_TAG_call_site
13535           || child_die->tag == DW_TAG_GNU_call_site)
13536         continue;
13537
13538       /* For each CHILD_DIE, find the corresponding child of
13539          ORIGIN_DIE.  If there is more than one layer of
13540          DW_AT_abstract_origin, follow them all; there shouldn't be,
13541          but GCC versions at least through 4.4 generate this (GCC PR
13542          40573).  */
13543       child_origin_die = child_die;
13544       child_origin_cu = cu;
13545       while (1)
13546         {
13547           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13548                               child_origin_cu);
13549           if (attr == NULL)
13550             break;
13551           child_origin_die = follow_die_ref (child_origin_die, attr,
13552                                              &child_origin_cu);
13553         }
13554
13555       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13556          counterpart may exist.  */
13557       if (child_origin_die != child_die)
13558         {
13559           if (child_die->tag != child_origin_die->tag
13560               && !(child_die->tag == DW_TAG_inlined_subroutine
13561                    && child_origin_die->tag == DW_TAG_subprogram))
13562             complaint (_("Child DIE %s and its abstract origin %s have "
13563                          "different tags"),
13564                        sect_offset_str (child_die->sect_off),
13565                        sect_offset_str (child_origin_die->sect_off));
13566           if (child_origin_die->parent != origin_die)
13567             complaint (_("Child DIE %s and its abstract origin %s have "
13568                          "different parents"),
13569                        sect_offset_str (child_die->sect_off),
13570                        sect_offset_str (child_origin_die->sect_off));
13571           else
13572             offsets.push_back (child_origin_die->sect_off);
13573         }
13574     }
13575   std::sort (offsets.begin (), offsets.end ());
13576   sect_offset *offsets_end = offsets.data () + offsets.size ();
13577   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13578     if (offsetp[-1] == *offsetp)
13579       complaint (_("Multiple children of DIE %s refer "
13580                    "to DIE %s as their abstract origin"),
13581                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13582
13583   offsetp = offsets.data ();
13584   origin_child_die = origin_die->child;
13585   while (origin_child_die && origin_child_die->tag)
13586     {
13587       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13588       while (offsetp < offsets_end
13589              && *offsetp < origin_child_die->sect_off)
13590         offsetp++;
13591       if (offsetp >= offsets_end
13592           || *offsetp > origin_child_die->sect_off)
13593         {
13594           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13595              Check whether we're already processing ORIGIN_CHILD_DIE.
13596              This can happen with mutually referenced abstract_origins.
13597              PR 16581.  */
13598           if (!origin_child_die->in_process)
13599             process_die (origin_child_die, origin_cu);
13600         }
13601       origin_child_die = sibling_die (origin_child_die);
13602     }
13603   origin_cu->list_in_scope = origin_previous_list_in_scope;
13604 }
13605
13606 static void
13607 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13608 {
13609   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13610   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13611   struct context_stack *newobj;
13612   CORE_ADDR lowpc;
13613   CORE_ADDR highpc;
13614   struct die_info *child_die;
13615   struct attribute *attr, *call_line, *call_file;
13616   const char *name;
13617   CORE_ADDR baseaddr;
13618   struct block *block;
13619   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13620   std::vector<struct symbol *> template_args;
13621   struct template_symbol *templ_func = NULL;
13622
13623   if (inlined_func)
13624     {
13625       /* If we do not have call site information, we can't show the
13626          caller of this inlined function.  That's too confusing, so
13627          only use the scope for local variables.  */
13628       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13629       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13630       if (call_line == NULL || call_file == NULL)
13631         {
13632           read_lexical_block_scope (die, cu);
13633           return;
13634         }
13635     }
13636
13637   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13638
13639   name = dwarf2_name (die, cu);
13640
13641   /* Ignore functions with missing or empty names.  These are actually
13642      illegal according to the DWARF standard.  */
13643   if (name == NULL)
13644     {
13645       complaint (_("missing name for subprogram DIE at %s"),
13646                  sect_offset_str (die->sect_off));
13647       return;
13648     }
13649
13650   /* Ignore functions with missing or invalid low and high pc attributes.  */
13651   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13652       <= PC_BOUNDS_INVALID)
13653     {
13654       attr = dwarf2_attr (die, DW_AT_external, cu);
13655       if (!attr || !DW_UNSND (attr))
13656         complaint (_("cannot get low and high bounds "
13657                      "for subprogram DIE at %s"),
13658                    sect_offset_str (die->sect_off));
13659       return;
13660     }
13661
13662   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13663   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13664
13665   /* If we have any template arguments, then we must allocate a
13666      different sort of symbol.  */
13667   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13668     {
13669       if (child_die->tag == DW_TAG_template_type_param
13670           || child_die->tag == DW_TAG_template_value_param)
13671         {
13672           templ_func = allocate_template_symbol (objfile);
13673           templ_func->subclass = SYMBOL_TEMPLATE;
13674           break;
13675         }
13676     }
13677
13678   newobj = cu->get_builder ()->push_context (0, lowpc);
13679   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13680                              (struct symbol *) templ_func);
13681
13682   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13683     set_objfile_main_name (objfile, SYMBOL_LINKAGE_NAME (newobj->name),
13684                            cu->language);
13685
13686   /* If there is a location expression for DW_AT_frame_base, record
13687      it.  */
13688   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13689   if (attr)
13690     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13691
13692   /* If there is a location for the static link, record it.  */
13693   newobj->static_link = NULL;
13694   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13695   if (attr)
13696     {
13697       newobj->static_link
13698         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13699       attr_to_dynamic_prop (attr, die, cu, newobj->static_link,
13700                             dwarf2_per_cu_addr_type (cu->per_cu));
13701     }
13702
13703   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13704
13705   if (die->child != NULL)
13706     {
13707       child_die = die->child;
13708       while (child_die && child_die->tag)
13709         {
13710           if (child_die->tag == DW_TAG_template_type_param
13711               || child_die->tag == DW_TAG_template_value_param)
13712             {
13713               struct symbol *arg = new_symbol (child_die, NULL, cu);
13714
13715               if (arg != NULL)
13716                 template_args.push_back (arg);
13717             }
13718           else
13719             process_die (child_die, cu);
13720           child_die = sibling_die (child_die);
13721         }
13722     }
13723
13724   inherit_abstract_dies (die, cu);
13725
13726   /* If we have a DW_AT_specification, we might need to import using
13727      directives from the context of the specification DIE.  See the
13728      comment in determine_prefix.  */
13729   if (cu->language == language_cplus
13730       && dwarf2_attr (die, DW_AT_specification, cu))
13731     {
13732       struct dwarf2_cu *spec_cu = cu;
13733       struct die_info *spec_die = die_specification (die, &spec_cu);
13734
13735       while (spec_die)
13736         {
13737           child_die = spec_die->child;
13738           while (child_die && child_die->tag)
13739             {
13740               if (child_die->tag == DW_TAG_imported_module)
13741                 process_die (child_die, spec_cu);
13742               child_die = sibling_die (child_die);
13743             }
13744
13745           /* In some cases, GCC generates specification DIEs that
13746              themselves contain DW_AT_specification attributes.  */
13747           spec_die = die_specification (spec_die, &spec_cu);
13748         }
13749     }
13750
13751   struct context_stack cstk = cu->get_builder ()->pop_context ();
13752   /* Make a block for the local symbols within.  */
13753   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13754                                      cstk.static_link, lowpc, highpc);
13755
13756   /* For C++, set the block's scope.  */
13757   if ((cu->language == language_cplus
13758        || cu->language == language_fortran
13759        || cu->language == language_d
13760        || cu->language == language_rust)
13761       && cu->processing_has_namespace_info)
13762     block_set_scope (block, determine_prefix (die, cu),
13763                      &objfile->objfile_obstack);
13764
13765   /* If we have address ranges, record them.  */
13766   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13767
13768   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13769
13770   /* Attach template arguments to function.  */
13771   if (!template_args.empty ())
13772     {
13773       gdb_assert (templ_func != NULL);
13774
13775       templ_func->n_template_arguments = template_args.size ();
13776       templ_func->template_arguments
13777         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13778                      templ_func->n_template_arguments);
13779       memcpy (templ_func->template_arguments,
13780               template_args.data (),
13781               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13782
13783       /* Make sure that the symtab is set on the new symbols.  Even
13784          though they don't appear in this symtab directly, other parts
13785          of gdb assume that symbols do, and this is reasonably
13786          true.  */
13787       for (symbol *sym : template_args)
13788         symbol_set_symtab (sym, symbol_symtab (templ_func));
13789     }
13790
13791   /* In C++, we can have functions nested inside functions (e.g., when
13792      a function declares a class that has methods).  This means that
13793      when we finish processing a function scope, we may need to go
13794      back to building a containing block's symbol lists.  */
13795   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13796   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13797
13798   /* If we've finished processing a top-level function, subsequent
13799      symbols go in the file symbol list.  */
13800   if (cu->get_builder ()->outermost_context_p ())
13801     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13802 }
13803
13804 /* Process all the DIES contained within a lexical block scope.  Start
13805    a new scope, process the dies, and then close the scope.  */
13806
13807 static void
13808 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13809 {
13810   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13811   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13812   CORE_ADDR lowpc, highpc;
13813   struct die_info *child_die;
13814   CORE_ADDR baseaddr;
13815
13816   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13817
13818   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13819   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13820      as multiple lexical blocks?  Handling children in a sane way would
13821      be nasty.  Might be easier to properly extend generic blocks to
13822      describe ranges.  */
13823   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13824     {
13825     case PC_BOUNDS_NOT_PRESENT:
13826       /* DW_TAG_lexical_block has no attributes, process its children as if
13827          there was no wrapping by that DW_TAG_lexical_block.
13828          GCC does no longer produces such DWARF since GCC r224161.  */
13829       for (child_die = die->child;
13830            child_die != NULL && child_die->tag;
13831            child_die = sibling_die (child_die))
13832         process_die (child_die, cu);
13833       return;
13834     case PC_BOUNDS_INVALID:
13835       return;
13836     }
13837   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13838   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13839
13840   cu->get_builder ()->push_context (0, lowpc);
13841   if (die->child != NULL)
13842     {
13843       child_die = die->child;
13844       while (child_die && child_die->tag)
13845         {
13846           process_die (child_die, cu);
13847           child_die = sibling_die (child_die);
13848         }
13849     }
13850   inherit_abstract_dies (die, cu);
13851   struct context_stack cstk = cu->get_builder ()->pop_context ();
13852
13853   if (*cu->get_builder ()->get_local_symbols () != NULL
13854       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13855     {
13856       struct block *block
13857         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13858                                      cstk.start_addr, highpc);
13859
13860       /* Note that recording ranges after traversing children, as we
13861          do here, means that recording a parent's ranges entails
13862          walking across all its children's ranges as they appear in
13863          the address map, which is quadratic behavior.
13864
13865          It would be nicer to record the parent's ranges before
13866          traversing its children, simply overriding whatever you find
13867          there.  But since we don't even decide whether to create a
13868          block until after we've traversed its children, that's hard
13869          to do.  */
13870       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13871     }
13872   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13873   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13874 }
13875
13876 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13877
13878 static void
13879 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13880 {
13881   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13882   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13883   CORE_ADDR pc, baseaddr;
13884   struct attribute *attr;
13885   struct call_site *call_site, call_site_local;
13886   void **slot;
13887   int nparams;
13888   struct die_info *child_die;
13889
13890   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13891
13892   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13893   if (attr == NULL)
13894     {
13895       /* This was a pre-DWARF-5 GNU extension alias
13896          for DW_AT_call_return_pc.  */
13897       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13898     }
13899   if (!attr)
13900     {
13901       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13902                    "DIE %s [in module %s]"),
13903                  sect_offset_str (die->sect_off), objfile_name (objfile));
13904       return;
13905     }
13906   pc = attr_value_as_address (attr) + baseaddr;
13907   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13908
13909   if (cu->call_site_htab == NULL)
13910     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13911                                                NULL, &objfile->objfile_obstack,
13912                                                hashtab_obstack_allocate, NULL);
13913   call_site_local.pc = pc;
13914   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13915   if (*slot != NULL)
13916     {
13917       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13918                    "DIE %s [in module %s]"),
13919                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13920                  objfile_name (objfile));
13921       return;
13922     }
13923
13924   /* Count parameters at the caller.  */
13925
13926   nparams = 0;
13927   for (child_die = die->child; child_die && child_die->tag;
13928        child_die = sibling_die (child_die))
13929     {
13930       if (child_die->tag != DW_TAG_call_site_parameter
13931           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13932         {
13933           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13934                        "DW_TAG_call_site child DIE %s [in module %s]"),
13935                      child_die->tag, sect_offset_str (child_die->sect_off),
13936                      objfile_name (objfile));
13937           continue;
13938         }
13939
13940       nparams++;
13941     }
13942
13943   call_site
13944     = ((struct call_site *)
13945        obstack_alloc (&objfile->objfile_obstack,
13946                       sizeof (*call_site)
13947                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13948   *slot = call_site;
13949   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13950   call_site->pc = pc;
13951
13952   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13953       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13954     {
13955       struct die_info *func_die;
13956
13957       /* Skip also over DW_TAG_inlined_subroutine.  */
13958       for (func_die = die->parent;
13959            func_die && func_die->tag != DW_TAG_subprogram
13960            && func_die->tag != DW_TAG_subroutine_type;
13961            func_die = func_die->parent);
13962
13963       /* DW_AT_call_all_calls is a superset
13964          of DW_AT_call_all_tail_calls.  */
13965       if (func_die
13966           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13967           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13968           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13969           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13970         {
13971           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13972              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13973              both the initial caller containing the real return address PC and
13974              the final callee containing the current PC of a chain of tail
13975              calls do not need to have the tail call list complete.  But any
13976              function candidate for a virtual tail call frame searched via
13977              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13978              determined unambiguously.  */
13979         }
13980       else
13981         {
13982           struct type *func_type = NULL;
13983
13984           if (func_die)
13985             func_type = get_die_type (func_die, cu);
13986           if (func_type != NULL)
13987             {
13988               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13989
13990               /* Enlist this call site to the function.  */
13991               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13992               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13993             }
13994           else
13995             complaint (_("Cannot find function owning DW_TAG_call_site "
13996                          "DIE %s [in module %s]"),
13997                        sect_offset_str (die->sect_off), objfile_name (objfile));
13998         }
13999     }
14000
14001   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14002   if (attr == NULL)
14003     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14004   if (attr == NULL)
14005     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14006   if (attr == NULL)
14007     {
14008       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14009       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14010     }
14011   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14012   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14013     /* Keep NULL DWARF_BLOCK.  */;
14014   else if (attr_form_is_block (attr))
14015     {
14016       struct dwarf2_locexpr_baton *dlbaton;
14017
14018       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14019       dlbaton->data = DW_BLOCK (attr)->data;
14020       dlbaton->size = DW_BLOCK (attr)->size;
14021       dlbaton->per_cu = cu->per_cu;
14022
14023       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14024     }
14025   else if (attr_form_is_ref (attr))
14026     {
14027       struct dwarf2_cu *target_cu = cu;
14028       struct die_info *target_die;
14029
14030       target_die = follow_die_ref (die, attr, &target_cu);
14031       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14032       if (die_is_declaration (target_die, target_cu))
14033         {
14034           const char *target_physname;
14035
14036           /* Prefer the mangled name; otherwise compute the demangled one.  */
14037           target_physname = dw2_linkage_name (target_die, target_cu);
14038           if (target_physname == NULL)
14039             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14040           if (target_physname == NULL)
14041             complaint (_("DW_AT_call_target target DIE has invalid "
14042                          "physname, for referencing DIE %s [in module %s]"),
14043                        sect_offset_str (die->sect_off), objfile_name (objfile));
14044           else
14045             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14046         }
14047       else
14048         {
14049           CORE_ADDR lowpc;
14050
14051           /* DW_AT_entry_pc should be preferred.  */
14052           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14053               <= PC_BOUNDS_INVALID)
14054             complaint (_("DW_AT_call_target target DIE has invalid "
14055                          "low pc, for referencing DIE %s [in module %s]"),
14056                        sect_offset_str (die->sect_off), objfile_name (objfile));
14057           else
14058             {
14059               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14060               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14061             }
14062         }
14063     }
14064   else
14065     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14066                  "block nor reference, for DIE %s [in module %s]"),
14067                sect_offset_str (die->sect_off), objfile_name (objfile));
14068
14069   call_site->per_cu = cu->per_cu;
14070
14071   for (child_die = die->child;
14072        child_die && child_die->tag;
14073        child_die = sibling_die (child_die))
14074     {
14075       struct call_site_parameter *parameter;
14076       struct attribute *loc, *origin;
14077
14078       if (child_die->tag != DW_TAG_call_site_parameter
14079           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14080         {
14081           /* Already printed the complaint above.  */
14082           continue;
14083         }
14084
14085       gdb_assert (call_site->parameter_count < nparams);
14086       parameter = &call_site->parameter[call_site->parameter_count];
14087
14088       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14089          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14090          register is contained in DW_AT_call_value.  */
14091
14092       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14093       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14094       if (origin == NULL)
14095         {
14096           /* This was a pre-DWARF-5 GNU extension alias
14097              for DW_AT_call_parameter.  */
14098           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14099         }
14100       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14101         {
14102           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14103
14104           sect_offset sect_off
14105             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14106           if (!offset_in_cu_p (&cu->header, sect_off))
14107             {
14108               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14109                  binding can be done only inside one CU.  Such referenced DIE
14110                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14111               complaint (_("DW_AT_call_parameter offset is not in CU for "
14112                            "DW_TAG_call_site child DIE %s [in module %s]"),
14113                          sect_offset_str (child_die->sect_off),
14114                          objfile_name (objfile));
14115               continue;
14116             }
14117           parameter->u.param_cu_off
14118             = (cu_offset) (sect_off - cu->header.sect_off);
14119         }
14120       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14121         {
14122           complaint (_("No DW_FORM_block* DW_AT_location for "
14123                        "DW_TAG_call_site child DIE %s [in module %s]"),
14124                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14125           continue;
14126         }
14127       else
14128         {
14129           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14130             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14131           if (parameter->u.dwarf_reg != -1)
14132             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14133           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14134                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14135                                              &parameter->u.fb_offset))
14136             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14137           else
14138             {
14139               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14140                            "for DW_FORM_block* DW_AT_location is supported for "
14141                            "DW_TAG_call_site child DIE %s "
14142                            "[in module %s]"),
14143                          sect_offset_str (child_die->sect_off),
14144                          objfile_name (objfile));
14145               continue;
14146             }
14147         }
14148
14149       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14150       if (attr == NULL)
14151         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14152       if (!attr_form_is_block (attr))
14153         {
14154           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14155                        "DW_TAG_call_site child DIE %s [in module %s]"),
14156                      sect_offset_str (child_die->sect_off),
14157                      objfile_name (objfile));
14158           continue;
14159         }
14160       parameter->value = DW_BLOCK (attr)->data;
14161       parameter->value_size = DW_BLOCK (attr)->size;
14162
14163       /* Parameters are not pre-cleared by memset above.  */
14164       parameter->data_value = NULL;
14165       parameter->data_value_size = 0;
14166       call_site->parameter_count++;
14167
14168       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14169       if (attr == NULL)
14170         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14171       if (attr)
14172         {
14173           if (!attr_form_is_block (attr))
14174             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14175                          "DW_TAG_call_site child DIE %s [in module %s]"),
14176                        sect_offset_str (child_die->sect_off),
14177                        objfile_name (objfile));
14178           else
14179             {
14180               parameter->data_value = DW_BLOCK (attr)->data;
14181               parameter->data_value_size = DW_BLOCK (attr)->size;
14182             }
14183         }
14184     }
14185 }
14186
14187 /* Helper function for read_variable.  If DIE represents a virtual
14188    table, then return the type of the concrete object that is
14189    associated with the virtual table.  Otherwise, return NULL.  */
14190
14191 static struct type *
14192 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14193 {
14194   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14195   if (attr == NULL)
14196     return NULL;
14197
14198   /* Find the type DIE.  */
14199   struct die_info *type_die = NULL;
14200   struct dwarf2_cu *type_cu = cu;
14201
14202   if (attr_form_is_ref (attr))
14203     type_die = follow_die_ref (die, attr, &type_cu);
14204   if (type_die == NULL)
14205     return NULL;
14206
14207   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14208     return NULL;
14209   return die_containing_type (type_die, type_cu);
14210 }
14211
14212 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14213
14214 static void
14215 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14216 {
14217   struct rust_vtable_symbol *storage = NULL;
14218
14219   if (cu->language == language_rust)
14220     {
14221       struct type *containing_type = rust_containing_type (die, cu);
14222
14223       if (containing_type != NULL)
14224         {
14225           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14226
14227           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14228                                     struct rust_vtable_symbol);
14229           initialize_objfile_symbol (storage);
14230           storage->concrete_type = containing_type;
14231           storage->subclass = SYMBOL_RUST_VTABLE;
14232         }
14233     }
14234
14235   struct symbol *res = new_symbol (die, NULL, cu, storage);
14236   struct attribute *abstract_origin
14237     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14238   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
14239   if (res == NULL && loc && abstract_origin)
14240     {
14241       /* We have a variable without a name, but with a location and an abstract
14242          origin.  This may be a concrete instance of an abstract variable
14243          referenced from an DW_OP_GNU_variable_value, so save it to find it back
14244          later.  */
14245       struct dwarf2_cu *origin_cu = cu;
14246       struct die_info *origin_die
14247         = follow_die_ref (die, abstract_origin, &origin_cu);
14248       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
14249       dpo->abstract_to_concrete[origin_die->sect_off].push_back (die->sect_off);
14250     }
14251 }
14252
14253 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14254    reading .debug_rnglists.
14255    Callback's type should be:
14256     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14257    Return true if the attributes are present and valid, otherwise,
14258    return false.  */
14259
14260 template <typename Callback>
14261 static bool
14262 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14263                          Callback &&callback)
14264 {
14265   struct dwarf2_per_objfile *dwarf2_per_objfile
14266     = cu->per_cu->dwarf2_per_objfile;
14267   struct objfile *objfile = dwarf2_per_objfile->objfile;
14268   bfd *obfd = objfile->obfd;
14269   /* Base address selection entry.  */
14270   CORE_ADDR base;
14271   int found_base;
14272   const gdb_byte *buffer;
14273   CORE_ADDR baseaddr;
14274   bool overflow = false;
14275
14276   found_base = cu->base_known;
14277   base = cu->base_address;
14278
14279   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14280   if (offset >= dwarf2_per_objfile->rnglists.size)
14281     {
14282       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14283                  offset);
14284       return false;
14285     }
14286   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14287
14288   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14289
14290   while (1)
14291     {
14292       /* Initialize it due to a false compiler warning.  */
14293       CORE_ADDR range_beginning = 0, range_end = 0;
14294       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14295                                  + dwarf2_per_objfile->rnglists.size);
14296       unsigned int bytes_read;
14297
14298       if (buffer == buf_end)
14299         {
14300           overflow = true;
14301           break;
14302         }
14303       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14304       switch (rlet)
14305         {
14306         case DW_RLE_end_of_list:
14307           break;
14308         case DW_RLE_base_address:
14309           if (buffer + cu->header.addr_size > buf_end)
14310             {
14311               overflow = true;
14312               break;
14313             }
14314           base = read_address (obfd, buffer, cu, &bytes_read);
14315           found_base = 1;
14316           buffer += bytes_read;
14317           break;
14318         case DW_RLE_start_length:
14319           if (buffer + cu->header.addr_size > buf_end)
14320             {
14321               overflow = true;
14322               break;
14323             }
14324           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14325           buffer += bytes_read;
14326           range_end = (range_beginning
14327                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14328           buffer += bytes_read;
14329           if (buffer > buf_end)
14330             {
14331               overflow = true;
14332               break;
14333             }
14334           break;
14335         case DW_RLE_offset_pair:
14336           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14337           buffer += bytes_read;
14338           if (buffer > buf_end)
14339             {
14340               overflow = true;
14341               break;
14342             }
14343           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14344           buffer += bytes_read;
14345           if (buffer > buf_end)
14346             {
14347               overflow = true;
14348               break;
14349             }
14350           break;
14351         case DW_RLE_start_end:
14352           if (buffer + 2 * cu->header.addr_size > buf_end)
14353             {
14354               overflow = true;
14355               break;
14356             }
14357           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14358           buffer += bytes_read;
14359           range_end = read_address (obfd, buffer, cu, &bytes_read);
14360           buffer += bytes_read;
14361           break;
14362         default:
14363           complaint (_("Invalid .debug_rnglists data (no base address)"));
14364           return false;
14365         }
14366       if (rlet == DW_RLE_end_of_list || overflow)
14367         break;
14368       if (rlet == DW_RLE_base_address)
14369         continue;
14370
14371       if (!found_base)
14372         {
14373           /* We have no valid base address for the ranges
14374              data.  */
14375           complaint (_("Invalid .debug_rnglists data (no base address)"));
14376           return false;
14377         }
14378
14379       if (range_beginning > range_end)
14380         {
14381           /* Inverted range entries are invalid.  */
14382           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14383           return false;
14384         }
14385
14386       /* Empty range entries have no effect.  */
14387       if (range_beginning == range_end)
14388         continue;
14389
14390       range_beginning += base;
14391       range_end += base;
14392
14393       /* A not-uncommon case of bad debug info.
14394          Don't pollute the addrmap with bad data.  */
14395       if (range_beginning + baseaddr == 0
14396           && !dwarf2_per_objfile->has_section_at_zero)
14397         {
14398           complaint (_(".debug_rnglists entry has start address of zero"
14399                        " [in module %s]"), objfile_name (objfile));
14400           continue;
14401         }
14402
14403       callback (range_beginning, range_end);
14404     }
14405
14406   if (overflow)
14407     {
14408       complaint (_("Offset %d is not terminated "
14409                    "for DW_AT_ranges attribute"),
14410                  offset);
14411       return false;
14412     }
14413
14414   return true;
14415 }
14416
14417 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14418    Callback's type should be:
14419     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14420    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14421
14422 template <typename Callback>
14423 static int
14424 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14425                        Callback &&callback)
14426 {
14427   struct dwarf2_per_objfile *dwarf2_per_objfile
14428       = cu->per_cu->dwarf2_per_objfile;
14429   struct objfile *objfile = dwarf2_per_objfile->objfile;
14430   struct comp_unit_head *cu_header = &cu->header;
14431   bfd *obfd = objfile->obfd;
14432   unsigned int addr_size = cu_header->addr_size;
14433   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14434   /* Base address selection entry.  */
14435   CORE_ADDR base;
14436   int found_base;
14437   unsigned int dummy;
14438   const gdb_byte *buffer;
14439   CORE_ADDR baseaddr;
14440
14441   if (cu_header->version >= 5)
14442     return dwarf2_rnglists_process (offset, cu, callback);
14443
14444   found_base = cu->base_known;
14445   base = cu->base_address;
14446
14447   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14448   if (offset >= dwarf2_per_objfile->ranges.size)
14449     {
14450       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14451                  offset);
14452       return 0;
14453     }
14454   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14455
14456   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14457
14458   while (1)
14459     {
14460       CORE_ADDR range_beginning, range_end;
14461
14462       range_beginning = read_address (obfd, buffer, cu, &dummy);
14463       buffer += addr_size;
14464       range_end = read_address (obfd, buffer, cu, &dummy);
14465       buffer += addr_size;
14466       offset += 2 * addr_size;
14467
14468       /* An end of list marker is a pair of zero addresses.  */
14469       if (range_beginning == 0 && range_end == 0)
14470         /* Found the end of list entry.  */
14471         break;
14472
14473       /* Each base address selection entry is a pair of 2 values.
14474          The first is the largest possible address, the second is
14475          the base address.  Check for a base address here.  */
14476       if ((range_beginning & mask) == mask)
14477         {
14478           /* If we found the largest possible address, then we already
14479              have the base address in range_end.  */
14480           base = range_end;
14481           found_base = 1;
14482           continue;
14483         }
14484
14485       if (!found_base)
14486         {
14487           /* We have no valid base address for the ranges
14488              data.  */
14489           complaint (_("Invalid .debug_ranges data (no base address)"));
14490           return 0;
14491         }
14492
14493       if (range_beginning > range_end)
14494         {
14495           /* Inverted range entries are invalid.  */
14496           complaint (_("Invalid .debug_ranges data (inverted range)"));
14497           return 0;
14498         }
14499
14500       /* Empty range entries have no effect.  */
14501       if (range_beginning == range_end)
14502         continue;
14503
14504       range_beginning += base;
14505       range_end += base;
14506
14507       /* A not-uncommon case of bad debug info.
14508          Don't pollute the addrmap with bad data.  */
14509       if (range_beginning + baseaddr == 0
14510           && !dwarf2_per_objfile->has_section_at_zero)
14511         {
14512           complaint (_(".debug_ranges entry has start address of zero"
14513                        " [in module %s]"), objfile_name (objfile));
14514           continue;
14515         }
14516
14517       callback (range_beginning, range_end);
14518     }
14519
14520   return 1;
14521 }
14522
14523 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14524    Return 1 if the attributes are present and valid, otherwise, return 0.
14525    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14526
14527 static int
14528 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14529                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14530                     struct partial_symtab *ranges_pst)
14531 {
14532   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14533   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14534   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14535                                        SECT_OFF_TEXT (objfile));
14536   int low_set = 0;
14537   CORE_ADDR low = 0;
14538   CORE_ADDR high = 0;
14539   int retval;
14540
14541   retval = dwarf2_ranges_process (offset, cu,
14542     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14543     {
14544       if (ranges_pst != NULL)
14545         {
14546           CORE_ADDR lowpc;
14547           CORE_ADDR highpc;
14548
14549           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14550                                                range_beginning + baseaddr)
14551                    - baseaddr);
14552           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14553                                                 range_end + baseaddr)
14554                     - baseaddr);
14555           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
14556                              lowpc, highpc - 1, ranges_pst);
14557         }
14558
14559       /* FIXME: This is recording everything as a low-high
14560          segment of consecutive addresses.  We should have a
14561          data structure for discontiguous block ranges
14562          instead.  */
14563       if (! low_set)
14564         {
14565           low = range_beginning;
14566           high = range_end;
14567           low_set = 1;
14568         }
14569       else
14570         {
14571           if (range_beginning < low)
14572             low = range_beginning;
14573           if (range_end > high)
14574             high = range_end;
14575         }
14576     });
14577   if (!retval)
14578     return 0;
14579
14580   if (! low_set)
14581     /* If the first entry is an end-of-list marker, the range
14582        describes an empty scope, i.e. no instructions.  */
14583     return 0;
14584
14585   if (low_return)
14586     *low_return = low;
14587   if (high_return)
14588     *high_return = high;
14589   return 1;
14590 }
14591
14592 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14593    definition for the return value.  *LOWPC and *HIGHPC are set iff
14594    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14595
14596 static enum pc_bounds_kind
14597 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14598                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14599                       struct partial_symtab *pst)
14600 {
14601   struct dwarf2_per_objfile *dwarf2_per_objfile
14602     = cu->per_cu->dwarf2_per_objfile;
14603   struct attribute *attr;
14604   struct attribute *attr_high;
14605   CORE_ADDR low = 0;
14606   CORE_ADDR high = 0;
14607   enum pc_bounds_kind ret;
14608
14609   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14610   if (attr_high)
14611     {
14612       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14613       if (attr)
14614         {
14615           low = attr_value_as_address (attr);
14616           high = attr_value_as_address (attr_high);
14617           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14618             high += low;
14619         }
14620       else
14621         /* Found high w/o low attribute.  */
14622         return PC_BOUNDS_INVALID;
14623
14624       /* Found consecutive range of addresses.  */
14625       ret = PC_BOUNDS_HIGH_LOW;
14626     }
14627   else
14628     {
14629       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14630       if (attr != NULL)
14631         {
14632           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14633              We take advantage of the fact that DW_AT_ranges does not appear
14634              in DW_TAG_compile_unit of DWO files.  */
14635           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14636           unsigned int ranges_offset = (DW_UNSND (attr)
14637                                         + (need_ranges_base
14638                                            ? cu->ranges_base
14639                                            : 0));
14640
14641           /* Value of the DW_AT_ranges attribute is the offset in the
14642              .debug_ranges section.  */
14643           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14644             return PC_BOUNDS_INVALID;
14645           /* Found discontinuous range of addresses.  */
14646           ret = PC_BOUNDS_RANGES;
14647         }
14648       else
14649         return PC_BOUNDS_NOT_PRESENT;
14650     }
14651
14652   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14653   if (high <= low)
14654     return PC_BOUNDS_INVALID;
14655
14656   /* When using the GNU linker, .gnu.linkonce. sections are used to
14657      eliminate duplicate copies of functions and vtables and such.
14658      The linker will arbitrarily choose one and discard the others.
14659      The AT_*_pc values for such functions refer to local labels in
14660      these sections.  If the section from that file was discarded, the
14661      labels are not in the output, so the relocs get a value of 0.
14662      If this is a discarded function, mark the pc bounds as invalid,
14663      so that GDB will ignore it.  */
14664   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14665     return PC_BOUNDS_INVALID;
14666
14667   *lowpc = low;
14668   if (highpc)
14669     *highpc = high;
14670   return ret;
14671 }
14672
14673 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14674    its low and high PC addresses.  Do nothing if these addresses could not
14675    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14676    and HIGHPC to the high address if greater than HIGHPC.  */
14677
14678 static void
14679 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14680                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14681                                  struct dwarf2_cu *cu)
14682 {
14683   CORE_ADDR low, high;
14684   struct die_info *child = die->child;
14685
14686   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14687     {
14688       *lowpc = std::min (*lowpc, low);
14689       *highpc = std::max (*highpc, high);
14690     }
14691
14692   /* If the language does not allow nested subprograms (either inside
14693      subprograms or lexical blocks), we're done.  */
14694   if (cu->language != language_ada)
14695     return;
14696
14697   /* Check all the children of the given DIE.  If it contains nested
14698      subprograms, then check their pc bounds.  Likewise, we need to
14699      check lexical blocks as well, as they may also contain subprogram
14700      definitions.  */
14701   while (child && child->tag)
14702     {
14703       if (child->tag == DW_TAG_subprogram
14704           || child->tag == DW_TAG_lexical_block)
14705         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14706       child = sibling_die (child);
14707     }
14708 }
14709
14710 /* Get the low and high pc's represented by the scope DIE, and store
14711    them in *LOWPC and *HIGHPC.  If the correct values can't be
14712    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14713
14714 static void
14715 get_scope_pc_bounds (struct die_info *die,
14716                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14717                      struct dwarf2_cu *cu)
14718 {
14719   CORE_ADDR best_low = (CORE_ADDR) -1;
14720   CORE_ADDR best_high = (CORE_ADDR) 0;
14721   CORE_ADDR current_low, current_high;
14722
14723   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14724       >= PC_BOUNDS_RANGES)
14725     {
14726       best_low = current_low;
14727       best_high = current_high;
14728     }
14729   else
14730     {
14731       struct die_info *child = die->child;
14732
14733       while (child && child->tag)
14734         {
14735           switch (child->tag) {
14736           case DW_TAG_subprogram:
14737             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14738             break;
14739           case DW_TAG_namespace:
14740           case DW_TAG_module:
14741             /* FIXME: carlton/2004-01-16: Should we do this for
14742                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14743                that current GCC's always emit the DIEs corresponding
14744                to definitions of methods of classes as children of a
14745                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14746                the DIEs giving the declarations, which could be
14747                anywhere).  But I don't see any reason why the
14748                standards says that they have to be there.  */
14749             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14750
14751             if (current_low != ((CORE_ADDR) -1))
14752               {
14753                 best_low = std::min (best_low, current_low);
14754                 best_high = std::max (best_high, current_high);
14755               }
14756             break;
14757           default:
14758             /* Ignore.  */
14759             break;
14760           }
14761
14762           child = sibling_die (child);
14763         }
14764     }
14765
14766   *lowpc = best_low;
14767   *highpc = best_high;
14768 }
14769
14770 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14771    in DIE.  */
14772
14773 static void
14774 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14775                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14776 {
14777   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14778   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14779   struct attribute *attr;
14780   struct attribute *attr_high;
14781
14782   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14783   if (attr_high)
14784     {
14785       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14786       if (attr)
14787         {
14788           CORE_ADDR low = attr_value_as_address (attr);
14789           CORE_ADDR high = attr_value_as_address (attr_high);
14790
14791           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14792             high += low;
14793
14794           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14795           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14796           cu->get_builder ()->record_block_range (block, low, high - 1);
14797         }
14798     }
14799
14800   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14801   if (attr)
14802     {
14803       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14804          We take advantage of the fact that DW_AT_ranges does not appear
14805          in DW_TAG_compile_unit of DWO files.  */
14806       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14807
14808       /* The value of the DW_AT_ranges attribute is the offset of the
14809          address range list in the .debug_ranges section.  */
14810       unsigned long offset = (DW_UNSND (attr)
14811                               + (need_ranges_base ? cu->ranges_base : 0));
14812
14813       std::vector<blockrange> blockvec;
14814       dwarf2_ranges_process (offset, cu,
14815         [&] (CORE_ADDR start, CORE_ADDR end)
14816         {
14817           start += baseaddr;
14818           end += baseaddr;
14819           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14820           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14821           cu->get_builder ()->record_block_range (block, start, end - 1);
14822           blockvec.emplace_back (start, end);
14823         });
14824
14825       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14826     }
14827 }
14828
14829 /* Check whether the producer field indicates either of GCC < 4.6, or the
14830    Intel C/C++ compiler, and cache the result in CU.  */
14831
14832 static void
14833 check_producer (struct dwarf2_cu *cu)
14834 {
14835   int major, minor;
14836
14837   if (cu->producer == NULL)
14838     {
14839       /* For unknown compilers expect their behavior is DWARF version
14840          compliant.
14841
14842          GCC started to support .debug_types sections by -gdwarf-4 since
14843          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14844          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14845          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14846          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14847     }
14848   else if (producer_is_gcc (cu->producer, &major, &minor))
14849     {
14850       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14851       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14852     }
14853   else if (producer_is_icc (cu->producer, &major, &minor))
14854     {
14855       cu->producer_is_icc = true;
14856       cu->producer_is_icc_lt_14 = major < 14;
14857     }
14858   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14859     cu->producer_is_codewarrior = true;
14860   else
14861     {
14862       /* For other non-GCC compilers, expect their behavior is DWARF version
14863          compliant.  */
14864     }
14865
14866   cu->checked_producer = true;
14867 }
14868
14869 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14870    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14871    during 4.6.0 experimental.  */
14872
14873 static bool
14874 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14875 {
14876   if (!cu->checked_producer)
14877     check_producer (cu);
14878
14879   return cu->producer_is_gxx_lt_4_6;
14880 }
14881
14882
14883 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14884    with incorrect is_stmt attributes.  */
14885
14886 static bool
14887 producer_is_codewarrior (struct dwarf2_cu *cu)
14888 {
14889   if (!cu->checked_producer)
14890     check_producer (cu);
14891
14892   return cu->producer_is_codewarrior;
14893 }
14894
14895 /* Return the default accessibility type if it is not overriden by
14896    DW_AT_accessibility.  */
14897
14898 static enum dwarf_access_attribute
14899 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14900 {
14901   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14902     {
14903       /* The default DWARF 2 accessibility for members is public, the default
14904          accessibility for inheritance is private.  */
14905
14906       if (die->tag != DW_TAG_inheritance)
14907         return DW_ACCESS_public;
14908       else
14909         return DW_ACCESS_private;
14910     }
14911   else
14912     {
14913       /* DWARF 3+ defines the default accessibility a different way.  The same
14914          rules apply now for DW_TAG_inheritance as for the members and it only
14915          depends on the container kind.  */
14916
14917       if (die->parent->tag == DW_TAG_class_type)
14918         return DW_ACCESS_private;
14919       else
14920         return DW_ACCESS_public;
14921     }
14922 }
14923
14924 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14925    offset.  If the attribute was not found return 0, otherwise return
14926    1.  If it was found but could not properly be handled, set *OFFSET
14927    to 0.  */
14928
14929 static int
14930 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14931                              LONGEST *offset)
14932 {
14933   struct attribute *attr;
14934
14935   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14936   if (attr != NULL)
14937     {
14938       *offset = 0;
14939
14940       /* Note that we do not check for a section offset first here.
14941          This is because DW_AT_data_member_location is new in DWARF 4,
14942          so if we see it, we can assume that a constant form is really
14943          a constant and not a section offset.  */
14944       if (attr_form_is_constant (attr))
14945         *offset = dwarf2_get_attr_constant_value (attr, 0);
14946       else if (attr_form_is_section_offset (attr))
14947         dwarf2_complex_location_expr_complaint ();
14948       else if (attr_form_is_block (attr))
14949         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14950       else
14951         dwarf2_complex_location_expr_complaint ();
14952
14953       return 1;
14954     }
14955
14956   return 0;
14957 }
14958
14959 /* Add an aggregate field to the field list.  */
14960
14961 static void
14962 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14963                   struct dwarf2_cu *cu)
14964 {
14965   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14966   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14967   struct nextfield *new_field;
14968   struct attribute *attr;
14969   struct field *fp;
14970   const char *fieldname = "";
14971
14972   if (die->tag == DW_TAG_inheritance)
14973     {
14974       fip->baseclasses.emplace_back ();
14975       new_field = &fip->baseclasses.back ();
14976     }
14977   else
14978     {
14979       fip->fields.emplace_back ();
14980       new_field = &fip->fields.back ();
14981     }
14982
14983   fip->nfields++;
14984
14985   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14986   if (attr)
14987     new_field->accessibility = DW_UNSND (attr);
14988   else
14989     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14990   if (new_field->accessibility != DW_ACCESS_public)
14991     fip->non_public_fields = 1;
14992
14993   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14994   if (attr)
14995     new_field->virtuality = DW_UNSND (attr);
14996   else
14997     new_field->virtuality = DW_VIRTUALITY_none;
14998
14999   fp = &new_field->field;
15000
15001   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15002     {
15003       LONGEST offset;
15004
15005       /* Data member other than a C++ static data member.  */
15006
15007       /* Get type of field.  */
15008       fp->type = die_type (die, cu);
15009
15010       SET_FIELD_BITPOS (*fp, 0);
15011
15012       /* Get bit size of field (zero if none).  */
15013       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15014       if (attr)
15015         {
15016           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15017         }
15018       else
15019         {
15020           FIELD_BITSIZE (*fp) = 0;
15021         }
15022
15023       /* Get bit offset of field.  */
15024       if (handle_data_member_location (die, cu, &offset))
15025         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15026       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15027       if (attr)
15028         {
15029           if (gdbarch_bits_big_endian (gdbarch))
15030             {
15031               /* For big endian bits, the DW_AT_bit_offset gives the
15032                  additional bit offset from the MSB of the containing
15033                  anonymous object to the MSB of the field.  We don't
15034                  have to do anything special since we don't need to
15035                  know the size of the anonymous object.  */
15036               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15037             }
15038           else
15039             {
15040               /* For little endian bits, compute the bit offset to the
15041                  MSB of the anonymous object, subtract off the number of
15042                  bits from the MSB of the field to the MSB of the
15043                  object, and then subtract off the number of bits of
15044                  the field itself.  The result is the bit offset of
15045                  the LSB of the field.  */
15046               int anonymous_size;
15047               int bit_offset = DW_UNSND (attr);
15048
15049               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15050               if (attr)
15051                 {
15052                   /* The size of the anonymous object containing
15053                      the bit field is explicit, so use the
15054                      indicated size (in bytes).  */
15055                   anonymous_size = DW_UNSND (attr);
15056                 }
15057               else
15058                 {
15059                   /* The size of the anonymous object containing
15060                      the bit field must be inferred from the type
15061                      attribute of the data member containing the
15062                      bit field.  */
15063                   anonymous_size = TYPE_LENGTH (fp->type);
15064                 }
15065               SET_FIELD_BITPOS (*fp,
15066                                 (FIELD_BITPOS (*fp)
15067                                  + anonymous_size * bits_per_byte
15068                                  - bit_offset - FIELD_BITSIZE (*fp)));
15069             }
15070         }
15071       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15072       if (attr != NULL)
15073         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15074                                 + dwarf2_get_attr_constant_value (attr, 0)));
15075
15076       /* Get name of field.  */
15077       fieldname = dwarf2_name (die, cu);
15078       if (fieldname == NULL)
15079         fieldname = "";
15080
15081       /* The name is already allocated along with this objfile, so we don't
15082          need to duplicate it for the type.  */
15083       fp->name = fieldname;
15084
15085       /* Change accessibility for artificial fields (e.g. virtual table
15086          pointer or virtual base class pointer) to private.  */
15087       if (dwarf2_attr (die, DW_AT_artificial, cu))
15088         {
15089           FIELD_ARTIFICIAL (*fp) = 1;
15090           new_field->accessibility = DW_ACCESS_private;
15091           fip->non_public_fields = 1;
15092         }
15093     }
15094   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15095     {
15096       /* C++ static member.  */
15097
15098       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15099          is a declaration, but all versions of G++ as of this writing
15100          (so through at least 3.2.1) incorrectly generate
15101          DW_TAG_variable tags.  */
15102
15103       const char *physname;
15104
15105       /* Get name of field.  */
15106       fieldname = dwarf2_name (die, cu);
15107       if (fieldname == NULL)
15108         return;
15109
15110       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15111       if (attr
15112           /* Only create a symbol if this is an external value.
15113              new_symbol checks this and puts the value in the global symbol
15114              table, which we want.  If it is not external, new_symbol
15115              will try to put the value in cu->list_in_scope which is wrong.  */
15116           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15117         {
15118           /* A static const member, not much different than an enum as far as
15119              we're concerned, except that we can support more types.  */
15120           new_symbol (die, NULL, cu);
15121         }
15122
15123       /* Get physical name.  */
15124       physname = dwarf2_physname (fieldname, die, cu);
15125
15126       /* The name is already allocated along with this objfile, so we don't
15127          need to duplicate it for the type.  */
15128       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15129       FIELD_TYPE (*fp) = die_type (die, cu);
15130       FIELD_NAME (*fp) = fieldname;
15131     }
15132   else if (die->tag == DW_TAG_inheritance)
15133     {
15134       LONGEST offset;
15135
15136       /* C++ base class field.  */
15137       if (handle_data_member_location (die, cu, &offset))
15138         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15139       FIELD_BITSIZE (*fp) = 0;
15140       FIELD_TYPE (*fp) = die_type (die, cu);
15141       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15142     }
15143   else if (die->tag == DW_TAG_variant_part)
15144     {
15145       /* process_structure_scope will treat this DIE as a union.  */
15146       process_structure_scope (die, cu);
15147
15148       /* The variant part is relative to the start of the enclosing
15149          structure.  */
15150       SET_FIELD_BITPOS (*fp, 0);
15151       fp->type = get_die_type (die, cu);
15152       fp->artificial = 1;
15153       fp->name = "<<variant>>";
15154
15155       /* Normally a DW_TAG_variant_part won't have a size, but our
15156          representation requires one, so set it to the maximum of the
15157          child sizes.  */
15158       if (TYPE_LENGTH (fp->type) == 0)
15159         {
15160           unsigned max = 0;
15161           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
15162             if (TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)) > max)
15163               max = TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i));
15164           TYPE_LENGTH (fp->type) = max;
15165         }
15166     }
15167   else
15168     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15169 }
15170
15171 /* Can the type given by DIE define another type?  */
15172
15173 static bool
15174 type_can_define_types (const struct die_info *die)
15175 {
15176   switch (die->tag)
15177     {
15178     case DW_TAG_typedef:
15179     case DW_TAG_class_type:
15180     case DW_TAG_structure_type:
15181     case DW_TAG_union_type:
15182     case DW_TAG_enumeration_type:
15183       return true;
15184
15185     default:
15186       return false;
15187     }
15188 }
15189
15190 /* Add a type definition defined in the scope of the FIP's class.  */
15191
15192 static void
15193 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15194                       struct dwarf2_cu *cu)
15195 {
15196   struct decl_field fp;
15197   memset (&fp, 0, sizeof (fp));
15198
15199   gdb_assert (type_can_define_types (die));
15200
15201   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15202   fp.name = dwarf2_name (die, cu);
15203   fp.type = read_type_die (die, cu);
15204
15205   /* Save accessibility.  */
15206   enum dwarf_access_attribute accessibility;
15207   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15208   if (attr != NULL)
15209     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15210   else
15211     accessibility = dwarf2_default_access_attribute (die, cu);
15212   switch (accessibility)
15213     {
15214     case DW_ACCESS_public:
15215       /* The assumed value if neither private nor protected.  */
15216       break;
15217     case DW_ACCESS_private:
15218       fp.is_private = 1;
15219       break;
15220     case DW_ACCESS_protected:
15221       fp.is_protected = 1;
15222       break;
15223     default:
15224       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15225     }
15226
15227   if (die->tag == DW_TAG_typedef)
15228     fip->typedef_field_list.push_back (fp);
15229   else
15230     fip->nested_types_list.push_back (fp);
15231 }
15232
15233 /* Create the vector of fields, and attach it to the type.  */
15234
15235 static void
15236 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15237                               struct dwarf2_cu *cu)
15238 {
15239   int nfields = fip->nfields;
15240
15241   /* Record the field count, allocate space for the array of fields,
15242      and create blank accessibility bitfields if necessary.  */
15243   TYPE_NFIELDS (type) = nfields;
15244   TYPE_FIELDS (type) = (struct field *)
15245     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15246
15247   if (fip->non_public_fields && cu->language != language_ada)
15248     {
15249       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15250
15251       TYPE_FIELD_PRIVATE_BITS (type) =
15252         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15253       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15254
15255       TYPE_FIELD_PROTECTED_BITS (type) =
15256         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15257       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15258
15259       TYPE_FIELD_IGNORE_BITS (type) =
15260         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15261       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15262     }
15263
15264   /* If the type has baseclasses, allocate and clear a bit vector for
15265      TYPE_FIELD_VIRTUAL_BITS.  */
15266   if (!fip->baseclasses.empty () && cu->language != language_ada)
15267     {
15268       int num_bytes = B_BYTES (fip->baseclasses.size ());
15269       unsigned char *pointer;
15270
15271       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15272       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15273       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15274       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15275       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15276     }
15277
15278   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15279     {
15280       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15281
15282       for (int index = 0; index < nfields; ++index)
15283         {
15284           struct nextfield &field = fip->fields[index];
15285
15286           if (field.variant.is_discriminant)
15287             di->discriminant_index = index;
15288           else if (field.variant.default_branch)
15289             di->default_index = index;
15290           else
15291             di->discriminants[index] = field.variant.discriminant_value;
15292         }
15293     }
15294
15295   /* Copy the saved-up fields into the field vector.  */
15296   for (int i = 0; i < nfields; ++i)
15297     {
15298       struct nextfield &field
15299         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15300            : fip->fields[i - fip->baseclasses.size ()]);
15301
15302       TYPE_FIELD (type, i) = field.field;
15303       switch (field.accessibility)
15304         {
15305         case DW_ACCESS_private:
15306           if (cu->language != language_ada)
15307             SET_TYPE_FIELD_PRIVATE (type, i);
15308           break;
15309
15310         case DW_ACCESS_protected:
15311           if (cu->language != language_ada)
15312             SET_TYPE_FIELD_PROTECTED (type, i);
15313           break;
15314
15315         case DW_ACCESS_public:
15316           break;
15317
15318         default:
15319           /* Unknown accessibility.  Complain and treat it as public.  */
15320           {
15321             complaint (_("unsupported accessibility %d"),
15322                        field.accessibility);
15323           }
15324           break;
15325         }
15326       if (i < fip->baseclasses.size ())
15327         {
15328           switch (field.virtuality)
15329             {
15330             case DW_VIRTUALITY_virtual:
15331             case DW_VIRTUALITY_pure_virtual:
15332               if (cu->language == language_ada)
15333                 error (_("unexpected virtuality in component of Ada type"));
15334               SET_TYPE_FIELD_VIRTUAL (type, i);
15335               break;
15336             }
15337         }
15338     }
15339 }
15340
15341 /* Return true if this member function is a constructor, false
15342    otherwise.  */
15343
15344 static int
15345 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15346 {
15347   const char *fieldname;
15348   const char *type_name;
15349   int len;
15350
15351   if (die->parent == NULL)
15352     return 0;
15353
15354   if (die->parent->tag != DW_TAG_structure_type
15355       && die->parent->tag != DW_TAG_union_type
15356       && die->parent->tag != DW_TAG_class_type)
15357     return 0;
15358
15359   fieldname = dwarf2_name (die, cu);
15360   type_name = dwarf2_name (die->parent, cu);
15361   if (fieldname == NULL || type_name == NULL)
15362     return 0;
15363
15364   len = strlen (fieldname);
15365   return (strncmp (fieldname, type_name, len) == 0
15366           && (type_name[len] == '\0' || type_name[len] == '<'));
15367 }
15368
15369 /* Add a member function to the proper fieldlist.  */
15370
15371 static void
15372 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15373                       struct type *type, struct dwarf2_cu *cu)
15374 {
15375   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15376   struct attribute *attr;
15377   int i;
15378   struct fnfieldlist *flp = nullptr;
15379   struct fn_field *fnp;
15380   const char *fieldname;
15381   struct type *this_type;
15382   enum dwarf_access_attribute accessibility;
15383
15384   if (cu->language == language_ada)
15385     error (_("unexpected member function in Ada type"));
15386
15387   /* Get name of member function.  */
15388   fieldname = dwarf2_name (die, cu);
15389   if (fieldname == NULL)
15390     return;
15391
15392   /* Look up member function name in fieldlist.  */
15393   for (i = 0; i < fip->fnfieldlists.size (); i++)
15394     {
15395       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15396         {
15397           flp = &fip->fnfieldlists[i];
15398           break;
15399         }
15400     }
15401
15402   /* Create a new fnfieldlist if necessary.  */
15403   if (flp == nullptr)
15404     {
15405       fip->fnfieldlists.emplace_back ();
15406       flp = &fip->fnfieldlists.back ();
15407       flp->name = fieldname;
15408       i = fip->fnfieldlists.size () - 1;
15409     }
15410
15411   /* Create a new member function field and add it to the vector of
15412      fnfieldlists.  */
15413   flp->fnfields.emplace_back ();
15414   fnp = &flp->fnfields.back ();
15415
15416   /* Delay processing of the physname until later.  */
15417   if (cu->language == language_cplus)
15418     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15419                         die, cu);
15420   else
15421     {
15422       const char *physname = dwarf2_physname (fieldname, die, cu);
15423       fnp->physname = physname ? physname : "";
15424     }
15425
15426   fnp->type = alloc_type (objfile);
15427   this_type = read_type_die (die, cu);
15428   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15429     {
15430       int nparams = TYPE_NFIELDS (this_type);
15431
15432       /* TYPE is the domain of this method, and THIS_TYPE is the type
15433            of the method itself (TYPE_CODE_METHOD).  */
15434       smash_to_method_type (fnp->type, type,
15435                             TYPE_TARGET_TYPE (this_type),
15436                             TYPE_FIELDS (this_type),
15437                             TYPE_NFIELDS (this_type),
15438                             TYPE_VARARGS (this_type));
15439
15440       /* Handle static member functions.
15441          Dwarf2 has no clean way to discern C++ static and non-static
15442          member functions.  G++ helps GDB by marking the first
15443          parameter for non-static member functions (which is the this
15444          pointer) as artificial.  We obtain this information from
15445          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15446       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15447         fnp->voffset = VOFFSET_STATIC;
15448     }
15449   else
15450     complaint (_("member function type missing for '%s'"),
15451                dwarf2_full_name (fieldname, die, cu));
15452
15453   /* Get fcontext from DW_AT_containing_type if present.  */
15454   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15455     fnp->fcontext = die_containing_type (die, cu);
15456
15457   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15458      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15459
15460   /* Get accessibility.  */
15461   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15462   if (attr)
15463     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15464   else
15465     accessibility = dwarf2_default_access_attribute (die, cu);
15466   switch (accessibility)
15467     {
15468     case DW_ACCESS_private:
15469       fnp->is_private = 1;
15470       break;
15471     case DW_ACCESS_protected:
15472       fnp->is_protected = 1;
15473       break;
15474     }
15475
15476   /* Check for artificial methods.  */
15477   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15478   if (attr && DW_UNSND (attr) != 0)
15479     fnp->is_artificial = 1;
15480
15481   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15482
15483   /* Get index in virtual function table if it is a virtual member
15484      function.  For older versions of GCC, this is an offset in the
15485      appropriate virtual table, as specified by DW_AT_containing_type.
15486      For everyone else, it is an expression to be evaluated relative
15487      to the object address.  */
15488
15489   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15490   if (attr)
15491     {
15492       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15493         {
15494           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15495             {
15496               /* Old-style GCC.  */
15497               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15498             }
15499           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15500                    || (DW_BLOCK (attr)->size > 1
15501                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15502                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15503             {
15504               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15505               if ((fnp->voffset % cu->header.addr_size) != 0)
15506                 dwarf2_complex_location_expr_complaint ();
15507               else
15508                 fnp->voffset /= cu->header.addr_size;
15509               fnp->voffset += 2;
15510             }
15511           else
15512             dwarf2_complex_location_expr_complaint ();
15513
15514           if (!fnp->fcontext)
15515             {
15516               /* If there is no `this' field and no DW_AT_containing_type,
15517                  we cannot actually find a base class context for the
15518                  vtable!  */
15519               if (TYPE_NFIELDS (this_type) == 0
15520                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15521                 {
15522                   complaint (_("cannot determine context for virtual member "
15523                                "function \"%s\" (offset %s)"),
15524                              fieldname, sect_offset_str (die->sect_off));
15525                 }
15526               else
15527                 {
15528                   fnp->fcontext
15529                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15530                 }
15531             }
15532         }
15533       else if (attr_form_is_section_offset (attr))
15534         {
15535           dwarf2_complex_location_expr_complaint ();
15536         }
15537       else
15538         {
15539           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15540                                                  fieldname);
15541         }
15542     }
15543   else
15544     {
15545       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15546       if (attr && DW_UNSND (attr))
15547         {
15548           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15549           complaint (_("Member function \"%s\" (offset %s) is virtual "
15550                        "but the vtable offset is not specified"),
15551                      fieldname, sect_offset_str (die->sect_off));
15552           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15553           TYPE_CPLUS_DYNAMIC (type) = 1;
15554         }
15555     }
15556 }
15557
15558 /* Create the vector of member function fields, and attach it to the type.  */
15559
15560 static void
15561 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15562                                  struct dwarf2_cu *cu)
15563 {
15564   if (cu->language == language_ada)
15565     error (_("unexpected member functions in Ada type"));
15566
15567   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15568   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15569     TYPE_ALLOC (type,
15570                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15571
15572   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15573     {
15574       struct fnfieldlist &nf = fip->fnfieldlists[i];
15575       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15576
15577       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15578       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15579       fn_flp->fn_fields = (struct fn_field *)
15580         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15581
15582       for (int k = 0; k < nf.fnfields.size (); ++k)
15583         fn_flp->fn_fields[k] = nf.fnfields[k];
15584     }
15585
15586   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15587 }
15588
15589 /* Returns non-zero if NAME is the name of a vtable member in CU's
15590    language, zero otherwise.  */
15591 static int
15592 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15593 {
15594   static const char vptr[] = "_vptr";
15595
15596   /* Look for the C++ form of the vtable.  */
15597   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15598     return 1;
15599
15600   return 0;
15601 }
15602
15603 /* GCC outputs unnamed structures that are really pointers to member
15604    functions, with the ABI-specified layout.  If TYPE describes
15605    such a structure, smash it into a member function type.
15606
15607    GCC shouldn't do this; it should just output pointer to member DIEs.
15608    This is GCC PR debug/28767.  */
15609
15610 static void
15611 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15612 {
15613   struct type *pfn_type, *self_type, *new_type;
15614
15615   /* Check for a structure with no name and two children.  */
15616   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15617     return;
15618
15619   /* Check for __pfn and __delta members.  */
15620   if (TYPE_FIELD_NAME (type, 0) == NULL
15621       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15622       || TYPE_FIELD_NAME (type, 1) == NULL
15623       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15624     return;
15625
15626   /* Find the type of the method.  */
15627   pfn_type = TYPE_FIELD_TYPE (type, 0);
15628   if (pfn_type == NULL
15629       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15630       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15631     return;
15632
15633   /* Look for the "this" argument.  */
15634   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15635   if (TYPE_NFIELDS (pfn_type) == 0
15636       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15637       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15638     return;
15639
15640   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15641   new_type = alloc_type (objfile);
15642   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15643                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15644                         TYPE_VARARGS (pfn_type));
15645   smash_to_methodptr_type (type, new_type);
15646 }
15647
15648 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15649    appropriate error checking and issuing complaints if there is a
15650    problem.  */
15651
15652 static ULONGEST
15653 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15654 {
15655   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15656
15657   if (attr == nullptr)
15658     return 0;
15659
15660   if (!attr_form_is_constant (attr))
15661     {
15662       complaint (_("DW_AT_alignment must have constant form"
15663                    " - DIE at %s [in module %s]"),
15664                  sect_offset_str (die->sect_off),
15665                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15666       return 0;
15667     }
15668
15669   ULONGEST align;
15670   if (attr->form == DW_FORM_sdata)
15671     {
15672       LONGEST val = DW_SND (attr);
15673       if (val < 0)
15674         {
15675           complaint (_("DW_AT_alignment value must not be negative"
15676                        " - DIE at %s [in module %s]"),
15677                      sect_offset_str (die->sect_off),
15678                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15679           return 0;
15680         }
15681       align = val;
15682     }
15683   else
15684     align = DW_UNSND (attr);
15685
15686   if (align == 0)
15687     {
15688       complaint (_("DW_AT_alignment value must not be zero"
15689                    " - DIE at %s [in module %s]"),
15690                  sect_offset_str (die->sect_off),
15691                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15692       return 0;
15693     }
15694   if ((align & (align - 1)) != 0)
15695     {
15696       complaint (_("DW_AT_alignment value must be a power of 2"
15697                    " - DIE at %s [in module %s]"),
15698                  sect_offset_str (die->sect_off),
15699                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15700       return 0;
15701     }
15702
15703   return align;
15704 }
15705
15706 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15707    the alignment for TYPE.  */
15708
15709 static void
15710 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15711                      struct type *type)
15712 {
15713   if (!set_type_align (type, get_alignment (cu, die)))
15714     complaint (_("DW_AT_alignment value too large"
15715                  " - DIE at %s [in module %s]"),
15716                sect_offset_str (die->sect_off),
15717                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15718 }
15719
15720 /* Called when we find the DIE that starts a structure or union scope
15721    (definition) to create a type for the structure or union.  Fill in
15722    the type's name and general properties; the members will not be
15723    processed until process_structure_scope.  A symbol table entry for
15724    the type will also not be done until process_structure_scope (assuming
15725    the type has a name).
15726
15727    NOTE: we need to call these functions regardless of whether or not the
15728    DIE has a DW_AT_name attribute, since it might be an anonymous
15729    structure or union.  This gets the type entered into our set of
15730    user defined types.  */
15731
15732 static struct type *
15733 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15734 {
15735   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15736   struct type *type;
15737   struct attribute *attr;
15738   const char *name;
15739
15740   /* If the definition of this type lives in .debug_types, read that type.
15741      Don't follow DW_AT_specification though, that will take us back up
15742      the chain and we want to go down.  */
15743   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15744   if (attr)
15745     {
15746       type = get_DW_AT_signature_type (die, attr, cu);
15747
15748       /* The type's CU may not be the same as CU.
15749          Ensure TYPE is recorded with CU in die_type_hash.  */
15750       return set_die_type (die, type, cu);
15751     }
15752
15753   type = alloc_type (objfile);
15754   INIT_CPLUS_SPECIFIC (type);
15755
15756   name = dwarf2_name (die, cu);
15757   if (name != NULL)
15758     {
15759       if (cu->language == language_cplus
15760           || cu->language == language_d
15761           || cu->language == language_rust)
15762         {
15763           const char *full_name = dwarf2_full_name (name, die, cu);
15764
15765           /* dwarf2_full_name might have already finished building the DIE's
15766              type.  If so, there is no need to continue.  */
15767           if (get_die_type (die, cu) != NULL)
15768             return get_die_type (die, cu);
15769
15770           TYPE_NAME (type) = full_name;
15771         }
15772       else
15773         {
15774           /* The name is already allocated along with this objfile, so
15775              we don't need to duplicate it for the type.  */
15776           TYPE_NAME (type) = name;
15777         }
15778     }
15779
15780   if (die->tag == DW_TAG_structure_type)
15781     {
15782       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15783     }
15784   else if (die->tag == DW_TAG_union_type)
15785     {
15786       TYPE_CODE (type) = TYPE_CODE_UNION;
15787     }
15788   else if (die->tag == DW_TAG_variant_part)
15789     {
15790       TYPE_CODE (type) = TYPE_CODE_UNION;
15791       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15792     }
15793   else
15794     {
15795       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15796     }
15797
15798   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15799     TYPE_DECLARED_CLASS (type) = 1;
15800
15801   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15802   if (attr)
15803     {
15804       if (attr_form_is_constant (attr))
15805         TYPE_LENGTH (type) = DW_UNSND (attr);
15806       else
15807         {
15808           /* For the moment, dynamic type sizes are not supported
15809              by GDB's struct type.  The actual size is determined
15810              on-demand when resolving the type of a given object,
15811              so set the type's length to zero for now.  Otherwise,
15812              we record an expression as the length, and that expression
15813              could lead to a very large value, which could eventually
15814              lead to us trying to allocate that much memory when creating
15815              a value of that type.  */
15816           TYPE_LENGTH (type) = 0;
15817         }
15818     }
15819   else
15820     {
15821       TYPE_LENGTH (type) = 0;
15822     }
15823
15824   maybe_set_alignment (cu, die, type);
15825
15826   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15827     {
15828       /* ICC<14 does not output the required DW_AT_declaration on
15829          incomplete types, but gives them a size of zero.  */
15830       TYPE_STUB (type) = 1;
15831     }
15832   else
15833     TYPE_STUB_SUPPORTED (type) = 1;
15834
15835   if (die_is_declaration (die, cu))
15836     TYPE_STUB (type) = 1;
15837   else if (attr == NULL && die->child == NULL
15838            && producer_is_realview (cu->producer))
15839     /* RealView does not output the required DW_AT_declaration
15840        on incomplete types.  */
15841     TYPE_STUB (type) = 1;
15842
15843   /* We need to add the type field to the die immediately so we don't
15844      infinitely recurse when dealing with pointers to the structure
15845      type within the structure itself.  */
15846   set_die_type (die, type, cu);
15847
15848   /* set_die_type should be already done.  */
15849   set_descriptive_type (type, die, cu);
15850
15851   return type;
15852 }
15853
15854 /* A helper for process_structure_scope that handles a single member
15855    DIE.  */
15856
15857 static void
15858 handle_struct_member_die (struct die_info *child_die, struct type *type,
15859                           struct field_info *fi,
15860                           std::vector<struct symbol *> *template_args,
15861                           struct dwarf2_cu *cu)
15862 {
15863   if (child_die->tag == DW_TAG_member
15864       || child_die->tag == DW_TAG_variable
15865       || child_die->tag == DW_TAG_variant_part)
15866     {
15867       /* NOTE: carlton/2002-11-05: A C++ static data member
15868          should be a DW_TAG_member that is a declaration, but
15869          all versions of G++ as of this writing (so through at
15870          least 3.2.1) incorrectly generate DW_TAG_variable
15871          tags for them instead.  */
15872       dwarf2_add_field (fi, child_die, cu);
15873     }
15874   else if (child_die->tag == DW_TAG_subprogram)
15875     {
15876       /* Rust doesn't have member functions in the C++ sense.
15877          However, it does emit ordinary functions as children
15878          of a struct DIE.  */
15879       if (cu->language == language_rust)
15880         read_func_scope (child_die, cu);
15881       else
15882         {
15883           /* C++ member function.  */
15884           dwarf2_add_member_fn (fi, child_die, type, cu);
15885         }
15886     }
15887   else if (child_die->tag == DW_TAG_inheritance)
15888     {
15889       /* C++ base class field.  */
15890       dwarf2_add_field (fi, child_die, cu);
15891     }
15892   else if (type_can_define_types (child_die))
15893     dwarf2_add_type_defn (fi, child_die, cu);
15894   else if (child_die->tag == DW_TAG_template_type_param
15895            || child_die->tag == DW_TAG_template_value_param)
15896     {
15897       struct symbol *arg = new_symbol (child_die, NULL, cu);
15898
15899       if (arg != NULL)
15900         template_args->push_back (arg);
15901     }
15902   else if (child_die->tag == DW_TAG_variant)
15903     {
15904       /* In a variant we want to get the discriminant and also add a
15905          field for our sole member child.  */
15906       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15907
15908       for (die_info *variant_child = child_die->child;
15909            variant_child != NULL;
15910            variant_child = sibling_die (variant_child))
15911         {
15912           if (variant_child->tag == DW_TAG_member)
15913             {
15914               handle_struct_member_die (variant_child, type, fi,
15915                                         template_args, cu);
15916               /* Only handle the one.  */
15917               break;
15918             }
15919         }
15920
15921       /* We don't handle this but we might as well report it if we see
15922          it.  */
15923       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15924           complaint (_("DW_AT_discr_list is not supported yet"
15925                        " - DIE at %s [in module %s]"),
15926                      sect_offset_str (child_die->sect_off),
15927                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15928
15929       /* The first field was just added, so we can stash the
15930          discriminant there.  */
15931       gdb_assert (!fi->fields.empty ());
15932       if (discr == NULL)
15933         fi->fields.back ().variant.default_branch = true;
15934       else
15935         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15936     }
15937 }
15938
15939 /* Finish creating a structure or union type, including filling in
15940    its members and creating a symbol for it.  */
15941
15942 static void
15943 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15944 {
15945   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15946   struct die_info *child_die;
15947   struct type *type;
15948
15949   type = get_die_type (die, cu);
15950   if (type == NULL)
15951     type = read_structure_type (die, cu);
15952
15953   /* When reading a DW_TAG_variant_part, we need to notice when we
15954      read the discriminant member, so we can record it later in the
15955      discriminant_info.  */
15956   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15957   sect_offset discr_offset;
15958   bool has_template_parameters = false;
15959
15960   if (is_variant_part)
15961     {
15962       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15963       if (discr == NULL)
15964         {
15965           /* Maybe it's a univariant form, an extension we support.
15966              In this case arrange not to check the offset.  */
15967           is_variant_part = false;
15968         }
15969       else if (attr_form_is_ref (discr))
15970         {
15971           struct dwarf2_cu *target_cu = cu;
15972           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15973
15974           discr_offset = target_die->sect_off;
15975         }
15976       else
15977         {
15978           complaint (_("DW_AT_discr does not have DIE reference form"
15979                        " - DIE at %s [in module %s]"),
15980                      sect_offset_str (die->sect_off),
15981                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15982           is_variant_part = false;
15983         }
15984     }
15985
15986   if (die->child != NULL && ! die_is_declaration (die, cu))
15987     {
15988       struct field_info fi;
15989       std::vector<struct symbol *> template_args;
15990
15991       child_die = die->child;
15992
15993       while (child_die && child_die->tag)
15994         {
15995           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15996
15997           if (is_variant_part && discr_offset == child_die->sect_off)
15998             fi.fields.back ().variant.is_discriminant = true;
15999
16000           child_die = sibling_die (child_die);
16001         }
16002
16003       /* Attach template arguments to type.  */
16004       if (!template_args.empty ())
16005         {
16006           has_template_parameters = true;
16007           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16008           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16009           TYPE_TEMPLATE_ARGUMENTS (type)
16010             = XOBNEWVEC (&objfile->objfile_obstack,
16011                          struct symbol *,
16012                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16013           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16014                   template_args.data (),
16015                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16016                    * sizeof (struct symbol *)));
16017         }
16018
16019       /* Attach fields and member functions to the type.  */
16020       if (fi.nfields)
16021         dwarf2_attach_fields_to_type (&fi, type, cu);
16022       if (!fi.fnfieldlists.empty ())
16023         {
16024           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16025
16026           /* Get the type which refers to the base class (possibly this
16027              class itself) which contains the vtable pointer for the current
16028              class from the DW_AT_containing_type attribute.  This use of
16029              DW_AT_containing_type is a GNU extension.  */
16030
16031           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16032             {
16033               struct type *t = die_containing_type (die, cu);
16034
16035               set_type_vptr_basetype (type, t);
16036               if (type == t)
16037                 {
16038                   int i;
16039
16040                   /* Our own class provides vtbl ptr.  */
16041                   for (i = TYPE_NFIELDS (t) - 1;
16042                        i >= TYPE_N_BASECLASSES (t);
16043                        --i)
16044                     {
16045                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16046
16047                       if (is_vtable_name (fieldname, cu))
16048                         {
16049                           set_type_vptr_fieldno (type, i);
16050                           break;
16051                         }
16052                     }
16053
16054                   /* Complain if virtual function table field not found.  */
16055                   if (i < TYPE_N_BASECLASSES (t))
16056                     complaint (_("virtual function table pointer "
16057                                  "not found when defining class '%s'"),
16058                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
16059                 }
16060               else
16061                 {
16062                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16063                 }
16064             }
16065           else if (cu->producer
16066                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16067             {
16068               /* The IBM XLC compiler does not provide direct indication
16069                  of the containing type, but the vtable pointer is
16070                  always named __vfp.  */
16071
16072               int i;
16073
16074               for (i = TYPE_NFIELDS (type) - 1;
16075                    i >= TYPE_N_BASECLASSES (type);
16076                    --i)
16077                 {
16078                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16079                     {
16080                       set_type_vptr_fieldno (type, i);
16081                       set_type_vptr_basetype (type, type);
16082                       break;
16083                     }
16084                 }
16085             }
16086         }
16087
16088       /* Copy fi.typedef_field_list linked list elements content into the
16089          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16090       if (!fi.typedef_field_list.empty ())
16091         {
16092           int count = fi.typedef_field_list.size ();
16093
16094           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16095           TYPE_TYPEDEF_FIELD_ARRAY (type)
16096             = ((struct decl_field *)
16097                TYPE_ALLOC (type,
16098                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16099           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16100
16101           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16102             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16103         }
16104
16105       /* Copy fi.nested_types_list linked list elements content into the
16106          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16107       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16108         {
16109           int count = fi.nested_types_list.size ();
16110
16111           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16112           TYPE_NESTED_TYPES_ARRAY (type)
16113             = ((struct decl_field *)
16114                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16115           TYPE_NESTED_TYPES_COUNT (type) = count;
16116
16117           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16118             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16119         }
16120     }
16121
16122   quirk_gcc_member_function_pointer (type, objfile);
16123   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16124     cu->rust_unions.push_back (type);
16125
16126   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16127      snapshots) has been known to create a die giving a declaration
16128      for a class that has, as a child, a die giving a definition for a
16129      nested class.  So we have to process our children even if the
16130      current die is a declaration.  Normally, of course, a declaration
16131      won't have any children at all.  */
16132
16133   child_die = die->child;
16134
16135   while (child_die != NULL && child_die->tag)
16136     {
16137       if (child_die->tag == DW_TAG_member
16138           || child_die->tag == DW_TAG_variable
16139           || child_die->tag == DW_TAG_inheritance
16140           || child_die->tag == DW_TAG_template_value_param
16141           || child_die->tag == DW_TAG_template_type_param)
16142         {
16143           /* Do nothing.  */
16144         }
16145       else
16146         process_die (child_die, cu);
16147
16148       child_die = sibling_die (child_die);
16149     }
16150
16151   /* Do not consider external references.  According to the DWARF standard,
16152      these DIEs are identified by the fact that they have no byte_size
16153      attribute, and a declaration attribute.  */
16154   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16155       || !die_is_declaration (die, cu))
16156     {
16157       struct symbol *sym = new_symbol (die, type, cu);
16158
16159       if (has_template_parameters)
16160         {
16161           struct symtab *symtab;
16162           if (sym != nullptr)
16163             symtab = symbol_symtab (sym);
16164           else if (cu->line_header != nullptr)
16165             {
16166               /* Any related symtab will do.  */
16167               symtab
16168                 = cu->line_header->file_name_at (file_name_index (1))->symtab;
16169             }
16170           else
16171             {
16172               symtab = nullptr;
16173               complaint (_("could not find suitable "
16174                            "symtab for template parameter"
16175                            " - DIE at %s [in module %s]"),
16176                          sect_offset_str (die->sect_off),
16177                          objfile_name (objfile));
16178             }
16179
16180           if (symtab != nullptr)
16181             {
16182               /* Make sure that the symtab is set on the new symbols.
16183                  Even though they don't appear in this symtab directly,
16184                  other parts of gdb assume that symbols do, and this is
16185                  reasonably true.  */
16186               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16187                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
16188             }
16189         }
16190     }
16191 }
16192
16193 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16194    update TYPE using some information only available in DIE's children.  */
16195
16196 static void
16197 update_enumeration_type_from_children (struct die_info *die,
16198                                        struct type *type,
16199                                        struct dwarf2_cu *cu)
16200 {
16201   struct die_info *child_die;
16202   int unsigned_enum = 1;
16203   int flag_enum = 1;
16204   ULONGEST mask = 0;
16205
16206   auto_obstack obstack;
16207
16208   for (child_die = die->child;
16209        child_die != NULL && child_die->tag;
16210        child_die = sibling_die (child_die))
16211     {
16212       struct attribute *attr;
16213       LONGEST value;
16214       const gdb_byte *bytes;
16215       struct dwarf2_locexpr_baton *baton;
16216       const char *name;
16217
16218       if (child_die->tag != DW_TAG_enumerator)
16219         continue;
16220
16221       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16222       if (attr == NULL)
16223         continue;
16224
16225       name = dwarf2_name (child_die, cu);
16226       if (name == NULL)
16227         name = "<anonymous enumerator>";
16228
16229       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16230                                &value, &bytes, &baton);
16231       if (value < 0)
16232         {
16233           unsigned_enum = 0;
16234           flag_enum = 0;
16235         }
16236       else if ((mask & value) != 0)
16237         flag_enum = 0;
16238       else
16239         mask |= value;
16240
16241       /* If we already know that the enum type is neither unsigned, nor
16242          a flag type, no need to look at the rest of the enumerates.  */
16243       if (!unsigned_enum && !flag_enum)
16244         break;
16245     }
16246
16247   if (unsigned_enum)
16248     TYPE_UNSIGNED (type) = 1;
16249   if (flag_enum)
16250     TYPE_FLAG_ENUM (type) = 1;
16251 }
16252
16253 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16254    complete the type's fields yet, or create any symbols.  */
16255
16256 static struct type *
16257 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16258 {
16259   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16260   struct type *type;
16261   struct attribute *attr;
16262   const char *name;
16263
16264   /* If the definition of this type lives in .debug_types, read that type.
16265      Don't follow DW_AT_specification though, that will take us back up
16266      the chain and we want to go down.  */
16267   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16268   if (attr)
16269     {
16270       type = get_DW_AT_signature_type (die, attr, cu);
16271
16272       /* The type's CU may not be the same as CU.
16273          Ensure TYPE is recorded with CU in die_type_hash.  */
16274       return set_die_type (die, type, cu);
16275     }
16276
16277   type = alloc_type (objfile);
16278
16279   TYPE_CODE (type) = TYPE_CODE_ENUM;
16280   name = dwarf2_full_name (NULL, die, cu);
16281   if (name != NULL)
16282     TYPE_NAME (type) = name;
16283
16284   attr = dwarf2_attr (die, DW_AT_type, cu);
16285   if (attr != NULL)
16286     {
16287       struct type *underlying_type = die_type (die, cu);
16288
16289       TYPE_TARGET_TYPE (type) = underlying_type;
16290     }
16291
16292   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16293   if (attr)
16294     {
16295       TYPE_LENGTH (type) = DW_UNSND (attr);
16296     }
16297   else
16298     {
16299       TYPE_LENGTH (type) = 0;
16300     }
16301
16302   maybe_set_alignment (cu, die, type);
16303
16304   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16305      declared as private in the package spec, and then defined only
16306      inside the package body.  Such types are known as Taft Amendment
16307      Types.  When another package uses such a type, an incomplete DIE
16308      may be generated by the compiler.  */
16309   if (die_is_declaration (die, cu))
16310     TYPE_STUB (type) = 1;
16311
16312   /* Finish the creation of this type by using the enum's children.
16313      We must call this even when the underlying type has been provided
16314      so that we can determine if we're looking at a "flag" enum.  */
16315   update_enumeration_type_from_children (die, type, cu);
16316
16317   /* If this type has an underlying type that is not a stub, then we
16318      may use its attributes.  We always use the "unsigned" attribute
16319      in this situation, because ordinarily we guess whether the type
16320      is unsigned -- but the guess can be wrong and the underlying type
16321      can tell us the reality.  However, we defer to a local size
16322      attribute if one exists, because this lets the compiler override
16323      the underlying type if needed.  */
16324   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16325     {
16326       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16327       if (TYPE_LENGTH (type) == 0)
16328         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16329       if (TYPE_RAW_ALIGN (type) == 0
16330           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16331         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16332     }
16333
16334   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16335
16336   return set_die_type (die, type, cu);
16337 }
16338
16339 /* Given a pointer to a die which begins an enumeration, process all
16340    the dies that define the members of the enumeration, and create the
16341    symbol for the enumeration type.
16342
16343    NOTE: We reverse the order of the element list.  */
16344
16345 static void
16346 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16347 {
16348   struct type *this_type;
16349
16350   this_type = get_die_type (die, cu);
16351   if (this_type == NULL)
16352     this_type = read_enumeration_type (die, cu);
16353
16354   if (die->child != NULL)
16355     {
16356       struct die_info *child_die;
16357       struct symbol *sym;
16358       struct field *fields = NULL;
16359       int num_fields = 0;
16360       const char *name;
16361
16362       child_die = die->child;
16363       while (child_die && child_die->tag)
16364         {
16365           if (child_die->tag != DW_TAG_enumerator)
16366             {
16367               process_die (child_die, cu);
16368             }
16369           else
16370             {
16371               name = dwarf2_name (child_die, cu);
16372               if (name)
16373                 {
16374                   sym = new_symbol (child_die, this_type, cu);
16375
16376                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16377                     {
16378                       fields = (struct field *)
16379                         xrealloc (fields,
16380                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16381                                   * sizeof (struct field));
16382                     }
16383
16384                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16385                   FIELD_TYPE (fields[num_fields]) = NULL;
16386                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16387                   FIELD_BITSIZE (fields[num_fields]) = 0;
16388
16389                   num_fields++;
16390                 }
16391             }
16392
16393           child_die = sibling_die (child_die);
16394         }
16395
16396       if (num_fields)
16397         {
16398           TYPE_NFIELDS (this_type) = num_fields;
16399           TYPE_FIELDS (this_type) = (struct field *)
16400             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16401           memcpy (TYPE_FIELDS (this_type), fields,
16402                   sizeof (struct field) * num_fields);
16403           xfree (fields);
16404         }
16405     }
16406
16407   /* If we are reading an enum from a .debug_types unit, and the enum
16408      is a declaration, and the enum is not the signatured type in the
16409      unit, then we do not want to add a symbol for it.  Adding a
16410      symbol would in some cases obscure the true definition of the
16411      enum, giving users an incomplete type when the definition is
16412      actually available.  Note that we do not want to do this for all
16413      enums which are just declarations, because C++0x allows forward
16414      enum declarations.  */
16415   if (cu->per_cu->is_debug_types
16416       && die_is_declaration (die, cu))
16417     {
16418       struct signatured_type *sig_type;
16419
16420       sig_type = (struct signatured_type *) cu->per_cu;
16421       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16422       if (sig_type->type_offset_in_section != die->sect_off)
16423         return;
16424     }
16425
16426   new_symbol (die, this_type, cu);
16427 }
16428
16429 /* Extract all information from a DW_TAG_array_type DIE and put it in
16430    the DIE's type field.  For now, this only handles one dimensional
16431    arrays.  */
16432
16433 static struct type *
16434 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16435 {
16436   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16437   struct die_info *child_die;
16438   struct type *type;
16439   struct type *element_type, *range_type, *index_type;
16440   struct attribute *attr;
16441   const char *name;
16442   struct dynamic_prop *byte_stride_prop = NULL;
16443   unsigned int bit_stride = 0;
16444
16445   element_type = die_type (die, cu);
16446
16447   /* The die_type call above may have already set the type for this DIE.  */
16448   type = get_die_type (die, cu);
16449   if (type)
16450     return type;
16451
16452   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16453   if (attr != NULL)
16454     {
16455       int stride_ok;
16456       struct type *prop_type
16457         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
16458
16459       byte_stride_prop
16460         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16461       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop,
16462                                         prop_type);
16463       if (!stride_ok)
16464         {
16465           complaint (_("unable to read array DW_AT_byte_stride "
16466                        " - DIE at %s [in module %s]"),
16467                      sect_offset_str (die->sect_off),
16468                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16469           /* Ignore this attribute.  We will likely not be able to print
16470              arrays of this type correctly, but there is little we can do
16471              to help if we cannot read the attribute's value.  */
16472           byte_stride_prop = NULL;
16473         }
16474     }
16475
16476   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16477   if (attr != NULL)
16478     bit_stride = DW_UNSND (attr);
16479
16480   /* Irix 6.2 native cc creates array types without children for
16481      arrays with unspecified length.  */
16482   if (die->child == NULL)
16483     {
16484       index_type = objfile_type (objfile)->builtin_int;
16485       range_type = create_static_range_type (NULL, index_type, 0, -1);
16486       type = create_array_type_with_stride (NULL, element_type, range_type,
16487                                             byte_stride_prop, bit_stride);
16488       return set_die_type (die, type, cu);
16489     }
16490
16491   std::vector<struct type *> range_types;
16492   child_die = die->child;
16493   while (child_die && child_die->tag)
16494     {
16495       if (child_die->tag == DW_TAG_subrange_type)
16496         {
16497           struct type *child_type = read_type_die (child_die, cu);
16498
16499           if (child_type != NULL)
16500             {
16501               /* The range type was succesfully read.  Save it for the
16502                  array type creation.  */
16503               range_types.push_back (child_type);
16504             }
16505         }
16506       child_die = sibling_die (child_die);
16507     }
16508
16509   /* Dwarf2 dimensions are output from left to right, create the
16510      necessary array types in backwards order.  */
16511
16512   type = element_type;
16513
16514   if (read_array_order (die, cu) == DW_ORD_col_major)
16515     {
16516       int i = 0;
16517
16518       while (i < range_types.size ())
16519         type = create_array_type_with_stride (NULL, type, range_types[i++],
16520                                               byte_stride_prop, bit_stride);
16521     }
16522   else
16523     {
16524       size_t ndim = range_types.size ();
16525       while (ndim-- > 0)
16526         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16527                                               byte_stride_prop, bit_stride);
16528     }
16529
16530   /* Understand Dwarf2 support for vector types (like they occur on
16531      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16532      array type.  This is not part of the Dwarf2/3 standard yet, but a
16533      custom vendor extension.  The main difference between a regular
16534      array and the vector variant is that vectors are passed by value
16535      to functions.  */
16536   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16537   if (attr)
16538     make_vector_type (type);
16539
16540   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16541      implementation may choose to implement triple vectors using this
16542      attribute.  */
16543   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16544   if (attr)
16545     {
16546       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16547         TYPE_LENGTH (type) = DW_UNSND (attr);
16548       else
16549         complaint (_("DW_AT_byte_size for array type smaller "
16550                      "than the total size of elements"));
16551     }
16552
16553   name = dwarf2_name (die, cu);
16554   if (name)
16555     TYPE_NAME (type) = name;
16556
16557   maybe_set_alignment (cu, die, type);
16558
16559   /* Install the type in the die.  */
16560   set_die_type (die, type, cu);
16561
16562   /* set_die_type should be already done.  */
16563   set_descriptive_type (type, die, cu);
16564
16565   return type;
16566 }
16567
16568 static enum dwarf_array_dim_ordering
16569 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16570 {
16571   struct attribute *attr;
16572
16573   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16574
16575   if (attr)
16576     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16577
16578   /* GNU F77 is a special case, as at 08/2004 array type info is the
16579      opposite order to the dwarf2 specification, but data is still
16580      laid out as per normal fortran.
16581
16582      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16583      version checking.  */
16584
16585   if (cu->language == language_fortran
16586       && cu->producer && strstr (cu->producer, "GNU F77"))
16587     {
16588       return DW_ORD_row_major;
16589     }
16590
16591   switch (cu->language_defn->la_array_ordering)
16592     {
16593     case array_column_major:
16594       return DW_ORD_col_major;
16595     case array_row_major:
16596     default:
16597       return DW_ORD_row_major;
16598     };
16599 }
16600
16601 /* Extract all information from a DW_TAG_set_type DIE and put it in
16602    the DIE's type field.  */
16603
16604 static struct type *
16605 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16606 {
16607   struct type *domain_type, *set_type;
16608   struct attribute *attr;
16609
16610   domain_type = die_type (die, cu);
16611
16612   /* The die_type call above may have already set the type for this DIE.  */
16613   set_type = get_die_type (die, cu);
16614   if (set_type)
16615     return set_type;
16616
16617   set_type = create_set_type (NULL, domain_type);
16618
16619   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16620   if (attr)
16621     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16622
16623   maybe_set_alignment (cu, die, set_type);
16624
16625   return set_die_type (die, set_type, cu);
16626 }
16627
16628 /* A helper for read_common_block that creates a locexpr baton.
16629    SYM is the symbol which we are marking as computed.
16630    COMMON_DIE is the DIE for the common block.
16631    COMMON_LOC is the location expression attribute for the common
16632    block itself.
16633    MEMBER_LOC is the location expression attribute for the particular
16634    member of the common block that we are processing.
16635    CU is the CU from which the above come.  */
16636
16637 static void
16638 mark_common_block_symbol_computed (struct symbol *sym,
16639                                    struct die_info *common_die,
16640                                    struct attribute *common_loc,
16641                                    struct attribute *member_loc,
16642                                    struct dwarf2_cu *cu)
16643 {
16644   struct dwarf2_per_objfile *dwarf2_per_objfile
16645     = cu->per_cu->dwarf2_per_objfile;
16646   struct objfile *objfile = dwarf2_per_objfile->objfile;
16647   struct dwarf2_locexpr_baton *baton;
16648   gdb_byte *ptr;
16649   unsigned int cu_off;
16650   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16651   LONGEST offset = 0;
16652
16653   gdb_assert (common_loc && member_loc);
16654   gdb_assert (attr_form_is_block (common_loc));
16655   gdb_assert (attr_form_is_block (member_loc)
16656               || attr_form_is_constant (member_loc));
16657
16658   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16659   baton->per_cu = cu->per_cu;
16660   gdb_assert (baton->per_cu);
16661
16662   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16663
16664   if (attr_form_is_constant (member_loc))
16665     {
16666       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16667       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16668     }
16669   else
16670     baton->size += DW_BLOCK (member_loc)->size;
16671
16672   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16673   baton->data = ptr;
16674
16675   *ptr++ = DW_OP_call4;
16676   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16677   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16678   ptr += 4;
16679
16680   if (attr_form_is_constant (member_loc))
16681     {
16682       *ptr++ = DW_OP_addr;
16683       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16684       ptr += cu->header.addr_size;
16685     }
16686   else
16687     {
16688       /* We have to copy the data here, because DW_OP_call4 will only
16689          use a DW_AT_location attribute.  */
16690       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16691       ptr += DW_BLOCK (member_loc)->size;
16692     }
16693
16694   *ptr++ = DW_OP_plus;
16695   gdb_assert (ptr - baton->data == baton->size);
16696
16697   SYMBOL_LOCATION_BATON (sym) = baton;
16698   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16699 }
16700
16701 /* Create appropriate locally-scoped variables for all the
16702    DW_TAG_common_block entries.  Also create a struct common_block
16703    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16704    is used to sepate the common blocks name namespace from regular
16705    variable names.  */
16706
16707 static void
16708 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16709 {
16710   struct attribute *attr;
16711
16712   attr = dwarf2_attr (die, DW_AT_location, cu);
16713   if (attr)
16714     {
16715       /* Support the .debug_loc offsets.  */
16716       if (attr_form_is_block (attr))
16717         {
16718           /* Ok.  */
16719         }
16720       else if (attr_form_is_section_offset (attr))
16721         {
16722           dwarf2_complex_location_expr_complaint ();
16723           attr = NULL;
16724         }
16725       else
16726         {
16727           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16728                                                  "common block member");
16729           attr = NULL;
16730         }
16731     }
16732
16733   if (die->child != NULL)
16734     {
16735       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16736       struct die_info *child_die;
16737       size_t n_entries = 0, size;
16738       struct common_block *common_block;
16739       struct symbol *sym;
16740
16741       for (child_die = die->child;
16742            child_die && child_die->tag;
16743            child_die = sibling_die (child_die))
16744         ++n_entries;
16745
16746       size = (sizeof (struct common_block)
16747               + (n_entries - 1) * sizeof (struct symbol *));
16748       common_block
16749         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16750                                                  size);
16751       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16752       common_block->n_entries = 0;
16753
16754       for (child_die = die->child;
16755            child_die && child_die->tag;
16756            child_die = sibling_die (child_die))
16757         {
16758           /* Create the symbol in the DW_TAG_common_block block in the current
16759              symbol scope.  */
16760           sym = new_symbol (child_die, NULL, cu);
16761           if (sym != NULL)
16762             {
16763               struct attribute *member_loc;
16764
16765               common_block->contents[common_block->n_entries++] = sym;
16766
16767               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16768                                         cu);
16769               if (member_loc)
16770                 {
16771                   /* GDB has handled this for a long time, but it is
16772                      not specified by DWARF.  It seems to have been
16773                      emitted by gfortran at least as recently as:
16774                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16775                   complaint (_("Variable in common block has "
16776                                "DW_AT_data_member_location "
16777                                "- DIE at %s [in module %s]"),
16778                                sect_offset_str (child_die->sect_off),
16779                              objfile_name (objfile));
16780
16781                   if (attr_form_is_section_offset (member_loc))
16782                     dwarf2_complex_location_expr_complaint ();
16783                   else if (attr_form_is_constant (member_loc)
16784                            || attr_form_is_block (member_loc))
16785                     {
16786                       if (attr)
16787                         mark_common_block_symbol_computed (sym, die, attr,
16788                                                            member_loc, cu);
16789                     }
16790                   else
16791                     dwarf2_complex_location_expr_complaint ();
16792                 }
16793             }
16794         }
16795
16796       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16797       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16798     }
16799 }
16800
16801 /* Create a type for a C++ namespace.  */
16802
16803 static struct type *
16804 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16805 {
16806   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16807   const char *previous_prefix, *name;
16808   int is_anonymous;
16809   struct type *type;
16810
16811   /* For extensions, reuse the type of the original namespace.  */
16812   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16813     {
16814       struct die_info *ext_die;
16815       struct dwarf2_cu *ext_cu = cu;
16816
16817       ext_die = dwarf2_extension (die, &ext_cu);
16818       type = read_type_die (ext_die, ext_cu);
16819
16820       /* EXT_CU may not be the same as CU.
16821          Ensure TYPE is recorded with CU in die_type_hash.  */
16822       return set_die_type (die, type, cu);
16823     }
16824
16825   name = namespace_name (die, &is_anonymous, cu);
16826
16827   /* Now build the name of the current namespace.  */
16828
16829   previous_prefix = determine_prefix (die, cu);
16830   if (previous_prefix[0] != '\0')
16831     name = typename_concat (&objfile->objfile_obstack,
16832                             previous_prefix, name, 0, cu);
16833
16834   /* Create the type.  */
16835   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16836
16837   return set_die_type (die, type, cu);
16838 }
16839
16840 /* Read a namespace scope.  */
16841
16842 static void
16843 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16844 {
16845   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16846   int is_anonymous;
16847
16848   /* Add a symbol associated to this if we haven't seen the namespace
16849      before.  Also, add a using directive if it's an anonymous
16850      namespace.  */
16851
16852   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16853     {
16854       struct type *type;
16855
16856       type = read_type_die (die, cu);
16857       new_symbol (die, type, cu);
16858
16859       namespace_name (die, &is_anonymous, cu);
16860       if (is_anonymous)
16861         {
16862           const char *previous_prefix = determine_prefix (die, cu);
16863
16864           std::vector<const char *> excludes;
16865           add_using_directive (using_directives (cu),
16866                                previous_prefix, TYPE_NAME (type), NULL,
16867                                NULL, excludes, 0, &objfile->objfile_obstack);
16868         }
16869     }
16870
16871   if (die->child != NULL)
16872     {
16873       struct die_info *child_die = die->child;
16874
16875       while (child_die && child_die->tag)
16876         {
16877           process_die (child_die, cu);
16878           child_die = sibling_die (child_die);
16879         }
16880     }
16881 }
16882
16883 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16884    imported module.  Still we need that type as local Fortran "use ... only"
16885    declaration imports depend on the created type in determine_prefix.  */
16886
16887 static struct type *
16888 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16889 {
16890   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16891   const char *module_name;
16892   struct type *type;
16893
16894   module_name = dwarf2_name (die, cu);
16895   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16896
16897   return set_die_type (die, type, cu);
16898 }
16899
16900 /* Read a Fortran module.  */
16901
16902 static void
16903 read_module (struct die_info *die, struct dwarf2_cu *cu)
16904 {
16905   struct die_info *child_die = die->child;
16906   struct type *type;
16907
16908   type = read_type_die (die, cu);
16909   new_symbol (die, type, cu);
16910
16911   while (child_die && child_die->tag)
16912     {
16913       process_die (child_die, cu);
16914       child_die = sibling_die (child_die);
16915     }
16916 }
16917
16918 /* Return the name of the namespace represented by DIE.  Set
16919    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16920    namespace.  */
16921
16922 static const char *
16923 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16924 {
16925   struct die_info *current_die;
16926   const char *name = NULL;
16927
16928   /* Loop through the extensions until we find a name.  */
16929
16930   for (current_die = die;
16931        current_die != NULL;
16932        current_die = dwarf2_extension (die, &cu))
16933     {
16934       /* We don't use dwarf2_name here so that we can detect the absence
16935          of a name -> anonymous namespace.  */
16936       name = dwarf2_string_attr (die, DW_AT_name, cu);
16937
16938       if (name != NULL)
16939         break;
16940     }
16941
16942   /* Is it an anonymous namespace?  */
16943
16944   *is_anonymous = (name == NULL);
16945   if (*is_anonymous)
16946     name = CP_ANONYMOUS_NAMESPACE_STR;
16947
16948   return name;
16949 }
16950
16951 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16952    the user defined type vector.  */
16953
16954 static struct type *
16955 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16956 {
16957   struct gdbarch *gdbarch
16958     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16959   struct comp_unit_head *cu_header = &cu->header;
16960   struct type *type;
16961   struct attribute *attr_byte_size;
16962   struct attribute *attr_address_class;
16963   int byte_size, addr_class;
16964   struct type *target_type;
16965
16966   target_type = die_type (die, cu);
16967
16968   /* The die_type call above may have already set the type for this DIE.  */
16969   type = get_die_type (die, cu);
16970   if (type)
16971     return type;
16972
16973   type = lookup_pointer_type (target_type);
16974
16975   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16976   if (attr_byte_size)
16977     byte_size = DW_UNSND (attr_byte_size);
16978   else
16979     byte_size = cu_header->addr_size;
16980
16981   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16982   if (attr_address_class)
16983     addr_class = DW_UNSND (attr_address_class);
16984   else
16985     addr_class = DW_ADDR_none;
16986
16987   ULONGEST alignment = get_alignment (cu, die);
16988
16989   /* If the pointer size, alignment, or address class is different
16990      than the default, create a type variant marked as such and set
16991      the length accordingly.  */
16992   if (TYPE_LENGTH (type) != byte_size
16993       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16994           && alignment != TYPE_RAW_ALIGN (type))
16995       || addr_class != DW_ADDR_none)
16996     {
16997       if (gdbarch_address_class_type_flags_p (gdbarch))
16998         {
16999           int type_flags;
17000
17001           type_flags = gdbarch_address_class_type_flags
17002                          (gdbarch, byte_size, addr_class);
17003           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17004                       == 0);
17005           type = make_type_with_address_space (type, type_flags);
17006         }
17007       else if (TYPE_LENGTH (type) != byte_size)
17008         {
17009           complaint (_("invalid pointer size %d"), byte_size);
17010         }
17011       else if (TYPE_RAW_ALIGN (type) != alignment)
17012         {
17013           complaint (_("Invalid DW_AT_alignment"
17014                        " - DIE at %s [in module %s]"),
17015                      sect_offset_str (die->sect_off),
17016                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17017         }
17018       else
17019         {
17020           /* Should we also complain about unhandled address classes?  */
17021         }
17022     }
17023
17024   TYPE_LENGTH (type) = byte_size;
17025   set_type_align (type, alignment);
17026   return set_die_type (die, type, cu);
17027 }
17028
17029 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17030    the user defined type vector.  */
17031
17032 static struct type *
17033 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17034 {
17035   struct type *type;
17036   struct type *to_type;
17037   struct type *domain;
17038
17039   to_type = die_type (die, cu);
17040   domain = die_containing_type (die, cu);
17041
17042   /* The calls above may have already set the type for this DIE.  */
17043   type = get_die_type (die, cu);
17044   if (type)
17045     return type;
17046
17047   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17048     type = lookup_methodptr_type (to_type);
17049   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17050     {
17051       struct type *new_type
17052         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17053
17054       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17055                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17056                             TYPE_VARARGS (to_type));
17057       type = lookup_methodptr_type (new_type);
17058     }
17059   else
17060     type = lookup_memberptr_type (to_type, domain);
17061
17062   return set_die_type (die, type, cu);
17063 }
17064
17065 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17066    the user defined type vector.  */
17067
17068 static struct type *
17069 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17070                           enum type_code refcode)
17071 {
17072   struct comp_unit_head *cu_header = &cu->header;
17073   struct type *type, *target_type;
17074   struct attribute *attr;
17075
17076   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17077
17078   target_type = die_type (die, cu);
17079
17080   /* The die_type call above may have already set the type for this DIE.  */
17081   type = get_die_type (die, cu);
17082   if (type)
17083     return type;
17084
17085   type = lookup_reference_type (target_type, refcode);
17086   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17087   if (attr)
17088     {
17089       TYPE_LENGTH (type) = DW_UNSND (attr);
17090     }
17091   else
17092     {
17093       TYPE_LENGTH (type) = cu_header->addr_size;
17094     }
17095   maybe_set_alignment (cu, die, type);
17096   return set_die_type (die, type, cu);
17097 }
17098
17099 /* Add the given cv-qualifiers to the element type of the array.  GCC
17100    outputs DWARF type qualifiers that apply to an array, not the
17101    element type.  But GDB relies on the array element type to carry
17102    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17103    specification.  */
17104
17105 static struct type *
17106 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17107                    struct type *base_type, int cnst, int voltl)
17108 {
17109   struct type *el_type, *inner_array;
17110
17111   base_type = copy_type (base_type);
17112   inner_array = base_type;
17113
17114   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17115     {
17116       TYPE_TARGET_TYPE (inner_array) =
17117         copy_type (TYPE_TARGET_TYPE (inner_array));
17118       inner_array = TYPE_TARGET_TYPE (inner_array);
17119     }
17120
17121   el_type = TYPE_TARGET_TYPE (inner_array);
17122   cnst |= TYPE_CONST (el_type);
17123   voltl |= TYPE_VOLATILE (el_type);
17124   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17125
17126   return set_die_type (die, base_type, cu);
17127 }
17128
17129 static struct type *
17130 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17131 {
17132   struct type *base_type, *cv_type;
17133
17134   base_type = die_type (die, cu);
17135
17136   /* The die_type call above may have already set the type for this DIE.  */
17137   cv_type = get_die_type (die, cu);
17138   if (cv_type)
17139     return cv_type;
17140
17141   /* In case the const qualifier is applied to an array type, the element type
17142      is so qualified, not the array type (section 6.7.3 of C99).  */
17143   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17144     return add_array_cv_type (die, cu, base_type, 1, 0);
17145
17146   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17147   return set_die_type (die, cv_type, cu);
17148 }
17149
17150 static struct type *
17151 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17152 {
17153   struct type *base_type, *cv_type;
17154
17155   base_type = die_type (die, cu);
17156
17157   /* The die_type call above may have already set the type for this DIE.  */
17158   cv_type = get_die_type (die, cu);
17159   if (cv_type)
17160     return cv_type;
17161
17162   /* In case the volatile qualifier is applied to an array type, the
17163      element type is so qualified, not the array type (section 6.7.3
17164      of C99).  */
17165   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17166     return add_array_cv_type (die, cu, base_type, 0, 1);
17167
17168   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17169   return set_die_type (die, cv_type, cu);
17170 }
17171
17172 /* Handle DW_TAG_restrict_type.  */
17173
17174 static struct type *
17175 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17176 {
17177   struct type *base_type, *cv_type;
17178
17179   base_type = die_type (die, cu);
17180
17181   /* The die_type call above may have already set the type for this DIE.  */
17182   cv_type = get_die_type (die, cu);
17183   if (cv_type)
17184     return cv_type;
17185
17186   cv_type = make_restrict_type (base_type);
17187   return set_die_type (die, cv_type, cu);
17188 }
17189
17190 /* Handle DW_TAG_atomic_type.  */
17191
17192 static struct type *
17193 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17194 {
17195   struct type *base_type, *cv_type;
17196
17197   base_type = die_type (die, cu);
17198
17199   /* The die_type call above may have already set the type for this DIE.  */
17200   cv_type = get_die_type (die, cu);
17201   if (cv_type)
17202     return cv_type;
17203
17204   cv_type = make_atomic_type (base_type);
17205   return set_die_type (die, cv_type, cu);
17206 }
17207
17208 /* Extract all information from a DW_TAG_string_type DIE and add to
17209    the user defined type vector.  It isn't really a user defined type,
17210    but it behaves like one, with other DIE's using an AT_user_def_type
17211    attribute to reference it.  */
17212
17213 static struct type *
17214 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17215 {
17216   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17217   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17218   struct type *type, *range_type, *index_type, *char_type;
17219   struct attribute *attr;
17220   unsigned int length;
17221
17222   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17223   if (attr)
17224     {
17225       length = DW_UNSND (attr);
17226     }
17227   else
17228     {
17229       /* Check for the DW_AT_byte_size attribute.  */
17230       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17231       if (attr)
17232         {
17233           length = DW_UNSND (attr);
17234         }
17235       else
17236         {
17237           length = 1;
17238         }
17239     }
17240
17241   index_type = objfile_type (objfile)->builtin_int;
17242   range_type = create_static_range_type (NULL, index_type, 1, length);
17243   char_type = language_string_char_type (cu->language_defn, gdbarch);
17244   type = create_string_type (NULL, char_type, range_type);
17245
17246   return set_die_type (die, type, cu);
17247 }
17248
17249 /* Assuming that DIE corresponds to a function, returns nonzero
17250    if the function is prototyped.  */
17251
17252 static int
17253 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17254 {
17255   struct attribute *attr;
17256
17257   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17258   if (attr && (DW_UNSND (attr) != 0))
17259     return 1;
17260
17261   /* The DWARF standard implies that the DW_AT_prototyped attribute
17262      is only meaninful for C, but the concept also extends to other
17263      languages that allow unprototyped functions (Eg: Objective C).
17264      For all other languages, assume that functions are always
17265      prototyped.  */
17266   if (cu->language != language_c
17267       && cu->language != language_objc
17268       && cu->language != language_opencl)
17269     return 1;
17270
17271   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17272      prototyped and unprototyped functions; default to prototyped,
17273      since that is more common in modern code (and RealView warns
17274      about unprototyped functions).  */
17275   if (producer_is_realview (cu->producer))
17276     return 1;
17277
17278   return 0;
17279 }
17280
17281 /* Handle DIES due to C code like:
17282
17283    struct foo
17284    {
17285    int (*funcp)(int a, long l);
17286    int b;
17287    };
17288
17289    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17290
17291 static struct type *
17292 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17293 {
17294   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17295   struct type *type;            /* Type that this function returns.  */
17296   struct type *ftype;           /* Function that returns above type.  */
17297   struct attribute *attr;
17298
17299   type = die_type (die, cu);
17300
17301   /* The die_type call above may have already set the type for this DIE.  */
17302   ftype = get_die_type (die, cu);
17303   if (ftype)
17304     return ftype;
17305
17306   ftype = lookup_function_type (type);
17307
17308   if (prototyped_function_p (die, cu))
17309     TYPE_PROTOTYPED (ftype) = 1;
17310
17311   /* Store the calling convention in the type if it's available in
17312      the subroutine die.  Otherwise set the calling convention to
17313      the default value DW_CC_normal.  */
17314   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17315   if (attr)
17316     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17317   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17318     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17319   else
17320     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17321
17322   /* Record whether the function returns normally to its caller or not
17323      if the DWARF producer set that information.  */
17324   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17325   if (attr && (DW_UNSND (attr) != 0))
17326     TYPE_NO_RETURN (ftype) = 1;
17327
17328   /* We need to add the subroutine type to the die immediately so
17329      we don't infinitely recurse when dealing with parameters
17330      declared as the same subroutine type.  */
17331   set_die_type (die, ftype, cu);
17332
17333   if (die->child != NULL)
17334     {
17335       struct type *void_type = objfile_type (objfile)->builtin_void;
17336       struct die_info *child_die;
17337       int nparams, iparams;
17338
17339       /* Count the number of parameters.
17340          FIXME: GDB currently ignores vararg functions, but knows about
17341          vararg member functions.  */
17342       nparams = 0;
17343       child_die = die->child;
17344       while (child_die && child_die->tag)
17345         {
17346           if (child_die->tag == DW_TAG_formal_parameter)
17347             nparams++;
17348           else if (child_die->tag == DW_TAG_unspecified_parameters)
17349             TYPE_VARARGS (ftype) = 1;
17350           child_die = sibling_die (child_die);
17351         }
17352
17353       /* Allocate storage for parameters and fill them in.  */
17354       TYPE_NFIELDS (ftype) = nparams;
17355       TYPE_FIELDS (ftype) = (struct field *)
17356         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17357
17358       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17359          even if we error out during the parameters reading below.  */
17360       for (iparams = 0; iparams < nparams; iparams++)
17361         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17362
17363       iparams = 0;
17364       child_die = die->child;
17365       while (child_die && child_die->tag)
17366         {
17367           if (child_die->tag == DW_TAG_formal_parameter)
17368             {
17369               struct type *arg_type;
17370
17371               /* DWARF version 2 has no clean way to discern C++
17372                  static and non-static member functions.  G++ helps
17373                  GDB by marking the first parameter for non-static
17374                  member functions (which is the this pointer) as
17375                  artificial.  We pass this information to
17376                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17377
17378                  DWARF version 3 added DW_AT_object_pointer, which GCC
17379                  4.5 does not yet generate.  */
17380               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17381               if (attr)
17382                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17383               else
17384                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17385               arg_type = die_type (child_die, cu);
17386
17387               /* RealView does not mark THIS as const, which the testsuite
17388                  expects.  GCC marks THIS as const in method definitions,
17389                  but not in the class specifications (GCC PR 43053).  */
17390               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17391                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17392                 {
17393                   int is_this = 0;
17394                   struct dwarf2_cu *arg_cu = cu;
17395                   const char *name = dwarf2_name (child_die, cu);
17396
17397                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17398                   if (attr)
17399                     {
17400                       /* If the compiler emits this, use it.  */
17401                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17402                         is_this = 1;
17403                     }
17404                   else if (name && strcmp (name, "this") == 0)
17405                     /* Function definitions will have the argument names.  */
17406                     is_this = 1;
17407                   else if (name == NULL && iparams == 0)
17408                     /* Declarations may not have the names, so like
17409                        elsewhere in GDB, assume an artificial first
17410                        argument is "this".  */
17411                     is_this = 1;
17412
17413                   if (is_this)
17414                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17415                                              arg_type, 0);
17416                 }
17417
17418               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17419               iparams++;
17420             }
17421           child_die = sibling_die (child_die);
17422         }
17423     }
17424
17425   return ftype;
17426 }
17427
17428 static struct type *
17429 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17430 {
17431   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17432   const char *name = NULL;
17433   struct type *this_type, *target_type;
17434
17435   name = dwarf2_full_name (NULL, die, cu);
17436   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17437   TYPE_TARGET_STUB (this_type) = 1;
17438   set_die_type (die, this_type, cu);
17439   target_type = die_type (die, cu);
17440   if (target_type != this_type)
17441     TYPE_TARGET_TYPE (this_type) = target_type;
17442   else
17443     {
17444       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17445          spec and cause infinite loops in GDB.  */
17446       complaint (_("Self-referential DW_TAG_typedef "
17447                    "- DIE at %s [in module %s]"),
17448                  sect_offset_str (die->sect_off), objfile_name (objfile));
17449       TYPE_TARGET_TYPE (this_type) = NULL;
17450     }
17451   return this_type;
17452 }
17453
17454 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17455    (which may be different from NAME) to the architecture back-end to allow
17456    it to guess the correct format if necessary.  */
17457
17458 static struct type *
17459 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17460                         const char *name_hint)
17461 {
17462   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17463   const struct floatformat **format;
17464   struct type *type;
17465
17466   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17467   if (format)
17468     type = init_float_type (objfile, bits, name, format);
17469   else
17470     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17471
17472   return type;
17473 }
17474
17475 /* Allocate an integer type of size BITS and name NAME.  */
17476
17477 static struct type *
17478 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17479                           int bits, int unsigned_p, const char *name)
17480 {
17481   struct type *type;
17482
17483   /* Versions of Intel's C Compiler generate an integer type called "void"
17484      instead of using DW_TAG_unspecified_type.  This has been seen on
17485      at least versions 14, 17, and 18.  */
17486   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17487       && strcmp (name, "void") == 0)
17488     type = objfile_type (objfile)->builtin_void;
17489   else
17490     type = init_integer_type (objfile, bits, unsigned_p, name);
17491
17492   return type;
17493 }
17494
17495 /* Initialise and return a floating point type of size BITS suitable for
17496    use as a component of a complex number.  The NAME_HINT is passed through
17497    when initialising the floating point type and is the name of the complex
17498    type.
17499
17500    As DWARF doesn't currently provide an explicit name for the components
17501    of a complex number, but it can be helpful to have these components
17502    named, we try to select a suitable name based on the size of the
17503    component.  */
17504 static struct type *
17505 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17506                                  struct objfile *objfile,
17507                                  int bits, const char *name_hint)
17508 {
17509   gdbarch *gdbarch = get_objfile_arch (objfile);
17510   struct type *tt = nullptr;
17511
17512   /* Try to find a suitable floating point builtin type of size BITS.
17513      We're going to use the name of this type as the name for the complex
17514      target type that we are about to create.  */
17515   switch (cu->language)
17516     {
17517     case language_fortran:
17518       switch (bits)
17519         {
17520         case 32:
17521           tt = builtin_f_type (gdbarch)->builtin_real;
17522           break;
17523         case 64:
17524           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17525           break;
17526         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17527         case 128:
17528           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17529           break;
17530         }
17531       break;
17532     default:
17533       switch (bits)
17534         {
17535         case 32:
17536           tt = builtin_type (gdbarch)->builtin_float;
17537           break;
17538         case 64:
17539           tt = builtin_type (gdbarch)->builtin_double;
17540           break;
17541         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17542         case 128:
17543           tt = builtin_type (gdbarch)->builtin_long_double;
17544           break;
17545         }
17546       break;
17547     }
17548
17549   /* If the type we found doesn't match the size we were looking for, then
17550      pretend we didn't find a type at all, the complex target type we
17551      create will then be nameless.  */
17552   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17553     tt = nullptr;
17554
17555   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
17556   return dwarf2_init_float_type (objfile, bits, name, name_hint);
17557 }
17558
17559 /* Find a representation of a given base type and install
17560    it in the TYPE field of the die.  */
17561
17562 static struct type *
17563 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17564 {
17565   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17566   struct type *type;
17567   struct attribute *attr;
17568   int encoding = 0, bits = 0;
17569   const char *name;
17570
17571   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17572   if (attr)
17573     {
17574       encoding = DW_UNSND (attr);
17575     }
17576   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17577   if (attr)
17578     {
17579       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17580     }
17581   name = dwarf2_name (die, cu);
17582   if (!name)
17583     {
17584       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17585     }
17586
17587   switch (encoding)
17588     {
17589       case DW_ATE_address:
17590         /* Turn DW_ATE_address into a void * pointer.  */
17591         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17592         type = init_pointer_type (objfile, bits, name, type);
17593         break;
17594       case DW_ATE_boolean:
17595         type = init_boolean_type (objfile, bits, 1, name);
17596         break;
17597       case DW_ATE_complex_float:
17598         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name);
17599         type = init_complex_type (objfile, name, type);
17600         break;
17601       case DW_ATE_decimal_float:
17602         type = init_decfloat_type (objfile, bits, name);
17603         break;
17604       case DW_ATE_float:
17605         type = dwarf2_init_float_type (objfile, bits, name, name);
17606         break;
17607       case DW_ATE_signed:
17608         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17609         break;
17610       case DW_ATE_unsigned:
17611         if (cu->language == language_fortran
17612             && name
17613             && startswith (name, "character("))
17614           type = init_character_type (objfile, bits, 1, name);
17615         else
17616           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17617         break;
17618       case DW_ATE_signed_char:
17619         if (cu->language == language_ada || cu->language == language_m2
17620             || cu->language == language_pascal
17621             || cu->language == language_fortran)
17622           type = init_character_type (objfile, bits, 0, name);
17623         else
17624           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17625         break;
17626       case DW_ATE_unsigned_char:
17627         if (cu->language == language_ada || cu->language == language_m2
17628             || cu->language == language_pascal
17629             || cu->language == language_fortran
17630             || cu->language == language_rust)
17631           type = init_character_type (objfile, bits, 1, name);
17632         else
17633           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17634         break;
17635       case DW_ATE_UTF:
17636         {
17637           gdbarch *arch = get_objfile_arch (objfile);
17638
17639           if (bits == 16)
17640             type = builtin_type (arch)->builtin_char16;
17641           else if (bits == 32)
17642             type = builtin_type (arch)->builtin_char32;
17643           else
17644             {
17645               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17646                          bits);
17647               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17648             }
17649           return set_die_type (die, type, cu);
17650         }
17651         break;
17652
17653       default:
17654         complaint (_("unsupported DW_AT_encoding: '%s'"),
17655                    dwarf_type_encoding_name (encoding));
17656         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17657         break;
17658     }
17659
17660   if (name && strcmp (name, "char") == 0)
17661     TYPE_NOSIGN (type) = 1;
17662
17663   maybe_set_alignment (cu, die, type);
17664
17665   return set_die_type (die, type, cu);
17666 }
17667
17668 /* Parse dwarf attribute if it's a block, reference or constant and put the
17669    resulting value of the attribute into struct bound_prop.
17670    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17671
17672 static int
17673 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17674                       struct dwarf2_cu *cu, struct dynamic_prop *prop,
17675                       struct type *default_type)
17676 {
17677   struct dwarf2_property_baton *baton;
17678   struct obstack *obstack
17679     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17680
17681   gdb_assert (default_type != NULL);
17682
17683   if (attr == NULL || prop == NULL)
17684     return 0;
17685
17686   if (attr_form_is_block (attr))
17687     {
17688       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17689       baton->property_type = default_type;
17690       baton->locexpr.per_cu = cu->per_cu;
17691       baton->locexpr.size = DW_BLOCK (attr)->size;
17692       baton->locexpr.data = DW_BLOCK (attr)->data;
17693       baton->locexpr.is_reference = false;
17694       prop->data.baton = baton;
17695       prop->kind = PROP_LOCEXPR;
17696       gdb_assert (prop->data.baton != NULL);
17697     }
17698   else if (attr_form_is_ref (attr))
17699     {
17700       struct dwarf2_cu *target_cu = cu;
17701       struct die_info *target_die;
17702       struct attribute *target_attr;
17703
17704       target_die = follow_die_ref (die, attr, &target_cu);
17705       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17706       if (target_attr == NULL)
17707         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17708                                    target_cu);
17709       if (target_attr == NULL)
17710         return 0;
17711
17712       switch (target_attr->name)
17713         {
17714           case DW_AT_location:
17715             if (attr_form_is_section_offset (target_attr))
17716               {
17717                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17718                 baton->property_type = die_type (target_die, target_cu);
17719                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17720                 prop->data.baton = baton;
17721                 prop->kind = PROP_LOCLIST;
17722                 gdb_assert (prop->data.baton != NULL);
17723               }
17724             else if (attr_form_is_block (target_attr))
17725               {
17726                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17727                 baton->property_type = die_type (target_die, target_cu);
17728                 baton->locexpr.per_cu = cu->per_cu;
17729                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17730                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17731                 baton->locexpr.is_reference = true;
17732                 prop->data.baton = baton;
17733                 prop->kind = PROP_LOCEXPR;
17734                 gdb_assert (prop->data.baton != NULL);
17735               }
17736             else
17737               {
17738                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17739                                                        "dynamic property");
17740                 return 0;
17741               }
17742             break;
17743           case DW_AT_data_member_location:
17744             {
17745               LONGEST offset;
17746
17747               if (!handle_data_member_location (target_die, target_cu,
17748                                                 &offset))
17749                 return 0;
17750
17751               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17752               baton->property_type = read_type_die (target_die->parent,
17753                                                       target_cu);
17754               baton->offset_info.offset = offset;
17755               baton->offset_info.type = die_type (target_die, target_cu);
17756               prop->data.baton = baton;
17757               prop->kind = PROP_ADDR_OFFSET;
17758               break;
17759             }
17760         }
17761     }
17762   else if (attr_form_is_constant (attr))
17763     {
17764       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17765       prop->kind = PROP_CONST;
17766     }
17767   else
17768     {
17769       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17770                                              dwarf2_name (die, cu));
17771       return 0;
17772     }
17773
17774   return 1;
17775 }
17776
17777 /* Find an integer type the same size as the address size given in the
17778    compilation unit header for PER_CU.  UNSIGNED_P controls if the integer
17779    is unsigned or not.  */
17780
17781 static struct type *
17782 dwarf2_per_cu_addr_sized_int_type (struct dwarf2_per_cu_data *per_cu,
17783                                    bool unsigned_p)
17784 {
17785   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
17786   int addr_size = dwarf2_per_cu_addr_size (per_cu);
17787   struct type *int_type;
17788
17789   /* Helper macro to examine the various builtin types.  */
17790 #define TRY_TYPE(F)                                             \
17791   int_type = (unsigned_p                                        \
17792               ? objfile_type (objfile)->builtin_unsigned_ ## F  \
17793               : objfile_type (objfile)->builtin_ ## F);         \
17794   if (int_type != NULL && TYPE_LENGTH (int_type) == addr_size)  \
17795     return int_type
17796
17797   TRY_TYPE (char);
17798   TRY_TYPE (short);
17799   TRY_TYPE (int);
17800   TRY_TYPE (long);
17801   TRY_TYPE (long_long);
17802
17803 #undef TRY_TYPE
17804
17805   gdb_assert_not_reached ("unable to find suitable integer type");
17806 }
17807
17808 /* Read the DW_AT_type attribute for a sub-range.  If this attribute is not
17809    present (which is valid) then compute the default type based on the
17810    compilation units address size.  */
17811
17812 static struct type *
17813 read_subrange_index_type (struct die_info *die, struct dwarf2_cu *cu)
17814 {
17815   struct type *index_type = die_type (die, cu);
17816
17817   /* Dwarf-2 specifications explicitly allows to create subrange types
17818      without specifying a base type.
17819      In that case, the base type must be set to the type of
17820      the lower bound, upper bound or count, in that order, if any of these
17821      three attributes references an object that has a type.
17822      If no base type is found, the Dwarf-2 specifications say that
17823      a signed integer type of size equal to the size of an address should
17824      be used.
17825      For the following C code: `extern char gdb_int [];'
17826      GCC produces an empty range DIE.
17827      FIXME: muller/2010-05-28: Possible references to object for low bound,
17828      high bound or count are not yet handled by this code.  */
17829   if (TYPE_CODE (index_type) == TYPE_CODE_VOID)
17830     index_type = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
17831
17832   return index_type;
17833 }
17834
17835 /* Read the given DW_AT_subrange DIE.  */
17836
17837 static struct type *
17838 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17839 {
17840   struct type *base_type, *orig_base_type;
17841   struct type *range_type;
17842   struct attribute *attr;
17843   struct dynamic_prop low, high;
17844   int low_default_is_valid;
17845   int high_bound_is_count = 0;
17846   const char *name;
17847   ULONGEST negative_mask;
17848
17849   orig_base_type = read_subrange_index_type (die, cu);
17850
17851   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17852      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17853      creating the range type, but we use the result of check_typedef
17854      when examining properties of the type.  */
17855   base_type = check_typedef (orig_base_type);
17856
17857   /* The die_type call above may have already set the type for this DIE.  */
17858   range_type = get_die_type (die, cu);
17859   if (range_type)
17860     return range_type;
17861
17862   low.kind = PROP_CONST;
17863   high.kind = PROP_CONST;
17864   high.data.const_val = 0;
17865
17866   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17867      omitting DW_AT_lower_bound.  */
17868   switch (cu->language)
17869     {
17870     case language_c:
17871     case language_cplus:
17872       low.data.const_val = 0;
17873       low_default_is_valid = 1;
17874       break;
17875     case language_fortran:
17876       low.data.const_val = 1;
17877       low_default_is_valid = 1;
17878       break;
17879     case language_d:
17880     case language_objc:
17881     case language_rust:
17882       low.data.const_val = 0;
17883       low_default_is_valid = (cu->header.version >= 4);
17884       break;
17885     case language_ada:
17886     case language_m2:
17887     case language_pascal:
17888       low.data.const_val = 1;
17889       low_default_is_valid = (cu->header.version >= 4);
17890       break;
17891     default:
17892       low.data.const_val = 0;
17893       low_default_is_valid = 0;
17894       break;
17895     }
17896
17897   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17898   if (attr)
17899     attr_to_dynamic_prop (attr, die, cu, &low, base_type);
17900   else if (!low_default_is_valid)
17901     complaint (_("Missing DW_AT_lower_bound "
17902                                       "- DIE at %s [in module %s]"),
17903                sect_offset_str (die->sect_off),
17904                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17905
17906   struct attribute *attr_ub, *attr_count;
17907   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17908   if (!attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17909     {
17910       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17911       if (attr_to_dynamic_prop (attr, die, cu, &high, base_type))
17912         {
17913           /* If bounds are constant do the final calculation here.  */
17914           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17915             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17916           else
17917             high_bound_is_count = 1;
17918         }
17919       else
17920         {
17921           if (attr_ub != NULL)
17922             complaint (_("Unresolved DW_AT_upper_bound "
17923                          "- DIE at %s [in module %s]"),
17924                        sect_offset_str (die->sect_off),
17925                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17926           if (attr_count != NULL)
17927             complaint (_("Unresolved DW_AT_count "
17928                          "- DIE at %s [in module %s]"),
17929                        sect_offset_str (die->sect_off),
17930                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17931         }
17932     }
17933
17934   LONGEST bias = 0;
17935   struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu);
17936   if (bias_attr != nullptr && attr_form_is_constant (bias_attr))
17937     bias = dwarf2_get_attr_constant_value (bias_attr, 0);
17938
17939   /* Normally, the DWARF producers are expected to use a signed
17940      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17941      But this is unfortunately not always the case, as witnessed
17942      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17943      is used instead.  To work around that ambiguity, we treat
17944      the bounds as signed, and thus sign-extend their values, when
17945      the base type is signed.  */
17946   negative_mask =
17947     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17948   if (low.kind == PROP_CONST
17949       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17950     low.data.const_val |= negative_mask;
17951   if (high.kind == PROP_CONST
17952       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17953     high.data.const_val |= negative_mask;
17954
17955   range_type = create_range_type (NULL, orig_base_type, &low, &high, bias);
17956
17957   if (high_bound_is_count)
17958     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17959
17960   /* Ada expects an empty array on no boundary attributes.  */
17961   if (attr == NULL && cu->language != language_ada)
17962     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17963
17964   name = dwarf2_name (die, cu);
17965   if (name)
17966     TYPE_NAME (range_type) = name;
17967
17968   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17969   if (attr)
17970     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17971
17972   maybe_set_alignment (cu, die, range_type);
17973
17974   set_die_type (die, range_type, cu);
17975
17976   /* set_die_type should be already done.  */
17977   set_descriptive_type (range_type, die, cu);
17978
17979   return range_type;
17980 }
17981
17982 static struct type *
17983 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17984 {
17985   struct type *type;
17986
17987   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17988                     NULL);
17989   TYPE_NAME (type) = dwarf2_name (die, cu);
17990
17991   /* In Ada, an unspecified type is typically used when the description
17992      of the type is defered to a different unit.  When encountering
17993      such a type, we treat it as a stub, and try to resolve it later on,
17994      when needed.  */
17995   if (cu->language == language_ada)
17996     TYPE_STUB (type) = 1;
17997
17998   return set_die_type (die, type, cu);
17999 }
18000
18001 /* Read a single die and all its descendents.  Set the die's sibling
18002    field to NULL; set other fields in the die correctly, and set all
18003    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18004    location of the info_ptr after reading all of those dies.  PARENT
18005    is the parent of the die in question.  */
18006
18007 static struct die_info *
18008 read_die_and_children (const struct die_reader_specs *reader,
18009                        const gdb_byte *info_ptr,
18010                        const gdb_byte **new_info_ptr,
18011                        struct die_info *parent)
18012 {
18013   struct die_info *die;
18014   const gdb_byte *cur_ptr;
18015   int has_children;
18016
18017   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
18018   if (die == NULL)
18019     {
18020       *new_info_ptr = cur_ptr;
18021       return NULL;
18022     }
18023   store_in_ref_table (die, reader->cu);
18024
18025   if (has_children)
18026     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18027   else
18028     {
18029       die->child = NULL;
18030       *new_info_ptr = cur_ptr;
18031     }
18032
18033   die->sibling = NULL;
18034   die->parent = parent;
18035   return die;
18036 }
18037
18038 /* Read a die, all of its descendents, and all of its siblings; set
18039    all of the fields of all of the dies correctly.  Arguments are as
18040    in read_die_and_children.  */
18041
18042 static struct die_info *
18043 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18044                          const gdb_byte *info_ptr,
18045                          const gdb_byte **new_info_ptr,
18046                          struct die_info *parent)
18047 {
18048   struct die_info *first_die, *last_sibling;
18049   const gdb_byte *cur_ptr;
18050
18051   cur_ptr = info_ptr;
18052   first_die = last_sibling = NULL;
18053
18054   while (1)
18055     {
18056       struct die_info *die
18057         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18058
18059       if (die == NULL)
18060         {
18061           *new_info_ptr = cur_ptr;
18062           return first_die;
18063         }
18064
18065       if (!first_die)
18066         first_die = die;
18067       else
18068         last_sibling->sibling = die;
18069
18070       last_sibling = die;
18071     }
18072 }
18073
18074 /* Read a die, all of its descendents, and all of its siblings; set
18075    all of the fields of all of the dies correctly.  Arguments are as
18076    in read_die_and_children.
18077    This the main entry point for reading a DIE and all its children.  */
18078
18079 static struct die_info *
18080 read_die_and_siblings (const struct die_reader_specs *reader,
18081                        const gdb_byte *info_ptr,
18082                        const gdb_byte **new_info_ptr,
18083                        struct die_info *parent)
18084 {
18085   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18086                                                   new_info_ptr, parent);
18087
18088   if (dwarf_die_debug)
18089     {
18090       fprintf_unfiltered (gdb_stdlog,
18091                           "Read die from %s@0x%x of %s:\n",
18092                           get_section_name (reader->die_section),
18093                           (unsigned) (info_ptr - reader->die_section->buffer),
18094                           bfd_get_filename (reader->abfd));
18095       dump_die (die, dwarf_die_debug);
18096     }
18097
18098   return die;
18099 }
18100
18101 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18102    attributes.
18103    The caller is responsible for filling in the extra attributes
18104    and updating (*DIEP)->num_attrs.
18105    Set DIEP to point to a newly allocated die with its information,
18106    except for its child, sibling, and parent fields.
18107    Set HAS_CHILDREN to tell whether the die has children or not.  */
18108
18109 static const gdb_byte *
18110 read_full_die_1 (const struct die_reader_specs *reader,
18111                  struct die_info **diep, const gdb_byte *info_ptr,
18112                  int *has_children, int num_extra_attrs)
18113 {
18114   unsigned int abbrev_number, bytes_read, i;
18115   struct abbrev_info *abbrev;
18116   struct die_info *die;
18117   struct dwarf2_cu *cu = reader->cu;
18118   bfd *abfd = reader->abfd;
18119
18120   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18121   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18122   info_ptr += bytes_read;
18123   if (!abbrev_number)
18124     {
18125       *diep = NULL;
18126       *has_children = 0;
18127       return info_ptr;
18128     }
18129
18130   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18131   if (!abbrev)
18132     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18133            abbrev_number,
18134            bfd_get_filename (abfd));
18135
18136   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18137   die->sect_off = sect_off;
18138   die->tag = abbrev->tag;
18139   die->abbrev = abbrev_number;
18140
18141   /* Make the result usable.
18142      The caller needs to update num_attrs after adding the extra
18143      attributes.  */
18144   die->num_attrs = abbrev->num_attrs;
18145
18146   for (i = 0; i < abbrev->num_attrs; ++i)
18147     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18148                                info_ptr);
18149
18150   *diep = die;
18151   *has_children = abbrev->has_children;
18152   return info_ptr;
18153 }
18154
18155 /* Read a die and all its attributes.
18156    Set DIEP to point to a newly allocated die with its information,
18157    except for its child, sibling, and parent fields.
18158    Set HAS_CHILDREN to tell whether the die has children or not.  */
18159
18160 static const gdb_byte *
18161 read_full_die (const struct die_reader_specs *reader,
18162                struct die_info **diep, const gdb_byte *info_ptr,
18163                int *has_children)
18164 {
18165   const gdb_byte *result;
18166
18167   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18168
18169   if (dwarf_die_debug)
18170     {
18171       fprintf_unfiltered (gdb_stdlog,
18172                           "Read die from %s@0x%x of %s:\n",
18173                           get_section_name (reader->die_section),
18174                           (unsigned) (info_ptr - reader->die_section->buffer),
18175                           bfd_get_filename (reader->abfd));
18176       dump_die (*diep, dwarf_die_debug);
18177     }
18178
18179   return result;
18180 }
18181 \f
18182 /* Abbreviation tables.
18183
18184    In DWARF version 2, the description of the debugging information is
18185    stored in a separate .debug_abbrev section.  Before we read any
18186    dies from a section we read in all abbreviations and install them
18187    in a hash table.  */
18188
18189 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18190
18191 struct abbrev_info *
18192 abbrev_table::alloc_abbrev ()
18193 {
18194   struct abbrev_info *abbrev;
18195
18196   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18197   memset (abbrev, 0, sizeof (struct abbrev_info));
18198
18199   return abbrev;
18200 }
18201
18202 /* Add an abbreviation to the table.  */
18203
18204 void
18205 abbrev_table::add_abbrev (unsigned int abbrev_number,
18206                           struct abbrev_info *abbrev)
18207 {
18208   unsigned int hash_number;
18209
18210   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18211   abbrev->next = m_abbrevs[hash_number];
18212   m_abbrevs[hash_number] = abbrev;
18213 }
18214
18215 /* Look up an abbrev in the table.
18216    Returns NULL if the abbrev is not found.  */
18217
18218 struct abbrev_info *
18219 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18220 {
18221   unsigned int hash_number;
18222   struct abbrev_info *abbrev;
18223
18224   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18225   abbrev = m_abbrevs[hash_number];
18226
18227   while (abbrev)
18228     {
18229       if (abbrev->number == abbrev_number)
18230         return abbrev;
18231       abbrev = abbrev->next;
18232     }
18233   return NULL;
18234 }
18235
18236 /* Read in an abbrev table.  */
18237
18238 static abbrev_table_up
18239 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18240                          struct dwarf2_section_info *section,
18241                          sect_offset sect_off)
18242 {
18243   struct objfile *objfile = dwarf2_per_objfile->objfile;
18244   bfd *abfd = get_section_bfd_owner (section);
18245   const gdb_byte *abbrev_ptr;
18246   struct abbrev_info *cur_abbrev;
18247   unsigned int abbrev_number, bytes_read, abbrev_name;
18248   unsigned int abbrev_form;
18249   struct attr_abbrev *cur_attrs;
18250   unsigned int allocated_attrs;
18251
18252   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18253
18254   dwarf2_read_section (objfile, section);
18255   abbrev_ptr = section->buffer + to_underlying (sect_off);
18256   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18257   abbrev_ptr += bytes_read;
18258
18259   allocated_attrs = ATTR_ALLOC_CHUNK;
18260   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18261
18262   /* Loop until we reach an abbrev number of 0.  */
18263   while (abbrev_number)
18264     {
18265       cur_abbrev = abbrev_table->alloc_abbrev ();
18266
18267       /* read in abbrev header */
18268       cur_abbrev->number = abbrev_number;
18269       cur_abbrev->tag
18270         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18271       abbrev_ptr += bytes_read;
18272       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18273       abbrev_ptr += 1;
18274
18275       /* now read in declarations */
18276       for (;;)
18277         {
18278           LONGEST implicit_const;
18279
18280           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18281           abbrev_ptr += bytes_read;
18282           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18283           abbrev_ptr += bytes_read;
18284           if (abbrev_form == DW_FORM_implicit_const)
18285             {
18286               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18287                                                    &bytes_read);
18288               abbrev_ptr += bytes_read;
18289             }
18290           else
18291             {
18292               /* Initialize it due to a false compiler warning.  */
18293               implicit_const = -1;
18294             }
18295
18296           if (abbrev_name == 0)
18297             break;
18298
18299           if (cur_abbrev->num_attrs == allocated_attrs)
18300             {
18301               allocated_attrs += ATTR_ALLOC_CHUNK;
18302               cur_attrs
18303                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18304             }
18305
18306           cur_attrs[cur_abbrev->num_attrs].name
18307             = (enum dwarf_attribute) abbrev_name;
18308           cur_attrs[cur_abbrev->num_attrs].form
18309             = (enum dwarf_form) abbrev_form;
18310           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18311           ++cur_abbrev->num_attrs;
18312         }
18313
18314       cur_abbrev->attrs =
18315         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18316                    cur_abbrev->num_attrs);
18317       memcpy (cur_abbrev->attrs, cur_attrs,
18318               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18319
18320       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18321
18322       /* Get next abbreviation.
18323          Under Irix6 the abbreviations for a compilation unit are not
18324          always properly terminated with an abbrev number of 0.
18325          Exit loop if we encounter an abbreviation which we have
18326          already read (which means we are about to read the abbreviations
18327          for the next compile unit) or if the end of the abbreviation
18328          table is reached.  */
18329       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18330         break;
18331       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18332       abbrev_ptr += bytes_read;
18333       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18334         break;
18335     }
18336
18337   xfree (cur_attrs);
18338   return abbrev_table;
18339 }
18340
18341 /* Returns nonzero if TAG represents a type that we might generate a partial
18342    symbol for.  */
18343
18344 static int
18345 is_type_tag_for_partial (int tag)
18346 {
18347   switch (tag)
18348     {
18349 #if 0
18350     /* Some types that would be reasonable to generate partial symbols for,
18351        that we don't at present.  */
18352     case DW_TAG_array_type:
18353     case DW_TAG_file_type:
18354     case DW_TAG_ptr_to_member_type:
18355     case DW_TAG_set_type:
18356     case DW_TAG_string_type:
18357     case DW_TAG_subroutine_type:
18358 #endif
18359     case DW_TAG_base_type:
18360     case DW_TAG_class_type:
18361     case DW_TAG_interface_type:
18362     case DW_TAG_enumeration_type:
18363     case DW_TAG_structure_type:
18364     case DW_TAG_subrange_type:
18365     case DW_TAG_typedef:
18366     case DW_TAG_union_type:
18367       return 1;
18368     default:
18369       return 0;
18370     }
18371 }
18372
18373 /* Load all DIEs that are interesting for partial symbols into memory.  */
18374
18375 static struct partial_die_info *
18376 load_partial_dies (const struct die_reader_specs *reader,
18377                    const gdb_byte *info_ptr, int building_psymtab)
18378 {
18379   struct dwarf2_cu *cu = reader->cu;
18380   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18381   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18382   unsigned int bytes_read;
18383   unsigned int load_all = 0;
18384   int nesting_level = 1;
18385
18386   parent_die = NULL;
18387   last_die = NULL;
18388
18389   gdb_assert (cu->per_cu != NULL);
18390   if (cu->per_cu->load_all_dies)
18391     load_all = 1;
18392
18393   cu->partial_dies
18394     = htab_create_alloc_ex (cu->header.length / 12,
18395                             partial_die_hash,
18396                             partial_die_eq,
18397                             NULL,
18398                             &cu->comp_unit_obstack,
18399                             hashtab_obstack_allocate,
18400                             dummy_obstack_deallocate);
18401
18402   while (1)
18403     {
18404       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18405
18406       /* A NULL abbrev means the end of a series of children.  */
18407       if (abbrev == NULL)
18408         {
18409           if (--nesting_level == 0)
18410             return first_die;
18411
18412           info_ptr += bytes_read;
18413           last_die = parent_die;
18414           parent_die = parent_die->die_parent;
18415           continue;
18416         }
18417
18418       /* Check for template arguments.  We never save these; if
18419          they're seen, we just mark the parent, and go on our way.  */
18420       if (parent_die != NULL
18421           && cu->language == language_cplus
18422           && (abbrev->tag == DW_TAG_template_type_param
18423               || abbrev->tag == DW_TAG_template_value_param))
18424         {
18425           parent_die->has_template_arguments = 1;
18426
18427           if (!load_all)
18428             {
18429               /* We don't need a partial DIE for the template argument.  */
18430               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18431               continue;
18432             }
18433         }
18434
18435       /* We only recurse into c++ subprograms looking for template arguments.
18436          Skip their other children.  */
18437       if (!load_all
18438           && cu->language == language_cplus
18439           && parent_die != NULL
18440           && parent_die->tag == DW_TAG_subprogram)
18441         {
18442           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18443           continue;
18444         }
18445
18446       /* Check whether this DIE is interesting enough to save.  Normally
18447          we would not be interested in members here, but there may be
18448          later variables referencing them via DW_AT_specification (for
18449          static members).  */
18450       if (!load_all
18451           && !is_type_tag_for_partial (abbrev->tag)
18452           && abbrev->tag != DW_TAG_constant
18453           && abbrev->tag != DW_TAG_enumerator
18454           && abbrev->tag != DW_TAG_subprogram
18455           && abbrev->tag != DW_TAG_inlined_subroutine
18456           && abbrev->tag != DW_TAG_lexical_block
18457           && abbrev->tag != DW_TAG_variable
18458           && abbrev->tag != DW_TAG_namespace
18459           && abbrev->tag != DW_TAG_module
18460           && abbrev->tag != DW_TAG_member
18461           && abbrev->tag != DW_TAG_imported_unit
18462           && abbrev->tag != DW_TAG_imported_declaration)
18463         {
18464           /* Otherwise we skip to the next sibling, if any.  */
18465           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18466           continue;
18467         }
18468
18469       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18470                                    abbrev);
18471
18472       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18473
18474       /* This two-pass algorithm for processing partial symbols has a
18475          high cost in cache pressure.  Thus, handle some simple cases
18476          here which cover the majority of C partial symbols.  DIEs
18477          which neither have specification tags in them, nor could have
18478          specification tags elsewhere pointing at them, can simply be
18479          processed and discarded.
18480
18481          This segment is also optional; scan_partial_symbols and
18482          add_partial_symbol will handle these DIEs if we chain
18483          them in normally.  When compilers which do not emit large
18484          quantities of duplicate debug information are more common,
18485          this code can probably be removed.  */
18486
18487       /* Any complete simple types at the top level (pretty much all
18488          of them, for a language without namespaces), can be processed
18489          directly.  */
18490       if (parent_die == NULL
18491           && pdi.has_specification == 0
18492           && pdi.is_declaration == 0
18493           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18494               || pdi.tag == DW_TAG_base_type
18495               || pdi.tag == DW_TAG_subrange_type))
18496         {
18497           if (building_psymtab && pdi.name != NULL)
18498             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18499                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18500                                  psymbol_placement::STATIC,
18501                                  0, cu->language, objfile);
18502           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18503           continue;
18504         }
18505
18506       /* The exception for DW_TAG_typedef with has_children above is
18507          a workaround of GCC PR debug/47510.  In the case of this complaint
18508          type_name_or_error will error on such types later.
18509
18510          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18511          it could not find the child DIEs referenced later, this is checked
18512          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18513
18514       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18515         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18516                      "- DIE at %s [in module %s]"),
18517                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18518
18519       /* If we're at the second level, and we're an enumerator, and
18520          our parent has no specification (meaning possibly lives in a
18521          namespace elsewhere), then we can add the partial symbol now
18522          instead of queueing it.  */
18523       if (pdi.tag == DW_TAG_enumerator
18524           && parent_die != NULL
18525           && parent_die->die_parent == NULL
18526           && parent_die->tag == DW_TAG_enumeration_type
18527           && parent_die->has_specification == 0)
18528         {
18529           if (pdi.name == NULL)
18530             complaint (_("malformed enumerator DIE ignored"));
18531           else if (building_psymtab)
18532             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18533                                  VAR_DOMAIN, LOC_CONST, -1,
18534                                  cu->language == language_cplus
18535                                  ? psymbol_placement::GLOBAL
18536                                  : psymbol_placement::STATIC,
18537                                  0, cu->language, objfile);
18538
18539           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18540           continue;
18541         }
18542
18543       struct partial_die_info *part_die
18544         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18545
18546       /* We'll save this DIE so link it in.  */
18547       part_die->die_parent = parent_die;
18548       part_die->die_sibling = NULL;
18549       part_die->die_child = NULL;
18550
18551       if (last_die && last_die == parent_die)
18552         last_die->die_child = part_die;
18553       else if (last_die)
18554         last_die->die_sibling = part_die;
18555
18556       last_die = part_die;
18557
18558       if (first_die == NULL)
18559         first_die = part_die;
18560
18561       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18562          find interesting need to be in the hash table, because we
18563          also have the parent/sibling/child chains; only those that we
18564          might refer to by offset later during partial symbol reading.
18565
18566          For now this means things that might have be the target of a
18567          DW_AT_specification, DW_AT_abstract_origin, or
18568          DW_AT_extension.  DW_AT_extension will refer only to
18569          namespaces; DW_AT_abstract_origin refers to functions (and
18570          many things under the function DIE, but we do not recurse
18571          into function DIEs during partial symbol reading) and
18572          possibly variables as well; DW_AT_specification refers to
18573          declarations.  Declarations ought to have the DW_AT_declaration
18574          flag.  It happens that GCC forgets to put it in sometimes, but
18575          only for functions, not for types.
18576
18577          Adding more things than necessary to the hash table is harmless
18578          except for the performance cost.  Adding too few will result in
18579          wasted time in find_partial_die, when we reread the compilation
18580          unit with load_all_dies set.  */
18581
18582       if (load_all
18583           || abbrev->tag == DW_TAG_constant
18584           || abbrev->tag == DW_TAG_subprogram
18585           || abbrev->tag == DW_TAG_variable
18586           || abbrev->tag == DW_TAG_namespace
18587           || part_die->is_declaration)
18588         {
18589           void **slot;
18590
18591           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18592                                            to_underlying (part_die->sect_off),
18593                                            INSERT);
18594           *slot = part_die;
18595         }
18596
18597       /* For some DIEs we want to follow their children (if any).  For C
18598          we have no reason to follow the children of structures; for other
18599          languages we have to, so that we can get at method physnames
18600          to infer fully qualified class names, for DW_AT_specification,
18601          and for C++ template arguments.  For C++, we also look one level
18602          inside functions to find template arguments (if the name of the
18603          function does not already contain the template arguments).
18604
18605          For Ada, we need to scan the children of subprograms and lexical
18606          blocks as well because Ada allows the definition of nested
18607          entities that could be interesting for the debugger, such as
18608          nested subprograms for instance.  */
18609       if (last_die->has_children
18610           && (load_all
18611               || last_die->tag == DW_TAG_namespace
18612               || last_die->tag == DW_TAG_module
18613               || last_die->tag == DW_TAG_enumeration_type
18614               || (cu->language == language_cplus
18615                   && last_die->tag == DW_TAG_subprogram
18616                   && (last_die->name == NULL
18617                       || strchr (last_die->name, '<') == NULL))
18618               || (cu->language != language_c
18619                   && (last_die->tag == DW_TAG_class_type
18620                       || last_die->tag == DW_TAG_interface_type
18621                       || last_die->tag == DW_TAG_structure_type
18622                       || last_die->tag == DW_TAG_union_type))
18623               || (cu->language == language_ada
18624                   && (last_die->tag == DW_TAG_subprogram
18625                       || last_die->tag == DW_TAG_lexical_block))))
18626         {
18627           nesting_level++;
18628           parent_die = last_die;
18629           continue;
18630         }
18631
18632       /* Otherwise we skip to the next sibling, if any.  */
18633       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18634
18635       /* Back to the top, do it again.  */
18636     }
18637 }
18638
18639 partial_die_info::partial_die_info (sect_offset sect_off_,
18640                                     struct abbrev_info *abbrev)
18641   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18642 {
18643 }
18644
18645 /* Read a minimal amount of information into the minimal die structure.
18646    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18647
18648 const gdb_byte *
18649 partial_die_info::read (const struct die_reader_specs *reader,
18650                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18651 {
18652   struct dwarf2_cu *cu = reader->cu;
18653   struct dwarf2_per_objfile *dwarf2_per_objfile
18654     = cu->per_cu->dwarf2_per_objfile;
18655   unsigned int i;
18656   int has_low_pc_attr = 0;
18657   int has_high_pc_attr = 0;
18658   int high_pc_relative = 0;
18659
18660   for (i = 0; i < abbrev.num_attrs; ++i)
18661     {
18662       struct attribute attr;
18663
18664       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18665
18666       /* Store the data if it is of an attribute we want to keep in a
18667          partial symbol table.  */
18668       switch (attr.name)
18669         {
18670         case DW_AT_name:
18671           switch (tag)
18672             {
18673             case DW_TAG_compile_unit:
18674             case DW_TAG_partial_unit:
18675             case DW_TAG_type_unit:
18676               /* Compilation units have a DW_AT_name that is a filename, not
18677                  a source language identifier.  */
18678             case DW_TAG_enumeration_type:
18679             case DW_TAG_enumerator:
18680               /* These tags always have simple identifiers already; no need
18681                  to canonicalize them.  */
18682               name = DW_STRING (&attr);
18683               break;
18684             default:
18685               {
18686                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18687
18688                 name
18689                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18690                                               &objfile->per_bfd->storage_obstack);
18691               }
18692               break;
18693             }
18694           break;
18695         case DW_AT_linkage_name:
18696         case DW_AT_MIPS_linkage_name:
18697           /* Note that both forms of linkage name might appear.  We
18698              assume they will be the same, and we only store the last
18699              one we see.  */
18700           linkage_name = DW_STRING (&attr);
18701           break;
18702         case DW_AT_low_pc:
18703           has_low_pc_attr = 1;
18704           lowpc = attr_value_as_address (&attr);
18705           break;
18706         case DW_AT_high_pc:
18707           has_high_pc_attr = 1;
18708           highpc = attr_value_as_address (&attr);
18709           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18710                 high_pc_relative = 1;
18711           break;
18712         case DW_AT_location:
18713           /* Support the .debug_loc offsets.  */
18714           if (attr_form_is_block (&attr))
18715             {
18716                d.locdesc = DW_BLOCK (&attr);
18717             }
18718           else if (attr_form_is_section_offset (&attr))
18719             {
18720               dwarf2_complex_location_expr_complaint ();
18721             }
18722           else
18723             {
18724               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18725                                                      "partial symbol information");
18726             }
18727           break;
18728         case DW_AT_external:
18729           is_external = DW_UNSND (&attr);
18730           break;
18731         case DW_AT_declaration:
18732           is_declaration = DW_UNSND (&attr);
18733           break;
18734         case DW_AT_type:
18735           has_type = 1;
18736           break;
18737         case DW_AT_abstract_origin:
18738         case DW_AT_specification:
18739         case DW_AT_extension:
18740           has_specification = 1;
18741           spec_offset = dwarf2_get_ref_die_offset (&attr);
18742           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18743                                    || cu->per_cu->is_dwz);
18744           break;
18745         case DW_AT_sibling:
18746           /* Ignore absolute siblings, they might point outside of
18747              the current compile unit.  */
18748           if (attr.form == DW_FORM_ref_addr)
18749             complaint (_("ignoring absolute DW_AT_sibling"));
18750           else
18751             {
18752               const gdb_byte *buffer = reader->buffer;
18753               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18754               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18755
18756               if (sibling_ptr < info_ptr)
18757                 complaint (_("DW_AT_sibling points backwards"));
18758               else if (sibling_ptr > reader->buffer_end)
18759                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18760               else
18761                 sibling = sibling_ptr;
18762             }
18763           break;
18764         case DW_AT_byte_size:
18765           has_byte_size = 1;
18766           break;
18767         case DW_AT_const_value:
18768           has_const_value = 1;
18769           break;
18770         case DW_AT_calling_convention:
18771           /* DWARF doesn't provide a way to identify a program's source-level
18772              entry point.  DW_AT_calling_convention attributes are only meant
18773              to describe functions' calling conventions.
18774
18775              However, because it's a necessary piece of information in
18776              Fortran, and before DWARF 4 DW_CC_program was the only
18777              piece of debugging information whose definition refers to
18778              a 'main program' at all, several compilers marked Fortran
18779              main programs with DW_CC_program --- even when those
18780              functions use the standard calling conventions.
18781
18782              Although DWARF now specifies a way to provide this
18783              information, we support this practice for backward
18784              compatibility.  */
18785           if (DW_UNSND (&attr) == DW_CC_program
18786               && cu->language == language_fortran)
18787             main_subprogram = 1;
18788           break;
18789         case DW_AT_inline:
18790           if (DW_UNSND (&attr) == DW_INL_inlined
18791               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18792             may_be_inlined = 1;
18793           break;
18794
18795         case DW_AT_import:
18796           if (tag == DW_TAG_imported_unit)
18797             {
18798               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18799               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18800                                   || cu->per_cu->is_dwz);
18801             }
18802           break;
18803
18804         case DW_AT_main_subprogram:
18805           main_subprogram = DW_UNSND (&attr);
18806           break;
18807
18808         case DW_AT_ranges:
18809           {
18810             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18811                but that requires a full DIE, so instead we just
18812                reimplement it.  */
18813             int need_ranges_base = tag != DW_TAG_compile_unit;
18814             unsigned int ranges_offset = (DW_UNSND (&attr)
18815                                           + (need_ranges_base
18816                                              ? cu->ranges_base
18817                                              : 0));
18818
18819             /* Value of the DW_AT_ranges attribute is the offset in the
18820                .debug_ranges section.  */
18821             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18822                                     nullptr))
18823               has_pc_info = 1;
18824           }
18825           break;
18826
18827         default:
18828           break;
18829         }
18830     }
18831
18832   /* For Ada, if both the name and the linkage name appear, we prefer
18833      the latter.  This lets "catch exception" work better, regardless
18834      of the order in which the name and linkage name were emitted.
18835      Really, though, this is just a workaround for the fact that gdb
18836      doesn't store both the name and the linkage name.  */
18837   if (cu->language == language_ada && linkage_name != nullptr)
18838     name = linkage_name;
18839
18840   if (high_pc_relative)
18841     highpc += lowpc;
18842
18843   if (has_low_pc_attr && has_high_pc_attr)
18844     {
18845       /* When using the GNU linker, .gnu.linkonce. sections are used to
18846          eliminate duplicate copies of functions and vtables and such.
18847          The linker will arbitrarily choose one and discard the others.
18848          The AT_*_pc values for such functions refer to local labels in
18849          these sections.  If the section from that file was discarded, the
18850          labels are not in the output, so the relocs get a value of 0.
18851          If this is a discarded function, mark the pc bounds as invalid,
18852          so that GDB will ignore it.  */
18853       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18854         {
18855           struct objfile *objfile = dwarf2_per_objfile->objfile;
18856           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18857
18858           complaint (_("DW_AT_low_pc %s is zero "
18859                        "for DIE at %s [in module %s]"),
18860                      paddress (gdbarch, lowpc),
18861                      sect_offset_str (sect_off),
18862                      objfile_name (objfile));
18863         }
18864       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18865       else if (lowpc >= highpc)
18866         {
18867           struct objfile *objfile = dwarf2_per_objfile->objfile;
18868           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18869
18870           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18871                        "for DIE at %s [in module %s]"),
18872                      paddress (gdbarch, lowpc),
18873                      paddress (gdbarch, highpc),
18874                      sect_offset_str (sect_off),
18875                      objfile_name (objfile));
18876         }
18877       else
18878         has_pc_info = 1;
18879     }
18880
18881   return info_ptr;
18882 }
18883
18884 /* Find a cached partial DIE at OFFSET in CU.  */
18885
18886 struct partial_die_info *
18887 dwarf2_cu::find_partial_die (sect_offset sect_off)
18888 {
18889   struct partial_die_info *lookup_die = NULL;
18890   struct partial_die_info part_die (sect_off);
18891
18892   lookup_die = ((struct partial_die_info *)
18893                 htab_find_with_hash (partial_dies, &part_die,
18894                                      to_underlying (sect_off)));
18895
18896   return lookup_die;
18897 }
18898
18899 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18900    except in the case of .debug_types DIEs which do not reference
18901    outside their CU (they do however referencing other types via
18902    DW_FORM_ref_sig8).  */
18903
18904 static const struct cu_partial_die_info
18905 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18906 {
18907   struct dwarf2_per_objfile *dwarf2_per_objfile
18908     = cu->per_cu->dwarf2_per_objfile;
18909   struct objfile *objfile = dwarf2_per_objfile->objfile;
18910   struct dwarf2_per_cu_data *per_cu = NULL;
18911   struct partial_die_info *pd = NULL;
18912
18913   if (offset_in_dwz == cu->per_cu->is_dwz
18914       && offset_in_cu_p (&cu->header, sect_off))
18915     {
18916       pd = cu->find_partial_die (sect_off);
18917       if (pd != NULL)
18918         return { cu, pd };
18919       /* We missed recording what we needed.
18920          Load all dies and try again.  */
18921       per_cu = cu->per_cu;
18922     }
18923   else
18924     {
18925       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18926       if (cu->per_cu->is_debug_types)
18927         {
18928           error (_("Dwarf Error: Type Unit at offset %s contains"
18929                    " external reference to offset %s [in module %s].\n"),
18930                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18931                  bfd_get_filename (objfile->obfd));
18932         }
18933       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18934                                                  dwarf2_per_objfile);
18935
18936       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18937         load_partial_comp_unit (per_cu);
18938
18939       per_cu->cu->last_used = 0;
18940       pd = per_cu->cu->find_partial_die (sect_off);
18941     }
18942
18943   /* If we didn't find it, and not all dies have been loaded,
18944      load them all and try again.  */
18945
18946   if (pd == NULL && per_cu->load_all_dies == 0)
18947     {
18948       per_cu->load_all_dies = 1;
18949
18950       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18951          THIS_CU->cu may already be in use.  So we can't just free it and
18952          replace its DIEs with the ones we read in.  Instead, we leave those
18953          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18954          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18955          set.  */
18956       load_partial_comp_unit (per_cu);
18957
18958       pd = per_cu->cu->find_partial_die (sect_off);
18959     }
18960
18961   if (pd == NULL)
18962     internal_error (__FILE__, __LINE__,
18963                     _("could not find partial DIE %s "
18964                       "in cache [from module %s]\n"),
18965                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18966   return { per_cu->cu, pd };
18967 }
18968
18969 /* See if we can figure out if the class lives in a namespace.  We do
18970    this by looking for a member function; its demangled name will
18971    contain namespace info, if there is any.  */
18972
18973 static void
18974 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18975                                   struct dwarf2_cu *cu)
18976 {
18977   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18978      what template types look like, because the demangler
18979      frequently doesn't give the same name as the debug info.  We
18980      could fix this by only using the demangled name to get the
18981      prefix (but see comment in read_structure_type).  */
18982
18983   struct partial_die_info *real_pdi;
18984   struct partial_die_info *child_pdi;
18985
18986   /* If this DIE (this DIE's specification, if any) has a parent, then
18987      we should not do this.  We'll prepend the parent's fully qualified
18988      name when we create the partial symbol.  */
18989
18990   real_pdi = struct_pdi;
18991   while (real_pdi->has_specification)
18992     {
18993       auto res = find_partial_die (real_pdi->spec_offset,
18994                                    real_pdi->spec_is_dwz, cu);
18995       real_pdi = res.pdi;
18996       cu = res.cu;
18997     }
18998
18999   if (real_pdi->die_parent != NULL)
19000     return;
19001
19002   for (child_pdi = struct_pdi->die_child;
19003        child_pdi != NULL;
19004        child_pdi = child_pdi->die_sibling)
19005     {
19006       if (child_pdi->tag == DW_TAG_subprogram
19007           && child_pdi->linkage_name != NULL)
19008         {
19009           char *actual_class_name
19010             = language_class_name_from_physname (cu->language_defn,
19011                                                  child_pdi->linkage_name);
19012           if (actual_class_name != NULL)
19013             {
19014               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19015               struct_pdi->name
19016                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
19017                                   actual_class_name);
19018               xfree (actual_class_name);
19019             }
19020           break;
19021         }
19022     }
19023 }
19024
19025 void
19026 partial_die_info::fixup (struct dwarf2_cu *cu)
19027 {
19028   /* Once we've fixed up a die, there's no point in doing so again.
19029      This also avoids a memory leak if we were to call
19030      guess_partial_die_structure_name multiple times.  */
19031   if (fixup_called)
19032     return;
19033
19034   /* If we found a reference attribute and the DIE has no name, try
19035      to find a name in the referred to DIE.  */
19036
19037   if (name == NULL && has_specification)
19038     {
19039       struct partial_die_info *spec_die;
19040
19041       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19042       spec_die = res.pdi;
19043       cu = res.cu;
19044
19045       spec_die->fixup (cu);
19046
19047       if (spec_die->name)
19048         {
19049           name = spec_die->name;
19050
19051           /* Copy DW_AT_external attribute if it is set.  */
19052           if (spec_die->is_external)
19053             is_external = spec_die->is_external;
19054         }
19055     }
19056
19057   /* Set default names for some unnamed DIEs.  */
19058
19059   if (name == NULL && tag == DW_TAG_namespace)
19060     name = CP_ANONYMOUS_NAMESPACE_STR;
19061
19062   /* If there is no parent die to provide a namespace, and there are
19063      children, see if we can determine the namespace from their linkage
19064      name.  */
19065   if (cu->language == language_cplus
19066       && !cu->per_cu->dwarf2_per_objfile->types.empty ()
19067       && die_parent == NULL
19068       && has_children
19069       && (tag == DW_TAG_class_type
19070           || tag == DW_TAG_structure_type
19071           || tag == DW_TAG_union_type))
19072     guess_partial_die_structure_name (this, cu);
19073
19074   /* GCC might emit a nameless struct or union that has a linkage
19075      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19076   if (name == NULL
19077       && (tag == DW_TAG_class_type
19078           || tag == DW_TAG_interface_type
19079           || tag == DW_TAG_structure_type
19080           || tag == DW_TAG_union_type)
19081       && linkage_name != NULL)
19082     {
19083       char *demangled;
19084
19085       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
19086       if (demangled)
19087         {
19088           const char *base;
19089
19090           /* Strip any leading namespaces/classes, keep only the base name.
19091              DW_AT_name for named DIEs does not contain the prefixes.  */
19092           base = strrchr (demangled, ':');
19093           if (base && base > demangled && base[-1] == ':')
19094             base++;
19095           else
19096             base = demangled;
19097
19098           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19099           name = obstack_strdup (&objfile->per_bfd->storage_obstack, base);
19100           xfree (demangled);
19101         }
19102     }
19103
19104   fixup_called = 1;
19105 }
19106
19107 /* Read an attribute value described by an attribute form.  */
19108
19109 static const gdb_byte *
19110 read_attribute_value (const struct die_reader_specs *reader,
19111                       struct attribute *attr, unsigned form,
19112                       LONGEST implicit_const, const gdb_byte *info_ptr)
19113 {
19114   struct dwarf2_cu *cu = reader->cu;
19115   struct dwarf2_per_objfile *dwarf2_per_objfile
19116     = cu->per_cu->dwarf2_per_objfile;
19117   struct objfile *objfile = dwarf2_per_objfile->objfile;
19118   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19119   bfd *abfd = reader->abfd;
19120   struct comp_unit_head *cu_header = &cu->header;
19121   unsigned int bytes_read;
19122   struct dwarf_block *blk;
19123
19124   attr->form = (enum dwarf_form) form;
19125   switch (form)
19126     {
19127     case DW_FORM_ref_addr:
19128       if (cu->header.version == 2)
19129         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19130       else
19131         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19132                                        &cu->header, &bytes_read);
19133       info_ptr += bytes_read;
19134       break;
19135     case DW_FORM_GNU_ref_alt:
19136       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19137       info_ptr += bytes_read;
19138       break;
19139     case DW_FORM_addr:
19140       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19141       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19142       info_ptr += bytes_read;
19143       break;
19144     case DW_FORM_block2:
19145       blk = dwarf_alloc_block (cu);
19146       blk->size = read_2_bytes (abfd, info_ptr);
19147       info_ptr += 2;
19148       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19149       info_ptr += blk->size;
19150       DW_BLOCK (attr) = blk;
19151       break;
19152     case DW_FORM_block4:
19153       blk = dwarf_alloc_block (cu);
19154       blk->size = read_4_bytes (abfd, info_ptr);
19155       info_ptr += 4;
19156       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19157       info_ptr += blk->size;
19158       DW_BLOCK (attr) = blk;
19159       break;
19160     case DW_FORM_data2:
19161       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19162       info_ptr += 2;
19163       break;
19164     case DW_FORM_data4:
19165       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19166       info_ptr += 4;
19167       break;
19168     case DW_FORM_data8:
19169       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19170       info_ptr += 8;
19171       break;
19172     case DW_FORM_data16:
19173       blk = dwarf_alloc_block (cu);
19174       blk->size = 16;
19175       blk->data = read_n_bytes (abfd, info_ptr, 16);
19176       info_ptr += 16;
19177       DW_BLOCK (attr) = blk;
19178       break;
19179     case DW_FORM_sec_offset:
19180       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19181       info_ptr += bytes_read;
19182       break;
19183     case DW_FORM_string:
19184       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19185       DW_STRING_IS_CANONICAL (attr) = 0;
19186       info_ptr += bytes_read;
19187       break;
19188     case DW_FORM_strp:
19189       if (!cu->per_cu->is_dwz)
19190         {
19191           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19192                                                    abfd, info_ptr, cu_header,
19193                                                    &bytes_read);
19194           DW_STRING_IS_CANONICAL (attr) = 0;
19195           info_ptr += bytes_read;
19196           break;
19197         }
19198       /* FALLTHROUGH */
19199     case DW_FORM_line_strp:
19200       if (!cu->per_cu->is_dwz)
19201         {
19202           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19203                                                         abfd, info_ptr,
19204                                                         cu_header, &bytes_read);
19205           DW_STRING_IS_CANONICAL (attr) = 0;
19206           info_ptr += bytes_read;
19207           break;
19208         }
19209       /* FALLTHROUGH */
19210     case DW_FORM_GNU_strp_alt:
19211       {
19212         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19213         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19214                                           &bytes_read);
19215
19216         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19217                                                           dwz, str_offset);
19218         DW_STRING_IS_CANONICAL (attr) = 0;
19219         info_ptr += bytes_read;
19220       }
19221       break;
19222     case DW_FORM_exprloc:
19223     case DW_FORM_block:
19224       blk = dwarf_alloc_block (cu);
19225       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19226       info_ptr += bytes_read;
19227       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19228       info_ptr += blk->size;
19229       DW_BLOCK (attr) = blk;
19230       break;
19231     case DW_FORM_block1:
19232       blk = dwarf_alloc_block (cu);
19233       blk->size = read_1_byte (abfd, info_ptr);
19234       info_ptr += 1;
19235       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19236       info_ptr += blk->size;
19237       DW_BLOCK (attr) = blk;
19238       break;
19239     case DW_FORM_data1:
19240       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19241       info_ptr += 1;
19242       break;
19243     case DW_FORM_flag:
19244       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19245       info_ptr += 1;
19246       break;
19247     case DW_FORM_flag_present:
19248       DW_UNSND (attr) = 1;
19249       break;
19250     case DW_FORM_sdata:
19251       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19252       info_ptr += bytes_read;
19253       break;
19254     case DW_FORM_udata:
19255       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19256       info_ptr += bytes_read;
19257       break;
19258     case DW_FORM_ref1:
19259       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19260                          + read_1_byte (abfd, info_ptr));
19261       info_ptr += 1;
19262       break;
19263     case DW_FORM_ref2:
19264       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19265                          + read_2_bytes (abfd, info_ptr));
19266       info_ptr += 2;
19267       break;
19268     case DW_FORM_ref4:
19269       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19270                          + read_4_bytes (abfd, info_ptr));
19271       info_ptr += 4;
19272       break;
19273     case DW_FORM_ref8:
19274       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19275                          + read_8_bytes (abfd, info_ptr));
19276       info_ptr += 8;
19277       break;
19278     case DW_FORM_ref_sig8:
19279       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19280       info_ptr += 8;
19281       break;
19282     case DW_FORM_ref_udata:
19283       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19284                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19285       info_ptr += bytes_read;
19286       break;
19287     case DW_FORM_indirect:
19288       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19289       info_ptr += bytes_read;
19290       if (form == DW_FORM_implicit_const)
19291         {
19292           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19293           info_ptr += bytes_read;
19294         }
19295       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19296                                        info_ptr);
19297       break;
19298     case DW_FORM_implicit_const:
19299       DW_SND (attr) = implicit_const;
19300       break;
19301     case DW_FORM_addrx:
19302     case DW_FORM_GNU_addr_index:
19303       if (reader->dwo_file == NULL)
19304         {
19305           /* For now flag a hard error.
19306              Later we can turn this into a complaint.  */
19307           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19308                  dwarf_form_name (form),
19309                  bfd_get_filename (abfd));
19310         }
19311       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19312       info_ptr += bytes_read;
19313       break;
19314     case DW_FORM_strx:
19315     case DW_FORM_strx1:
19316     case DW_FORM_strx2:
19317     case DW_FORM_strx3:
19318     case DW_FORM_strx4:
19319     case DW_FORM_GNU_str_index:
19320       if (reader->dwo_file == NULL)
19321         {
19322           /* For now flag a hard error.
19323              Later we can turn this into a complaint if warranted.  */
19324           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19325                  dwarf_form_name (form),
19326                  bfd_get_filename (abfd));
19327         }
19328       {
19329         ULONGEST str_index;
19330         if (form == DW_FORM_strx1)
19331           {
19332             str_index = read_1_byte (abfd, info_ptr);
19333             info_ptr += 1;
19334           }
19335         else if (form == DW_FORM_strx2)
19336           {
19337             str_index = read_2_bytes (abfd, info_ptr);
19338             info_ptr += 2;
19339           }
19340         else if (form == DW_FORM_strx3)
19341           {
19342             str_index = read_3_bytes (abfd, info_ptr);
19343             info_ptr += 3;
19344           }
19345         else if (form == DW_FORM_strx4)
19346           {
19347             str_index = read_4_bytes (abfd, info_ptr);
19348             info_ptr += 4;
19349           }
19350         else
19351           {
19352             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19353             info_ptr += bytes_read;
19354           }
19355         DW_STRING (attr) = read_str_index (reader, str_index);
19356         DW_STRING_IS_CANONICAL (attr) = 0;
19357       }
19358       break;
19359     default:
19360       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19361              dwarf_form_name (form),
19362              bfd_get_filename (abfd));
19363     }
19364
19365   /* Super hack.  */
19366   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19367     attr->form = DW_FORM_GNU_ref_alt;
19368
19369   /* We have seen instances where the compiler tried to emit a byte
19370      size attribute of -1 which ended up being encoded as an unsigned
19371      0xffffffff.  Although 0xffffffff is technically a valid size value,
19372      an object of this size seems pretty unlikely so we can relatively
19373      safely treat these cases as if the size attribute was invalid and
19374      treat them as zero by default.  */
19375   if (attr->name == DW_AT_byte_size
19376       && form == DW_FORM_data4
19377       && DW_UNSND (attr) >= 0xffffffff)
19378     {
19379       complaint
19380         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19381          hex_string (DW_UNSND (attr)));
19382       DW_UNSND (attr) = 0;
19383     }
19384
19385   return info_ptr;
19386 }
19387
19388 /* Read an attribute described by an abbreviated attribute.  */
19389
19390 static const gdb_byte *
19391 read_attribute (const struct die_reader_specs *reader,
19392                 struct attribute *attr, struct attr_abbrev *abbrev,
19393                 const gdb_byte *info_ptr)
19394 {
19395   attr->name = abbrev->name;
19396   return read_attribute_value (reader, attr, abbrev->form,
19397                                abbrev->implicit_const, info_ptr);
19398 }
19399
19400 /* Read dwarf information from a buffer.  */
19401
19402 static unsigned int
19403 read_1_byte (bfd *abfd, const gdb_byte *buf)
19404 {
19405   return bfd_get_8 (abfd, buf);
19406 }
19407
19408 static int
19409 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19410 {
19411   return bfd_get_signed_8 (abfd, buf);
19412 }
19413
19414 static unsigned int
19415 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19416 {
19417   return bfd_get_16 (abfd, buf);
19418 }
19419
19420 static int
19421 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19422 {
19423   return bfd_get_signed_16 (abfd, buf);
19424 }
19425
19426 static unsigned int
19427 read_3_bytes (bfd *abfd, const gdb_byte *buf)
19428 {
19429   unsigned int result = 0;
19430   for (int i = 0; i < 3; ++i)
19431     {
19432       unsigned char byte = bfd_get_8 (abfd, buf);
19433       buf++;
19434       result |= ((unsigned int) byte << (i * 8));
19435     }
19436   return result;
19437 }
19438
19439 static unsigned int
19440 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19441 {
19442   return bfd_get_32 (abfd, buf);
19443 }
19444
19445 static int
19446 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19447 {
19448   return bfd_get_signed_32 (abfd, buf);
19449 }
19450
19451 static ULONGEST
19452 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19453 {
19454   return bfd_get_64 (abfd, buf);
19455 }
19456
19457 static CORE_ADDR
19458 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19459               unsigned int *bytes_read)
19460 {
19461   struct comp_unit_head *cu_header = &cu->header;
19462   CORE_ADDR retval = 0;
19463
19464   if (cu_header->signed_addr_p)
19465     {
19466       switch (cu_header->addr_size)
19467         {
19468         case 2:
19469           retval = bfd_get_signed_16 (abfd, buf);
19470           break;
19471         case 4:
19472           retval = bfd_get_signed_32 (abfd, buf);
19473           break;
19474         case 8:
19475           retval = bfd_get_signed_64 (abfd, buf);
19476           break;
19477         default:
19478           internal_error (__FILE__, __LINE__,
19479                           _("read_address: bad switch, signed [in module %s]"),
19480                           bfd_get_filename (abfd));
19481         }
19482     }
19483   else
19484     {
19485       switch (cu_header->addr_size)
19486         {
19487         case 2:
19488           retval = bfd_get_16 (abfd, buf);
19489           break;
19490         case 4:
19491           retval = bfd_get_32 (abfd, buf);
19492           break;
19493         case 8:
19494           retval = bfd_get_64 (abfd, buf);
19495           break;
19496         default:
19497           internal_error (__FILE__, __LINE__,
19498                           _("read_address: bad switch, "
19499                             "unsigned [in module %s]"),
19500                           bfd_get_filename (abfd));
19501         }
19502     }
19503
19504   *bytes_read = cu_header->addr_size;
19505   return retval;
19506 }
19507
19508 /* Read the initial length from a section.  The (draft) DWARF 3
19509    specification allows the initial length to take up either 4 bytes
19510    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19511    bytes describe the length and all offsets will be 8 bytes in length
19512    instead of 4.
19513
19514    An older, non-standard 64-bit format is also handled by this
19515    function.  The older format in question stores the initial length
19516    as an 8-byte quantity without an escape value.  Lengths greater
19517    than 2^32 aren't very common which means that the initial 4 bytes
19518    is almost always zero.  Since a length value of zero doesn't make
19519    sense for the 32-bit format, this initial zero can be considered to
19520    be an escape value which indicates the presence of the older 64-bit
19521    format.  As written, the code can't detect (old format) lengths
19522    greater than 4GB.  If it becomes necessary to handle lengths
19523    somewhat larger than 4GB, we could allow other small values (such
19524    as the non-sensical values of 1, 2, and 3) to also be used as
19525    escape values indicating the presence of the old format.
19526
19527    The value returned via bytes_read should be used to increment the
19528    relevant pointer after calling read_initial_length().
19529
19530    [ Note:  read_initial_length() and read_offset() are based on the
19531      document entitled "DWARF Debugging Information Format", revision
19532      3, draft 8, dated November 19, 2001.  This document was obtained
19533      from:
19534
19535         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19536
19537      This document is only a draft and is subject to change.  (So beware.)
19538
19539      Details regarding the older, non-standard 64-bit format were
19540      determined empirically by examining 64-bit ELF files produced by
19541      the SGI toolchain on an IRIX 6.5 machine.
19542
19543      - Kevin, July 16, 2002
19544    ] */
19545
19546 static LONGEST
19547 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19548 {
19549   LONGEST length = bfd_get_32 (abfd, buf);
19550
19551   if (length == 0xffffffff)
19552     {
19553       length = bfd_get_64 (abfd, buf + 4);
19554       *bytes_read = 12;
19555     }
19556   else if (length == 0)
19557     {
19558       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19559       length = bfd_get_64 (abfd, buf);
19560       *bytes_read = 8;
19561     }
19562   else
19563     {
19564       *bytes_read = 4;
19565     }
19566
19567   return length;
19568 }
19569
19570 /* Cover function for read_initial_length.
19571    Returns the length of the object at BUF, and stores the size of the
19572    initial length in *BYTES_READ and stores the size that offsets will be in
19573    *OFFSET_SIZE.
19574    If the initial length size is not equivalent to that specified in
19575    CU_HEADER then issue a complaint.
19576    This is useful when reading non-comp-unit headers.  */
19577
19578 static LONGEST
19579 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19580                                         const struct comp_unit_head *cu_header,
19581                                         unsigned int *bytes_read,
19582                                         unsigned int *offset_size)
19583 {
19584   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19585
19586   gdb_assert (cu_header->initial_length_size == 4
19587               || cu_header->initial_length_size == 8
19588               || cu_header->initial_length_size == 12);
19589
19590   if (cu_header->initial_length_size != *bytes_read)
19591     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19592
19593   *offset_size = (*bytes_read == 4) ? 4 : 8;
19594   return length;
19595 }
19596
19597 /* Read an offset from the data stream.  The size of the offset is
19598    given by cu_header->offset_size.  */
19599
19600 static LONGEST
19601 read_offset (bfd *abfd, const gdb_byte *buf,
19602              const struct comp_unit_head *cu_header,
19603              unsigned int *bytes_read)
19604 {
19605   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19606
19607   *bytes_read = cu_header->offset_size;
19608   return offset;
19609 }
19610
19611 /* Read an offset from the data stream.  */
19612
19613 static LONGEST
19614 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19615 {
19616   LONGEST retval = 0;
19617
19618   switch (offset_size)
19619     {
19620     case 4:
19621       retval = bfd_get_32 (abfd, buf);
19622       break;
19623     case 8:
19624       retval = bfd_get_64 (abfd, buf);
19625       break;
19626     default:
19627       internal_error (__FILE__, __LINE__,
19628                       _("read_offset_1: bad switch [in module %s]"),
19629                       bfd_get_filename (abfd));
19630     }
19631
19632   return retval;
19633 }
19634
19635 static const gdb_byte *
19636 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19637 {
19638   /* If the size of a host char is 8 bits, we can return a pointer
19639      to the buffer, otherwise we have to copy the data to a buffer
19640      allocated on the temporary obstack.  */
19641   gdb_assert (HOST_CHAR_BIT == 8);
19642   return buf;
19643 }
19644
19645 static const char *
19646 read_direct_string (bfd *abfd, const gdb_byte *buf,
19647                     unsigned int *bytes_read_ptr)
19648 {
19649   /* If the size of a host char is 8 bits, we can return a pointer
19650      to the string, otherwise we have to copy the string to a buffer
19651      allocated on the temporary obstack.  */
19652   gdb_assert (HOST_CHAR_BIT == 8);
19653   if (*buf == '\0')
19654     {
19655       *bytes_read_ptr = 1;
19656       return NULL;
19657     }
19658   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19659   return (const char *) buf;
19660 }
19661
19662 /* Return pointer to string at section SECT offset STR_OFFSET with error
19663    reporting strings FORM_NAME and SECT_NAME.  */
19664
19665 static const char *
19666 read_indirect_string_at_offset_from (struct objfile *objfile,
19667                                      bfd *abfd, LONGEST str_offset,
19668                                      struct dwarf2_section_info *sect,
19669                                      const char *form_name,
19670                                      const char *sect_name)
19671 {
19672   dwarf2_read_section (objfile, sect);
19673   if (sect->buffer == NULL)
19674     error (_("%s used without %s section [in module %s]"),
19675            form_name, sect_name, bfd_get_filename (abfd));
19676   if (str_offset >= sect->size)
19677     error (_("%s pointing outside of %s section [in module %s]"),
19678            form_name, sect_name, bfd_get_filename (abfd));
19679   gdb_assert (HOST_CHAR_BIT == 8);
19680   if (sect->buffer[str_offset] == '\0')
19681     return NULL;
19682   return (const char *) (sect->buffer + str_offset);
19683 }
19684
19685 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19686
19687 static const char *
19688 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19689                                 bfd *abfd, LONGEST str_offset)
19690 {
19691   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19692                                               abfd, str_offset,
19693                                               &dwarf2_per_objfile->str,
19694                                               "DW_FORM_strp", ".debug_str");
19695 }
19696
19697 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19698
19699 static const char *
19700 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19701                                      bfd *abfd, LONGEST str_offset)
19702 {
19703   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19704                                               abfd, str_offset,
19705                                               &dwarf2_per_objfile->line_str,
19706                                               "DW_FORM_line_strp",
19707                                               ".debug_line_str");
19708 }
19709
19710 /* Read a string at offset STR_OFFSET in the .debug_str section from
19711    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19712    the string consists of a single NUL byte, return NULL; otherwise
19713    return a pointer to the string.  */
19714
19715 static const char *
19716 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19717                                LONGEST str_offset)
19718 {
19719   dwarf2_read_section (objfile, &dwz->str);
19720
19721   if (dwz->str.buffer == NULL)
19722     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19723              "section [in module %s]"),
19724            bfd_get_filename (dwz->dwz_bfd));
19725   if (str_offset >= dwz->str.size)
19726     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19727              ".debug_str section [in module %s]"),
19728            bfd_get_filename (dwz->dwz_bfd));
19729   gdb_assert (HOST_CHAR_BIT == 8);
19730   if (dwz->str.buffer[str_offset] == '\0')
19731     return NULL;
19732   return (const char *) (dwz->str.buffer + str_offset);
19733 }
19734
19735 /* Return pointer to string at .debug_str offset as read from BUF.
19736    BUF is assumed to be in a compilation unit described by CU_HEADER.
19737    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19738
19739 static const char *
19740 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19741                       const gdb_byte *buf,
19742                       const struct comp_unit_head *cu_header,
19743                       unsigned int *bytes_read_ptr)
19744 {
19745   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19746
19747   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19748 }
19749
19750 /* Return pointer to string at .debug_line_str offset as read from BUF.
19751    BUF is assumed to be in a compilation unit described by CU_HEADER.
19752    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19753
19754 static const char *
19755 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19756                            bfd *abfd, const gdb_byte *buf,
19757                            const struct comp_unit_head *cu_header,
19758                            unsigned int *bytes_read_ptr)
19759 {
19760   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19761
19762   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19763                                               str_offset);
19764 }
19765
19766 ULONGEST
19767 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19768                           unsigned int *bytes_read_ptr)
19769 {
19770   ULONGEST result;
19771   unsigned int num_read;
19772   int shift;
19773   unsigned char byte;
19774
19775   result = 0;
19776   shift = 0;
19777   num_read = 0;
19778   while (1)
19779     {
19780       byte = bfd_get_8 (abfd, buf);
19781       buf++;
19782       num_read++;
19783       result |= ((ULONGEST) (byte & 127) << shift);
19784       if ((byte & 128) == 0)
19785         {
19786           break;
19787         }
19788       shift += 7;
19789     }
19790   *bytes_read_ptr = num_read;
19791   return result;
19792 }
19793
19794 static LONGEST
19795 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19796                     unsigned int *bytes_read_ptr)
19797 {
19798   ULONGEST result;
19799   int shift, num_read;
19800   unsigned char byte;
19801
19802   result = 0;
19803   shift = 0;
19804   num_read = 0;
19805   while (1)
19806     {
19807       byte = bfd_get_8 (abfd, buf);
19808       buf++;
19809       num_read++;
19810       result |= ((ULONGEST) (byte & 127) << shift);
19811       shift += 7;
19812       if ((byte & 128) == 0)
19813         {
19814           break;
19815         }
19816     }
19817   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19818     result |= -(((ULONGEST) 1) << shift);
19819   *bytes_read_ptr = num_read;
19820   return result;
19821 }
19822
19823 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19824    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19825    ADDR_SIZE is the size of addresses from the CU header.  */
19826
19827 static CORE_ADDR
19828 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19829                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19830 {
19831   struct objfile *objfile = dwarf2_per_objfile->objfile;
19832   bfd *abfd = objfile->obfd;
19833   const gdb_byte *info_ptr;
19834
19835   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19836   if (dwarf2_per_objfile->addr.buffer == NULL)
19837     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19838            objfile_name (objfile));
19839   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19840     error (_("DW_FORM_addr_index pointing outside of "
19841              ".debug_addr section [in module %s]"),
19842            objfile_name (objfile));
19843   info_ptr = (dwarf2_per_objfile->addr.buffer
19844               + addr_base + addr_index * addr_size);
19845   if (addr_size == 4)
19846     return bfd_get_32 (abfd, info_ptr);
19847   else
19848     return bfd_get_64 (abfd, info_ptr);
19849 }
19850
19851 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19852
19853 static CORE_ADDR
19854 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19855 {
19856   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19857                             cu->addr_base, cu->header.addr_size);
19858 }
19859
19860 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19861
19862 static CORE_ADDR
19863 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19864                              unsigned int *bytes_read)
19865 {
19866   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19867   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19868
19869   return read_addr_index (cu, addr_index);
19870 }
19871
19872 /* Data structure to pass results from dwarf2_read_addr_index_reader
19873    back to dwarf2_read_addr_index.  */
19874
19875 struct dwarf2_read_addr_index_data
19876 {
19877   ULONGEST addr_base;
19878   int addr_size;
19879 };
19880
19881 /* die_reader_func for dwarf2_read_addr_index.  */
19882
19883 static void
19884 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19885                                const gdb_byte *info_ptr,
19886                                struct die_info *comp_unit_die,
19887                                int has_children,
19888                                void *data)
19889 {
19890   struct dwarf2_cu *cu = reader->cu;
19891   struct dwarf2_read_addr_index_data *aidata =
19892     (struct dwarf2_read_addr_index_data *) data;
19893
19894   aidata->addr_base = cu->addr_base;
19895   aidata->addr_size = cu->header.addr_size;
19896 }
19897
19898 /* Given an index in .debug_addr, fetch the value.
19899    NOTE: This can be called during dwarf expression evaluation,
19900    long after the debug information has been read, and thus per_cu->cu
19901    may no longer exist.  */
19902
19903 CORE_ADDR
19904 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19905                         unsigned int addr_index)
19906 {
19907   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19908   struct dwarf2_cu *cu = per_cu->cu;
19909   ULONGEST addr_base;
19910   int addr_size;
19911
19912   /* We need addr_base and addr_size.
19913      If we don't have PER_CU->cu, we have to get it.
19914      Nasty, but the alternative is storing the needed info in PER_CU,
19915      which at this point doesn't seem justified: it's not clear how frequently
19916      it would get used and it would increase the size of every PER_CU.
19917      Entry points like dwarf2_per_cu_addr_size do a similar thing
19918      so we're not in uncharted territory here.
19919      Alas we need to be a bit more complicated as addr_base is contained
19920      in the DIE.
19921
19922      We don't need to read the entire CU(/TU).
19923      We just need the header and top level die.
19924
19925      IWBN to use the aging mechanism to let us lazily later discard the CU.
19926      For now we skip this optimization.  */
19927
19928   if (cu != NULL)
19929     {
19930       addr_base = cu->addr_base;
19931       addr_size = cu->header.addr_size;
19932     }
19933   else
19934     {
19935       struct dwarf2_read_addr_index_data aidata;
19936
19937       /* Note: We can't use init_cutu_and_read_dies_simple here,
19938          we need addr_base.  */
19939       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19940                                dwarf2_read_addr_index_reader, &aidata);
19941       addr_base = aidata.addr_base;
19942       addr_size = aidata.addr_size;
19943     }
19944
19945   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19946                             addr_size);
19947 }
19948
19949 /* Given a DW_FORM_GNU_str_index or DW_FORM_strx, fetch the string.
19950    This is only used by the Fission support.  */
19951
19952 static const char *
19953 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19954 {
19955   struct dwarf2_cu *cu = reader->cu;
19956   struct dwarf2_per_objfile *dwarf2_per_objfile
19957     = cu->per_cu->dwarf2_per_objfile;
19958   struct objfile *objfile = dwarf2_per_objfile->objfile;
19959   const char *objf_name = objfile_name (objfile);
19960   bfd *abfd = objfile->obfd;
19961   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19962   struct dwarf2_section_info *str_offsets_section =
19963     &reader->dwo_file->sections.str_offsets;
19964   const gdb_byte *info_ptr;
19965   ULONGEST str_offset;
19966   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
19967
19968   dwarf2_read_section (objfile, str_section);
19969   dwarf2_read_section (objfile, str_offsets_section);
19970   if (str_section->buffer == NULL)
19971     error (_("%s used without .debug_str.dwo section"
19972              " in CU at offset %s [in module %s]"),
19973            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19974   if (str_offsets_section->buffer == NULL)
19975     error (_("%s used without .debug_str_offsets.dwo section"
19976              " in CU at offset %s [in module %s]"),
19977            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19978   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19979     error (_("%s pointing outside of .debug_str_offsets.dwo"
19980              " section in CU at offset %s [in module %s]"),
19981            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19982   info_ptr = (str_offsets_section->buffer
19983               + str_index * cu->header.offset_size);
19984   if (cu->header.offset_size == 4)
19985     str_offset = bfd_get_32 (abfd, info_ptr);
19986   else
19987     str_offset = bfd_get_64 (abfd, info_ptr);
19988   if (str_offset >= str_section->size)
19989     error (_("Offset from %s pointing outside of"
19990              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19991            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19992   return (const char *) (str_section->buffer + str_offset);
19993 }
19994
19995 /* Return the length of an LEB128 number in BUF.  */
19996
19997 static int
19998 leb128_size (const gdb_byte *buf)
19999 {
20000   const gdb_byte *begin = buf;
20001   gdb_byte byte;
20002
20003   while (1)
20004     {
20005       byte = *buf++;
20006       if ((byte & 128) == 0)
20007         return buf - begin;
20008     }
20009 }
20010
20011 static void
20012 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
20013 {
20014   switch (lang)
20015     {
20016     case DW_LANG_C89:
20017     case DW_LANG_C99:
20018     case DW_LANG_C11:
20019     case DW_LANG_C:
20020     case DW_LANG_UPC:
20021       cu->language = language_c;
20022       break;
20023     case DW_LANG_Java:
20024     case DW_LANG_C_plus_plus:
20025     case DW_LANG_C_plus_plus_11:
20026     case DW_LANG_C_plus_plus_14:
20027       cu->language = language_cplus;
20028       break;
20029     case DW_LANG_D:
20030       cu->language = language_d;
20031       break;
20032     case DW_LANG_Fortran77:
20033     case DW_LANG_Fortran90:
20034     case DW_LANG_Fortran95:
20035     case DW_LANG_Fortran03:
20036     case DW_LANG_Fortran08:
20037       cu->language = language_fortran;
20038       break;
20039     case DW_LANG_Go:
20040       cu->language = language_go;
20041       break;
20042     case DW_LANG_Mips_Assembler:
20043       cu->language = language_asm;
20044       break;
20045     case DW_LANG_Ada83:
20046     case DW_LANG_Ada95:
20047       cu->language = language_ada;
20048       break;
20049     case DW_LANG_Modula2:
20050       cu->language = language_m2;
20051       break;
20052     case DW_LANG_Pascal83:
20053       cu->language = language_pascal;
20054       break;
20055     case DW_LANG_ObjC:
20056       cu->language = language_objc;
20057       break;
20058     case DW_LANG_Rust:
20059     case DW_LANG_Rust_old:
20060       cu->language = language_rust;
20061       break;
20062     case DW_LANG_Cobol74:
20063     case DW_LANG_Cobol85:
20064     default:
20065       cu->language = language_minimal;
20066       break;
20067     }
20068   cu->language_defn = language_def (cu->language);
20069 }
20070
20071 /* Return the named attribute or NULL if not there.  */
20072
20073 static struct attribute *
20074 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20075 {
20076   for (;;)
20077     {
20078       unsigned int i;
20079       struct attribute *spec = NULL;
20080
20081       for (i = 0; i < die->num_attrs; ++i)
20082         {
20083           if (die->attrs[i].name == name)
20084             return &die->attrs[i];
20085           if (die->attrs[i].name == DW_AT_specification
20086               || die->attrs[i].name == DW_AT_abstract_origin)
20087             spec = &die->attrs[i];
20088         }
20089
20090       if (!spec)
20091         break;
20092
20093       die = follow_die_ref (die, spec, &cu);
20094     }
20095
20096   return NULL;
20097 }
20098
20099 /* Return the named attribute or NULL if not there,
20100    but do not follow DW_AT_specification, etc.
20101    This is for use in contexts where we're reading .debug_types dies.
20102    Following DW_AT_specification, DW_AT_abstract_origin will take us
20103    back up the chain, and we want to go down.  */
20104
20105 static struct attribute *
20106 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20107 {
20108   unsigned int i;
20109
20110   for (i = 0; i < die->num_attrs; ++i)
20111     if (die->attrs[i].name == name)
20112       return &die->attrs[i];
20113
20114   return NULL;
20115 }
20116
20117 /* Return the string associated with a string-typed attribute, or NULL if it
20118    is either not found or is of an incorrect type.  */
20119
20120 static const char *
20121 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20122 {
20123   struct attribute *attr;
20124   const char *str = NULL;
20125
20126   attr = dwarf2_attr (die, name, cu);
20127
20128   if (attr != NULL)
20129     {
20130       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20131           || attr->form == DW_FORM_string
20132           || attr->form == DW_FORM_strx
20133           || attr->form == DW_FORM_GNU_str_index
20134           || attr->form == DW_FORM_GNU_strp_alt)
20135         str = DW_STRING (attr);
20136       else
20137         complaint (_("string type expected for attribute %s for "
20138                      "DIE at %s in module %s"),
20139                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20140                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20141     }
20142
20143   return str;
20144 }
20145
20146 /* Return the dwo name or NULL if not present. If present, it is in either
20147    DW_AT_GNU_dwo_name or DW_AT_dwo_name atrribute.  */
20148 static const char *
20149 dwarf2_dwo_name (struct die_info *die, struct dwarf2_cu *cu)
20150 {
20151   const char *dwo_name = dwarf2_string_attr (die, DW_AT_GNU_dwo_name, cu);
20152   if (dwo_name == nullptr)
20153     dwo_name = dwarf2_string_attr (die, DW_AT_dwo_name, cu);
20154   return dwo_name;
20155 }
20156
20157 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20158    and holds a non-zero value.  This function should only be used for
20159    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20160
20161 static int
20162 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20163 {
20164   struct attribute *attr = dwarf2_attr (die, name, cu);
20165
20166   return (attr && DW_UNSND (attr));
20167 }
20168
20169 static int
20170 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20171 {
20172   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20173      which value is non-zero.  However, we have to be careful with
20174      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20175      (via dwarf2_flag_true_p) follows this attribute.  So we may
20176      end up accidently finding a declaration attribute that belongs
20177      to a different DIE referenced by the specification attribute,
20178      even though the given DIE does not have a declaration attribute.  */
20179   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20180           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20181 }
20182
20183 /* Return the die giving the specification for DIE, if there is
20184    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20185    containing the return value on output.  If there is no
20186    specification, but there is an abstract origin, that is
20187    returned.  */
20188
20189 static struct die_info *
20190 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20191 {
20192   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20193                                              *spec_cu);
20194
20195   if (spec_attr == NULL)
20196     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20197
20198   if (spec_attr == NULL)
20199     return NULL;
20200   else
20201     return follow_die_ref (die, spec_attr, spec_cu);
20202 }
20203
20204 /* Stub for free_line_header to match void * callback types.  */
20205
20206 static void
20207 free_line_header_voidp (void *arg)
20208 {
20209   struct line_header *lh = (struct line_header *) arg;
20210
20211   delete lh;
20212 }
20213
20214 void
20215 line_header::add_include_dir (const char *include_dir)
20216 {
20217   if (dwarf_line_debug >= 2)
20218     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20219                         include_dirs.size () + 1, include_dir);
20220
20221   include_dirs.push_back (include_dir);
20222 }
20223
20224 void
20225 line_header::add_file_name (const char *name,
20226                             dir_index d_index,
20227                             unsigned int mod_time,
20228                             unsigned int length)
20229 {
20230   if (dwarf_line_debug >= 2)
20231     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20232                         (unsigned) file_names.size () + 1, name);
20233
20234   file_names.emplace_back (name, d_index, mod_time, length);
20235 }
20236
20237 /* A convenience function to find the proper .debug_line section for a CU.  */
20238
20239 static struct dwarf2_section_info *
20240 get_debug_line_section (struct dwarf2_cu *cu)
20241 {
20242   struct dwarf2_section_info *section;
20243   struct dwarf2_per_objfile *dwarf2_per_objfile
20244     = cu->per_cu->dwarf2_per_objfile;
20245
20246   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20247      DWO file.  */
20248   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20249     section = &cu->dwo_unit->dwo_file->sections.line;
20250   else if (cu->per_cu->is_dwz)
20251     {
20252       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20253
20254       section = &dwz->line;
20255     }
20256   else
20257     section = &dwarf2_per_objfile->line;
20258
20259   return section;
20260 }
20261
20262 /* Read directory or file name entry format, starting with byte of
20263    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20264    entries count and the entries themselves in the described entry
20265    format.  */
20266
20267 static void
20268 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20269                         bfd *abfd, const gdb_byte **bufp,
20270                         struct line_header *lh,
20271                         const struct comp_unit_head *cu_header,
20272                         void (*callback) (struct line_header *lh,
20273                                           const char *name,
20274                                           dir_index d_index,
20275                                           unsigned int mod_time,
20276                                           unsigned int length))
20277 {
20278   gdb_byte format_count, formati;
20279   ULONGEST data_count, datai;
20280   const gdb_byte *buf = *bufp;
20281   const gdb_byte *format_header_data;
20282   unsigned int bytes_read;
20283
20284   format_count = read_1_byte (abfd, buf);
20285   buf += 1;
20286   format_header_data = buf;
20287   for (formati = 0; formati < format_count; formati++)
20288     {
20289       read_unsigned_leb128 (abfd, buf, &bytes_read);
20290       buf += bytes_read;
20291       read_unsigned_leb128 (abfd, buf, &bytes_read);
20292       buf += bytes_read;
20293     }
20294
20295   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20296   buf += bytes_read;
20297   for (datai = 0; datai < data_count; datai++)
20298     {
20299       const gdb_byte *format = format_header_data;
20300       struct file_entry fe;
20301
20302       for (formati = 0; formati < format_count; formati++)
20303         {
20304           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20305           format += bytes_read;
20306
20307           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20308           format += bytes_read;
20309
20310           gdb::optional<const char *> string;
20311           gdb::optional<unsigned int> uint;
20312
20313           switch (form)
20314             {
20315             case DW_FORM_string:
20316               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20317               buf += bytes_read;
20318               break;
20319
20320             case DW_FORM_line_strp:
20321               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20322                                                          abfd, buf,
20323                                                          cu_header,
20324                                                          &bytes_read));
20325               buf += bytes_read;
20326               break;
20327
20328             case DW_FORM_data1:
20329               uint.emplace (read_1_byte (abfd, buf));
20330               buf += 1;
20331               break;
20332
20333             case DW_FORM_data2:
20334               uint.emplace (read_2_bytes (abfd, buf));
20335               buf += 2;
20336               break;
20337
20338             case DW_FORM_data4:
20339               uint.emplace (read_4_bytes (abfd, buf));
20340               buf += 4;
20341               break;
20342
20343             case DW_FORM_data8:
20344               uint.emplace (read_8_bytes (abfd, buf));
20345               buf += 8;
20346               break;
20347
20348             case DW_FORM_udata:
20349               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20350               buf += bytes_read;
20351               break;
20352
20353             case DW_FORM_block:
20354               /* It is valid only for DW_LNCT_timestamp which is ignored by
20355                  current GDB.  */
20356               break;
20357             }
20358
20359           switch (content_type)
20360             {
20361             case DW_LNCT_path:
20362               if (string.has_value ())
20363                 fe.name = *string;
20364               break;
20365             case DW_LNCT_directory_index:
20366               if (uint.has_value ())
20367                 fe.d_index = (dir_index) *uint;
20368               break;
20369             case DW_LNCT_timestamp:
20370               if (uint.has_value ())
20371                 fe.mod_time = *uint;
20372               break;
20373             case DW_LNCT_size:
20374               if (uint.has_value ())
20375                 fe.length = *uint;
20376               break;
20377             case DW_LNCT_MD5:
20378               break;
20379             default:
20380               complaint (_("Unknown format content type %s"),
20381                          pulongest (content_type));
20382             }
20383         }
20384
20385       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20386     }
20387
20388   *bufp = buf;
20389 }
20390
20391 /* Read the statement program header starting at OFFSET in
20392    .debug_line, or .debug_line.dwo.  Return a pointer
20393    to a struct line_header, allocated using xmalloc.
20394    Returns NULL if there is a problem reading the header, e.g., if it
20395    has a version we don't understand.
20396
20397    NOTE: the strings in the include directory and file name tables of
20398    the returned object point into the dwarf line section buffer,
20399    and must not be freed.  */
20400
20401 static line_header_up
20402 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20403 {
20404   const gdb_byte *line_ptr;
20405   unsigned int bytes_read, offset_size;
20406   int i;
20407   const char *cur_dir, *cur_file;
20408   struct dwarf2_section_info *section;
20409   bfd *abfd;
20410   struct dwarf2_per_objfile *dwarf2_per_objfile
20411     = cu->per_cu->dwarf2_per_objfile;
20412
20413   section = get_debug_line_section (cu);
20414   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20415   if (section->buffer == NULL)
20416     {
20417       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20418         complaint (_("missing .debug_line.dwo section"));
20419       else
20420         complaint (_("missing .debug_line section"));
20421       return 0;
20422     }
20423
20424   /* We can't do this until we know the section is non-empty.
20425      Only then do we know we have such a section.  */
20426   abfd = get_section_bfd_owner (section);
20427
20428   /* Make sure that at least there's room for the total_length field.
20429      That could be 12 bytes long, but we're just going to fudge that.  */
20430   if (to_underlying (sect_off) + 4 >= section->size)
20431     {
20432       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20433       return 0;
20434     }
20435
20436   line_header_up lh (new line_header ());
20437
20438   lh->sect_off = sect_off;
20439   lh->offset_in_dwz = cu->per_cu->is_dwz;
20440
20441   line_ptr = section->buffer + to_underlying (sect_off);
20442
20443   /* Read in the header.  */
20444   lh->total_length =
20445     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20446                                             &bytes_read, &offset_size);
20447   line_ptr += bytes_read;
20448   if (line_ptr + lh->total_length > (section->buffer + section->size))
20449     {
20450       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20451       return 0;
20452     }
20453   lh->statement_program_end = line_ptr + lh->total_length;
20454   lh->version = read_2_bytes (abfd, line_ptr);
20455   line_ptr += 2;
20456   if (lh->version > 5)
20457     {
20458       /* This is a version we don't understand.  The format could have
20459          changed in ways we don't handle properly so just punt.  */
20460       complaint (_("unsupported version in .debug_line section"));
20461       return NULL;
20462     }
20463   if (lh->version >= 5)
20464     {
20465       gdb_byte segment_selector_size;
20466
20467       /* Skip address size.  */
20468       read_1_byte (abfd, line_ptr);
20469       line_ptr += 1;
20470
20471       segment_selector_size = read_1_byte (abfd, line_ptr);
20472       line_ptr += 1;
20473       if (segment_selector_size != 0)
20474         {
20475           complaint (_("unsupported segment selector size %u "
20476                        "in .debug_line section"),
20477                      segment_selector_size);
20478           return NULL;
20479         }
20480     }
20481   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20482   line_ptr += offset_size;
20483   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20484   line_ptr += 1;
20485   if (lh->version >= 4)
20486     {
20487       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20488       line_ptr += 1;
20489     }
20490   else
20491     lh->maximum_ops_per_instruction = 1;
20492
20493   if (lh->maximum_ops_per_instruction == 0)
20494     {
20495       lh->maximum_ops_per_instruction = 1;
20496       complaint (_("invalid maximum_ops_per_instruction "
20497                    "in `.debug_line' section"));
20498     }
20499
20500   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20501   line_ptr += 1;
20502   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20503   line_ptr += 1;
20504   lh->line_range = read_1_byte (abfd, line_ptr);
20505   line_ptr += 1;
20506   lh->opcode_base = read_1_byte (abfd, line_ptr);
20507   line_ptr += 1;
20508   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20509
20510   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20511   for (i = 1; i < lh->opcode_base; ++i)
20512     {
20513       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20514       line_ptr += 1;
20515     }
20516
20517   if (lh->version >= 5)
20518     {
20519       /* Read directory table.  */
20520       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20521                               &cu->header,
20522                               [] (struct line_header *header, const char *name,
20523                                   dir_index d_index, unsigned int mod_time,
20524                                   unsigned int length)
20525         {
20526           header->add_include_dir (name);
20527         });
20528
20529       /* Read file name table.  */
20530       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20531                               &cu->header,
20532                               [] (struct line_header *header, const char *name,
20533                                   dir_index d_index, unsigned int mod_time,
20534                                   unsigned int length)
20535         {
20536           header->add_file_name (name, d_index, mod_time, length);
20537         });
20538     }
20539   else
20540     {
20541       /* Read directory table.  */
20542       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20543         {
20544           line_ptr += bytes_read;
20545           lh->add_include_dir (cur_dir);
20546         }
20547       line_ptr += bytes_read;
20548
20549       /* Read file name table.  */
20550       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20551         {
20552           unsigned int mod_time, length;
20553           dir_index d_index;
20554
20555           line_ptr += bytes_read;
20556           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20557           line_ptr += bytes_read;
20558           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20559           line_ptr += bytes_read;
20560           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20561           line_ptr += bytes_read;
20562
20563           lh->add_file_name (cur_file, d_index, mod_time, length);
20564         }
20565       line_ptr += bytes_read;
20566     }
20567   lh->statement_program_start = line_ptr;
20568
20569   if (line_ptr > (section->buffer + section->size))
20570     complaint (_("line number info header doesn't "
20571                  "fit in `.debug_line' section"));
20572
20573   return lh;
20574 }
20575
20576 /* Subroutine of dwarf_decode_lines to simplify it.
20577    Return the file name of the psymtab for included file FILE_INDEX
20578    in line header LH of PST.
20579    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20580    If space for the result is malloc'd, *NAME_HOLDER will be set.
20581    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20582
20583 static const char *
20584 psymtab_include_file_name (const struct line_header *lh, int file_index,
20585                            const struct partial_symtab *pst,
20586                            const char *comp_dir,
20587                            gdb::unique_xmalloc_ptr<char> *name_holder)
20588 {
20589   const file_entry &fe = lh->file_names[file_index];
20590   const char *include_name = fe.name;
20591   const char *include_name_to_compare = include_name;
20592   const char *pst_filename;
20593   int file_is_pst;
20594
20595   const char *dir_name = fe.include_dir (lh);
20596
20597   gdb::unique_xmalloc_ptr<char> hold_compare;
20598   if (!IS_ABSOLUTE_PATH (include_name)
20599       && (dir_name != NULL || comp_dir != NULL))
20600     {
20601       /* Avoid creating a duplicate psymtab for PST.
20602          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20603          Before we do the comparison, however, we need to account
20604          for DIR_NAME and COMP_DIR.
20605          First prepend dir_name (if non-NULL).  If we still don't
20606          have an absolute path prepend comp_dir (if non-NULL).
20607          However, the directory we record in the include-file's
20608          psymtab does not contain COMP_DIR (to match the
20609          corresponding symtab(s)).
20610
20611          Example:
20612
20613          bash$ cd /tmp
20614          bash$ gcc -g ./hello.c
20615          include_name = "hello.c"
20616          dir_name = "."
20617          DW_AT_comp_dir = comp_dir = "/tmp"
20618          DW_AT_name = "./hello.c"
20619
20620       */
20621
20622       if (dir_name != NULL)
20623         {
20624           name_holder->reset (concat (dir_name, SLASH_STRING,
20625                                       include_name, (char *) NULL));
20626           include_name = name_holder->get ();
20627           include_name_to_compare = include_name;
20628         }
20629       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20630         {
20631           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20632                                       include_name, (char *) NULL));
20633           include_name_to_compare = hold_compare.get ();
20634         }
20635     }
20636
20637   pst_filename = pst->filename;
20638   gdb::unique_xmalloc_ptr<char> copied_name;
20639   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20640     {
20641       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20642                                  pst_filename, (char *) NULL));
20643       pst_filename = copied_name.get ();
20644     }
20645
20646   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20647
20648   if (file_is_pst)
20649     return NULL;
20650   return include_name;
20651 }
20652
20653 /* State machine to track the state of the line number program.  */
20654
20655 class lnp_state_machine
20656 {
20657 public:
20658   /* Initialize a machine state for the start of a line number
20659      program.  */
20660   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20661                      bool record_lines_p);
20662
20663   file_entry *current_file ()
20664   {
20665     /* lh->file_names is 0-based, but the file name numbers in the
20666        statement program are 1-based.  */
20667     return m_line_header->file_name_at (m_file);
20668   }
20669
20670   /* Record the line in the state machine.  END_SEQUENCE is true if
20671      we're processing the end of a sequence.  */
20672   void record_line (bool end_sequence);
20673
20674   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20675      nop-out rest of the lines in this sequence.  */
20676   void check_line_address (struct dwarf2_cu *cu,
20677                            const gdb_byte *line_ptr,
20678                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20679
20680   void handle_set_discriminator (unsigned int discriminator)
20681   {
20682     m_discriminator = discriminator;
20683     m_line_has_non_zero_discriminator |= discriminator != 0;
20684   }
20685
20686   /* Handle DW_LNE_set_address.  */
20687   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20688   {
20689     m_op_index = 0;
20690     address += baseaddr;
20691     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20692   }
20693
20694   /* Handle DW_LNS_advance_pc.  */
20695   void handle_advance_pc (CORE_ADDR adjust);
20696
20697   /* Handle a special opcode.  */
20698   void handle_special_opcode (unsigned char op_code);
20699
20700   /* Handle DW_LNS_advance_line.  */
20701   void handle_advance_line (int line_delta)
20702   {
20703     advance_line (line_delta);
20704   }
20705
20706   /* Handle DW_LNS_set_file.  */
20707   void handle_set_file (file_name_index file);
20708
20709   /* Handle DW_LNS_negate_stmt.  */
20710   void handle_negate_stmt ()
20711   {
20712     m_is_stmt = !m_is_stmt;
20713   }
20714
20715   /* Handle DW_LNS_const_add_pc.  */
20716   void handle_const_add_pc ();
20717
20718   /* Handle DW_LNS_fixed_advance_pc.  */
20719   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20720   {
20721     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20722     m_op_index = 0;
20723   }
20724
20725   /* Handle DW_LNS_copy.  */
20726   void handle_copy ()
20727   {
20728     record_line (false);
20729     m_discriminator = 0;
20730   }
20731
20732   /* Handle DW_LNE_end_sequence.  */
20733   void handle_end_sequence ()
20734   {
20735     m_currently_recording_lines = true;
20736   }
20737
20738 private:
20739   /* Advance the line by LINE_DELTA.  */
20740   void advance_line (int line_delta)
20741   {
20742     m_line += line_delta;
20743
20744     if (line_delta != 0)
20745       m_line_has_non_zero_discriminator = m_discriminator != 0;
20746   }
20747
20748   struct dwarf2_cu *m_cu;
20749
20750   gdbarch *m_gdbarch;
20751
20752   /* True if we're recording lines.
20753      Otherwise we're building partial symtabs and are just interested in
20754      finding include files mentioned by the line number program.  */
20755   bool m_record_lines_p;
20756
20757   /* The line number header.  */
20758   line_header *m_line_header;
20759
20760   /* These are part of the standard DWARF line number state machine,
20761      and initialized according to the DWARF spec.  */
20762
20763   unsigned char m_op_index = 0;
20764   /* The line table index (1-based) of the current file.  */
20765   file_name_index m_file = (file_name_index) 1;
20766   unsigned int m_line = 1;
20767
20768   /* These are initialized in the constructor.  */
20769
20770   CORE_ADDR m_address;
20771   bool m_is_stmt;
20772   unsigned int m_discriminator;
20773
20774   /* Additional bits of state we need to track.  */
20775
20776   /* The last file that we called dwarf2_start_subfile for.
20777      This is only used for TLLs.  */
20778   unsigned int m_last_file = 0;
20779   /* The last file a line number was recorded for.  */
20780   struct subfile *m_last_subfile = NULL;
20781
20782   /* When true, record the lines we decode.  */
20783   bool m_currently_recording_lines = false;
20784
20785   /* The last line number that was recorded, used to coalesce
20786      consecutive entries for the same line.  This can happen, for
20787      example, when discriminators are present.  PR 17276.  */
20788   unsigned int m_last_line = 0;
20789   bool m_line_has_non_zero_discriminator = false;
20790 };
20791
20792 void
20793 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20794 {
20795   CORE_ADDR addr_adj = (((m_op_index + adjust)
20796                          / m_line_header->maximum_ops_per_instruction)
20797                         * m_line_header->minimum_instruction_length);
20798   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20799   m_op_index = ((m_op_index + adjust)
20800                 % m_line_header->maximum_ops_per_instruction);
20801 }
20802
20803 void
20804 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20805 {
20806   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20807   CORE_ADDR addr_adj = (((m_op_index
20808                           + (adj_opcode / m_line_header->line_range))
20809                          / m_line_header->maximum_ops_per_instruction)
20810                         * m_line_header->minimum_instruction_length);
20811   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20812   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20813                 % m_line_header->maximum_ops_per_instruction);
20814
20815   int line_delta = (m_line_header->line_base
20816                     + (adj_opcode % m_line_header->line_range));
20817   advance_line (line_delta);
20818   record_line (false);
20819   m_discriminator = 0;
20820 }
20821
20822 void
20823 lnp_state_machine::handle_set_file (file_name_index file)
20824 {
20825   m_file = file;
20826
20827   const file_entry *fe = current_file ();
20828   if (fe == NULL)
20829     dwarf2_debug_line_missing_file_complaint ();
20830   else if (m_record_lines_p)
20831     {
20832       const char *dir = fe->include_dir (m_line_header);
20833
20834       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20835       m_line_has_non_zero_discriminator = m_discriminator != 0;
20836       dwarf2_start_subfile (m_cu, fe->name, dir);
20837     }
20838 }
20839
20840 void
20841 lnp_state_machine::handle_const_add_pc ()
20842 {
20843   CORE_ADDR adjust
20844     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20845
20846   CORE_ADDR addr_adj
20847     = (((m_op_index + adjust)
20848         / m_line_header->maximum_ops_per_instruction)
20849        * m_line_header->minimum_instruction_length);
20850
20851   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20852   m_op_index = ((m_op_index + adjust)
20853                 % m_line_header->maximum_ops_per_instruction);
20854 }
20855
20856 /* Return non-zero if we should add LINE to the line number table.
20857    LINE is the line to add, LAST_LINE is the last line that was added,
20858    LAST_SUBFILE is the subfile for LAST_LINE.
20859    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20860    had a non-zero discriminator.
20861
20862    We have to be careful in the presence of discriminators.
20863    E.g., for this line:
20864
20865      for (i = 0; i < 100000; i++);
20866
20867    clang can emit four line number entries for that one line,
20868    each with a different discriminator.
20869    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20870
20871    However, we want gdb to coalesce all four entries into one.
20872    Otherwise the user could stepi into the middle of the line and
20873    gdb would get confused about whether the pc really was in the
20874    middle of the line.
20875
20876    Things are further complicated by the fact that two consecutive
20877    line number entries for the same line is a heuristic used by gcc
20878    to denote the end of the prologue.  So we can't just discard duplicate
20879    entries, we have to be selective about it.  The heuristic we use is
20880    that we only collapse consecutive entries for the same line if at least
20881    one of those entries has a non-zero discriminator.  PR 17276.
20882
20883    Note: Addresses in the line number state machine can never go backwards
20884    within one sequence, thus this coalescing is ok.  */
20885
20886 static int
20887 dwarf_record_line_p (struct dwarf2_cu *cu,
20888                      unsigned int line, unsigned int last_line,
20889                      int line_has_non_zero_discriminator,
20890                      struct subfile *last_subfile)
20891 {
20892   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20893     return 1;
20894   if (line != last_line)
20895     return 1;
20896   /* Same line for the same file that we've seen already.
20897      As a last check, for pr 17276, only record the line if the line
20898      has never had a non-zero discriminator.  */
20899   if (!line_has_non_zero_discriminator)
20900     return 1;
20901   return 0;
20902 }
20903
20904 /* Use the CU's builder to record line number LINE beginning at
20905    address ADDRESS in the line table of subfile SUBFILE.  */
20906
20907 static void
20908 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20909                      unsigned int line, CORE_ADDR address,
20910                      struct dwarf2_cu *cu)
20911 {
20912   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20913
20914   if (dwarf_line_debug)
20915     {
20916       fprintf_unfiltered (gdb_stdlog,
20917                           "Recording line %u, file %s, address %s\n",
20918                           line, lbasename (subfile->name),
20919                           paddress (gdbarch, address));
20920     }
20921
20922   if (cu != nullptr)
20923     cu->get_builder ()->record_line (subfile, line, addr);
20924 }
20925
20926 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20927    Mark the end of a set of line number records.
20928    The arguments are the same as for dwarf_record_line_1.
20929    If SUBFILE is NULL the request is ignored.  */
20930
20931 static void
20932 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20933                    CORE_ADDR address, struct dwarf2_cu *cu)
20934 {
20935   if (subfile == NULL)
20936     return;
20937
20938   if (dwarf_line_debug)
20939     {
20940       fprintf_unfiltered (gdb_stdlog,
20941                           "Finishing current line, file %s, address %s\n",
20942                           lbasename (subfile->name),
20943                           paddress (gdbarch, address));
20944     }
20945
20946   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20947 }
20948
20949 void
20950 lnp_state_machine::record_line (bool end_sequence)
20951 {
20952   if (dwarf_line_debug)
20953     {
20954       fprintf_unfiltered (gdb_stdlog,
20955                           "Processing actual line %u: file %u,"
20956                           " address %s, is_stmt %u, discrim %u\n",
20957                           m_line, to_underlying (m_file),
20958                           paddress (m_gdbarch, m_address),
20959                           m_is_stmt, m_discriminator);
20960     }
20961
20962   file_entry *fe = current_file ();
20963
20964   if (fe == NULL)
20965     dwarf2_debug_line_missing_file_complaint ();
20966   /* For now we ignore lines not starting on an instruction boundary.
20967      But not when processing end_sequence for compatibility with the
20968      previous version of the code.  */
20969   else if (m_op_index == 0 || end_sequence)
20970     {
20971       fe->included_p = 1;
20972       if (m_record_lines_p && (producer_is_codewarrior (m_cu) || m_is_stmt))
20973         {
20974           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
20975               || end_sequence)
20976             {
20977               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20978                                  m_currently_recording_lines ? m_cu : nullptr);
20979             }
20980
20981           if (!end_sequence)
20982             {
20983               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20984                                        m_line_has_non_zero_discriminator,
20985                                        m_last_subfile))
20986                 {
20987                   buildsym_compunit *builder = m_cu->get_builder ();
20988                   dwarf_record_line_1 (m_gdbarch,
20989                                        builder->get_current_subfile (),
20990                                        m_line, m_address,
20991                                        m_currently_recording_lines ? m_cu : nullptr);
20992                 }
20993               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20994               m_last_line = m_line;
20995             }
20996         }
20997     }
20998 }
20999
21000 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
21001                                       line_header *lh, bool record_lines_p)
21002 {
21003   m_cu = cu;
21004   m_gdbarch = arch;
21005   m_record_lines_p = record_lines_p;
21006   m_line_header = lh;
21007
21008   m_currently_recording_lines = true;
21009
21010   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21011      was a line entry for it so that the backend has a chance to adjust it
21012      and also record it in case it needs it.  This is currently used by MIPS
21013      code, cf. `mips_adjust_dwarf2_line'.  */
21014   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21015   m_is_stmt = lh->default_is_stmt;
21016   m_discriminator = 0;
21017 }
21018
21019 void
21020 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21021                                        const gdb_byte *line_ptr,
21022                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
21023 {
21024   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
21025      the pc range of the CU.  However, we restrict the test to only ADDRESS
21026      values of zero to preserve GDB's previous behaviour which is to handle
21027      the specific case of a function being GC'd by the linker.  */
21028
21029   if (address == 0 && address < unrelocated_lowpc)
21030     {
21031       /* This line table is for a function which has been
21032          GCd by the linker.  Ignore it.  PR gdb/12528 */
21033
21034       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21035       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21036
21037       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21038                  line_offset, objfile_name (objfile));
21039       m_currently_recording_lines = false;
21040       /* Note: m_currently_recording_lines is left as false until we see
21041          DW_LNE_end_sequence.  */
21042     }
21043 }
21044
21045 /* Subroutine of dwarf_decode_lines to simplify it.
21046    Process the line number information in LH.
21047    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21048    program in order to set included_p for every referenced header.  */
21049
21050 static void
21051 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21052                       const int decode_for_pst_p, CORE_ADDR lowpc)
21053 {
21054   const gdb_byte *line_ptr, *extended_end;
21055   const gdb_byte *line_end;
21056   unsigned int bytes_read, extended_len;
21057   unsigned char op_code, extended_op;
21058   CORE_ADDR baseaddr;
21059   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21060   bfd *abfd = objfile->obfd;
21061   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21062   /* True if we're recording line info (as opposed to building partial
21063      symtabs and just interested in finding include files mentioned by
21064      the line number program).  */
21065   bool record_lines_p = !decode_for_pst_p;
21066
21067   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21068
21069   line_ptr = lh->statement_program_start;
21070   line_end = lh->statement_program_end;
21071
21072   /* Read the statement sequences until there's nothing left.  */
21073   while (line_ptr < line_end)
21074     {
21075       /* The DWARF line number program state machine.  Reset the state
21076          machine at the start of each sequence.  */
21077       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21078       bool end_sequence = false;
21079
21080       if (record_lines_p)
21081         {
21082           /* Start a subfile for the current file of the state
21083              machine.  */
21084           const file_entry *fe = state_machine.current_file ();
21085
21086           if (fe != NULL)
21087             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21088         }
21089
21090       /* Decode the table.  */
21091       while (line_ptr < line_end && !end_sequence)
21092         {
21093           op_code = read_1_byte (abfd, line_ptr);
21094           line_ptr += 1;
21095
21096           if (op_code >= lh->opcode_base)
21097             {
21098               /* Special opcode.  */
21099               state_machine.handle_special_opcode (op_code);
21100             }
21101           else switch (op_code)
21102             {
21103             case DW_LNS_extended_op:
21104               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21105                                                    &bytes_read);
21106               line_ptr += bytes_read;
21107               extended_end = line_ptr + extended_len;
21108               extended_op = read_1_byte (abfd, line_ptr);
21109               line_ptr += 1;
21110               switch (extended_op)
21111                 {
21112                 case DW_LNE_end_sequence:
21113                   state_machine.handle_end_sequence ();
21114                   end_sequence = true;
21115                   break;
21116                 case DW_LNE_set_address:
21117                   {
21118                     CORE_ADDR address
21119                       = read_address (abfd, line_ptr, cu, &bytes_read);
21120                     line_ptr += bytes_read;
21121
21122                     state_machine.check_line_address (cu, line_ptr,
21123                                                       lowpc - baseaddr, address);
21124                     state_machine.handle_set_address (baseaddr, address);
21125                   }
21126                   break;
21127                 case DW_LNE_define_file:
21128                   {
21129                     const char *cur_file;
21130                     unsigned int mod_time, length;
21131                     dir_index dindex;
21132
21133                     cur_file = read_direct_string (abfd, line_ptr,
21134                                                    &bytes_read);
21135                     line_ptr += bytes_read;
21136                     dindex = (dir_index)
21137                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21138                     line_ptr += bytes_read;
21139                     mod_time =
21140                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21141                     line_ptr += bytes_read;
21142                     length =
21143                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21144                     line_ptr += bytes_read;
21145                     lh->add_file_name (cur_file, dindex, mod_time, length);
21146                   }
21147                   break;
21148                 case DW_LNE_set_discriminator:
21149                   {
21150                     /* The discriminator is not interesting to the
21151                        debugger; just ignore it.  We still need to
21152                        check its value though:
21153                        if there are consecutive entries for the same
21154                        (non-prologue) line we want to coalesce them.
21155                        PR 17276.  */
21156                     unsigned int discr
21157                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21158                     line_ptr += bytes_read;
21159
21160                     state_machine.handle_set_discriminator (discr);
21161                   }
21162                   break;
21163                 default:
21164                   complaint (_("mangled .debug_line section"));
21165                   return;
21166                 }
21167               /* Make sure that we parsed the extended op correctly.  If e.g.
21168                  we expected a different address size than the producer used,
21169                  we may have read the wrong number of bytes.  */
21170               if (line_ptr != extended_end)
21171                 {
21172                   complaint (_("mangled .debug_line section"));
21173                   return;
21174                 }
21175               break;
21176             case DW_LNS_copy:
21177               state_machine.handle_copy ();
21178               break;
21179             case DW_LNS_advance_pc:
21180               {
21181                 CORE_ADDR adjust
21182                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21183                 line_ptr += bytes_read;
21184
21185                 state_machine.handle_advance_pc (adjust);
21186               }
21187               break;
21188             case DW_LNS_advance_line:
21189               {
21190                 int line_delta
21191                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21192                 line_ptr += bytes_read;
21193
21194                 state_machine.handle_advance_line (line_delta);
21195               }
21196               break;
21197             case DW_LNS_set_file:
21198               {
21199                 file_name_index file
21200                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21201                                                             &bytes_read);
21202                 line_ptr += bytes_read;
21203
21204                 state_machine.handle_set_file (file);
21205               }
21206               break;
21207             case DW_LNS_set_column:
21208               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21209               line_ptr += bytes_read;
21210               break;
21211             case DW_LNS_negate_stmt:
21212               state_machine.handle_negate_stmt ();
21213               break;
21214             case DW_LNS_set_basic_block:
21215               break;
21216             /* Add to the address register of the state machine the
21217                address increment value corresponding to special opcode
21218                255.  I.e., this value is scaled by the minimum
21219                instruction length since special opcode 255 would have
21220                scaled the increment.  */
21221             case DW_LNS_const_add_pc:
21222               state_machine.handle_const_add_pc ();
21223               break;
21224             case DW_LNS_fixed_advance_pc:
21225               {
21226                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21227                 line_ptr += 2;
21228
21229                 state_machine.handle_fixed_advance_pc (addr_adj);
21230               }
21231               break;
21232             default:
21233               {
21234                 /* Unknown standard opcode, ignore it.  */
21235                 int i;
21236
21237                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21238                   {
21239                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21240                     line_ptr += bytes_read;
21241                   }
21242               }
21243             }
21244         }
21245
21246       if (!end_sequence)
21247         dwarf2_debug_line_missing_end_sequence_complaint ();
21248
21249       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21250          in which case we still finish recording the last line).  */
21251       state_machine.record_line (true);
21252     }
21253 }
21254
21255 /* Decode the Line Number Program (LNP) for the given line_header
21256    structure and CU.  The actual information extracted and the type
21257    of structures created from the LNP depends on the value of PST.
21258
21259    1. If PST is NULL, then this procedure uses the data from the program
21260       to create all necessary symbol tables, and their linetables.
21261
21262    2. If PST is not NULL, this procedure reads the program to determine
21263       the list of files included by the unit represented by PST, and
21264       builds all the associated partial symbol tables.
21265
21266    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21267    It is used for relative paths in the line table.
21268    NOTE: When processing partial symtabs (pst != NULL),
21269    comp_dir == pst->dirname.
21270
21271    NOTE: It is important that psymtabs have the same file name (via strcmp)
21272    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21273    symtab we don't use it in the name of the psymtabs we create.
21274    E.g. expand_line_sal requires this when finding psymtabs to expand.
21275    A good testcase for this is mb-inline.exp.
21276
21277    LOWPC is the lowest address in CU (or 0 if not known).
21278
21279    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21280    for its PC<->lines mapping information.  Otherwise only the filename
21281    table is read in.  */
21282
21283 static void
21284 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21285                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21286                     CORE_ADDR lowpc, int decode_mapping)
21287 {
21288   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21289   const int decode_for_pst_p = (pst != NULL);
21290
21291   if (decode_mapping)
21292     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21293
21294   if (decode_for_pst_p)
21295     {
21296       int file_index;
21297
21298       /* Now that we're done scanning the Line Header Program, we can
21299          create the psymtab of each included file.  */
21300       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21301         if (lh->file_names[file_index].included_p == 1)
21302           {
21303             gdb::unique_xmalloc_ptr<char> name_holder;
21304             const char *include_name =
21305               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21306                                          &name_holder);
21307             if (include_name != NULL)
21308               dwarf2_create_include_psymtab (include_name, pst, objfile);
21309           }
21310     }
21311   else
21312     {
21313       /* Make sure a symtab is created for every file, even files
21314          which contain only variables (i.e. no code with associated
21315          line numbers).  */
21316       buildsym_compunit *builder = cu->get_builder ();
21317       struct compunit_symtab *cust = builder->get_compunit_symtab ();
21318       int i;
21319
21320       for (i = 0; i < lh->file_names.size (); i++)
21321         {
21322           file_entry &fe = lh->file_names[i];
21323
21324           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21325
21326           if (builder->get_current_subfile ()->symtab == NULL)
21327             {
21328               builder->get_current_subfile ()->symtab
21329                 = allocate_symtab (cust,
21330                                    builder->get_current_subfile ()->name);
21331             }
21332           fe.symtab = builder->get_current_subfile ()->symtab;
21333         }
21334     }
21335 }
21336
21337 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21338    DIRNAME the name of the source directory which contains FILENAME
21339    or NULL if not known.
21340    This routine tries to keep line numbers from identical absolute and
21341    relative file names in a common subfile.
21342
21343    Using the `list' example from the GDB testsuite, which resides in
21344    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21345    of /srcdir/list0.c yields the following debugging information for list0.c:
21346
21347    DW_AT_name:          /srcdir/list0.c
21348    DW_AT_comp_dir:      /compdir
21349    files.files[0].name: list0.h
21350    files.files[0].dir:  /srcdir
21351    files.files[1].name: list0.c
21352    files.files[1].dir:  /srcdir
21353
21354    The line number information for list0.c has to end up in a single
21355    subfile, so that `break /srcdir/list0.c:1' works as expected.
21356    start_subfile will ensure that this happens provided that we pass the
21357    concatenation of files.files[1].dir and files.files[1].name as the
21358    subfile's name.  */
21359
21360 static void
21361 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21362                       const char *dirname)
21363 {
21364   char *copy = NULL;
21365
21366   /* In order not to lose the line information directory,
21367      we concatenate it to the filename when it makes sense.
21368      Note that the Dwarf3 standard says (speaking of filenames in line
21369      information): ``The directory index is ignored for file names
21370      that represent full path names''.  Thus ignoring dirname in the
21371      `else' branch below isn't an issue.  */
21372
21373   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21374     {
21375       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21376       filename = copy;
21377     }
21378
21379   cu->get_builder ()->start_subfile (filename);
21380
21381   if (copy != NULL)
21382     xfree (copy);
21383 }
21384
21385 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21386    buildsym_compunit constructor.  */
21387
21388 struct compunit_symtab *
21389 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
21390                          CORE_ADDR low_pc)
21391 {
21392   gdb_assert (m_builder == nullptr);
21393
21394   m_builder.reset (new struct buildsym_compunit
21395                    (per_cu->dwarf2_per_objfile->objfile,
21396                     name, comp_dir, language, low_pc));
21397
21398   list_in_scope = get_builder ()->get_file_symbols ();
21399
21400   get_builder ()->record_debugformat ("DWARF 2");
21401   get_builder ()->record_producer (producer);
21402
21403   processing_has_namespace_info = false;
21404
21405   return get_builder ()->get_compunit_symtab ();
21406 }
21407
21408 static void
21409 var_decode_location (struct attribute *attr, struct symbol *sym,
21410                      struct dwarf2_cu *cu)
21411 {
21412   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21413   struct comp_unit_head *cu_header = &cu->header;
21414
21415   /* NOTE drow/2003-01-30: There used to be a comment and some special
21416      code here to turn a symbol with DW_AT_external and a
21417      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21418      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21419      with some versions of binutils) where shared libraries could have
21420      relocations against symbols in their debug information - the
21421      minimal symbol would have the right address, but the debug info
21422      would not.  It's no longer necessary, because we will explicitly
21423      apply relocations when we read in the debug information now.  */
21424
21425   /* A DW_AT_location attribute with no contents indicates that a
21426      variable has been optimized away.  */
21427   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21428     {
21429       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21430       return;
21431     }
21432
21433   /* Handle one degenerate form of location expression specially, to
21434      preserve GDB's previous behavior when section offsets are
21435      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21436      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21437
21438   if (attr_form_is_block (attr)
21439       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21440            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21441           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21442                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
21443               && (DW_BLOCK (attr)->size
21444                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21445     {
21446       unsigned int dummy;
21447
21448       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21449         SYMBOL_VALUE_ADDRESS (sym) =
21450           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21451       else
21452         SYMBOL_VALUE_ADDRESS (sym) =
21453           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21454       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21455       fixup_symbol_section (sym, objfile);
21456       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21457                                               SYMBOL_SECTION (sym));
21458       return;
21459     }
21460
21461   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21462      expression evaluator, and use LOC_COMPUTED only when necessary
21463      (i.e. when the value of a register or memory location is
21464      referenced, or a thread-local block, etc.).  Then again, it might
21465      not be worthwhile.  I'm assuming that it isn't unless performance
21466      or memory numbers show me otherwise.  */
21467
21468   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21469
21470   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21471     cu->has_loclist = true;
21472 }
21473
21474 /* Given a pointer to a DWARF information entry, figure out if we need
21475    to make a symbol table entry for it, and if so, create a new entry
21476    and return a pointer to it.
21477    If TYPE is NULL, determine symbol type from the die, otherwise
21478    used the passed type.
21479    If SPACE is not NULL, use it to hold the new symbol.  If it is
21480    NULL, allocate a new symbol on the objfile's obstack.  */
21481
21482 static struct symbol *
21483 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21484             struct symbol *space)
21485 {
21486   struct dwarf2_per_objfile *dwarf2_per_objfile
21487     = cu->per_cu->dwarf2_per_objfile;
21488   struct objfile *objfile = dwarf2_per_objfile->objfile;
21489   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21490   struct symbol *sym = NULL;
21491   const char *name;
21492   struct attribute *attr = NULL;
21493   struct attribute *attr2 = NULL;
21494   CORE_ADDR baseaddr;
21495   struct pending **list_to_add = NULL;
21496
21497   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21498
21499   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21500
21501   name = dwarf2_name (die, cu);
21502   if (name)
21503     {
21504       const char *linkagename;
21505       int suppress_add = 0;
21506
21507       if (space)
21508         sym = space;
21509       else
21510         sym = allocate_symbol (objfile);
21511       OBJSTAT (objfile, n_syms++);
21512
21513       /* Cache this symbol's name and the name's demangled form (if any).  */
21514       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21515       linkagename = dwarf2_physname (name, die, cu);
21516       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21517
21518       /* Fortran does not have mangling standard and the mangling does differ
21519          between gfortran, iFort etc.  */
21520       if (cu->language == language_fortran
21521           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21522         symbol_set_demangled_name (&(sym->ginfo),
21523                                    dwarf2_full_name (name, die, cu),
21524                                    NULL);
21525
21526       /* Default assumptions.
21527          Use the passed type or decode it from the die.  */
21528       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21529       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21530       if (type != NULL)
21531         SYMBOL_TYPE (sym) = type;
21532       else
21533         SYMBOL_TYPE (sym) = die_type (die, cu);
21534       attr = dwarf2_attr (die,
21535                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21536                           cu);
21537       if (attr)
21538         {
21539           SYMBOL_LINE (sym) = DW_UNSND (attr);
21540         }
21541
21542       attr = dwarf2_attr (die,
21543                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21544                           cu);
21545       if (attr)
21546         {
21547           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21548           struct file_entry *fe;
21549
21550           if (cu->line_header != NULL)
21551             fe = cu->line_header->file_name_at (file_index);
21552           else
21553             fe = NULL;
21554
21555           if (fe == NULL)
21556             complaint (_("file index out of range"));
21557           else
21558             symbol_set_symtab (sym, fe->symtab);
21559         }
21560
21561       switch (die->tag)
21562         {
21563         case DW_TAG_label:
21564           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21565           if (attr)
21566             {
21567               CORE_ADDR addr;
21568
21569               addr = attr_value_as_address (attr);
21570               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21571               SYMBOL_VALUE_ADDRESS (sym) = addr;
21572             }
21573           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21574           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21575           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21576           add_symbol_to_list (sym, cu->list_in_scope);
21577           break;
21578         case DW_TAG_subprogram:
21579           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21580              finish_block.  */
21581           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21582           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21583           if ((attr2 && (DW_UNSND (attr2) != 0))
21584               || cu->language == language_ada)
21585             {
21586               /* Subprograms marked external are stored as a global symbol.
21587                  Ada subprograms, whether marked external or not, are always
21588                  stored as a global symbol, because we want to be able to
21589                  access them globally.  For instance, we want to be able
21590                  to break on a nested subprogram without having to
21591                  specify the context.  */
21592               list_to_add = cu->get_builder ()->get_global_symbols ();
21593             }
21594           else
21595             {
21596               list_to_add = cu->list_in_scope;
21597             }
21598           break;
21599         case DW_TAG_inlined_subroutine:
21600           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21601              finish_block.  */
21602           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21603           SYMBOL_INLINED (sym) = 1;
21604           list_to_add = cu->list_in_scope;
21605           break;
21606         case DW_TAG_template_value_param:
21607           suppress_add = 1;
21608           /* Fall through.  */
21609         case DW_TAG_constant:
21610         case DW_TAG_variable:
21611         case DW_TAG_member:
21612           /* Compilation with minimal debug info may result in
21613              variables with missing type entries.  Change the
21614              misleading `void' type to something sensible.  */
21615           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21616             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21617
21618           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21619           /* In the case of DW_TAG_member, we should only be called for
21620              static const members.  */
21621           if (die->tag == DW_TAG_member)
21622             {
21623               /* dwarf2_add_field uses die_is_declaration,
21624                  so we do the same.  */
21625               gdb_assert (die_is_declaration (die, cu));
21626               gdb_assert (attr);
21627             }
21628           if (attr)
21629             {
21630               dwarf2_const_value (attr, sym, cu);
21631               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21632               if (!suppress_add)
21633                 {
21634                   if (attr2 && (DW_UNSND (attr2) != 0))
21635                     list_to_add = cu->get_builder ()->get_global_symbols ();
21636                   else
21637                     list_to_add = cu->list_in_scope;
21638                 }
21639               break;
21640             }
21641           attr = dwarf2_attr (die, DW_AT_location, cu);
21642           if (attr)
21643             {
21644               var_decode_location (attr, sym, cu);
21645               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21646
21647               /* Fortran explicitly imports any global symbols to the local
21648                  scope by DW_TAG_common_block.  */
21649               if (cu->language == language_fortran && die->parent
21650                   && die->parent->tag == DW_TAG_common_block)
21651                 attr2 = NULL;
21652
21653               if (SYMBOL_CLASS (sym) == LOC_STATIC
21654                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21655                   && !dwarf2_per_objfile->has_section_at_zero)
21656                 {
21657                   /* When a static variable is eliminated by the linker,
21658                      the corresponding debug information is not stripped
21659                      out, but the variable address is set to null;
21660                      do not add such variables into symbol table.  */
21661                 }
21662               else if (attr2 && (DW_UNSND (attr2) != 0))
21663                 {
21664                   /* Workaround gfortran PR debug/40040 - it uses
21665                      DW_AT_location for variables in -fPIC libraries which may
21666                      get overriden by other libraries/executable and get
21667                      a different address.  Resolve it by the minimal symbol
21668                      which may come from inferior's executable using copy
21669                      relocation.  Make this workaround only for gfortran as for
21670                      other compilers GDB cannot guess the minimal symbol
21671                      Fortran mangling kind.  */
21672                   if (cu->language == language_fortran && die->parent
21673                       && die->parent->tag == DW_TAG_module
21674                       && cu->producer
21675                       && startswith (cu->producer, "GNU Fortran"))
21676                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21677
21678                   /* A variable with DW_AT_external is never static,
21679                      but it may be block-scoped.  */
21680                   list_to_add
21681                     = ((cu->list_in_scope
21682                         == cu->get_builder ()->get_file_symbols ())
21683                        ? cu->get_builder ()->get_global_symbols ()
21684                        : cu->list_in_scope);
21685                 }
21686               else
21687                 list_to_add = cu->list_in_scope;
21688             }
21689           else
21690             {
21691               /* We do not know the address of this symbol.
21692                  If it is an external symbol and we have type information
21693                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21694                  The address of the variable will then be determined from
21695                  the minimal symbol table whenever the variable is
21696                  referenced.  */
21697               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21698
21699               /* Fortran explicitly imports any global symbols to the local
21700                  scope by DW_TAG_common_block.  */
21701               if (cu->language == language_fortran && die->parent
21702                   && die->parent->tag == DW_TAG_common_block)
21703                 {
21704                   /* SYMBOL_CLASS doesn't matter here because
21705                      read_common_block is going to reset it.  */
21706                   if (!suppress_add)
21707                     list_to_add = cu->list_in_scope;
21708                 }
21709               else if (attr2 && (DW_UNSND (attr2) != 0)
21710                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21711                 {
21712                   /* A variable with DW_AT_external is never static, but it
21713                      may be block-scoped.  */
21714                   list_to_add
21715                     = ((cu->list_in_scope
21716                         == cu->get_builder ()->get_file_symbols ())
21717                        ? cu->get_builder ()->get_global_symbols ()
21718                        : cu->list_in_scope);
21719
21720                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21721                 }
21722               else if (!die_is_declaration (die, cu))
21723                 {
21724                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21725                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21726                   if (!suppress_add)
21727                     list_to_add = cu->list_in_scope;
21728                 }
21729             }
21730           break;
21731         case DW_TAG_formal_parameter:
21732           {
21733             /* If we are inside a function, mark this as an argument.  If
21734                not, we might be looking at an argument to an inlined function
21735                when we do not have enough information to show inlined frames;
21736                pretend it's a local variable in that case so that the user can
21737                still see it.  */
21738             struct context_stack *curr
21739               = cu->get_builder ()->get_current_context_stack ();
21740             if (curr != nullptr && curr->name != nullptr)
21741               SYMBOL_IS_ARGUMENT (sym) = 1;
21742             attr = dwarf2_attr (die, DW_AT_location, cu);
21743             if (attr)
21744               {
21745                 var_decode_location (attr, sym, cu);
21746               }
21747             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21748             if (attr)
21749               {
21750                 dwarf2_const_value (attr, sym, cu);
21751               }
21752
21753             list_to_add = cu->list_in_scope;
21754           }
21755           break;
21756         case DW_TAG_unspecified_parameters:
21757           /* From varargs functions; gdb doesn't seem to have any
21758              interest in this information, so just ignore it for now.
21759              (FIXME?) */
21760           break;
21761         case DW_TAG_template_type_param:
21762           suppress_add = 1;
21763           /* Fall through.  */
21764         case DW_TAG_class_type:
21765         case DW_TAG_interface_type:
21766         case DW_TAG_structure_type:
21767         case DW_TAG_union_type:
21768         case DW_TAG_set_type:
21769         case DW_TAG_enumeration_type:
21770           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21771           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21772
21773           {
21774             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21775                really ever be static objects: otherwise, if you try
21776                to, say, break of a class's method and you're in a file
21777                which doesn't mention that class, it won't work unless
21778                the check for all static symbols in lookup_symbol_aux
21779                saves you.  See the OtherFileClass tests in
21780                gdb.c++/namespace.exp.  */
21781
21782             if (!suppress_add)
21783               {
21784                 buildsym_compunit *builder = cu->get_builder ();
21785                 list_to_add
21786                   = (cu->list_in_scope == builder->get_file_symbols ()
21787                      && cu->language == language_cplus
21788                      ? builder->get_global_symbols ()
21789                      : cu->list_in_scope);
21790
21791                 /* The semantics of C++ state that "struct foo {
21792                    ... }" also defines a typedef for "foo".  */
21793                 if (cu->language == language_cplus
21794                     || cu->language == language_ada
21795                     || cu->language == language_d
21796                     || cu->language == language_rust)
21797                   {
21798                     /* The symbol's name is already allocated along
21799                        with this objfile, so we don't need to
21800                        duplicate it for the type.  */
21801                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21802                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21803                   }
21804               }
21805           }
21806           break;
21807         case DW_TAG_typedef:
21808           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21809           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21810           list_to_add = cu->list_in_scope;
21811           break;
21812         case DW_TAG_base_type:
21813         case DW_TAG_subrange_type:
21814           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21815           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21816           list_to_add = cu->list_in_scope;
21817           break;
21818         case DW_TAG_enumerator:
21819           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21820           if (attr)
21821             {
21822               dwarf2_const_value (attr, sym, cu);
21823             }
21824           {
21825             /* NOTE: carlton/2003-11-10: See comment above in the
21826                DW_TAG_class_type, etc. block.  */
21827
21828             list_to_add
21829               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21830                  && cu->language == language_cplus
21831                  ? cu->get_builder ()->get_global_symbols ()
21832                  : cu->list_in_scope);
21833           }
21834           break;
21835         case DW_TAG_imported_declaration:
21836         case DW_TAG_namespace:
21837           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21838           list_to_add = cu->get_builder ()->get_global_symbols ();
21839           break;
21840         case DW_TAG_module:
21841           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21842           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21843           list_to_add = cu->get_builder ()->get_global_symbols ();
21844           break;
21845         case DW_TAG_common_block:
21846           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21847           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21848           add_symbol_to_list (sym, cu->list_in_scope);
21849           break;
21850         default:
21851           /* Not a tag we recognize.  Hopefully we aren't processing
21852              trash data, but since we must specifically ignore things
21853              we don't recognize, there is nothing else we should do at
21854              this point.  */
21855           complaint (_("unsupported tag: '%s'"),
21856                      dwarf_tag_name (die->tag));
21857           break;
21858         }
21859
21860       if (suppress_add)
21861         {
21862           sym->hash_next = objfile->template_symbols;
21863           objfile->template_symbols = sym;
21864           list_to_add = NULL;
21865         }
21866
21867       if (list_to_add != NULL)
21868         add_symbol_to_list (sym, list_to_add);
21869
21870       /* For the benefit of old versions of GCC, check for anonymous
21871          namespaces based on the demangled name.  */
21872       if (!cu->processing_has_namespace_info
21873           && cu->language == language_cplus)
21874         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21875     }
21876   return (sym);
21877 }
21878
21879 /* Given an attr with a DW_FORM_dataN value in host byte order,
21880    zero-extend it as appropriate for the symbol's type.  The DWARF
21881    standard (v4) is not entirely clear about the meaning of using
21882    DW_FORM_dataN for a constant with a signed type, where the type is
21883    wider than the data.  The conclusion of a discussion on the DWARF
21884    list was that this is unspecified.  We choose to always zero-extend
21885    because that is the interpretation long in use by GCC.  */
21886
21887 static gdb_byte *
21888 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21889                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21890 {
21891   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21892   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21893                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21894   LONGEST l = DW_UNSND (attr);
21895
21896   if (bits < sizeof (*value) * 8)
21897     {
21898       l &= ((LONGEST) 1 << bits) - 1;
21899       *value = l;
21900     }
21901   else if (bits == sizeof (*value) * 8)
21902     *value = l;
21903   else
21904     {
21905       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21906       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21907       return bytes;
21908     }
21909
21910   return NULL;
21911 }
21912
21913 /* Read a constant value from an attribute.  Either set *VALUE, or if
21914    the value does not fit in *VALUE, set *BYTES - either already
21915    allocated on the objfile obstack, or newly allocated on OBSTACK,
21916    or, set *BATON, if we translated the constant to a location
21917    expression.  */
21918
21919 static void
21920 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21921                          const char *name, struct obstack *obstack,
21922                          struct dwarf2_cu *cu,
21923                          LONGEST *value, const gdb_byte **bytes,
21924                          struct dwarf2_locexpr_baton **baton)
21925 {
21926   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21927   struct comp_unit_head *cu_header = &cu->header;
21928   struct dwarf_block *blk;
21929   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21930                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21931
21932   *value = 0;
21933   *bytes = NULL;
21934   *baton = NULL;
21935
21936   switch (attr->form)
21937     {
21938     case DW_FORM_addr:
21939     case DW_FORM_addrx:
21940     case DW_FORM_GNU_addr_index:
21941       {
21942         gdb_byte *data;
21943
21944         if (TYPE_LENGTH (type) != cu_header->addr_size)
21945           dwarf2_const_value_length_mismatch_complaint (name,
21946                                                         cu_header->addr_size,
21947                                                         TYPE_LENGTH (type));
21948         /* Symbols of this form are reasonably rare, so we just
21949            piggyback on the existing location code rather than writing
21950            a new implementation of symbol_computed_ops.  */
21951         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21952         (*baton)->per_cu = cu->per_cu;
21953         gdb_assert ((*baton)->per_cu);
21954
21955         (*baton)->size = 2 + cu_header->addr_size;
21956         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21957         (*baton)->data = data;
21958
21959         data[0] = DW_OP_addr;
21960         store_unsigned_integer (&data[1], cu_header->addr_size,
21961                                 byte_order, DW_ADDR (attr));
21962         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21963       }
21964       break;
21965     case DW_FORM_string:
21966     case DW_FORM_strp:
21967     case DW_FORM_strx:
21968     case DW_FORM_GNU_str_index:
21969     case DW_FORM_GNU_strp_alt:
21970       /* DW_STRING is already allocated on the objfile obstack, point
21971          directly to it.  */
21972       *bytes = (const gdb_byte *) DW_STRING (attr);
21973       break;
21974     case DW_FORM_block1:
21975     case DW_FORM_block2:
21976     case DW_FORM_block4:
21977     case DW_FORM_block:
21978     case DW_FORM_exprloc:
21979     case DW_FORM_data16:
21980       blk = DW_BLOCK (attr);
21981       if (TYPE_LENGTH (type) != blk->size)
21982         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21983                                                       TYPE_LENGTH (type));
21984       *bytes = blk->data;
21985       break;
21986
21987       /* The DW_AT_const_value attributes are supposed to carry the
21988          symbol's value "represented as it would be on the target
21989          architecture."  By the time we get here, it's already been
21990          converted to host endianness, so we just need to sign- or
21991          zero-extend it as appropriate.  */
21992     case DW_FORM_data1:
21993       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21994       break;
21995     case DW_FORM_data2:
21996       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21997       break;
21998     case DW_FORM_data4:
21999       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
22000       break;
22001     case DW_FORM_data8:
22002       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22003       break;
22004
22005     case DW_FORM_sdata:
22006     case DW_FORM_implicit_const:
22007       *value = DW_SND (attr);
22008       break;
22009
22010     case DW_FORM_udata:
22011       *value = DW_UNSND (attr);
22012       break;
22013
22014     default:
22015       complaint (_("unsupported const value attribute form: '%s'"),
22016                  dwarf_form_name (attr->form));
22017       *value = 0;
22018       break;
22019     }
22020 }
22021
22022
22023 /* Copy constant value from an attribute to a symbol.  */
22024
22025 static void
22026 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22027                     struct dwarf2_cu *cu)
22028 {
22029   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22030   LONGEST value;
22031   const gdb_byte *bytes;
22032   struct dwarf2_locexpr_baton *baton;
22033
22034   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22035                            SYMBOL_PRINT_NAME (sym),
22036                            &objfile->objfile_obstack, cu,
22037                            &value, &bytes, &baton);
22038
22039   if (baton != NULL)
22040     {
22041       SYMBOL_LOCATION_BATON (sym) = baton;
22042       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22043     }
22044   else if (bytes != NULL)
22045      {
22046       SYMBOL_VALUE_BYTES (sym) = bytes;
22047       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22048     }
22049   else
22050     {
22051       SYMBOL_VALUE (sym) = value;
22052       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22053     }
22054 }
22055
22056 /* Return the type of the die in question using its DW_AT_type attribute.  */
22057
22058 static struct type *
22059 die_type (struct die_info *die, struct dwarf2_cu *cu)
22060 {
22061   struct attribute *type_attr;
22062
22063   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22064   if (!type_attr)
22065     {
22066       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22067       /* A missing DW_AT_type represents a void type.  */
22068       return objfile_type (objfile)->builtin_void;
22069     }
22070
22071   return lookup_die_type (die, type_attr, cu);
22072 }
22073
22074 /* True iff CU's producer generates GNAT Ada auxiliary information
22075    that allows to find parallel types through that information instead
22076    of having to do expensive parallel lookups by type name.  */
22077
22078 static int
22079 need_gnat_info (struct dwarf2_cu *cu)
22080 {
22081   /* Assume that the Ada compiler was GNAT, which always produces
22082      the auxiliary information.  */
22083   return (cu->language == language_ada);
22084 }
22085
22086 /* Return the auxiliary type of the die in question using its
22087    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22088    attribute is not present.  */
22089
22090 static struct type *
22091 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22092 {
22093   struct attribute *type_attr;
22094
22095   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22096   if (!type_attr)
22097     return NULL;
22098
22099   return lookup_die_type (die, type_attr, cu);
22100 }
22101
22102 /* If DIE has a descriptive_type attribute, then set the TYPE's
22103    descriptive type accordingly.  */
22104
22105 static void
22106 set_descriptive_type (struct type *type, struct die_info *die,
22107                       struct dwarf2_cu *cu)
22108 {
22109   struct type *descriptive_type = die_descriptive_type (die, cu);
22110
22111   if (descriptive_type)
22112     {
22113       ALLOCATE_GNAT_AUX_TYPE (type);
22114       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22115     }
22116 }
22117
22118 /* Return the containing type of the die in question using its
22119    DW_AT_containing_type attribute.  */
22120
22121 static struct type *
22122 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22123 {
22124   struct attribute *type_attr;
22125   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22126
22127   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22128   if (!type_attr)
22129     error (_("Dwarf Error: Problem turning containing type into gdb type "
22130              "[in module %s]"), objfile_name (objfile));
22131
22132   return lookup_die_type (die, type_attr, cu);
22133 }
22134
22135 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22136
22137 static struct type *
22138 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22139 {
22140   struct dwarf2_per_objfile *dwarf2_per_objfile
22141     = cu->per_cu->dwarf2_per_objfile;
22142   struct objfile *objfile = dwarf2_per_objfile->objfile;
22143   char *saved;
22144
22145   std::string message
22146     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22147                      objfile_name (objfile),
22148                      sect_offset_str (cu->header.sect_off),
22149                      sect_offset_str (die->sect_off));
22150   saved = obstack_strdup (&objfile->objfile_obstack, message);
22151
22152   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22153 }
22154
22155 /* Look up the type of DIE in CU using its type attribute ATTR.
22156    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22157    DW_AT_containing_type.
22158    If there is no type substitute an error marker.  */
22159
22160 static struct type *
22161 lookup_die_type (struct die_info *die, const struct attribute *attr,
22162                  struct dwarf2_cu *cu)
22163 {
22164   struct dwarf2_per_objfile *dwarf2_per_objfile
22165     = cu->per_cu->dwarf2_per_objfile;
22166   struct objfile *objfile = dwarf2_per_objfile->objfile;
22167   struct type *this_type;
22168
22169   gdb_assert (attr->name == DW_AT_type
22170               || attr->name == DW_AT_GNAT_descriptive_type
22171               || attr->name == DW_AT_containing_type);
22172
22173   /* First see if we have it cached.  */
22174
22175   if (attr->form == DW_FORM_GNU_ref_alt)
22176     {
22177       struct dwarf2_per_cu_data *per_cu;
22178       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22179
22180       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22181                                                  dwarf2_per_objfile);
22182       this_type = get_die_type_at_offset (sect_off, per_cu);
22183     }
22184   else if (attr_form_is_ref (attr))
22185     {
22186       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22187
22188       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22189     }
22190   else if (attr->form == DW_FORM_ref_sig8)
22191     {
22192       ULONGEST signature = DW_SIGNATURE (attr);
22193
22194       return get_signatured_type (die, signature, cu);
22195     }
22196   else
22197     {
22198       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22199                    " at %s [in module %s]"),
22200                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22201                  objfile_name (objfile));
22202       return build_error_marker_type (cu, die);
22203     }
22204
22205   /* If not cached we need to read it in.  */
22206
22207   if (this_type == NULL)
22208     {
22209       struct die_info *type_die = NULL;
22210       struct dwarf2_cu *type_cu = cu;
22211
22212       if (attr_form_is_ref (attr))
22213         type_die = follow_die_ref (die, attr, &type_cu);
22214       if (type_die == NULL)
22215         return build_error_marker_type (cu, die);
22216       /* If we find the type now, it's probably because the type came
22217          from an inter-CU reference and the type's CU got expanded before
22218          ours.  */
22219       this_type = read_type_die (type_die, type_cu);
22220     }
22221
22222   /* If we still don't have a type use an error marker.  */
22223
22224   if (this_type == NULL)
22225     return build_error_marker_type (cu, die);
22226
22227   return this_type;
22228 }
22229
22230 /* Return the type in DIE, CU.
22231    Returns NULL for invalid types.
22232
22233    This first does a lookup in die_type_hash,
22234    and only reads the die in if necessary.
22235
22236    NOTE: This can be called when reading in partial or full symbols.  */
22237
22238 static struct type *
22239 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22240 {
22241   struct type *this_type;
22242
22243   this_type = get_die_type (die, cu);
22244   if (this_type)
22245     return this_type;
22246
22247   return read_type_die_1 (die, cu);
22248 }
22249
22250 /* Read the type in DIE, CU.
22251    Returns NULL for invalid types.  */
22252
22253 static struct type *
22254 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22255 {
22256   struct type *this_type = NULL;
22257
22258   switch (die->tag)
22259     {
22260     case DW_TAG_class_type:
22261     case DW_TAG_interface_type:
22262     case DW_TAG_structure_type:
22263     case DW_TAG_union_type:
22264       this_type = read_structure_type (die, cu);
22265       break;
22266     case DW_TAG_enumeration_type:
22267       this_type = read_enumeration_type (die, cu);
22268       break;
22269     case DW_TAG_subprogram:
22270     case DW_TAG_subroutine_type:
22271     case DW_TAG_inlined_subroutine:
22272       this_type = read_subroutine_type (die, cu);
22273       break;
22274     case DW_TAG_array_type:
22275       this_type = read_array_type (die, cu);
22276       break;
22277     case DW_TAG_set_type:
22278       this_type = read_set_type (die, cu);
22279       break;
22280     case DW_TAG_pointer_type:
22281       this_type = read_tag_pointer_type (die, cu);
22282       break;
22283     case DW_TAG_ptr_to_member_type:
22284       this_type = read_tag_ptr_to_member_type (die, cu);
22285       break;
22286     case DW_TAG_reference_type:
22287       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22288       break;
22289     case DW_TAG_rvalue_reference_type:
22290       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22291       break;
22292     case DW_TAG_const_type:
22293       this_type = read_tag_const_type (die, cu);
22294       break;
22295     case DW_TAG_volatile_type:
22296       this_type = read_tag_volatile_type (die, cu);
22297       break;
22298     case DW_TAG_restrict_type:
22299       this_type = read_tag_restrict_type (die, cu);
22300       break;
22301     case DW_TAG_string_type:
22302       this_type = read_tag_string_type (die, cu);
22303       break;
22304     case DW_TAG_typedef:
22305       this_type = read_typedef (die, cu);
22306       break;
22307     case DW_TAG_subrange_type:
22308       this_type = read_subrange_type (die, cu);
22309       break;
22310     case DW_TAG_base_type:
22311       this_type = read_base_type (die, cu);
22312       break;
22313     case DW_TAG_unspecified_type:
22314       this_type = read_unspecified_type (die, cu);
22315       break;
22316     case DW_TAG_namespace:
22317       this_type = read_namespace_type (die, cu);
22318       break;
22319     case DW_TAG_module:
22320       this_type = read_module_type (die, cu);
22321       break;
22322     case DW_TAG_atomic_type:
22323       this_type = read_tag_atomic_type (die, cu);
22324       break;
22325     default:
22326       complaint (_("unexpected tag in read_type_die: '%s'"),
22327                  dwarf_tag_name (die->tag));
22328       break;
22329     }
22330
22331   return this_type;
22332 }
22333
22334 /* See if we can figure out if the class lives in a namespace.  We do
22335    this by looking for a member function; its demangled name will
22336    contain namespace info, if there is any.
22337    Return the computed name or NULL.
22338    Space for the result is allocated on the objfile's obstack.
22339    This is the full-die version of guess_partial_die_structure_name.
22340    In this case we know DIE has no useful parent.  */
22341
22342 static char *
22343 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22344 {
22345   struct die_info *spec_die;
22346   struct dwarf2_cu *spec_cu;
22347   struct die_info *child;
22348   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22349
22350   spec_cu = cu;
22351   spec_die = die_specification (die, &spec_cu);
22352   if (spec_die != NULL)
22353     {
22354       die = spec_die;
22355       cu = spec_cu;
22356     }
22357
22358   for (child = die->child;
22359        child != NULL;
22360        child = child->sibling)
22361     {
22362       if (child->tag == DW_TAG_subprogram)
22363         {
22364           const char *linkage_name = dw2_linkage_name (child, cu);
22365
22366           if (linkage_name != NULL)
22367             {
22368               char *actual_name
22369                 = language_class_name_from_physname (cu->language_defn,
22370                                                      linkage_name);
22371               char *name = NULL;
22372
22373               if (actual_name != NULL)
22374                 {
22375                   const char *die_name = dwarf2_name (die, cu);
22376
22377                   if (die_name != NULL
22378                       && strcmp (die_name, actual_name) != 0)
22379                     {
22380                       /* Strip off the class name from the full name.
22381                          We want the prefix.  */
22382                       int die_name_len = strlen (die_name);
22383                       int actual_name_len = strlen (actual_name);
22384
22385                       /* Test for '::' as a sanity check.  */
22386                       if (actual_name_len > die_name_len + 2
22387                           && actual_name[actual_name_len
22388                                          - die_name_len - 1] == ':')
22389                         name = obstack_strndup (
22390                           &objfile->per_bfd->storage_obstack,
22391                           actual_name, actual_name_len - die_name_len - 2);
22392                     }
22393                 }
22394               xfree (actual_name);
22395               return name;
22396             }
22397         }
22398     }
22399
22400   return NULL;
22401 }
22402
22403 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22404    prefix part in such case.  See
22405    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22406
22407 static const char *
22408 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22409 {
22410   struct attribute *attr;
22411   const char *base;
22412
22413   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22414       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22415     return NULL;
22416
22417   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22418     return NULL;
22419
22420   attr = dw2_linkage_name_attr (die, cu);
22421   if (attr == NULL || DW_STRING (attr) == NULL)
22422     return NULL;
22423
22424   /* dwarf2_name had to be already called.  */
22425   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22426
22427   /* Strip the base name, keep any leading namespaces/classes.  */
22428   base = strrchr (DW_STRING (attr), ':');
22429   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22430     return "";
22431
22432   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22433   return obstack_strndup (&objfile->per_bfd->storage_obstack,
22434                           DW_STRING (attr),
22435                           &base[-1] - DW_STRING (attr));
22436 }
22437
22438 /* Return the name of the namespace/class that DIE is defined within,
22439    or "" if we can't tell.  The caller should not xfree the result.
22440
22441    For example, if we're within the method foo() in the following
22442    code:
22443
22444    namespace N {
22445      class C {
22446        void foo () {
22447        }
22448      };
22449    }
22450
22451    then determine_prefix on foo's die will return "N::C".  */
22452
22453 static const char *
22454 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22455 {
22456   struct dwarf2_per_objfile *dwarf2_per_objfile
22457     = cu->per_cu->dwarf2_per_objfile;
22458   struct die_info *parent, *spec_die;
22459   struct dwarf2_cu *spec_cu;
22460   struct type *parent_type;
22461   const char *retval;
22462
22463   if (cu->language != language_cplus
22464       && cu->language != language_fortran && cu->language != language_d
22465       && cu->language != language_rust)
22466     return "";
22467
22468   retval = anonymous_struct_prefix (die, cu);
22469   if (retval)
22470     return retval;
22471
22472   /* We have to be careful in the presence of DW_AT_specification.
22473      For example, with GCC 3.4, given the code
22474
22475      namespace N {
22476        void foo() {
22477          // Definition of N::foo.
22478        }
22479      }
22480
22481      then we'll have a tree of DIEs like this:
22482
22483      1: DW_TAG_compile_unit
22484        2: DW_TAG_namespace        // N
22485          3: DW_TAG_subprogram     // declaration of N::foo
22486        4: DW_TAG_subprogram       // definition of N::foo
22487             DW_AT_specification   // refers to die #3
22488
22489      Thus, when processing die #4, we have to pretend that we're in
22490      the context of its DW_AT_specification, namely the contex of die
22491      #3.  */
22492   spec_cu = cu;
22493   spec_die = die_specification (die, &spec_cu);
22494   if (spec_die == NULL)
22495     parent = die->parent;
22496   else
22497     {
22498       parent = spec_die->parent;
22499       cu = spec_cu;
22500     }
22501
22502   if (parent == NULL)
22503     return "";
22504   else if (parent->building_fullname)
22505     {
22506       const char *name;
22507       const char *parent_name;
22508
22509       /* It has been seen on RealView 2.2 built binaries,
22510          DW_TAG_template_type_param types actually _defined_ as
22511          children of the parent class:
22512
22513          enum E {};
22514          template class <class Enum> Class{};
22515          Class<enum E> class_e;
22516
22517          1: DW_TAG_class_type (Class)
22518            2: DW_TAG_enumeration_type (E)
22519              3: DW_TAG_enumerator (enum1:0)
22520              3: DW_TAG_enumerator (enum2:1)
22521              ...
22522            2: DW_TAG_template_type_param
22523               DW_AT_type  DW_FORM_ref_udata (E)
22524
22525          Besides being broken debug info, it can put GDB into an
22526          infinite loop.  Consider:
22527
22528          When we're building the full name for Class<E>, we'll start
22529          at Class, and go look over its template type parameters,
22530          finding E.  We'll then try to build the full name of E, and
22531          reach here.  We're now trying to build the full name of E,
22532          and look over the parent DIE for containing scope.  In the
22533          broken case, if we followed the parent DIE of E, we'd again
22534          find Class, and once again go look at its template type
22535          arguments, etc., etc.  Simply don't consider such parent die
22536          as source-level parent of this die (it can't be, the language
22537          doesn't allow it), and break the loop here.  */
22538       name = dwarf2_name (die, cu);
22539       parent_name = dwarf2_name (parent, cu);
22540       complaint (_("template param type '%s' defined within parent '%s'"),
22541                  name ? name : "<unknown>",
22542                  parent_name ? parent_name : "<unknown>");
22543       return "";
22544     }
22545   else
22546     switch (parent->tag)
22547       {
22548       case DW_TAG_namespace:
22549         parent_type = read_type_die (parent, cu);
22550         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22551            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22552            Work around this problem here.  */
22553         if (cu->language == language_cplus
22554             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22555           return "";
22556         /* We give a name to even anonymous namespaces.  */
22557         return TYPE_NAME (parent_type);
22558       case DW_TAG_class_type:
22559       case DW_TAG_interface_type:
22560       case DW_TAG_structure_type:
22561       case DW_TAG_union_type:
22562       case DW_TAG_module:
22563         parent_type = read_type_die (parent, cu);
22564         if (TYPE_NAME (parent_type) != NULL)
22565           return TYPE_NAME (parent_type);
22566         else
22567           /* An anonymous structure is only allowed non-static data
22568              members; no typedefs, no member functions, et cetera.
22569              So it does not need a prefix.  */
22570           return "";
22571       case DW_TAG_compile_unit:
22572       case DW_TAG_partial_unit:
22573         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22574         if (cu->language == language_cplus
22575             && !dwarf2_per_objfile->types.empty ()
22576             && die->child != NULL
22577             && (die->tag == DW_TAG_class_type
22578                 || die->tag == DW_TAG_structure_type
22579                 || die->tag == DW_TAG_union_type))
22580           {
22581             char *name = guess_full_die_structure_name (die, cu);
22582             if (name != NULL)
22583               return name;
22584           }
22585         return "";
22586       case DW_TAG_enumeration_type:
22587         parent_type = read_type_die (parent, cu);
22588         if (TYPE_DECLARED_CLASS (parent_type))
22589           {
22590             if (TYPE_NAME (parent_type) != NULL)
22591               return TYPE_NAME (parent_type);
22592             return "";
22593           }
22594         /* Fall through.  */
22595       default:
22596         return determine_prefix (parent, cu);
22597       }
22598 }
22599
22600 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22601    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22602    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22603    an obconcat, otherwise allocate storage for the result.  The CU argument is
22604    used to determine the language and hence, the appropriate separator.  */
22605
22606 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22607
22608 static char *
22609 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22610                  int physname, struct dwarf2_cu *cu)
22611 {
22612   const char *lead = "";
22613   const char *sep;
22614
22615   if (suffix == NULL || suffix[0] == '\0'
22616       || prefix == NULL || prefix[0] == '\0')
22617     sep = "";
22618   else if (cu->language == language_d)
22619     {
22620       /* For D, the 'main' function could be defined in any module, but it
22621          should never be prefixed.  */
22622       if (strcmp (suffix, "D main") == 0)
22623         {
22624           prefix = "";
22625           sep = "";
22626         }
22627       else
22628         sep = ".";
22629     }
22630   else if (cu->language == language_fortran && physname)
22631     {
22632       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22633          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22634
22635       lead = "__";
22636       sep = "_MOD_";
22637     }
22638   else
22639     sep = "::";
22640
22641   if (prefix == NULL)
22642     prefix = "";
22643   if (suffix == NULL)
22644     suffix = "";
22645
22646   if (obs == NULL)
22647     {
22648       char *retval
22649         = ((char *)
22650            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22651
22652       strcpy (retval, lead);
22653       strcat (retval, prefix);
22654       strcat (retval, sep);
22655       strcat (retval, suffix);
22656       return retval;
22657     }
22658   else
22659     {
22660       /* We have an obstack.  */
22661       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22662     }
22663 }
22664
22665 /* Return sibling of die, NULL if no sibling.  */
22666
22667 static struct die_info *
22668 sibling_die (struct die_info *die)
22669 {
22670   return die->sibling;
22671 }
22672
22673 /* Get name of a die, return NULL if not found.  */
22674
22675 static const char *
22676 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22677                           struct obstack *obstack)
22678 {
22679   if (name && cu->language == language_cplus)
22680     {
22681       std::string canon_name = cp_canonicalize_string (name);
22682
22683       if (!canon_name.empty ())
22684         {
22685           if (canon_name != name)
22686             name = obstack_strdup (obstack, canon_name);
22687         }
22688     }
22689
22690   return name;
22691 }
22692
22693 /* Get name of a die, return NULL if not found.
22694    Anonymous namespaces are converted to their magic string.  */
22695
22696 static const char *
22697 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22698 {
22699   struct attribute *attr;
22700   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22701
22702   attr = dwarf2_attr (die, DW_AT_name, cu);
22703   if ((!attr || !DW_STRING (attr))
22704       && die->tag != DW_TAG_namespace
22705       && die->tag != DW_TAG_class_type
22706       && die->tag != DW_TAG_interface_type
22707       && die->tag != DW_TAG_structure_type
22708       && die->tag != DW_TAG_union_type)
22709     return NULL;
22710
22711   switch (die->tag)
22712     {
22713     case DW_TAG_compile_unit:
22714     case DW_TAG_partial_unit:
22715       /* Compilation units have a DW_AT_name that is a filename, not
22716          a source language identifier.  */
22717     case DW_TAG_enumeration_type:
22718     case DW_TAG_enumerator:
22719       /* These tags always have simple identifiers already; no need
22720          to canonicalize them.  */
22721       return DW_STRING (attr);
22722
22723     case DW_TAG_namespace:
22724       if (attr != NULL && DW_STRING (attr) != NULL)
22725         return DW_STRING (attr);
22726       return CP_ANONYMOUS_NAMESPACE_STR;
22727
22728     case DW_TAG_class_type:
22729     case DW_TAG_interface_type:
22730     case DW_TAG_structure_type:
22731     case DW_TAG_union_type:
22732       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22733          structures or unions.  These were of the form "._%d" in GCC 4.1,
22734          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22735          and GCC 4.4.  We work around this problem by ignoring these.  */
22736       if (attr && DW_STRING (attr)
22737           && (startswith (DW_STRING (attr), "._")
22738               || startswith (DW_STRING (attr), "<anonymous")))
22739         return NULL;
22740
22741       /* GCC might emit a nameless typedef that has a linkage name.  See
22742          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22743       if (!attr || DW_STRING (attr) == NULL)
22744         {
22745           char *demangled = NULL;
22746
22747           attr = dw2_linkage_name_attr (die, cu);
22748           if (attr == NULL || DW_STRING (attr) == NULL)
22749             return NULL;
22750
22751           /* Avoid demangling DW_STRING (attr) the second time on a second
22752              call for the same DIE.  */
22753           if (!DW_STRING_IS_CANONICAL (attr))
22754             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22755
22756           if (demangled)
22757             {
22758               const char *base;
22759
22760               /* FIXME: we already did this for the partial symbol... */
22761               DW_STRING (attr)
22762                 = obstack_strdup (&objfile->per_bfd->storage_obstack,
22763                                   demangled);
22764               DW_STRING_IS_CANONICAL (attr) = 1;
22765               xfree (demangled);
22766
22767               /* Strip any leading namespaces/classes, keep only the base name.
22768                  DW_AT_name for named DIEs does not contain the prefixes.  */
22769               base = strrchr (DW_STRING (attr), ':');
22770               if (base && base > DW_STRING (attr) && base[-1] == ':')
22771                 return &base[1];
22772               else
22773                 return DW_STRING (attr);
22774             }
22775         }
22776       break;
22777
22778     default:
22779       break;
22780     }
22781
22782   if (!DW_STRING_IS_CANONICAL (attr))
22783     {
22784       DW_STRING (attr)
22785         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22786                                     &objfile->per_bfd->storage_obstack);
22787       DW_STRING_IS_CANONICAL (attr) = 1;
22788     }
22789   return DW_STRING (attr);
22790 }
22791
22792 /* Return the die that this die in an extension of, or NULL if there
22793    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22794    containing the return value on output.  */
22795
22796 static struct die_info *
22797 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22798 {
22799   struct attribute *attr;
22800
22801   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22802   if (attr == NULL)
22803     return NULL;
22804
22805   return follow_die_ref (die, attr, ext_cu);
22806 }
22807
22808 /* A convenience function that returns an "unknown" DWARF name,
22809    including the value of V.  STR is the name of the entity being
22810    printed, e.g., "TAG".  */
22811
22812 static const char *
22813 dwarf_unknown (const char *str, unsigned v)
22814 {
22815   char *cell = get_print_cell ();
22816   xsnprintf (cell, PRINT_CELL_SIZE, "DW_%s_<unknown: %u>", str, v);
22817   return cell;
22818 }
22819
22820 /* Convert a DIE tag into its string name.  */
22821
22822 static const char *
22823 dwarf_tag_name (unsigned tag)
22824 {
22825   const char *name = get_DW_TAG_name (tag);
22826
22827   if (name == NULL)
22828     return dwarf_unknown ("TAG", tag);
22829
22830   return name;
22831 }
22832
22833 /* Convert a DWARF attribute code into its string name.  */
22834
22835 static const char *
22836 dwarf_attr_name (unsigned attr)
22837 {
22838   const char *name;
22839
22840 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22841   if (attr == DW_AT_MIPS_fde)
22842     return "DW_AT_MIPS_fde";
22843 #else
22844   if (attr == DW_AT_HP_block_index)
22845     return "DW_AT_HP_block_index";
22846 #endif
22847
22848   name = get_DW_AT_name (attr);
22849
22850   if (name == NULL)
22851     return dwarf_unknown ("AT", attr);
22852
22853   return name;
22854 }
22855
22856 /* Convert a unit type to corresponding DW_UT name.  */
22857
22858 static const char *
22859 dwarf_unit_type_name (int unit_type) {
22860   switch (unit_type)
22861     {
22862       case 0x01:
22863         return "DW_UT_compile (0x01)";
22864       case 0x02:
22865         return "DW_UT_type (0x02)";
22866       case 0x03:
22867         return "DW_UT_partial (0x03)";
22868       case 0x04:
22869         return "DW_UT_skeleton (0x04)";
22870       case 0x05:
22871         return "DW_UT_split_compile (0x05)";
22872       case 0x06:
22873         return "DW_UT_split_type (0x06)";
22874       case 0x80:
22875         return "DW_UT_lo_user (0x80)";
22876       case 0xff:
22877         return "DW_UT_hi_user (0xff)";
22878       default:
22879         return nullptr;
22880     }
22881 }
22882
22883 /* Convert a DWARF value form code into its string name.  */
22884
22885 static const char *
22886 dwarf_form_name (unsigned form)
22887 {
22888   const char *name = get_DW_FORM_name (form);
22889
22890   if (name == NULL)
22891     return dwarf_unknown ("FORM", form);
22892
22893   return name;
22894 }
22895
22896 static const char *
22897 dwarf_bool_name (unsigned mybool)
22898 {
22899   if (mybool)
22900     return "TRUE";
22901   else
22902     return "FALSE";
22903 }
22904
22905 /* Convert a DWARF type code into its string name.  */
22906
22907 static const char *
22908 dwarf_type_encoding_name (unsigned enc)
22909 {
22910   const char *name = get_DW_ATE_name (enc);
22911
22912   if (name == NULL)
22913     return dwarf_unknown ("ATE", enc);
22914
22915   return name;
22916 }
22917
22918 static void
22919 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22920 {
22921   unsigned int i;
22922
22923   print_spaces (indent, f);
22924   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22925                       dwarf_tag_name (die->tag), die->abbrev,
22926                       sect_offset_str (die->sect_off));
22927
22928   if (die->parent != NULL)
22929     {
22930       print_spaces (indent, f);
22931       fprintf_unfiltered (f, "  parent at offset: %s\n",
22932                           sect_offset_str (die->parent->sect_off));
22933     }
22934
22935   print_spaces (indent, f);
22936   fprintf_unfiltered (f, "  has children: %s\n",
22937            dwarf_bool_name (die->child != NULL));
22938
22939   print_spaces (indent, f);
22940   fprintf_unfiltered (f, "  attributes:\n");
22941
22942   for (i = 0; i < die->num_attrs; ++i)
22943     {
22944       print_spaces (indent, f);
22945       fprintf_unfiltered (f, "    %s (%s) ",
22946                dwarf_attr_name (die->attrs[i].name),
22947                dwarf_form_name (die->attrs[i].form));
22948
22949       switch (die->attrs[i].form)
22950         {
22951         case DW_FORM_addr:
22952         case DW_FORM_addrx:
22953         case DW_FORM_GNU_addr_index:
22954           fprintf_unfiltered (f, "address: ");
22955           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22956           break;
22957         case DW_FORM_block2:
22958         case DW_FORM_block4:
22959         case DW_FORM_block:
22960         case DW_FORM_block1:
22961           fprintf_unfiltered (f, "block: size %s",
22962                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22963           break;
22964         case DW_FORM_exprloc:
22965           fprintf_unfiltered (f, "expression: size %s",
22966                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22967           break;
22968         case DW_FORM_data16:
22969           fprintf_unfiltered (f, "constant of 16 bytes");
22970           break;
22971         case DW_FORM_ref_addr:
22972           fprintf_unfiltered (f, "ref address: ");
22973           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22974           break;
22975         case DW_FORM_GNU_ref_alt:
22976           fprintf_unfiltered (f, "alt ref address: ");
22977           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22978           break;
22979         case DW_FORM_ref1:
22980         case DW_FORM_ref2:
22981         case DW_FORM_ref4:
22982         case DW_FORM_ref8:
22983         case DW_FORM_ref_udata:
22984           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22985                               (long) (DW_UNSND (&die->attrs[i])));
22986           break;
22987         case DW_FORM_data1:
22988         case DW_FORM_data2:
22989         case DW_FORM_data4:
22990         case DW_FORM_data8:
22991         case DW_FORM_udata:
22992         case DW_FORM_sdata:
22993           fprintf_unfiltered (f, "constant: %s",
22994                               pulongest (DW_UNSND (&die->attrs[i])));
22995           break;
22996         case DW_FORM_sec_offset:
22997           fprintf_unfiltered (f, "section offset: %s",
22998                               pulongest (DW_UNSND (&die->attrs[i])));
22999           break;
23000         case DW_FORM_ref_sig8:
23001           fprintf_unfiltered (f, "signature: %s",
23002                               hex_string (DW_SIGNATURE (&die->attrs[i])));
23003           break;
23004         case DW_FORM_string:
23005         case DW_FORM_strp:
23006         case DW_FORM_line_strp:
23007         case DW_FORM_strx:
23008         case DW_FORM_GNU_str_index:
23009         case DW_FORM_GNU_strp_alt:
23010           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
23011                    DW_STRING (&die->attrs[i])
23012                    ? DW_STRING (&die->attrs[i]) : "",
23013                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
23014           break;
23015         case DW_FORM_flag:
23016           if (DW_UNSND (&die->attrs[i]))
23017             fprintf_unfiltered (f, "flag: TRUE");
23018           else
23019             fprintf_unfiltered (f, "flag: FALSE");
23020           break;
23021         case DW_FORM_flag_present:
23022           fprintf_unfiltered (f, "flag: TRUE");
23023           break;
23024         case DW_FORM_indirect:
23025           /* The reader will have reduced the indirect form to
23026              the "base form" so this form should not occur.  */
23027           fprintf_unfiltered (f, 
23028                               "unexpected attribute form: DW_FORM_indirect");
23029           break;
23030         case DW_FORM_implicit_const:
23031           fprintf_unfiltered (f, "constant: %s",
23032                               plongest (DW_SND (&die->attrs[i])));
23033           break;
23034         default:
23035           fprintf_unfiltered (f, "unsupported attribute form: %d.",
23036                    die->attrs[i].form);
23037           break;
23038         }
23039       fprintf_unfiltered (f, "\n");
23040     }
23041 }
23042
23043 static void
23044 dump_die_for_error (struct die_info *die)
23045 {
23046   dump_die_shallow (gdb_stderr, 0, die);
23047 }
23048
23049 static void
23050 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23051 {
23052   int indent = level * 4;
23053
23054   gdb_assert (die != NULL);
23055
23056   if (level >= max_level)
23057     return;
23058
23059   dump_die_shallow (f, indent, die);
23060
23061   if (die->child != NULL)
23062     {
23063       print_spaces (indent, f);
23064       fprintf_unfiltered (f, "  Children:");
23065       if (level + 1 < max_level)
23066         {
23067           fprintf_unfiltered (f, "\n");
23068           dump_die_1 (f, level + 1, max_level, die->child);
23069         }
23070       else
23071         {
23072           fprintf_unfiltered (f,
23073                               " [not printed, max nesting level reached]\n");
23074         }
23075     }
23076
23077   if (die->sibling != NULL && level > 0)
23078     {
23079       dump_die_1 (f, level, max_level, die->sibling);
23080     }
23081 }
23082
23083 /* This is called from the pdie macro in gdbinit.in.
23084    It's not static so gcc will keep a copy callable from gdb.  */
23085
23086 void
23087 dump_die (struct die_info *die, int max_level)
23088 {
23089   dump_die_1 (gdb_stdlog, 0, max_level, die);
23090 }
23091
23092 static void
23093 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23094 {
23095   void **slot;
23096
23097   slot = htab_find_slot_with_hash (cu->die_hash, die,
23098                                    to_underlying (die->sect_off),
23099                                    INSERT);
23100
23101   *slot = die;
23102 }
23103
23104 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
23105    required kind.  */
23106
23107 static sect_offset
23108 dwarf2_get_ref_die_offset (const struct attribute *attr)
23109 {
23110   if (attr_form_is_ref (attr))
23111     return (sect_offset) DW_UNSND (attr);
23112
23113   complaint (_("unsupported die ref attribute form: '%s'"),
23114              dwarf_form_name (attr->form));
23115   return {};
23116 }
23117
23118 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
23119  * the value held by the attribute is not constant.  */
23120
23121 static LONGEST
23122 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
23123 {
23124   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
23125     return DW_SND (attr);
23126   else if (attr->form == DW_FORM_udata
23127            || attr->form == DW_FORM_data1
23128            || attr->form == DW_FORM_data2
23129            || attr->form == DW_FORM_data4
23130            || attr->form == DW_FORM_data8)
23131     return DW_UNSND (attr);
23132   else
23133     {
23134       /* For DW_FORM_data16 see attr_form_is_constant.  */
23135       complaint (_("Attribute value is not a constant (%s)"),
23136                  dwarf_form_name (attr->form));
23137       return default_value;
23138     }
23139 }
23140
23141 /* Follow reference or signature attribute ATTR of SRC_DIE.
23142    On entry *REF_CU is the CU of SRC_DIE.
23143    On exit *REF_CU is the CU of the result.  */
23144
23145 static struct die_info *
23146 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23147                        struct dwarf2_cu **ref_cu)
23148 {
23149   struct die_info *die;
23150
23151   if (attr_form_is_ref (attr))
23152     die = follow_die_ref (src_die, attr, ref_cu);
23153   else if (attr->form == DW_FORM_ref_sig8)
23154     die = follow_die_sig (src_die, attr, ref_cu);
23155   else
23156     {
23157       dump_die_for_error (src_die);
23158       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23159              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23160     }
23161
23162   return die;
23163 }
23164
23165 /* Follow reference OFFSET.
23166    On entry *REF_CU is the CU of the source die referencing OFFSET.
23167    On exit *REF_CU is the CU of the result.
23168    Returns NULL if OFFSET is invalid.  */
23169
23170 static struct die_info *
23171 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23172                    struct dwarf2_cu **ref_cu)
23173 {
23174   struct die_info temp_die;
23175   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23176   struct dwarf2_per_objfile *dwarf2_per_objfile
23177     = cu->per_cu->dwarf2_per_objfile;
23178
23179   gdb_assert (cu->per_cu != NULL);
23180
23181   target_cu = cu;
23182
23183   if (cu->per_cu->is_debug_types)
23184     {
23185       /* .debug_types CUs cannot reference anything outside their CU.
23186          If they need to, they have to reference a signatured type via
23187          DW_FORM_ref_sig8.  */
23188       if (!offset_in_cu_p (&cu->header, sect_off))
23189         return NULL;
23190     }
23191   else if (offset_in_dwz != cu->per_cu->is_dwz
23192            || !offset_in_cu_p (&cu->header, sect_off))
23193     {
23194       struct dwarf2_per_cu_data *per_cu;
23195
23196       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23197                                                  dwarf2_per_objfile);
23198
23199       /* If necessary, add it to the queue and load its DIEs.  */
23200       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23201         load_full_comp_unit (per_cu, false, cu->language);
23202
23203       target_cu = per_cu->cu;
23204     }
23205   else if (cu->dies == NULL)
23206     {
23207       /* We're loading full DIEs during partial symbol reading.  */
23208       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23209       load_full_comp_unit (cu->per_cu, false, language_minimal);
23210     }
23211
23212   *ref_cu = target_cu;
23213   temp_die.sect_off = sect_off;
23214
23215   if (target_cu != cu)
23216     target_cu->ancestor = cu;
23217
23218   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23219                                                   &temp_die,
23220                                                   to_underlying (sect_off));
23221 }
23222
23223 /* Follow reference attribute ATTR of SRC_DIE.
23224    On entry *REF_CU is the CU of SRC_DIE.
23225    On exit *REF_CU is the CU of the result.  */
23226
23227 static struct die_info *
23228 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23229                 struct dwarf2_cu **ref_cu)
23230 {
23231   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23232   struct dwarf2_cu *cu = *ref_cu;
23233   struct die_info *die;
23234
23235   die = follow_die_offset (sect_off,
23236                            (attr->form == DW_FORM_GNU_ref_alt
23237                             || cu->per_cu->is_dwz),
23238                            ref_cu);
23239   if (!die)
23240     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23241            "at %s [in module %s]"),
23242            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23243            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23244
23245   return die;
23246 }
23247
23248 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23249    Returned value is intended for DW_OP_call*.  Returned
23250    dwarf2_locexpr_baton->data has lifetime of
23251    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23252
23253 struct dwarf2_locexpr_baton
23254 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23255                                struct dwarf2_per_cu_data *per_cu,
23256                                CORE_ADDR (*get_frame_pc) (void *baton),
23257                                void *baton, bool resolve_abstract_p)
23258 {
23259   struct dwarf2_cu *cu;
23260   struct die_info *die;
23261   struct attribute *attr;
23262   struct dwarf2_locexpr_baton retval;
23263   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
23264   struct objfile *objfile = dwarf2_per_objfile->objfile;
23265
23266   if (per_cu->cu == NULL)
23267     load_cu (per_cu, false);
23268   cu = per_cu->cu;
23269   if (cu == NULL)
23270     {
23271       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23272          Instead just throw an error, not much else we can do.  */
23273       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23274              sect_offset_str (sect_off), objfile_name (objfile));
23275     }
23276
23277   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23278   if (!die)
23279     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23280            sect_offset_str (sect_off), objfile_name (objfile));
23281
23282   attr = dwarf2_attr (die, DW_AT_location, cu);
23283   if (!attr && resolve_abstract_p
23284       && (dwarf2_per_objfile->abstract_to_concrete.find (die->sect_off)
23285           != dwarf2_per_objfile->abstract_to_concrete.end ()))
23286     {
23287       CORE_ADDR pc = (*get_frame_pc) (baton);
23288       CORE_ADDR baseaddr
23289         = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23290       struct gdbarch *gdbarch = get_objfile_arch (objfile);
23291
23292       for (const auto &cand_off
23293              : dwarf2_per_objfile->abstract_to_concrete[die->sect_off])
23294         {
23295           struct dwarf2_cu *cand_cu = cu;
23296           struct die_info *cand
23297             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
23298           if (!cand
23299               || !cand->parent
23300               || cand->parent->tag != DW_TAG_subprogram)
23301             continue;
23302
23303           CORE_ADDR pc_low, pc_high;
23304           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23305           if (pc_low == ((CORE_ADDR) -1))
23306             continue;
23307           pc_low = gdbarch_adjust_dwarf2_addr (gdbarch, pc_low + baseaddr);
23308           pc_high = gdbarch_adjust_dwarf2_addr (gdbarch, pc_high + baseaddr);
23309           if (!(pc_low <= pc && pc < pc_high))
23310             continue;
23311
23312           die = cand;
23313           attr = dwarf2_attr (die, DW_AT_location, cu);
23314           break;
23315         }
23316     }
23317
23318   if (!attr)
23319     {
23320       /* DWARF: "If there is no such attribute, then there is no effect.".
23321          DATA is ignored if SIZE is 0.  */
23322
23323       retval.data = NULL;
23324       retval.size = 0;
23325     }
23326   else if (attr_form_is_section_offset (attr))
23327     {
23328       struct dwarf2_loclist_baton loclist_baton;
23329       CORE_ADDR pc = (*get_frame_pc) (baton);
23330       size_t size;
23331
23332       fill_in_loclist_baton (cu, &loclist_baton, attr);
23333
23334       retval.data = dwarf2_find_location_expression (&loclist_baton,
23335                                                      &size, pc);
23336       retval.size = size;
23337     }
23338   else
23339     {
23340       if (!attr_form_is_block (attr))
23341         error (_("Dwarf Error: DIE at %s referenced in module %s "
23342                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23343                sect_offset_str (sect_off), objfile_name (objfile));
23344
23345       retval.data = DW_BLOCK (attr)->data;
23346       retval.size = DW_BLOCK (attr)->size;
23347     }
23348   retval.per_cu = cu->per_cu;
23349
23350   age_cached_comp_units (dwarf2_per_objfile);
23351
23352   return retval;
23353 }
23354
23355 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23356    offset.  */
23357
23358 struct dwarf2_locexpr_baton
23359 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23360                              struct dwarf2_per_cu_data *per_cu,
23361                              CORE_ADDR (*get_frame_pc) (void *baton),
23362                              void *baton)
23363 {
23364   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23365
23366   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23367 }
23368
23369 /* Write a constant of a given type as target-ordered bytes into
23370    OBSTACK.  */
23371
23372 static const gdb_byte *
23373 write_constant_as_bytes (struct obstack *obstack,
23374                          enum bfd_endian byte_order,
23375                          struct type *type,
23376                          ULONGEST value,
23377                          LONGEST *len)
23378 {
23379   gdb_byte *result;
23380
23381   *len = TYPE_LENGTH (type);
23382   result = (gdb_byte *) obstack_alloc (obstack, *len);
23383   store_unsigned_integer (result, *len, byte_order, value);
23384
23385   return result;
23386 }
23387
23388 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23389    pointer to the constant bytes and set LEN to the length of the
23390    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23391    does not have a DW_AT_const_value, return NULL.  */
23392
23393 const gdb_byte *
23394 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23395                              struct dwarf2_per_cu_data *per_cu,
23396                              struct obstack *obstack,
23397                              LONGEST *len)
23398 {
23399   struct dwarf2_cu *cu;
23400   struct die_info *die;
23401   struct attribute *attr;
23402   const gdb_byte *result = NULL;
23403   struct type *type;
23404   LONGEST value;
23405   enum bfd_endian byte_order;
23406   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23407
23408   if (per_cu->cu == NULL)
23409     load_cu (per_cu, false);
23410   cu = per_cu->cu;
23411   if (cu == NULL)
23412     {
23413       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23414          Instead just throw an error, not much else we can do.  */
23415       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23416              sect_offset_str (sect_off), objfile_name (objfile));
23417     }
23418
23419   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23420   if (!die)
23421     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23422            sect_offset_str (sect_off), objfile_name (objfile));
23423
23424   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23425   if (attr == NULL)
23426     return NULL;
23427
23428   byte_order = (bfd_big_endian (objfile->obfd)
23429                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23430
23431   switch (attr->form)
23432     {
23433     case DW_FORM_addr:
23434     case DW_FORM_addrx:
23435     case DW_FORM_GNU_addr_index:
23436       {
23437         gdb_byte *tem;
23438
23439         *len = cu->header.addr_size;
23440         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23441         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23442         result = tem;
23443       }
23444       break;
23445     case DW_FORM_string:
23446     case DW_FORM_strp:
23447     case DW_FORM_strx:
23448     case DW_FORM_GNU_str_index:
23449     case DW_FORM_GNU_strp_alt:
23450       /* DW_STRING is already allocated on the objfile obstack, point
23451          directly to it.  */
23452       result = (const gdb_byte *) DW_STRING (attr);
23453       *len = strlen (DW_STRING (attr));
23454       break;
23455     case DW_FORM_block1:
23456     case DW_FORM_block2:
23457     case DW_FORM_block4:
23458     case DW_FORM_block:
23459     case DW_FORM_exprloc:
23460     case DW_FORM_data16:
23461       result = DW_BLOCK (attr)->data;
23462       *len = DW_BLOCK (attr)->size;
23463       break;
23464
23465       /* The DW_AT_const_value attributes are supposed to carry the
23466          symbol's value "represented as it would be on the target
23467          architecture."  By the time we get here, it's already been
23468          converted to host endianness, so we just need to sign- or
23469          zero-extend it as appropriate.  */
23470     case DW_FORM_data1:
23471       type = die_type (die, cu);
23472       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23473       if (result == NULL)
23474         result = write_constant_as_bytes (obstack, byte_order,
23475                                           type, value, len);
23476       break;
23477     case DW_FORM_data2:
23478       type = die_type (die, cu);
23479       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23480       if (result == NULL)
23481         result = write_constant_as_bytes (obstack, byte_order,
23482                                           type, value, len);
23483       break;
23484     case DW_FORM_data4:
23485       type = die_type (die, cu);
23486       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23487       if (result == NULL)
23488         result = write_constant_as_bytes (obstack, byte_order,
23489                                           type, value, len);
23490       break;
23491     case DW_FORM_data8:
23492       type = die_type (die, cu);
23493       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23494       if (result == NULL)
23495         result = write_constant_as_bytes (obstack, byte_order,
23496                                           type, value, len);
23497       break;
23498
23499     case DW_FORM_sdata:
23500     case DW_FORM_implicit_const:
23501       type = die_type (die, cu);
23502       result = write_constant_as_bytes (obstack, byte_order,
23503                                         type, DW_SND (attr), len);
23504       break;
23505
23506     case DW_FORM_udata:
23507       type = die_type (die, cu);
23508       result = write_constant_as_bytes (obstack, byte_order,
23509                                         type, DW_UNSND (attr), len);
23510       break;
23511
23512     default:
23513       complaint (_("unsupported const value attribute form: '%s'"),
23514                  dwarf_form_name (attr->form));
23515       break;
23516     }
23517
23518   return result;
23519 }
23520
23521 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23522    valid type for this die is found.  */
23523
23524 struct type *
23525 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23526                                 struct dwarf2_per_cu_data *per_cu)
23527 {
23528   struct dwarf2_cu *cu;
23529   struct die_info *die;
23530
23531   if (per_cu->cu == NULL)
23532     load_cu (per_cu, false);
23533   cu = per_cu->cu;
23534   if (!cu)
23535     return NULL;
23536
23537   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23538   if (!die)
23539     return NULL;
23540
23541   return die_type (die, cu);
23542 }
23543
23544 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23545    PER_CU.  */
23546
23547 struct type *
23548 dwarf2_get_die_type (cu_offset die_offset,
23549                      struct dwarf2_per_cu_data *per_cu)
23550 {
23551   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23552   return get_die_type_at_offset (die_offset_sect, per_cu);
23553 }
23554
23555 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23556    On entry *REF_CU is the CU of SRC_DIE.
23557    On exit *REF_CU is the CU of the result.
23558    Returns NULL if the referenced DIE isn't found.  */
23559
23560 static struct die_info *
23561 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23562                   struct dwarf2_cu **ref_cu)
23563 {
23564   struct die_info temp_die;
23565   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
23566   struct die_info *die;
23567
23568   /* While it might be nice to assert sig_type->type == NULL here,
23569      we can get here for DW_AT_imported_declaration where we need
23570      the DIE not the type.  */
23571
23572   /* If necessary, add it to the queue and load its DIEs.  */
23573
23574   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23575     read_signatured_type (sig_type);
23576
23577   sig_cu = sig_type->per_cu.cu;
23578   gdb_assert (sig_cu != NULL);
23579   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23580   temp_die.sect_off = sig_type->type_offset_in_section;
23581   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23582                                                  to_underlying (temp_die.sect_off));
23583   if (die)
23584     {
23585       struct dwarf2_per_objfile *dwarf2_per_objfile
23586         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23587
23588       /* For .gdb_index version 7 keep track of included TUs.
23589          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23590       if (dwarf2_per_objfile->index_table != NULL
23591           && dwarf2_per_objfile->index_table->version <= 7)
23592         {
23593           VEC_safe_push (dwarf2_per_cu_ptr,
23594                          (*ref_cu)->per_cu->imported_symtabs,
23595                          sig_cu->per_cu);
23596         }
23597
23598       *ref_cu = sig_cu;
23599       if (sig_cu != cu)
23600         sig_cu->ancestor = cu;
23601
23602       return die;
23603     }
23604
23605   return NULL;
23606 }
23607
23608 /* Follow signatured type referenced by ATTR in SRC_DIE.
23609    On entry *REF_CU is the CU of SRC_DIE.
23610    On exit *REF_CU is the CU of the result.
23611    The result is the DIE of the type.
23612    If the referenced type cannot be found an error is thrown.  */
23613
23614 static struct die_info *
23615 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23616                 struct dwarf2_cu **ref_cu)
23617 {
23618   ULONGEST signature = DW_SIGNATURE (attr);
23619   struct signatured_type *sig_type;
23620   struct die_info *die;
23621
23622   gdb_assert (attr->form == DW_FORM_ref_sig8);
23623
23624   sig_type = lookup_signatured_type (*ref_cu, signature);
23625   /* sig_type will be NULL if the signatured type is missing from
23626      the debug info.  */
23627   if (sig_type == NULL)
23628     {
23629       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23630                " from DIE at %s [in module %s]"),
23631              hex_string (signature), sect_offset_str (src_die->sect_off),
23632              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23633     }
23634
23635   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23636   if (die == NULL)
23637     {
23638       dump_die_for_error (src_die);
23639       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23640                " from DIE at %s [in module %s]"),
23641              hex_string (signature), sect_offset_str (src_die->sect_off),
23642              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23643     }
23644
23645   return die;
23646 }
23647
23648 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23649    reading in and processing the type unit if necessary.  */
23650
23651 static struct type *
23652 get_signatured_type (struct die_info *die, ULONGEST signature,
23653                      struct dwarf2_cu *cu)
23654 {
23655   struct dwarf2_per_objfile *dwarf2_per_objfile
23656     = cu->per_cu->dwarf2_per_objfile;
23657   struct signatured_type *sig_type;
23658   struct dwarf2_cu *type_cu;
23659   struct die_info *type_die;
23660   struct type *type;
23661
23662   sig_type = lookup_signatured_type (cu, signature);
23663   /* sig_type will be NULL if the signatured type is missing from
23664      the debug info.  */
23665   if (sig_type == NULL)
23666     {
23667       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23668                    " from DIE at %s [in module %s]"),
23669                  hex_string (signature), sect_offset_str (die->sect_off),
23670                  objfile_name (dwarf2_per_objfile->objfile));
23671       return build_error_marker_type (cu, die);
23672     }
23673
23674   /* If we already know the type we're done.  */
23675   if (sig_type->type != NULL)
23676     return sig_type->type;
23677
23678   type_cu = cu;
23679   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23680   if (type_die != NULL)
23681     {
23682       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23683          is created.  This is important, for example, because for c++ classes
23684          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23685       type = read_type_die (type_die, type_cu);
23686       if (type == NULL)
23687         {
23688           complaint (_("Dwarf Error: Cannot build signatured type %s"
23689                        " referenced from DIE at %s [in module %s]"),
23690                      hex_string (signature), sect_offset_str (die->sect_off),
23691                      objfile_name (dwarf2_per_objfile->objfile));
23692           type = build_error_marker_type (cu, die);
23693         }
23694     }
23695   else
23696     {
23697       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23698                    " from DIE at %s [in module %s]"),
23699                  hex_string (signature), sect_offset_str (die->sect_off),
23700                  objfile_name (dwarf2_per_objfile->objfile));
23701       type = build_error_marker_type (cu, die);
23702     }
23703   sig_type->type = type;
23704
23705   return type;
23706 }
23707
23708 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23709    reading in and processing the type unit if necessary.  */
23710
23711 static struct type *
23712 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23713                           struct dwarf2_cu *cu) /* ARI: editCase function */
23714 {
23715   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23716   if (attr_form_is_ref (attr))
23717     {
23718       struct dwarf2_cu *type_cu = cu;
23719       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23720
23721       return read_type_die (type_die, type_cu);
23722     }
23723   else if (attr->form == DW_FORM_ref_sig8)
23724     {
23725       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23726     }
23727   else
23728     {
23729       struct dwarf2_per_objfile *dwarf2_per_objfile
23730         = cu->per_cu->dwarf2_per_objfile;
23731
23732       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23733                    " at %s [in module %s]"),
23734                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23735                  objfile_name (dwarf2_per_objfile->objfile));
23736       return build_error_marker_type (cu, die);
23737     }
23738 }
23739
23740 /* Load the DIEs associated with type unit PER_CU into memory.  */
23741
23742 static void
23743 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23744 {
23745   struct signatured_type *sig_type;
23746
23747   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23748   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23749
23750   /* We have the per_cu, but we need the signatured_type.
23751      Fortunately this is an easy translation.  */
23752   gdb_assert (per_cu->is_debug_types);
23753   sig_type = (struct signatured_type *) per_cu;
23754
23755   gdb_assert (per_cu->cu == NULL);
23756
23757   read_signatured_type (sig_type);
23758
23759   gdb_assert (per_cu->cu != NULL);
23760 }
23761
23762 /* die_reader_func for read_signatured_type.
23763    This is identical to load_full_comp_unit_reader,
23764    but is kept separate for now.  */
23765
23766 static void
23767 read_signatured_type_reader (const struct die_reader_specs *reader,
23768                              const gdb_byte *info_ptr,
23769                              struct die_info *comp_unit_die,
23770                              int has_children,
23771                              void *data)
23772 {
23773   struct dwarf2_cu *cu = reader->cu;
23774
23775   gdb_assert (cu->die_hash == NULL);
23776   cu->die_hash =
23777     htab_create_alloc_ex (cu->header.length / 12,
23778                           die_hash,
23779                           die_eq,
23780                           NULL,
23781                           &cu->comp_unit_obstack,
23782                           hashtab_obstack_allocate,
23783                           dummy_obstack_deallocate);
23784
23785   if (has_children)
23786     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23787                                                   &info_ptr, comp_unit_die);
23788   cu->dies = comp_unit_die;
23789   /* comp_unit_die is not stored in die_hash, no need.  */
23790
23791   /* We try not to read any attributes in this function, because not
23792      all CUs needed for references have been loaded yet, and symbol
23793      table processing isn't initialized.  But we have to set the CU language,
23794      or we won't be able to build types correctly.
23795      Similarly, if we do not read the producer, we can not apply
23796      producer-specific interpretation.  */
23797   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23798 }
23799
23800 /* Read in a signatured type and build its CU and DIEs.
23801    If the type is a stub for the real type in a DWO file,
23802    read in the real type from the DWO file as well.  */
23803
23804 static void
23805 read_signatured_type (struct signatured_type *sig_type)
23806 {
23807   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23808
23809   gdb_assert (per_cu->is_debug_types);
23810   gdb_assert (per_cu->cu == NULL);
23811
23812   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23813                            read_signatured_type_reader, NULL);
23814   sig_type->per_cu.tu_read = 1;
23815 }
23816
23817 /* Decode simple location descriptions.
23818    Given a pointer to a dwarf block that defines a location, compute
23819    the location and return the value.
23820
23821    NOTE drow/2003-11-18: This function is called in two situations
23822    now: for the address of static or global variables (partial symbols
23823    only) and for offsets into structures which are expected to be
23824    (more or less) constant.  The partial symbol case should go away,
23825    and only the constant case should remain.  That will let this
23826    function complain more accurately.  A few special modes are allowed
23827    without complaint for global variables (for instance, global
23828    register values and thread-local values).
23829
23830    A location description containing no operations indicates that the
23831    object is optimized out.  The return value is 0 for that case.
23832    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23833    callers will only want a very basic result and this can become a
23834    complaint.
23835
23836    Note that stack[0] is unused except as a default error return.  */
23837
23838 static CORE_ADDR
23839 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23840 {
23841   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23842   size_t i;
23843   size_t size = blk->size;
23844   const gdb_byte *data = blk->data;
23845   CORE_ADDR stack[64];
23846   int stacki;
23847   unsigned int bytes_read, unsnd;
23848   gdb_byte op;
23849
23850   i = 0;
23851   stacki = 0;
23852   stack[stacki] = 0;
23853   stack[++stacki] = 0;
23854
23855   while (i < size)
23856     {
23857       op = data[i++];
23858       switch (op)
23859         {
23860         case DW_OP_lit0:
23861         case DW_OP_lit1:
23862         case DW_OP_lit2:
23863         case DW_OP_lit3:
23864         case DW_OP_lit4:
23865         case DW_OP_lit5:
23866         case DW_OP_lit6:
23867         case DW_OP_lit7:
23868         case DW_OP_lit8:
23869         case DW_OP_lit9:
23870         case DW_OP_lit10:
23871         case DW_OP_lit11:
23872         case DW_OP_lit12:
23873         case DW_OP_lit13:
23874         case DW_OP_lit14:
23875         case DW_OP_lit15:
23876         case DW_OP_lit16:
23877         case DW_OP_lit17:
23878         case DW_OP_lit18:
23879         case DW_OP_lit19:
23880         case DW_OP_lit20:
23881         case DW_OP_lit21:
23882         case DW_OP_lit22:
23883         case DW_OP_lit23:
23884         case DW_OP_lit24:
23885         case DW_OP_lit25:
23886         case DW_OP_lit26:
23887         case DW_OP_lit27:
23888         case DW_OP_lit28:
23889         case DW_OP_lit29:
23890         case DW_OP_lit30:
23891         case DW_OP_lit31:
23892           stack[++stacki] = op - DW_OP_lit0;
23893           break;
23894
23895         case DW_OP_reg0:
23896         case DW_OP_reg1:
23897         case DW_OP_reg2:
23898         case DW_OP_reg3:
23899         case DW_OP_reg4:
23900         case DW_OP_reg5:
23901         case DW_OP_reg6:
23902         case DW_OP_reg7:
23903         case DW_OP_reg8:
23904         case DW_OP_reg9:
23905         case DW_OP_reg10:
23906         case DW_OP_reg11:
23907         case DW_OP_reg12:
23908         case DW_OP_reg13:
23909         case DW_OP_reg14:
23910         case DW_OP_reg15:
23911         case DW_OP_reg16:
23912         case DW_OP_reg17:
23913         case DW_OP_reg18:
23914         case DW_OP_reg19:
23915         case DW_OP_reg20:
23916         case DW_OP_reg21:
23917         case DW_OP_reg22:
23918         case DW_OP_reg23:
23919         case DW_OP_reg24:
23920         case DW_OP_reg25:
23921         case DW_OP_reg26:
23922         case DW_OP_reg27:
23923         case DW_OP_reg28:
23924         case DW_OP_reg29:
23925         case DW_OP_reg30:
23926         case DW_OP_reg31:
23927           stack[++stacki] = op - DW_OP_reg0;
23928           if (i < size)
23929             dwarf2_complex_location_expr_complaint ();
23930           break;
23931
23932         case DW_OP_regx:
23933           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23934           i += bytes_read;
23935           stack[++stacki] = unsnd;
23936           if (i < size)
23937             dwarf2_complex_location_expr_complaint ();
23938           break;
23939
23940         case DW_OP_addr:
23941           stack[++stacki] = read_address (objfile->obfd, &data[i],
23942                                           cu, &bytes_read);
23943           i += bytes_read;
23944           break;
23945
23946         case DW_OP_const1u:
23947           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23948           i += 1;
23949           break;
23950
23951         case DW_OP_const1s:
23952           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23953           i += 1;
23954           break;
23955
23956         case DW_OP_const2u:
23957           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23958           i += 2;
23959           break;
23960
23961         case DW_OP_const2s:
23962           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23963           i += 2;
23964           break;
23965
23966         case DW_OP_const4u:
23967           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23968           i += 4;
23969           break;
23970
23971         case DW_OP_const4s:
23972           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23973           i += 4;
23974           break;
23975
23976         case DW_OP_const8u:
23977           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23978           i += 8;
23979           break;
23980
23981         case DW_OP_constu:
23982           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23983                                                   &bytes_read);
23984           i += bytes_read;
23985           break;
23986
23987         case DW_OP_consts:
23988           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23989           i += bytes_read;
23990           break;
23991
23992         case DW_OP_dup:
23993           stack[stacki + 1] = stack[stacki];
23994           stacki++;
23995           break;
23996
23997         case DW_OP_plus:
23998           stack[stacki - 1] += stack[stacki];
23999           stacki--;
24000           break;
24001
24002         case DW_OP_plus_uconst:
24003           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
24004                                                  &bytes_read);
24005           i += bytes_read;
24006           break;
24007
24008         case DW_OP_minus:
24009           stack[stacki - 1] -= stack[stacki];
24010           stacki--;
24011           break;
24012
24013         case DW_OP_deref:
24014           /* If we're not the last op, then we definitely can't encode
24015              this using GDB's address_class enum.  This is valid for partial
24016              global symbols, although the variable's address will be bogus
24017              in the psymtab.  */
24018           if (i < size)
24019             dwarf2_complex_location_expr_complaint ();
24020           break;
24021
24022         case DW_OP_GNU_push_tls_address:
24023         case DW_OP_form_tls_address:
24024           /* The top of the stack has the offset from the beginning
24025              of the thread control block at which the variable is located.  */
24026           /* Nothing should follow this operator, so the top of stack would
24027              be returned.  */
24028           /* This is valid for partial global symbols, but the variable's
24029              address will be bogus in the psymtab.  Make it always at least
24030              non-zero to not look as a variable garbage collected by linker
24031              which have DW_OP_addr 0.  */
24032           if (i < size)
24033             dwarf2_complex_location_expr_complaint ();
24034           stack[stacki]++;
24035           break;
24036
24037         case DW_OP_GNU_uninit:
24038           break;
24039
24040         case DW_OP_addrx:
24041         case DW_OP_GNU_addr_index:
24042         case DW_OP_GNU_const_index:
24043           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
24044                                                          &bytes_read);
24045           i += bytes_read;
24046           break;
24047
24048         default:
24049           {
24050             const char *name = get_DW_OP_name (op);
24051
24052             if (name)
24053               complaint (_("unsupported stack op: '%s'"),
24054                          name);
24055             else
24056               complaint (_("unsupported stack op: '%02x'"),
24057                          op);
24058           }
24059
24060           return (stack[stacki]);
24061         }
24062
24063       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24064          outside of the allocated space.  Also enforce minimum>0.  */
24065       if (stacki >= ARRAY_SIZE (stack) - 1)
24066         {
24067           complaint (_("location description stack overflow"));
24068           return 0;
24069         }
24070
24071       if (stacki <= 0)
24072         {
24073           complaint (_("location description stack underflow"));
24074           return 0;
24075         }
24076     }
24077   return (stack[stacki]);
24078 }
24079
24080 /* memory allocation interface */
24081
24082 static struct dwarf_block *
24083 dwarf_alloc_block (struct dwarf2_cu *cu)
24084 {
24085   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24086 }
24087
24088 static struct die_info *
24089 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24090 {
24091   struct die_info *die;
24092   size_t size = sizeof (struct die_info);
24093
24094   if (num_attrs > 1)
24095     size += (num_attrs - 1) * sizeof (struct attribute);
24096
24097   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24098   memset (die, 0, sizeof (struct die_info));
24099   return (die);
24100 }
24101
24102 \f
24103 /* Macro support.  */
24104
24105 /* Return file name relative to the compilation directory of file number I in
24106    *LH's file name table.  The result is allocated using xmalloc; the caller is
24107    responsible for freeing it.  */
24108
24109 static char *
24110 file_file_name (int file, struct line_header *lh)
24111 {
24112   /* Is the file number a valid index into the line header's file name
24113      table?  Remember that file numbers start with one, not zero.  */
24114   if (1 <= file && file <= lh->file_names.size ())
24115     {
24116       const file_entry &fe = lh->file_names[file - 1];
24117
24118       if (!IS_ABSOLUTE_PATH (fe.name))
24119         {
24120           const char *dir = fe.include_dir (lh);
24121           if (dir != NULL)
24122             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
24123         }
24124       return xstrdup (fe.name);
24125     }
24126   else
24127     {
24128       /* The compiler produced a bogus file number.  We can at least
24129          record the macro definitions made in the file, even if we
24130          won't be able to find the file by name.  */
24131       char fake_name[80];
24132
24133       xsnprintf (fake_name, sizeof (fake_name),
24134                  "<bad macro file number %d>", file);
24135
24136       complaint (_("bad file number in macro information (%d)"),
24137                  file);
24138
24139       return xstrdup (fake_name);
24140     }
24141 }
24142
24143 /* Return the full name of file number I in *LH's file name table.
24144    Use COMP_DIR as the name of the current directory of the
24145    compilation.  The result is allocated using xmalloc; the caller is
24146    responsible for freeing it.  */
24147 static char *
24148 file_full_name (int file, struct line_header *lh, const char *comp_dir)
24149 {
24150   /* Is the file number a valid index into the line header's file name
24151      table?  Remember that file numbers start with one, not zero.  */
24152   if (1 <= file && file <= lh->file_names.size ())
24153     {
24154       char *relative = file_file_name (file, lh);
24155
24156       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
24157         return relative;
24158       return reconcat (relative, comp_dir, SLASH_STRING,
24159                        relative, (char *) NULL);
24160     }
24161   else
24162     return file_file_name (file, lh);
24163 }
24164
24165
24166 static struct macro_source_file *
24167 macro_start_file (struct dwarf2_cu *cu,
24168                   int file, int line,
24169                   struct macro_source_file *current_file,
24170                   struct line_header *lh)
24171 {
24172   /* File name relative to the compilation directory of this source file.  */
24173   char *file_name = file_file_name (file, lh);
24174
24175   if (! current_file)
24176     {
24177       /* Note: We don't create a macro table for this compilation unit
24178          at all until we actually get a filename.  */
24179       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
24180
24181       /* If we have no current file, then this must be the start_file
24182          directive for the compilation unit's main source file.  */
24183       current_file = macro_set_main (macro_table, file_name);
24184       macro_define_special (macro_table);
24185     }
24186   else
24187     current_file = macro_include (current_file, line, file_name);
24188
24189   xfree (file_name);
24190
24191   return current_file;
24192 }
24193
24194 static const char *
24195 consume_improper_spaces (const char *p, const char *body)
24196 {
24197   if (*p == ' ')
24198     {
24199       complaint (_("macro definition contains spaces "
24200                    "in formal argument list:\n`%s'"),
24201                  body);
24202
24203       while (*p == ' ')
24204         p++;
24205     }
24206
24207   return p;
24208 }
24209
24210
24211 static void
24212 parse_macro_definition (struct macro_source_file *file, int line,
24213                         const char *body)
24214 {
24215   const char *p;
24216
24217   /* The body string takes one of two forms.  For object-like macro
24218      definitions, it should be:
24219
24220         <macro name> " " <definition>
24221
24222      For function-like macro definitions, it should be:
24223
24224         <macro name> "() " <definition>
24225      or
24226         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24227
24228      Spaces may appear only where explicitly indicated, and in the
24229      <definition>.
24230
24231      The Dwarf 2 spec says that an object-like macro's name is always
24232      followed by a space, but versions of GCC around March 2002 omit
24233      the space when the macro's definition is the empty string.
24234
24235      The Dwarf 2 spec says that there should be no spaces between the
24236      formal arguments in a function-like macro's formal argument list,
24237      but versions of GCC around March 2002 include spaces after the
24238      commas.  */
24239
24240
24241   /* Find the extent of the macro name.  The macro name is terminated
24242      by either a space or null character (for an object-like macro) or
24243      an opening paren (for a function-like macro).  */
24244   for (p = body; *p; p++)
24245     if (*p == ' ' || *p == '(')
24246       break;
24247
24248   if (*p == ' ' || *p == '\0')
24249     {
24250       /* It's an object-like macro.  */
24251       int name_len = p - body;
24252       char *name = savestring (body, name_len);
24253       const char *replacement;
24254
24255       if (*p == ' ')
24256         replacement = body + name_len + 1;
24257       else
24258         {
24259           dwarf2_macro_malformed_definition_complaint (body);
24260           replacement = body + name_len;
24261         }
24262
24263       macro_define_object (file, line, name, replacement);
24264
24265       xfree (name);
24266     }
24267   else if (*p == '(')
24268     {
24269       /* It's a function-like macro.  */
24270       char *name = savestring (body, p - body);
24271       int argc = 0;
24272       int argv_size = 1;
24273       char **argv = XNEWVEC (char *, argv_size);
24274
24275       p++;
24276
24277       p = consume_improper_spaces (p, body);
24278
24279       /* Parse the formal argument list.  */
24280       while (*p && *p != ')')
24281         {
24282           /* Find the extent of the current argument name.  */
24283           const char *arg_start = p;
24284
24285           while (*p && *p != ',' && *p != ')' && *p != ' ')
24286             p++;
24287
24288           if (! *p || p == arg_start)
24289             dwarf2_macro_malformed_definition_complaint (body);
24290           else
24291             {
24292               /* Make sure argv has room for the new argument.  */
24293               if (argc >= argv_size)
24294                 {
24295                   argv_size *= 2;
24296                   argv = XRESIZEVEC (char *, argv, argv_size);
24297                 }
24298
24299               argv[argc++] = savestring (arg_start, p - arg_start);
24300             }
24301
24302           p = consume_improper_spaces (p, body);
24303
24304           /* Consume the comma, if present.  */
24305           if (*p == ',')
24306             {
24307               p++;
24308
24309               p = consume_improper_spaces (p, body);
24310             }
24311         }
24312
24313       if (*p == ')')
24314         {
24315           p++;
24316
24317           if (*p == ' ')
24318             /* Perfectly formed definition, no complaints.  */
24319             macro_define_function (file, line, name,
24320                                    argc, (const char **) argv,
24321                                    p + 1);
24322           else if (*p == '\0')
24323             {
24324               /* Complain, but do define it.  */
24325               dwarf2_macro_malformed_definition_complaint (body);
24326               macro_define_function (file, line, name,
24327                                      argc, (const char **) argv,
24328                                      p);
24329             }
24330           else
24331             /* Just complain.  */
24332             dwarf2_macro_malformed_definition_complaint (body);
24333         }
24334       else
24335         /* Just complain.  */
24336         dwarf2_macro_malformed_definition_complaint (body);
24337
24338       xfree (name);
24339       {
24340         int i;
24341
24342         for (i = 0; i < argc; i++)
24343           xfree (argv[i]);
24344       }
24345       xfree (argv);
24346     }
24347   else
24348     dwarf2_macro_malformed_definition_complaint (body);
24349 }
24350
24351 /* Skip some bytes from BYTES according to the form given in FORM.
24352    Returns the new pointer.  */
24353
24354 static const gdb_byte *
24355 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24356                  enum dwarf_form form,
24357                  unsigned int offset_size,
24358                  struct dwarf2_section_info *section)
24359 {
24360   unsigned int bytes_read;
24361
24362   switch (form)
24363     {
24364     case DW_FORM_data1:
24365     case DW_FORM_flag:
24366       ++bytes;
24367       break;
24368
24369     case DW_FORM_data2:
24370       bytes += 2;
24371       break;
24372
24373     case DW_FORM_data4:
24374       bytes += 4;
24375       break;
24376
24377     case DW_FORM_data8:
24378       bytes += 8;
24379       break;
24380
24381     case DW_FORM_data16:
24382       bytes += 16;
24383       break;
24384
24385     case DW_FORM_string:
24386       read_direct_string (abfd, bytes, &bytes_read);
24387       bytes += bytes_read;
24388       break;
24389
24390     case DW_FORM_sec_offset:
24391     case DW_FORM_strp:
24392     case DW_FORM_GNU_strp_alt:
24393       bytes += offset_size;
24394       break;
24395
24396     case DW_FORM_block:
24397       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24398       bytes += bytes_read;
24399       break;
24400
24401     case DW_FORM_block1:
24402       bytes += 1 + read_1_byte (abfd, bytes);
24403       break;
24404     case DW_FORM_block2:
24405       bytes += 2 + read_2_bytes (abfd, bytes);
24406       break;
24407     case DW_FORM_block4:
24408       bytes += 4 + read_4_bytes (abfd, bytes);
24409       break;
24410
24411     case DW_FORM_addrx:
24412     case DW_FORM_sdata:
24413     case DW_FORM_strx:
24414     case DW_FORM_udata:
24415     case DW_FORM_GNU_addr_index:
24416     case DW_FORM_GNU_str_index:
24417       bytes = gdb_skip_leb128 (bytes, buffer_end);
24418       if (bytes == NULL)
24419         {
24420           dwarf2_section_buffer_overflow_complaint (section);
24421           return NULL;
24422         }
24423       break;
24424
24425     case DW_FORM_implicit_const:
24426       break;
24427
24428     default:
24429       {
24430         complaint (_("invalid form 0x%x in `%s'"),
24431                    form, get_section_name (section));
24432         return NULL;
24433       }
24434     }
24435
24436   return bytes;
24437 }
24438
24439 /* A helper for dwarf_decode_macros that handles skipping an unknown
24440    opcode.  Returns an updated pointer to the macro data buffer; or,
24441    on error, issues a complaint and returns NULL.  */
24442
24443 static const gdb_byte *
24444 skip_unknown_opcode (unsigned int opcode,
24445                      const gdb_byte **opcode_definitions,
24446                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24447                      bfd *abfd,
24448                      unsigned int offset_size,
24449                      struct dwarf2_section_info *section)
24450 {
24451   unsigned int bytes_read, i;
24452   unsigned long arg;
24453   const gdb_byte *defn;
24454
24455   if (opcode_definitions[opcode] == NULL)
24456     {
24457       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24458                  opcode);
24459       return NULL;
24460     }
24461
24462   defn = opcode_definitions[opcode];
24463   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24464   defn += bytes_read;
24465
24466   for (i = 0; i < arg; ++i)
24467     {
24468       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24469                                  (enum dwarf_form) defn[i], offset_size,
24470                                  section);
24471       if (mac_ptr == NULL)
24472         {
24473           /* skip_form_bytes already issued the complaint.  */
24474           return NULL;
24475         }
24476     }
24477
24478   return mac_ptr;
24479 }
24480
24481 /* A helper function which parses the header of a macro section.
24482    If the macro section is the extended (for now called "GNU") type,
24483    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24484    the header, or issues a complaint and returns NULL on error.  */
24485
24486 static const gdb_byte *
24487 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24488                           bfd *abfd,
24489                           const gdb_byte *mac_ptr,
24490                           unsigned int *offset_size,
24491                           int section_is_gnu)
24492 {
24493   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24494
24495   if (section_is_gnu)
24496     {
24497       unsigned int version, flags;
24498
24499       version = read_2_bytes (abfd, mac_ptr);
24500       if (version != 4 && version != 5)
24501         {
24502           complaint (_("unrecognized version `%d' in .debug_macro section"),
24503                      version);
24504           return NULL;
24505         }
24506       mac_ptr += 2;
24507
24508       flags = read_1_byte (abfd, mac_ptr);
24509       ++mac_ptr;
24510       *offset_size = (flags & 1) ? 8 : 4;
24511
24512       if ((flags & 2) != 0)
24513         /* We don't need the line table offset.  */
24514         mac_ptr += *offset_size;
24515
24516       /* Vendor opcode descriptions.  */
24517       if ((flags & 4) != 0)
24518         {
24519           unsigned int i, count;
24520
24521           count = read_1_byte (abfd, mac_ptr);
24522           ++mac_ptr;
24523           for (i = 0; i < count; ++i)
24524             {
24525               unsigned int opcode, bytes_read;
24526               unsigned long arg;
24527
24528               opcode = read_1_byte (abfd, mac_ptr);
24529               ++mac_ptr;
24530               opcode_definitions[opcode] = mac_ptr;
24531               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24532               mac_ptr += bytes_read;
24533               mac_ptr += arg;
24534             }
24535         }
24536     }
24537
24538   return mac_ptr;
24539 }
24540
24541 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24542    including DW_MACRO_import.  */
24543
24544 static void
24545 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24546                           bfd *abfd,
24547                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24548                           struct macro_source_file *current_file,
24549                           struct line_header *lh,
24550                           struct dwarf2_section_info *section,
24551                           int section_is_gnu, int section_is_dwz,
24552                           unsigned int offset_size,
24553                           htab_t include_hash)
24554 {
24555   struct dwarf2_per_objfile *dwarf2_per_objfile
24556     = cu->per_cu->dwarf2_per_objfile;
24557   struct objfile *objfile = dwarf2_per_objfile->objfile;
24558   enum dwarf_macro_record_type macinfo_type;
24559   int at_commandline;
24560   const gdb_byte *opcode_definitions[256];
24561
24562   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24563                                       &offset_size, section_is_gnu);
24564   if (mac_ptr == NULL)
24565     {
24566       /* We already issued a complaint.  */
24567       return;
24568     }
24569
24570   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24571      GDB is still reading the definitions from command line.  First
24572      DW_MACINFO_start_file will need to be ignored as it was already executed
24573      to create CURRENT_FILE for the main source holding also the command line
24574      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24575      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24576
24577   at_commandline = 1;
24578
24579   do
24580     {
24581       /* Do we at least have room for a macinfo type byte?  */
24582       if (mac_ptr >= mac_end)
24583         {
24584           dwarf2_section_buffer_overflow_complaint (section);
24585           break;
24586         }
24587
24588       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24589       mac_ptr++;
24590
24591       /* Note that we rely on the fact that the corresponding GNU and
24592          DWARF constants are the same.  */
24593       DIAGNOSTIC_PUSH
24594       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24595       switch (macinfo_type)
24596         {
24597           /* A zero macinfo type indicates the end of the macro
24598              information.  */
24599         case 0:
24600           break;
24601
24602         case DW_MACRO_define:
24603         case DW_MACRO_undef:
24604         case DW_MACRO_define_strp:
24605         case DW_MACRO_undef_strp:
24606         case DW_MACRO_define_sup:
24607         case DW_MACRO_undef_sup:
24608           {
24609             unsigned int bytes_read;
24610             int line;
24611             const char *body;
24612             int is_define;
24613
24614             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24615             mac_ptr += bytes_read;
24616
24617             if (macinfo_type == DW_MACRO_define
24618                 || macinfo_type == DW_MACRO_undef)
24619               {
24620                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24621                 mac_ptr += bytes_read;
24622               }
24623             else
24624               {
24625                 LONGEST str_offset;
24626
24627                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24628                 mac_ptr += offset_size;
24629
24630                 if (macinfo_type == DW_MACRO_define_sup
24631                     || macinfo_type == DW_MACRO_undef_sup
24632                     || section_is_dwz)
24633                   {
24634                     struct dwz_file *dwz
24635                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24636
24637                     body = read_indirect_string_from_dwz (objfile,
24638                                                           dwz, str_offset);
24639                   }
24640                 else
24641                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24642                                                          abfd, str_offset);
24643               }
24644
24645             is_define = (macinfo_type == DW_MACRO_define
24646                          || macinfo_type == DW_MACRO_define_strp
24647                          || macinfo_type == DW_MACRO_define_sup);
24648             if (! current_file)
24649               {
24650                 /* DWARF violation as no main source is present.  */
24651                 complaint (_("debug info with no main source gives macro %s "
24652                              "on line %d: %s"),
24653                            is_define ? _("definition") : _("undefinition"),
24654                            line, body);
24655                 break;
24656               }
24657             if ((line == 0 && !at_commandline)
24658                 || (line != 0 && at_commandline))
24659               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24660                          at_commandline ? _("command-line") : _("in-file"),
24661                          is_define ? _("definition") : _("undefinition"),
24662                          line == 0 ? _("zero") : _("non-zero"), line, body);
24663
24664             if (body == NULL)
24665               {
24666                 /* Fedora's rpm-build's "debugedit" binary
24667                    corrupted .debug_macro sections.
24668
24669                    For more info, see
24670                    https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
24671                 complaint (_("debug info gives %s invalid macro %s "
24672                              "without body (corrupted?) at line %d "
24673                              "on file %s"),
24674                            at_commandline ? _("command-line") : _("in-file"),
24675                            is_define ? _("definition") : _("undefinition"),
24676                            line, current_file->filename);
24677               }
24678             else if (is_define)
24679               parse_macro_definition (current_file, line, body);
24680             else
24681               {
24682                 gdb_assert (macinfo_type == DW_MACRO_undef
24683                             || macinfo_type == DW_MACRO_undef_strp
24684                             || macinfo_type == DW_MACRO_undef_sup);
24685                 macro_undef (current_file, line, body);
24686               }
24687           }
24688           break;
24689
24690         case DW_MACRO_start_file:
24691           {
24692             unsigned int bytes_read;
24693             int line, file;
24694
24695             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24696             mac_ptr += bytes_read;
24697             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24698             mac_ptr += bytes_read;
24699
24700             if ((line == 0 && !at_commandline)
24701                 || (line != 0 && at_commandline))
24702               complaint (_("debug info gives source %d included "
24703                            "from %s at %s line %d"),
24704                          file, at_commandline ? _("command-line") : _("file"),
24705                          line == 0 ? _("zero") : _("non-zero"), line);
24706
24707             if (at_commandline)
24708               {
24709                 /* This DW_MACRO_start_file was executed in the
24710                    pass one.  */
24711                 at_commandline = 0;
24712               }
24713             else
24714               current_file = macro_start_file (cu, file, line, current_file,
24715                                                lh);
24716           }
24717           break;
24718
24719         case DW_MACRO_end_file:
24720           if (! current_file)
24721             complaint (_("macro debug info has an unmatched "
24722                          "`close_file' directive"));
24723           else
24724             {
24725               current_file = current_file->included_by;
24726               if (! current_file)
24727                 {
24728                   enum dwarf_macro_record_type next_type;
24729
24730                   /* GCC circa March 2002 doesn't produce the zero
24731                      type byte marking the end of the compilation
24732                      unit.  Complain if it's not there, but exit no
24733                      matter what.  */
24734
24735                   /* Do we at least have room for a macinfo type byte?  */
24736                   if (mac_ptr >= mac_end)
24737                     {
24738                       dwarf2_section_buffer_overflow_complaint (section);
24739                       return;
24740                     }
24741
24742                   /* We don't increment mac_ptr here, so this is just
24743                      a look-ahead.  */
24744                   next_type
24745                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24746                                                                   mac_ptr);
24747                   if (next_type != 0)
24748                     complaint (_("no terminating 0-type entry for "
24749                                  "macros in `.debug_macinfo' section"));
24750
24751                   return;
24752                 }
24753             }
24754           break;
24755
24756         case DW_MACRO_import:
24757         case DW_MACRO_import_sup:
24758           {
24759             LONGEST offset;
24760             void **slot;
24761             bfd *include_bfd = abfd;
24762             struct dwarf2_section_info *include_section = section;
24763             const gdb_byte *include_mac_end = mac_end;
24764             int is_dwz = section_is_dwz;
24765             const gdb_byte *new_mac_ptr;
24766
24767             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24768             mac_ptr += offset_size;
24769
24770             if (macinfo_type == DW_MACRO_import_sup)
24771               {
24772                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24773
24774                 dwarf2_read_section (objfile, &dwz->macro);
24775
24776                 include_section = &dwz->macro;
24777                 include_bfd = get_section_bfd_owner (include_section);
24778                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24779                 is_dwz = 1;
24780               }
24781
24782             new_mac_ptr = include_section->buffer + offset;
24783             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24784
24785             if (*slot != NULL)
24786               {
24787                 /* This has actually happened; see
24788                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24789                 complaint (_("recursive DW_MACRO_import in "
24790                              ".debug_macro section"));
24791               }
24792             else
24793               {
24794                 *slot = (void *) new_mac_ptr;
24795
24796                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24797                                           include_mac_end, current_file, lh,
24798                                           section, section_is_gnu, is_dwz,
24799                                           offset_size, include_hash);
24800
24801                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24802               }
24803           }
24804           break;
24805
24806         case DW_MACINFO_vendor_ext:
24807           if (!section_is_gnu)
24808             {
24809               unsigned int bytes_read;
24810
24811               /* This reads the constant, but since we don't recognize
24812                  any vendor extensions, we ignore it.  */
24813               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24814               mac_ptr += bytes_read;
24815               read_direct_string (abfd, mac_ptr, &bytes_read);
24816               mac_ptr += bytes_read;
24817
24818               /* We don't recognize any vendor extensions.  */
24819               break;
24820             }
24821           /* FALLTHROUGH */
24822
24823         default:
24824           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24825                                          mac_ptr, mac_end, abfd, offset_size,
24826                                          section);
24827           if (mac_ptr == NULL)
24828             return;
24829           break;
24830         }
24831       DIAGNOSTIC_POP
24832     } while (macinfo_type != 0);
24833 }
24834
24835 static void
24836 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24837                      int section_is_gnu)
24838 {
24839   struct dwarf2_per_objfile *dwarf2_per_objfile
24840     = cu->per_cu->dwarf2_per_objfile;
24841   struct objfile *objfile = dwarf2_per_objfile->objfile;
24842   struct line_header *lh = cu->line_header;
24843   bfd *abfd;
24844   const gdb_byte *mac_ptr, *mac_end;
24845   struct macro_source_file *current_file = 0;
24846   enum dwarf_macro_record_type macinfo_type;
24847   unsigned int offset_size = cu->header.offset_size;
24848   const gdb_byte *opcode_definitions[256];
24849   void **slot;
24850   struct dwarf2_section_info *section;
24851   const char *section_name;
24852
24853   if (cu->dwo_unit != NULL)
24854     {
24855       if (section_is_gnu)
24856         {
24857           section = &cu->dwo_unit->dwo_file->sections.macro;
24858           section_name = ".debug_macro.dwo";
24859         }
24860       else
24861         {
24862           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24863           section_name = ".debug_macinfo.dwo";
24864         }
24865     }
24866   else
24867     {
24868       if (section_is_gnu)
24869         {
24870           section = &dwarf2_per_objfile->macro;
24871           section_name = ".debug_macro";
24872         }
24873       else
24874         {
24875           section = &dwarf2_per_objfile->macinfo;
24876           section_name = ".debug_macinfo";
24877         }
24878     }
24879
24880   dwarf2_read_section (objfile, section);
24881   if (section->buffer == NULL)
24882     {
24883       complaint (_("missing %s section"), section_name);
24884       return;
24885     }
24886   abfd = get_section_bfd_owner (section);
24887
24888   /* First pass: Find the name of the base filename.
24889      This filename is needed in order to process all macros whose definition
24890      (or undefinition) comes from the command line.  These macros are defined
24891      before the first DW_MACINFO_start_file entry, and yet still need to be
24892      associated to the base file.
24893
24894      To determine the base file name, we scan the macro definitions until we
24895      reach the first DW_MACINFO_start_file entry.  We then initialize
24896      CURRENT_FILE accordingly so that any macro definition found before the
24897      first DW_MACINFO_start_file can still be associated to the base file.  */
24898
24899   mac_ptr = section->buffer + offset;
24900   mac_end = section->buffer + section->size;
24901
24902   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24903                                       &offset_size, section_is_gnu);
24904   if (mac_ptr == NULL)
24905     {
24906       /* We already issued a complaint.  */
24907       return;
24908     }
24909
24910   do
24911     {
24912       /* Do we at least have room for a macinfo type byte?  */
24913       if (mac_ptr >= mac_end)
24914         {
24915           /* Complaint is printed during the second pass as GDB will probably
24916              stop the first pass earlier upon finding
24917              DW_MACINFO_start_file.  */
24918           break;
24919         }
24920
24921       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24922       mac_ptr++;
24923
24924       /* Note that we rely on the fact that the corresponding GNU and
24925          DWARF constants are the same.  */
24926       DIAGNOSTIC_PUSH
24927       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24928       switch (macinfo_type)
24929         {
24930           /* A zero macinfo type indicates the end of the macro
24931              information.  */
24932         case 0:
24933           break;
24934
24935         case DW_MACRO_define:
24936         case DW_MACRO_undef:
24937           /* Only skip the data by MAC_PTR.  */
24938           {
24939             unsigned int bytes_read;
24940
24941             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24942             mac_ptr += bytes_read;
24943             read_direct_string (abfd, mac_ptr, &bytes_read);
24944             mac_ptr += bytes_read;
24945           }
24946           break;
24947
24948         case DW_MACRO_start_file:
24949           {
24950             unsigned int bytes_read;
24951             int line, file;
24952
24953             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24954             mac_ptr += bytes_read;
24955             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24956             mac_ptr += bytes_read;
24957
24958             current_file = macro_start_file (cu, file, line, current_file, lh);
24959           }
24960           break;
24961
24962         case DW_MACRO_end_file:
24963           /* No data to skip by MAC_PTR.  */
24964           break;
24965
24966         case DW_MACRO_define_strp:
24967         case DW_MACRO_undef_strp:
24968         case DW_MACRO_define_sup:
24969         case DW_MACRO_undef_sup:
24970           {
24971             unsigned int bytes_read;
24972
24973             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24974             mac_ptr += bytes_read;
24975             mac_ptr += offset_size;
24976           }
24977           break;
24978
24979         case DW_MACRO_import:
24980         case DW_MACRO_import_sup:
24981           /* Note that, according to the spec, a transparent include
24982              chain cannot call DW_MACRO_start_file.  So, we can just
24983              skip this opcode.  */
24984           mac_ptr += offset_size;
24985           break;
24986
24987         case DW_MACINFO_vendor_ext:
24988           /* Only skip the data by MAC_PTR.  */
24989           if (!section_is_gnu)
24990             {
24991               unsigned int bytes_read;
24992
24993               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24994               mac_ptr += bytes_read;
24995               read_direct_string (abfd, mac_ptr, &bytes_read);
24996               mac_ptr += bytes_read;
24997             }
24998           /* FALLTHROUGH */
24999
25000         default:
25001           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
25002                                          mac_ptr, mac_end, abfd, offset_size,
25003                                          section);
25004           if (mac_ptr == NULL)
25005             return;
25006           break;
25007         }
25008       DIAGNOSTIC_POP
25009     } while (macinfo_type != 0 && current_file == NULL);
25010
25011   /* Second pass: Process all entries.
25012
25013      Use the AT_COMMAND_LINE flag to determine whether we are still processing
25014      command-line macro definitions/undefinitions.  This flag is unset when we
25015      reach the first DW_MACINFO_start_file entry.  */
25016
25017   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
25018                                            htab_eq_pointer,
25019                                            NULL, xcalloc, xfree));
25020   mac_ptr = section->buffer + offset;
25021   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
25022   *slot = (void *) mac_ptr;
25023   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
25024                             current_file, lh, section,
25025                             section_is_gnu, 0, offset_size,
25026                             include_hash.get ());
25027 }
25028
25029 /* Check if the attribute's form is a DW_FORM_block*
25030    if so return true else false.  */
25031
25032 static int
25033 attr_form_is_block (const struct attribute *attr)
25034 {
25035   return (attr == NULL ? 0 :
25036       attr->form == DW_FORM_block1
25037       || attr->form == DW_FORM_block2
25038       || attr->form == DW_FORM_block4
25039       || attr->form == DW_FORM_block
25040       || attr->form == DW_FORM_exprloc);
25041 }
25042
25043 /* Return non-zero if ATTR's value is a section offset --- classes
25044    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
25045    You may use DW_UNSND (attr) to retrieve such offsets.
25046
25047    Section 7.5.4, "Attribute Encodings", explains that no attribute
25048    may have a value that belongs to more than one of these classes; it
25049    would be ambiguous if we did, because we use the same forms for all
25050    of them.  */
25051
25052 static int
25053 attr_form_is_section_offset (const struct attribute *attr)
25054 {
25055   return (attr->form == DW_FORM_data4
25056           || attr->form == DW_FORM_data8
25057           || attr->form == DW_FORM_sec_offset);
25058 }
25059
25060 /* Return non-zero if ATTR's value falls in the 'constant' class, or
25061    zero otherwise.  When this function returns true, you can apply
25062    dwarf2_get_attr_constant_value to it.
25063
25064    However, note that for some attributes you must check
25065    attr_form_is_section_offset before using this test.  DW_FORM_data4
25066    and DW_FORM_data8 are members of both the constant class, and of
25067    the classes that contain offsets into other debug sections
25068    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
25069    that, if an attribute's can be either a constant or one of the
25070    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
25071    taken as section offsets, not constants.
25072
25073    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
25074    cannot handle that.  */
25075
25076 static int
25077 attr_form_is_constant (const struct attribute *attr)
25078 {
25079   switch (attr->form)
25080     {
25081     case DW_FORM_sdata:
25082     case DW_FORM_udata:
25083     case DW_FORM_data1:
25084     case DW_FORM_data2:
25085     case DW_FORM_data4:
25086     case DW_FORM_data8:
25087     case DW_FORM_implicit_const:
25088       return 1;
25089     default:
25090       return 0;
25091     }
25092 }
25093
25094
25095 /* DW_ADDR is always stored already as sect_offset; despite for the forms
25096    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
25097
25098 static int
25099 attr_form_is_ref (const struct attribute *attr)
25100 {
25101   switch (attr->form)
25102     {
25103     case DW_FORM_ref_addr:
25104     case DW_FORM_ref1:
25105     case DW_FORM_ref2:
25106     case DW_FORM_ref4:
25107     case DW_FORM_ref8:
25108     case DW_FORM_ref_udata:
25109     case DW_FORM_GNU_ref_alt:
25110       return 1;
25111     default:
25112       return 0;
25113     }
25114 }
25115
25116 /* Return the .debug_loc section to use for CU.
25117    For DWO files use .debug_loc.dwo.  */
25118
25119 static struct dwarf2_section_info *
25120 cu_debug_loc_section (struct dwarf2_cu *cu)
25121 {
25122   struct dwarf2_per_objfile *dwarf2_per_objfile
25123     = cu->per_cu->dwarf2_per_objfile;
25124
25125   if (cu->dwo_unit)
25126     {
25127       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
25128       
25129       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
25130     }
25131   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
25132                                   : &dwarf2_per_objfile->loc);
25133 }
25134
25135 /* A helper function that fills in a dwarf2_loclist_baton.  */
25136
25137 static void
25138 fill_in_loclist_baton (struct dwarf2_cu *cu,
25139                        struct dwarf2_loclist_baton *baton,
25140                        const struct attribute *attr)
25141 {
25142   struct dwarf2_per_objfile *dwarf2_per_objfile
25143     = cu->per_cu->dwarf2_per_objfile;
25144   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25145
25146   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
25147
25148   baton->per_cu = cu->per_cu;
25149   gdb_assert (baton->per_cu);
25150   /* We don't know how long the location list is, but make sure we
25151      don't run off the edge of the section.  */
25152   baton->size = section->size - DW_UNSND (attr);
25153   baton->data = section->buffer + DW_UNSND (attr);
25154   baton->base_address = cu->base_address;
25155   baton->from_dwo = cu->dwo_unit != NULL;
25156 }
25157
25158 static void
25159 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
25160                              struct dwarf2_cu *cu, int is_block)
25161 {
25162   struct dwarf2_per_objfile *dwarf2_per_objfile
25163     = cu->per_cu->dwarf2_per_objfile;
25164   struct objfile *objfile = dwarf2_per_objfile->objfile;
25165   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25166
25167   if (attr_form_is_section_offset (attr)
25168       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
25169          the section.  If so, fall through to the complaint in the
25170          other branch.  */
25171       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
25172     {
25173       struct dwarf2_loclist_baton *baton;
25174
25175       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
25176
25177       fill_in_loclist_baton (cu, baton, attr);
25178
25179       if (cu->base_known == 0)
25180         complaint (_("Location list used without "
25181                      "specifying the CU base address."));
25182
25183       SYMBOL_ACLASS_INDEX (sym) = (is_block
25184                                    ? dwarf2_loclist_block_index
25185                                    : dwarf2_loclist_index);
25186       SYMBOL_LOCATION_BATON (sym) = baton;
25187     }
25188   else
25189     {
25190       struct dwarf2_locexpr_baton *baton;
25191
25192       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25193       baton->per_cu = cu->per_cu;
25194       gdb_assert (baton->per_cu);
25195
25196       if (attr_form_is_block (attr))
25197         {
25198           /* Note that we're just copying the block's data pointer
25199              here, not the actual data.  We're still pointing into the
25200              info_buffer for SYM's objfile; right now we never release
25201              that buffer, but when we do clean up properly this may
25202              need to change.  */
25203           baton->size = DW_BLOCK (attr)->size;
25204           baton->data = DW_BLOCK (attr)->data;
25205         }
25206       else
25207         {
25208           dwarf2_invalid_attrib_class_complaint ("location description",
25209                                                  SYMBOL_NATURAL_NAME (sym));
25210           baton->size = 0;
25211         }
25212
25213       SYMBOL_ACLASS_INDEX (sym) = (is_block
25214                                    ? dwarf2_locexpr_block_index
25215                                    : dwarf2_locexpr_index);
25216       SYMBOL_LOCATION_BATON (sym) = baton;
25217     }
25218 }
25219
25220 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25221    came from a separate debuginfo file, then the master objfile is
25222    returned.  */
25223
25224 struct objfile *
25225 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25226 {
25227   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25228
25229   /* Return the master objfile, so that we can report and look up the
25230      correct file containing this variable.  */
25231   if (objfile->separate_debug_objfile_backlink)
25232     objfile = objfile->separate_debug_objfile_backlink;
25233
25234   return objfile;
25235 }
25236
25237 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25238    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25239    CU_HEADERP first.  */
25240
25241 static const struct comp_unit_head *
25242 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25243                        struct dwarf2_per_cu_data *per_cu)
25244 {
25245   const gdb_byte *info_ptr;
25246
25247   if (per_cu->cu)
25248     return &per_cu->cu->header;
25249
25250   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25251
25252   memset (cu_headerp, 0, sizeof (*cu_headerp));
25253   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25254                        rcuh_kind::COMPILE);
25255
25256   return cu_headerp;
25257 }
25258
25259 /* Return the address size given in the compilation unit header for CU.  */
25260
25261 int
25262 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25263 {
25264   struct comp_unit_head cu_header_local;
25265   const struct comp_unit_head *cu_headerp;
25266
25267   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25268
25269   return cu_headerp->addr_size;
25270 }
25271
25272 /* Return the offset size given in the compilation unit header for CU.  */
25273
25274 int
25275 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25276 {
25277   struct comp_unit_head cu_header_local;
25278   const struct comp_unit_head *cu_headerp;
25279
25280   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25281
25282   return cu_headerp->offset_size;
25283 }
25284
25285 /* See its dwarf2loc.h declaration.  */
25286
25287 int
25288 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25289 {
25290   struct comp_unit_head cu_header_local;
25291   const struct comp_unit_head *cu_headerp;
25292
25293   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25294
25295   if (cu_headerp->version == 2)
25296     return cu_headerp->addr_size;
25297   else
25298     return cu_headerp->offset_size;
25299 }
25300
25301 /* Return the text offset of the CU.  The returned offset comes from
25302    this CU's objfile.  If this objfile came from a separate debuginfo
25303    file, then the offset may be different from the corresponding
25304    offset in the parent objfile.  */
25305
25306 CORE_ADDR
25307 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25308 {
25309   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25310
25311   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25312 }
25313
25314 /* Return a type that is a generic pointer type, the size of which matches
25315    the address size given in the compilation unit header for PER_CU.  */
25316 static struct type *
25317 dwarf2_per_cu_addr_type (struct dwarf2_per_cu_data *per_cu)
25318 {
25319   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25320   struct type *void_type = objfile_type (objfile)->builtin_void;
25321   struct type *addr_type = lookup_pointer_type (void_type);
25322   int addr_size = dwarf2_per_cu_addr_size (per_cu);
25323
25324   if (TYPE_LENGTH (addr_type) == addr_size)
25325     return addr_type;
25326
25327   addr_type
25328     = dwarf2_per_cu_addr_sized_int_type (per_cu, TYPE_UNSIGNED (addr_type));
25329   return addr_type;
25330 }
25331
25332 /* Return DWARF version number of PER_CU.  */
25333
25334 short
25335 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25336 {
25337   return per_cu->dwarf_version;
25338 }
25339
25340 /* Locate the .debug_info compilation unit from CU's objfile which contains
25341    the DIE at OFFSET.  Raises an error on failure.  */
25342
25343 static struct dwarf2_per_cu_data *
25344 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25345                                   unsigned int offset_in_dwz,
25346                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25347 {
25348   struct dwarf2_per_cu_data *this_cu;
25349   int low, high;
25350
25351   low = 0;
25352   high = dwarf2_per_objfile->all_comp_units.size () - 1;
25353   while (high > low)
25354     {
25355       struct dwarf2_per_cu_data *mid_cu;
25356       int mid = low + (high - low) / 2;
25357
25358       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25359       if (mid_cu->is_dwz > offset_in_dwz
25360           || (mid_cu->is_dwz == offset_in_dwz
25361               && mid_cu->sect_off + mid_cu->length >= sect_off))
25362         high = mid;
25363       else
25364         low = mid + 1;
25365     }
25366   gdb_assert (low == high);
25367   this_cu = dwarf2_per_objfile->all_comp_units[low];
25368   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
25369     {
25370       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25371         error (_("Dwarf Error: could not find partial DIE containing "
25372                "offset %s [in module %s]"),
25373                sect_offset_str (sect_off),
25374                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25375
25376       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25377                   <= sect_off);
25378       return dwarf2_per_objfile->all_comp_units[low-1];
25379     }
25380   else
25381     {
25382       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25383           && sect_off >= this_cu->sect_off + this_cu->length)
25384         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25385       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25386       return this_cu;
25387     }
25388 }
25389
25390 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25391
25392 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25393   : per_cu (per_cu_),
25394     mark (false),
25395     has_loclist (false),
25396     checked_producer (false),
25397     producer_is_gxx_lt_4_6 (false),
25398     producer_is_gcc_lt_4_3 (false),
25399     producer_is_icc (false),
25400     producer_is_icc_lt_14 (false),
25401     producer_is_codewarrior (false),
25402     processing_has_namespace_info (false)
25403 {
25404   per_cu->cu = this;
25405 }
25406
25407 /* Destroy a dwarf2_cu.  */
25408
25409 dwarf2_cu::~dwarf2_cu ()
25410 {
25411   per_cu->cu = NULL;
25412 }
25413
25414 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25415
25416 static void
25417 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25418                        enum language pretend_language)
25419 {
25420   struct attribute *attr;
25421
25422   /* Set the language we're debugging.  */
25423   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25424   if (attr)
25425     set_cu_language (DW_UNSND (attr), cu);
25426   else
25427     {
25428       cu->language = pretend_language;
25429       cu->language_defn = language_def (cu->language);
25430     }
25431
25432   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25433 }
25434
25435 /* Increase the age counter on each cached compilation unit, and free
25436    any that are too old.  */
25437
25438 static void
25439 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25440 {
25441   struct dwarf2_per_cu_data *per_cu, **last_chain;
25442
25443   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25444   per_cu = dwarf2_per_objfile->read_in_chain;
25445   while (per_cu != NULL)
25446     {
25447       per_cu->cu->last_used ++;
25448       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25449         dwarf2_mark (per_cu->cu);
25450       per_cu = per_cu->cu->read_in_chain;
25451     }
25452
25453   per_cu = dwarf2_per_objfile->read_in_chain;
25454   last_chain = &dwarf2_per_objfile->read_in_chain;
25455   while (per_cu != NULL)
25456     {
25457       struct dwarf2_per_cu_data *next_cu;
25458
25459       next_cu = per_cu->cu->read_in_chain;
25460
25461       if (!per_cu->cu->mark)
25462         {
25463           delete per_cu->cu;
25464           *last_chain = next_cu;
25465         }
25466       else
25467         last_chain = &per_cu->cu->read_in_chain;
25468
25469       per_cu = next_cu;
25470     }
25471 }
25472
25473 /* Remove a single compilation unit from the cache.  */
25474
25475 static void
25476 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25477 {
25478   struct dwarf2_per_cu_data *per_cu, **last_chain;
25479   struct dwarf2_per_objfile *dwarf2_per_objfile
25480     = target_per_cu->dwarf2_per_objfile;
25481
25482   per_cu = dwarf2_per_objfile->read_in_chain;
25483   last_chain = &dwarf2_per_objfile->read_in_chain;
25484   while (per_cu != NULL)
25485     {
25486       struct dwarf2_per_cu_data *next_cu;
25487
25488       next_cu = per_cu->cu->read_in_chain;
25489
25490       if (per_cu == target_per_cu)
25491         {
25492           delete per_cu->cu;
25493           per_cu->cu = NULL;
25494           *last_chain = next_cu;
25495           break;
25496         }
25497       else
25498         last_chain = &per_cu->cu->read_in_chain;
25499
25500       per_cu = next_cu;
25501     }
25502 }
25503
25504 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25505    We store these in a hash table separate from the DIEs, and preserve them
25506    when the DIEs are flushed out of cache.
25507
25508    The CU "per_cu" pointer is needed because offset alone is not enough to
25509    uniquely identify the type.  A file may have multiple .debug_types sections,
25510    or the type may come from a DWO file.  Furthermore, while it's more logical
25511    to use per_cu->section+offset, with Fission the section with the data is in
25512    the DWO file but we don't know that section at the point we need it.
25513    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25514    because we can enter the lookup routine, get_die_type_at_offset, from
25515    outside this file, and thus won't necessarily have PER_CU->cu.
25516    Fortunately, PER_CU is stable for the life of the objfile.  */
25517
25518 struct dwarf2_per_cu_offset_and_type
25519 {
25520   const struct dwarf2_per_cu_data *per_cu;
25521   sect_offset sect_off;
25522   struct type *type;
25523 };
25524
25525 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25526
25527 static hashval_t
25528 per_cu_offset_and_type_hash (const void *item)
25529 {
25530   const struct dwarf2_per_cu_offset_and_type *ofs
25531     = (const struct dwarf2_per_cu_offset_and_type *) item;
25532
25533   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25534 }
25535
25536 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25537
25538 static int
25539 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25540 {
25541   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25542     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25543   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25544     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25545
25546   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25547           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25548 }
25549
25550 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25551    table if necessary.  For convenience, return TYPE.
25552
25553    The DIEs reading must have careful ordering to:
25554     * Not cause infite loops trying to read in DIEs as a prerequisite for
25555       reading current DIE.
25556     * Not trying to dereference contents of still incompletely read in types
25557       while reading in other DIEs.
25558     * Enable referencing still incompletely read in types just by a pointer to
25559       the type without accessing its fields.
25560
25561    Therefore caller should follow these rules:
25562      * Try to fetch any prerequisite types we may need to build this DIE type
25563        before building the type and calling set_die_type.
25564      * After building type call set_die_type for current DIE as soon as
25565        possible before fetching more types to complete the current type.
25566      * Make the type as complete as possible before fetching more types.  */
25567
25568 static struct type *
25569 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25570 {
25571   struct dwarf2_per_objfile *dwarf2_per_objfile
25572     = cu->per_cu->dwarf2_per_objfile;
25573   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25574   struct objfile *objfile = dwarf2_per_objfile->objfile;
25575   struct attribute *attr;
25576   struct dynamic_prop prop;
25577
25578   /* For Ada types, make sure that the gnat-specific data is always
25579      initialized (if not already set).  There are a few types where
25580      we should not be doing so, because the type-specific area is
25581      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25582      where the type-specific area is used to store the floatformat).
25583      But this is not a problem, because the gnat-specific information
25584      is actually not needed for these types.  */
25585   if (need_gnat_info (cu)
25586       && TYPE_CODE (type) != TYPE_CODE_FUNC
25587       && TYPE_CODE (type) != TYPE_CODE_FLT
25588       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25589       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25590       && TYPE_CODE (type) != TYPE_CODE_METHOD
25591       && !HAVE_GNAT_AUX_INFO (type))
25592     INIT_GNAT_SPECIFIC (type);
25593
25594   /* Read DW_AT_allocated and set in type.  */
25595   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25596   if (attr_form_is_block (attr))
25597     {
25598       struct type *prop_type
25599         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
25600       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25601         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25602     }
25603   else if (attr != NULL)
25604     {
25605       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25606                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25607                  sect_offset_str (die->sect_off));
25608     }
25609
25610   /* Read DW_AT_associated and set in type.  */
25611   attr = dwarf2_attr (die, DW_AT_associated, cu);
25612   if (attr_form_is_block (attr))
25613     {
25614       struct type *prop_type
25615         = dwarf2_per_cu_addr_sized_int_type (cu->per_cu, false);
25616       if (attr_to_dynamic_prop (attr, die, cu, &prop, prop_type))
25617         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25618     }
25619   else if (attr != NULL)
25620     {
25621       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25622                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25623                  sect_offset_str (die->sect_off));
25624     }
25625
25626   /* Read DW_AT_data_location and set in type.  */
25627   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25628   if (attr_to_dynamic_prop (attr, die, cu, &prop,
25629                             dwarf2_per_cu_addr_type (cu->per_cu)))
25630     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25631
25632   if (dwarf2_per_objfile->die_type_hash == NULL)
25633     {
25634       dwarf2_per_objfile->die_type_hash =
25635         htab_create_alloc_ex (127,
25636                               per_cu_offset_and_type_hash,
25637                               per_cu_offset_and_type_eq,
25638                               NULL,
25639                               &objfile->objfile_obstack,
25640                               hashtab_obstack_allocate,
25641                               dummy_obstack_deallocate);
25642     }
25643
25644   ofs.per_cu = cu->per_cu;
25645   ofs.sect_off = die->sect_off;
25646   ofs.type = type;
25647   slot = (struct dwarf2_per_cu_offset_and_type **)
25648     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25649   if (*slot)
25650     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25651                sect_offset_str (die->sect_off));
25652   *slot = XOBNEW (&objfile->objfile_obstack,
25653                   struct dwarf2_per_cu_offset_and_type);
25654   **slot = ofs;
25655   return type;
25656 }
25657
25658 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25659    or return NULL if the die does not have a saved type.  */
25660
25661 static struct type *
25662 get_die_type_at_offset (sect_offset sect_off,
25663                         struct dwarf2_per_cu_data *per_cu)
25664 {
25665   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25666   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25667
25668   if (dwarf2_per_objfile->die_type_hash == NULL)
25669     return NULL;
25670
25671   ofs.per_cu = per_cu;
25672   ofs.sect_off = sect_off;
25673   slot = ((struct dwarf2_per_cu_offset_and_type *)
25674           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25675   if (slot)
25676     return slot->type;
25677   else
25678     return NULL;
25679 }
25680
25681 /* Look up the type for DIE in CU in die_type_hash,
25682    or return NULL if DIE does not have a saved type.  */
25683
25684 static struct type *
25685 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25686 {
25687   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25688 }
25689
25690 /* Add a dependence relationship from CU to REF_PER_CU.  */
25691
25692 static void
25693 dwarf2_add_dependence (struct dwarf2_cu *cu,
25694                        struct dwarf2_per_cu_data *ref_per_cu)
25695 {
25696   void **slot;
25697
25698   if (cu->dependencies == NULL)
25699     cu->dependencies
25700       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25701                               NULL, &cu->comp_unit_obstack,
25702                               hashtab_obstack_allocate,
25703                               dummy_obstack_deallocate);
25704
25705   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25706   if (*slot == NULL)
25707     *slot = ref_per_cu;
25708 }
25709
25710 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25711    Set the mark field in every compilation unit in the
25712    cache that we must keep because we are keeping CU.  */
25713
25714 static int
25715 dwarf2_mark_helper (void **slot, void *data)
25716 {
25717   struct dwarf2_per_cu_data *per_cu;
25718
25719   per_cu = (struct dwarf2_per_cu_data *) *slot;
25720
25721   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25722      reading of the chain.  As such dependencies remain valid it is not much
25723      useful to track and undo them during QUIT cleanups.  */
25724   if (per_cu->cu == NULL)
25725     return 1;
25726
25727   if (per_cu->cu->mark)
25728     return 1;
25729   per_cu->cu->mark = true;
25730
25731   if (per_cu->cu->dependencies != NULL)
25732     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25733
25734   return 1;
25735 }
25736
25737 /* Set the mark field in CU and in every other compilation unit in the
25738    cache that we must keep because we are keeping CU.  */
25739
25740 static void
25741 dwarf2_mark (struct dwarf2_cu *cu)
25742 {
25743   if (cu->mark)
25744     return;
25745   cu->mark = true;
25746   if (cu->dependencies != NULL)
25747     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25748 }
25749
25750 static void
25751 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25752 {
25753   while (per_cu)
25754     {
25755       per_cu->cu->mark = false;
25756       per_cu = per_cu->cu->read_in_chain;
25757     }
25758 }
25759
25760 /* Trivial hash function for partial_die_info: the hash value of a DIE
25761    is its offset in .debug_info for this objfile.  */
25762
25763 static hashval_t
25764 partial_die_hash (const void *item)
25765 {
25766   const struct partial_die_info *part_die
25767     = (const struct partial_die_info *) item;
25768
25769   return to_underlying (part_die->sect_off);
25770 }
25771
25772 /* Trivial comparison function for partial_die_info structures: two DIEs
25773    are equal if they have the same offset.  */
25774
25775 static int
25776 partial_die_eq (const void *item_lhs, const void *item_rhs)
25777 {
25778   const struct partial_die_info *part_die_lhs
25779     = (const struct partial_die_info *) item_lhs;
25780   const struct partial_die_info *part_die_rhs
25781     = (const struct partial_die_info *) item_rhs;
25782
25783   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25784 }
25785
25786 struct cmd_list_element *set_dwarf_cmdlist;
25787 struct cmd_list_element *show_dwarf_cmdlist;
25788
25789 static void
25790 set_dwarf_cmd (const char *args, int from_tty)
25791 {
25792   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25793              gdb_stdout);
25794 }
25795
25796 static void
25797 show_dwarf_cmd (const char *args, int from_tty)
25798 {
25799   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25800 }
25801
25802 int dwarf_always_disassemble;
25803
25804 static void
25805 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25806                                struct cmd_list_element *c, const char *value)
25807 {
25808   fprintf_filtered (file,
25809                     _("Whether to always disassemble "
25810                       "DWARF expressions is %s.\n"),
25811                     value);
25812 }
25813
25814 static void
25815 show_check_physname (struct ui_file *file, int from_tty,
25816                      struct cmd_list_element *c, const char *value)
25817 {
25818   fprintf_filtered (file,
25819                     _("Whether to check \"physname\" is %s.\n"),
25820                     value);
25821 }
25822
25823 void
25824 _initialize_dwarf2_read (void)
25825 {
25826   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25827 Set DWARF specific variables.\n\
25828 Configure DWARF variables such as the cache size."),
25829                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25830                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25831
25832   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25833 Show DWARF specific variables.\n\
25834 Show DWARF variables such as the cache size."),
25835                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25836                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25837
25838   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25839                             &dwarf_max_cache_age, _("\
25840 Set the upper bound on the age of cached DWARF compilation units."), _("\
25841 Show the upper bound on the age of cached DWARF compilation units."), _("\
25842 A higher limit means that cached compilation units will be stored\n\
25843 in memory longer, and more total memory will be used.  Zero disables\n\
25844 caching, which can slow down startup."),
25845                             NULL,
25846                             show_dwarf_max_cache_age,
25847                             &set_dwarf_cmdlist,
25848                             &show_dwarf_cmdlist);
25849
25850   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25851                            &dwarf_always_disassemble, _("\
25852 Set whether `info address' always disassembles DWARF expressions."), _("\
25853 Show whether `info address' always disassembles DWARF expressions."), _("\
25854 When enabled, DWARF expressions are always printed in an assembly-like\n\
25855 syntax.  When disabled, expressions will be printed in a more\n\
25856 conversational style, when possible."),
25857                            NULL,
25858                            show_dwarf_always_disassemble,
25859                            &set_dwarf_cmdlist,
25860                            &show_dwarf_cmdlist);
25861
25862   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25863 Set debugging of the DWARF reader."), _("\
25864 Show debugging of the DWARF reader."), _("\
25865 When enabled (non-zero), debugging messages are printed during DWARF\n\
25866 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25867 information.  A value greater than 1 provides more verbose information."),
25868                             NULL,
25869                             NULL,
25870                             &setdebuglist, &showdebuglist);
25871
25872   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25873 Set debugging of the DWARF DIE reader."), _("\
25874 Show debugging of the DWARF DIE reader."), _("\
25875 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25876 The value is the maximum depth to print."),
25877                              NULL,
25878                              NULL,
25879                              &setdebuglist, &showdebuglist);
25880
25881   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25882 Set debugging of the dwarf line reader."), _("\
25883 Show debugging of the dwarf line reader."), _("\
25884 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25885 A value of 1 (one) provides basic information.\n\
25886 A value greater than 1 provides more verbose information."),
25887                              NULL,
25888                              NULL,
25889                              &setdebuglist, &showdebuglist);
25890
25891   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25892 Set cross-checking of \"physname\" code against demangler."), _("\
25893 Show cross-checking of \"physname\" code against demangler."), _("\
25894 When enabled, GDB's internal \"physname\" code is checked against\n\
25895 the demangler."),
25896                            NULL, show_check_physname,
25897                            &setdebuglist, &showdebuglist);
25898
25899   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25900                            no_class, &use_deprecated_index_sections, _("\
25901 Set whether to use deprecated gdb_index sections."), _("\
25902 Show whether to use deprecated gdb_index sections."), _("\
25903 When enabled, deprecated .gdb_index sections are used anyway.\n\
25904 Normally they are ignored either because of a missing feature or\n\
25905 performance issue.\n\
25906 Warning: This option must be enabled before gdb reads the file."),
25907                            NULL,
25908                            NULL,
25909                            &setlist, &showlist);
25910
25911   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25912                                                         &dwarf2_locexpr_funcs);
25913   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25914                                                         &dwarf2_loclist_funcs);
25915
25916   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25917                                         &dwarf2_block_frame_base_locexpr_funcs);
25918   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25919                                         &dwarf2_block_frame_base_loclist_funcs);
25920
25921 #if GDB_SELF_TEST
25922   selftests::register_test ("dw2_expand_symtabs_matching",
25923                             selftests::dw2_expand_symtabs_matching::run_test);
25924 #endif
25925 }
This page took 1.496188 seconds and 4 git commands to generate.