Don't crash if dwarf_decode_macro_bytes's 'body' is NULL
[external/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 (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "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 "common/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 "common/filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "common/gdb_unlinker.h"
75 #include "common/function-view.h"
76 #include "common/gdb_optional.h"
77 #include "common/underlying.h"
78 #include "common/byte-vector.h"
79 #include "common/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 "common/selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "common/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;
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   /* 64-bit signature of this type unit - it is valid only for
377      UNIT_TYPE DW_UT_type.  */
378   ULONGEST signature;
379
380   /* For types, offset in the type's DIE of the type defined by this TU.  */
381   cu_offset type_cu_offset_in_tu;
382 };
383
384 /* Type used for delaying computation of method physnames.
385    See comments for compute_delayed_physnames.  */
386 struct delayed_method_info
387 {
388   /* The type to which the method is attached, i.e., its parent class.  */
389   struct type *type;
390
391   /* The index of the method in the type's function fieldlists.  */
392   int fnfield_index;
393
394   /* The index of the method in the fieldlist.  */
395   int index;
396
397   /* The name of the DIE.  */
398   const char *name;
399
400   /*  The DIE associated with this method.  */
401   struct die_info *die;
402 };
403
404 /* Internal state when decoding a particular compilation unit.  */
405 struct dwarf2_cu
406 {
407   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
408   ~dwarf2_cu ();
409
410   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
411
412   /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
413      Create the set of symtabs used by this TU, or if this TU is sharing
414      symtabs with another TU and the symtabs have already been created
415      then restore those symtabs in the line header.
416      We don't need the pc/line-number mapping for type units.  */
417   void setup_type_unit_groups (struct die_info *die);
418
419   /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
420      buildsym_compunit constructor.  */
421   struct compunit_symtab *start_symtab (const char *name,
422                                         const char *comp_dir,
423                                         CORE_ADDR low_pc);
424
425   /* Reset the builder.  */
426   void reset_builder () { m_builder.reset (); }
427
428   /* The header of the compilation unit.  */
429   struct comp_unit_head header {};
430
431   /* Base address of this compilation unit.  */
432   CORE_ADDR base_address = 0;
433
434   /* Non-zero if base_address has been set.  */
435   int base_known = 0;
436
437   /* The language we are debugging.  */
438   enum language language = language_unknown;
439   const struct language_defn *language_defn = nullptr;
440
441   const char *producer = nullptr;
442
443 private:
444   /* The symtab builder for this CU.  This is only non-NULL when full
445      symbols are being read.  */
446   std::unique_ptr<buildsym_compunit> m_builder;
447
448 public:
449   /* The generic symbol table building routines have separate lists for
450      file scope symbols and all all other scopes (local scopes).  So
451      we need to select the right one to pass to add_symbol_to_list().
452      We do it by keeping a pointer to the correct list in list_in_scope.
453
454      FIXME: The original dwarf code just treated the file scope as the
455      first local scope, and all other local scopes as nested local
456      scopes, and worked fine.  Check to see if we really need to
457      distinguish these in buildsym.c.  */
458   struct pending **list_in_scope = nullptr;
459
460   /* Hash table holding all the loaded partial DIEs
461      with partial_die->offset.SECT_OFF as hash.  */
462   htab_t partial_dies = nullptr;
463
464   /* Storage for things with the same lifetime as this read-in compilation
465      unit, including partial DIEs.  */
466   auto_obstack comp_unit_obstack;
467
468   /* When multiple dwarf2_cu structures are living in memory, this field
469      chains them all together, so that they can be released efficiently.
470      We will probably also want a generation counter so that most-recently-used
471      compilation units are cached...  */
472   struct dwarf2_per_cu_data *read_in_chain = nullptr;
473
474   /* Backlink to our per_cu entry.  */
475   struct dwarf2_per_cu_data *per_cu;
476
477   /* How many compilation units ago was this CU last referenced?  */
478   int last_used = 0;
479
480   /* A hash table of DIE cu_offset for following references with
481      die_info->offset.sect_off as hash.  */
482   htab_t die_hash = nullptr;
483
484   /* Full DIEs if read in.  */
485   struct die_info *dies = nullptr;
486
487   /* A set of pointers to dwarf2_per_cu_data objects for compilation
488      units referenced by this one.  Only set during full symbol processing;
489      partial symbol tables do not have dependencies.  */
490   htab_t dependencies = nullptr;
491
492   /* Header data from the line table, during full symbol processing.  */
493   struct line_header *line_header = nullptr;
494   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
495      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
496      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
497      to the line header as long as this DIE is being processed.  See
498      process_die_scope.  */
499   die_info *line_header_die_owner = nullptr;
500
501   /* A list of methods which need to have physnames computed
502      after all type information has been read.  */
503   std::vector<delayed_method_info> method_list;
504
505   /* To be copied to symtab->call_site_htab.  */
506   htab_t call_site_htab = nullptr;
507
508   /* Non-NULL if this CU came from a DWO file.
509      There is an invariant here that is important to remember:
510      Except for attributes copied from the top level DIE in the "main"
511      (or "stub") file in preparation for reading the DWO file
512      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
513      Either there isn't a DWO file (in which case this is NULL and the point
514      is moot), or there is and either we're not going to read it (in which
515      case this is NULL) or there is and we are reading it (in which case this
516      is non-NULL).  */
517   struct dwo_unit *dwo_unit = nullptr;
518
519   /* The DW_AT_addr_base attribute if present, zero otherwise
520      (zero is a valid value though).
521      Note this value comes from the Fission stub CU/TU's DIE.  */
522   ULONGEST addr_base = 0;
523
524   /* The DW_AT_ranges_base attribute if present, zero otherwise
525      (zero is a valid value though).
526      Note this value comes from the Fission stub CU/TU's DIE.
527      Also note that the value is zero in the non-DWO case so this value can
528      be used without needing to know whether DWO files are in use or not.
529      N.B. This does not apply to DW_AT_ranges appearing in
530      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
531      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
532      DW_AT_ranges_base *would* have to be applied, and we'd have to care
533      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
534   ULONGEST ranges_base = 0;
535
536   /* When reading debug info generated by older versions of rustc, we
537      have to rewrite some union types to be struct types with a
538      variant part.  This rewriting must be done after the CU is fully
539      read in, because otherwise at the point of rewriting some struct
540      type might not have been fully processed.  So, we keep a list of
541      all such types here and process them after expansion.  */
542   std::vector<struct type *> rust_unions;
543
544   /* Mark used when releasing cached dies.  */
545   bool mark : 1;
546
547   /* This CU references .debug_loc.  See the symtab->locations_valid field.
548      This test is imperfect as there may exist optimized debug code not using
549      any location list and still facing inlining issues if handled as
550      unoptimized code.  For a future better test see GCC PR other/32998.  */
551   bool has_loclist : 1;
552
553   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
554      if all the producer_is_* fields are valid.  This information is cached
555      because profiling CU expansion showed excessive time spent in
556      producer_is_gxx_lt_4_6.  */
557   bool checked_producer : 1;
558   bool producer_is_gxx_lt_4_6 : 1;
559   bool producer_is_gcc_lt_4_3 : 1;
560   bool producer_is_icc : 1;
561   bool producer_is_icc_lt_14 : 1;
562   bool producer_is_codewarrior : 1;
563
564   /* When true, the file that we're processing is known to have
565      debugging info for C++ namespaces.  GCC 3.3.x did not produce
566      this information, but later versions do.  */
567
568   bool processing_has_namespace_info : 1;
569
570   struct partial_die_info *find_partial_die (sect_offset sect_off);
571
572   /* If this CU was inherited by another CU (via specification,
573      abstract_origin, etc), this is the ancestor CU.  */
574   dwarf2_cu *ancestor;
575
576   /* Get the buildsym_compunit for this CU.  */
577   buildsym_compunit *get_builder ()
578   {
579     /* If this CU has a builder associated with it, use that.  */
580     if (m_builder != nullptr)
581       return m_builder.get ();
582
583     /* Otherwise, search ancestors for a valid builder.  */
584     if (ancestor != nullptr)
585       return ancestor->get_builder ();
586
587     return nullptr;
588   }
589 };
590
591 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
592    This includes type_unit_group and quick_file_names.  */
593
594 struct stmt_list_hash
595 {
596   /* The DWO unit this table is from or NULL if there is none.  */
597   struct dwo_unit *dwo_unit;
598
599   /* Offset in .debug_line or .debug_line.dwo.  */
600   sect_offset line_sect_off;
601 };
602
603 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
604    an object of this type.  */
605
606 struct type_unit_group
607 {
608   /* dwarf2read.c's main "handle" on a TU symtab.
609      To simplify things we create an artificial CU that "includes" all the
610      type units using this stmt_list so that the rest of the code still has
611      a "per_cu" handle on the symtab.
612      This PER_CU is recognized by having no section.  */
613 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
614   struct dwarf2_per_cu_data per_cu;
615
616   /* The TUs that share this DW_AT_stmt_list entry.
617      This is added to while parsing type units to build partial symtabs,
618      and is deleted afterwards and not used again.  */
619   VEC (sig_type_ptr) *tus;
620
621   /* The compunit symtab.
622      Type units in a group needn't all be defined in the same source file,
623      so we create an essentially anonymous symtab as the compunit symtab.  */
624   struct compunit_symtab *compunit_symtab;
625
626   /* The data used to construct the hash key.  */
627   struct stmt_list_hash hash;
628
629   /* The number of symtabs from the line header.
630      The value here must match line_header.num_file_names.  */
631   unsigned int num_symtabs;
632
633   /* The symbol tables for this TU (obtained from the files listed in
634      DW_AT_stmt_list).
635      WARNING: The order of entries here must match the order of entries
636      in the line header.  After the first TU using this type_unit_group, the
637      line header for the subsequent TUs is recreated from this.  This is done
638      because we need to use the same symtabs for each TU using the same
639      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
640      there's no guarantee the line header doesn't have duplicate entries.  */
641   struct symtab **symtabs;
642 };
643
644 /* These sections are what may appear in a (real or virtual) DWO file.  */
645
646 struct dwo_sections
647 {
648   struct dwarf2_section_info abbrev;
649   struct dwarf2_section_info line;
650   struct dwarf2_section_info loc;
651   struct dwarf2_section_info loclists;
652   struct dwarf2_section_info macinfo;
653   struct dwarf2_section_info macro;
654   struct dwarf2_section_info str;
655   struct dwarf2_section_info str_offsets;
656   /* In the case of a virtual DWO file, these two are unused.  */
657   struct dwarf2_section_info info;
658   VEC (dwarf2_section_info_def) *types;
659 };
660
661 /* CUs/TUs in DWP/DWO files.  */
662
663 struct dwo_unit
664 {
665   /* Backlink to the containing struct dwo_file.  */
666   struct dwo_file *dwo_file;
667
668   /* The "id" that distinguishes this CU/TU.
669      .debug_info calls this "dwo_id", .debug_types calls this "signature".
670      Since signatures came first, we stick with it for consistency.  */
671   ULONGEST signature;
672
673   /* The section this CU/TU lives in, in the DWO file.  */
674   struct dwarf2_section_info *section;
675
676   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
677   sect_offset sect_off;
678   unsigned int length;
679
680   /* For types, offset in the type's DIE of the type defined by this TU.  */
681   cu_offset type_offset_in_tu;
682 };
683
684 /* include/dwarf2.h defines the DWP section codes.
685    It defines a max value but it doesn't define a min value, which we
686    use for error checking, so provide one.  */
687
688 enum dwp_v2_section_ids
689 {
690   DW_SECT_MIN = 1
691 };
692
693 /* Data for one DWO file.
694
695    This includes virtual DWO files (a virtual DWO file is a DWO file as it
696    appears in a DWP file).  DWP files don't really have DWO files per se -
697    comdat folding of types "loses" the DWO file they came from, and from
698    a high level view DWP files appear to contain a mass of random types.
699    However, to maintain consistency with the non-DWP case we pretend DWP
700    files contain virtual DWO files, and we assign each TU with one virtual
701    DWO file (generally based on the line and abbrev section offsets -
702    a heuristic that seems to work in practice).  */
703
704 struct dwo_file
705 {
706   /* The DW_AT_GNU_dwo_name attribute.
707      For virtual DWO files the name is constructed from the section offsets
708      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
709      from related CU+TUs.  */
710   const char *dwo_name;
711
712   /* The DW_AT_comp_dir attribute.  */
713   const char *comp_dir;
714
715   /* The bfd, when the file is open.  Otherwise this is NULL.
716      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
717   bfd *dbfd;
718
719   /* The sections that make up this DWO file.
720      Remember that for virtual DWO files in DWP V2, these are virtual
721      sections (for lack of a better name).  */
722   struct dwo_sections sections;
723
724   /* The CUs in the file.
725      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
726      an extension to handle LLVM's Link Time Optimization output (where
727      multiple source files may be compiled into a single object/dwo pair). */
728   htab_t cus;
729
730   /* Table of TUs in the file.
731      Each element is a struct dwo_unit.  */
732   htab_t tus;
733 };
734
735 /* These sections are what may appear in a DWP file.  */
736
737 struct dwp_sections
738 {
739   /* These are used by both DWP version 1 and 2.  */
740   struct dwarf2_section_info str;
741   struct dwarf2_section_info cu_index;
742   struct dwarf2_section_info tu_index;
743
744   /* These are only used by DWP version 2 files.
745      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
746      sections are referenced by section number, and are not recorded here.
747      In DWP version 2 there is at most one copy of all these sections, each
748      section being (effectively) comprised of the concatenation of all of the
749      individual sections that exist in the version 1 format.
750      To keep the code simple we treat each of these concatenated pieces as a
751      section itself (a virtual section?).  */
752   struct dwarf2_section_info abbrev;
753   struct dwarf2_section_info info;
754   struct dwarf2_section_info line;
755   struct dwarf2_section_info loc;
756   struct dwarf2_section_info macinfo;
757   struct dwarf2_section_info macro;
758   struct dwarf2_section_info str_offsets;
759   struct dwarf2_section_info types;
760 };
761
762 /* These sections are what may appear in a virtual DWO file in DWP version 1.
763    A virtual DWO file is a DWO file as it appears in a DWP file.  */
764
765 struct virtual_v1_dwo_sections
766 {
767   struct dwarf2_section_info abbrev;
768   struct dwarf2_section_info line;
769   struct dwarf2_section_info loc;
770   struct dwarf2_section_info macinfo;
771   struct dwarf2_section_info macro;
772   struct dwarf2_section_info str_offsets;
773   /* Each DWP hash table entry records one CU or one TU.
774      That is recorded here, and copied to dwo_unit.section.  */
775   struct dwarf2_section_info info_or_types;
776 };
777
778 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
779    In version 2, the sections of the DWO files are concatenated together
780    and stored in one section of that name.  Thus each ELF section contains
781    several "virtual" sections.  */
782
783 struct virtual_v2_dwo_sections
784 {
785   bfd_size_type abbrev_offset;
786   bfd_size_type abbrev_size;
787
788   bfd_size_type line_offset;
789   bfd_size_type line_size;
790
791   bfd_size_type loc_offset;
792   bfd_size_type loc_size;
793
794   bfd_size_type macinfo_offset;
795   bfd_size_type macinfo_size;
796
797   bfd_size_type macro_offset;
798   bfd_size_type macro_size;
799
800   bfd_size_type str_offsets_offset;
801   bfd_size_type str_offsets_size;
802
803   /* Each DWP hash table entry records one CU or one TU.
804      That is recorded here, and copied to dwo_unit.section.  */
805   bfd_size_type info_or_types_offset;
806   bfd_size_type info_or_types_size;
807 };
808
809 /* Contents of DWP hash tables.  */
810
811 struct dwp_hash_table
812 {
813   uint32_t version, nr_columns;
814   uint32_t nr_units, nr_slots;
815   const gdb_byte *hash_table, *unit_table;
816   union
817   {
818     struct
819     {
820       const gdb_byte *indices;
821     } v1;
822     struct
823     {
824       /* This is indexed by column number and gives the id of the section
825          in that column.  */
826 #define MAX_NR_V2_DWO_SECTIONS \
827   (1 /* .debug_info or .debug_types */ \
828    + 1 /* .debug_abbrev */ \
829    + 1 /* .debug_line */ \
830    + 1 /* .debug_loc */ \
831    + 1 /* .debug_str_offsets */ \
832    + 1 /* .debug_macro or .debug_macinfo */)
833       int section_ids[MAX_NR_V2_DWO_SECTIONS];
834       const gdb_byte *offsets;
835       const gdb_byte *sizes;
836     } v2;
837   } section_pool;
838 };
839
840 /* Data for one DWP file.  */
841
842 struct dwp_file
843 {
844   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
845     : name (name_),
846       dbfd (std::move (abfd))
847   {
848   }
849
850   /* Name of the file.  */
851   const char *name;
852
853   /* File format version.  */
854   int version = 0;
855
856   /* The bfd.  */
857   gdb_bfd_ref_ptr dbfd;
858
859   /* Section info for this file.  */
860   struct dwp_sections sections {};
861
862   /* Table of CUs in the file.  */
863   const struct dwp_hash_table *cus = nullptr;
864
865   /* Table of TUs in the file.  */
866   const struct dwp_hash_table *tus = nullptr;
867
868   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
869   htab_t loaded_cus {};
870   htab_t loaded_tus {};
871
872   /* Table to map ELF section numbers to their sections.
873      This is only needed for the DWP V1 file format.  */
874   unsigned int num_sections = 0;
875   asection **elf_sections = nullptr;
876 };
877
878 /* This represents a '.dwz' file.  */
879
880 struct dwz_file
881 {
882   dwz_file (gdb_bfd_ref_ptr &&bfd)
883     : dwz_bfd (std::move (bfd))
884   {
885   }
886
887   /* A dwz file can only contain a few sections.  */
888   struct dwarf2_section_info abbrev {};
889   struct dwarf2_section_info info {};
890   struct dwarf2_section_info str {};
891   struct dwarf2_section_info line {};
892   struct dwarf2_section_info macro {};
893   struct dwarf2_section_info gdb_index {};
894   struct dwarf2_section_info debug_names {};
895
896   /* The dwz's BFD.  */
897   gdb_bfd_ref_ptr dwz_bfd;
898
899   /* If we loaded the index from an external file, this contains the
900      resources associated to the open file, memory mapping, etc.  */
901   std::unique_ptr<index_cache_resource> index_cache_res;
902 };
903
904 /* Struct used to pass misc. parameters to read_die_and_children, et
905    al.  which are used for both .debug_info and .debug_types dies.
906    All parameters here are unchanging for the life of the call.  This
907    struct exists to abstract away the constant parameters of die reading.  */
908
909 struct die_reader_specs
910 {
911   /* The bfd of die_section.  */
912   bfd* abfd;
913
914   /* The CU of the DIE we are parsing.  */
915   struct dwarf2_cu *cu;
916
917   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
918   struct dwo_file *dwo_file;
919
920   /* The section the die comes from.
921      This is either .debug_info or .debug_types, or the .dwo variants.  */
922   struct dwarf2_section_info *die_section;
923
924   /* die_section->buffer.  */
925   const gdb_byte *buffer;
926
927   /* The end of the buffer.  */
928   const gdb_byte *buffer_end;
929
930   /* The value of the DW_AT_comp_dir attribute.  */
931   const char *comp_dir;
932
933   /* The abbreviation table to use when reading the DIEs.  */
934   struct abbrev_table *abbrev_table;
935 };
936
937 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
938 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
939                                       const gdb_byte *info_ptr,
940                                       struct die_info *comp_unit_die,
941                                       int has_children,
942                                       void *data);
943
944 /* A 1-based directory index.  This is a strong typedef to prevent
945    accidentally using a directory index as a 0-based index into an
946    array/vector.  */
947 enum class dir_index : unsigned int {};
948
949 /* Likewise, a 1-based file name index.  */
950 enum class file_name_index : unsigned int {};
951
952 struct file_entry
953 {
954   file_entry () = default;
955
956   file_entry (const char *name_, dir_index d_index_,
957               unsigned int mod_time_, unsigned int length_)
958     : name (name_),
959       d_index (d_index_),
960       mod_time (mod_time_),
961       length (length_)
962   {}
963
964   /* Return the include directory at D_INDEX stored in LH.  Returns
965      NULL if D_INDEX is out of bounds.  */
966   const char *include_dir (const line_header *lh) const;
967
968   /* The file name.  Note this is an observing pointer.  The memory is
969      owned by debug_line_buffer.  */
970   const char *name {};
971
972   /* The directory index (1-based).  */
973   dir_index d_index {};
974
975   unsigned int mod_time {};
976
977   unsigned int length {};
978
979   /* True if referenced by the Line Number Program.  */
980   bool included_p {};
981
982   /* The associated symbol table, if any.  */
983   struct symtab *symtab {};
984 };
985
986 /* The line number information for a compilation unit (found in the
987    .debug_line section) begins with a "statement program header",
988    which contains the following information.  */
989 struct line_header
990 {
991   line_header ()
992     : offset_in_dwz {}
993   {}
994
995   /* Add an entry to the include directory table.  */
996   void add_include_dir (const char *include_dir);
997
998   /* Add an entry to the file name table.  */
999   void add_file_name (const char *name, dir_index d_index,
1000                       unsigned int mod_time, unsigned int length);
1001
1002   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1003      is out of bounds.  */
1004   const char *include_dir_at (dir_index index) const
1005   {
1006     /* Convert directory index number (1-based) to vector index
1007        (0-based).  */
1008     size_t vec_index = to_underlying (index) - 1;
1009
1010     if (vec_index >= include_dirs.size ())
1011       return NULL;
1012     return include_dirs[vec_index];
1013   }
1014
1015   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1016      is out of bounds.  */
1017   file_entry *file_name_at (file_name_index index)
1018   {
1019     /* Convert file name index number (1-based) to vector index
1020        (0-based).  */
1021     size_t vec_index = to_underlying (index) - 1;
1022
1023     if (vec_index >= file_names.size ())
1024       return NULL;
1025     return &file_names[vec_index];
1026   }
1027
1028   /* Offset of line number information in .debug_line section.  */
1029   sect_offset sect_off {};
1030
1031   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1032   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1033
1034   unsigned int total_length {};
1035   unsigned short version {};
1036   unsigned int header_length {};
1037   unsigned char minimum_instruction_length {};
1038   unsigned char maximum_ops_per_instruction {};
1039   unsigned char default_is_stmt {};
1040   int line_base {};
1041   unsigned char line_range {};
1042   unsigned char opcode_base {};
1043
1044   /* standard_opcode_lengths[i] is the number of operands for the
1045      standard opcode whose value is i.  This means that
1046      standard_opcode_lengths[0] is unused, and the last meaningful
1047      element is standard_opcode_lengths[opcode_base - 1].  */
1048   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1049
1050   /* The include_directories table.  Note these are observing
1051      pointers.  The memory is owned by debug_line_buffer.  */
1052   std::vector<const char *> include_dirs;
1053
1054   /* The file_names table.  */
1055   std::vector<file_entry> file_names;
1056
1057   /* The start and end of the statement program following this
1058      header.  These point into dwarf2_per_objfile->line_buffer.  */
1059   const gdb_byte *statement_program_start {}, *statement_program_end {};
1060 };
1061
1062 typedef std::unique_ptr<line_header> line_header_up;
1063
1064 const char *
1065 file_entry::include_dir (const line_header *lh) const
1066 {
1067   return lh->include_dir_at (d_index);
1068 }
1069
1070 /* When we construct a partial symbol table entry we only
1071    need this much information.  */
1072 struct partial_die_info : public allocate_on_obstack
1073   {
1074     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1075
1076     /* Disable assign but still keep copy ctor, which is needed
1077        load_partial_dies.   */
1078     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1079
1080     /* Adjust the partial die before generating a symbol for it.  This
1081        function may set the is_external flag or change the DIE's
1082        name.  */
1083     void fixup (struct dwarf2_cu *cu);
1084
1085     /* Read a minimal amount of information into the minimal die
1086        structure.  */
1087     const gdb_byte *read (const struct die_reader_specs *reader,
1088                           const struct abbrev_info &abbrev,
1089                           const gdb_byte *info_ptr);
1090
1091     /* Offset of this DIE.  */
1092     const sect_offset sect_off;
1093
1094     /* DWARF-2 tag for this DIE.  */
1095     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1096
1097     /* Assorted flags describing the data found in this DIE.  */
1098     const unsigned int has_children : 1;
1099
1100     unsigned int is_external : 1;
1101     unsigned int is_declaration : 1;
1102     unsigned int has_type : 1;
1103     unsigned int has_specification : 1;
1104     unsigned int has_pc_info : 1;
1105     unsigned int may_be_inlined : 1;
1106
1107     /* This DIE has been marked DW_AT_main_subprogram.  */
1108     unsigned int main_subprogram : 1;
1109
1110     /* Flag set if the SCOPE field of this structure has been
1111        computed.  */
1112     unsigned int scope_set : 1;
1113
1114     /* Flag set if the DIE has a byte_size attribute.  */
1115     unsigned int has_byte_size : 1;
1116
1117     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1118     unsigned int has_const_value : 1;
1119
1120     /* Flag set if any of the DIE's children are template arguments.  */
1121     unsigned int has_template_arguments : 1;
1122
1123     /* Flag set if fixup has been called on this die.  */
1124     unsigned int fixup_called : 1;
1125
1126     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1127     unsigned int is_dwz : 1;
1128
1129     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1130     unsigned int spec_is_dwz : 1;
1131
1132     /* The name of this DIE.  Normally the value of DW_AT_name, but
1133        sometimes a default name for unnamed DIEs.  */
1134     const char *name = nullptr;
1135
1136     /* The linkage name, if present.  */
1137     const char *linkage_name = nullptr;
1138
1139     /* The scope to prepend to our children.  This is generally
1140        allocated on the comp_unit_obstack, so will disappear
1141        when this compilation unit leaves the cache.  */
1142     const char *scope = nullptr;
1143
1144     /* Some data associated with the partial DIE.  The tag determines
1145        which field is live.  */
1146     union
1147     {
1148       /* The location description associated with this DIE, if any.  */
1149       struct dwarf_block *locdesc;
1150       /* The offset of an import, for DW_TAG_imported_unit.  */
1151       sect_offset sect_off;
1152     } d {};
1153
1154     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1155     CORE_ADDR lowpc = 0;
1156     CORE_ADDR highpc = 0;
1157
1158     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1159        DW_AT_sibling, if any.  */
1160     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1161        could return DW_AT_sibling values to its caller load_partial_dies.  */
1162     const gdb_byte *sibling = nullptr;
1163
1164     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1165        DW_AT_specification (or DW_AT_abstract_origin or
1166        DW_AT_extension).  */
1167     sect_offset spec_offset {};
1168
1169     /* Pointers to this DIE's parent, first child, and next sibling,
1170        if any.  */
1171     struct partial_die_info *die_parent = nullptr;
1172     struct partial_die_info *die_child = nullptr;
1173     struct partial_die_info *die_sibling = nullptr;
1174
1175     friend struct partial_die_info *
1176     dwarf2_cu::find_partial_die (sect_offset sect_off);
1177
1178   private:
1179     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1180     partial_die_info (sect_offset sect_off)
1181       : partial_die_info (sect_off, DW_TAG_padding, 0)
1182     {
1183     }
1184
1185     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1186                       int has_children_)
1187       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1188     {
1189       is_external = 0;
1190       is_declaration = 0;
1191       has_type = 0;
1192       has_specification = 0;
1193       has_pc_info = 0;
1194       may_be_inlined = 0;
1195       main_subprogram = 0;
1196       scope_set = 0;
1197       has_byte_size = 0;
1198       has_const_value = 0;
1199       has_template_arguments = 0;
1200       fixup_called = 0;
1201       is_dwz = 0;
1202       spec_is_dwz = 0;
1203     }
1204   };
1205
1206 /* This data structure holds the information of an abbrev.  */
1207 struct abbrev_info
1208   {
1209     unsigned int number;        /* number identifying abbrev */
1210     enum dwarf_tag tag;         /* dwarf tag */
1211     unsigned short has_children;                /* boolean */
1212     unsigned short num_attrs;   /* number of attributes */
1213     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1214     struct abbrev_info *next;   /* next in chain */
1215   };
1216
1217 struct attr_abbrev
1218   {
1219     ENUM_BITFIELD(dwarf_attribute) name : 16;
1220     ENUM_BITFIELD(dwarf_form) form : 16;
1221
1222     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1223     LONGEST implicit_const;
1224   };
1225
1226 /* Size of abbrev_table.abbrev_hash_table.  */
1227 #define ABBREV_HASH_SIZE 121
1228
1229 /* Top level data structure to contain an abbreviation table.  */
1230
1231 struct abbrev_table
1232 {
1233   explicit abbrev_table (sect_offset off)
1234     : sect_off (off)
1235   {
1236     m_abbrevs =
1237       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1238     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1239   }
1240
1241   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1242
1243   /* Allocate space for a struct abbrev_info object in
1244      ABBREV_TABLE.  */
1245   struct abbrev_info *alloc_abbrev ();
1246
1247   /* Add an abbreviation to the table.  */
1248   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1249
1250   /* Look up an abbrev in the table.
1251      Returns NULL if the abbrev is not found.  */
1252
1253   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1254
1255
1256   /* Where the abbrev table came from.
1257      This is used as a sanity check when the table is used.  */
1258   const sect_offset sect_off;
1259
1260   /* Storage for the abbrev table.  */
1261   auto_obstack abbrev_obstack;
1262
1263 private:
1264
1265   /* Hash table of abbrevs.
1266      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1267      It could be statically allocated, but the previous code didn't so we
1268      don't either.  */
1269   struct abbrev_info **m_abbrevs;
1270 };
1271
1272 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1273
1274 /* Attributes have a name and a value.  */
1275 struct attribute
1276   {
1277     ENUM_BITFIELD(dwarf_attribute) name : 16;
1278     ENUM_BITFIELD(dwarf_form) form : 15;
1279
1280     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1281        field should be in u.str (existing only for DW_STRING) but it is kept
1282        here for better struct attribute alignment.  */
1283     unsigned int string_is_canonical : 1;
1284
1285     union
1286       {
1287         const char *str;
1288         struct dwarf_block *blk;
1289         ULONGEST unsnd;
1290         LONGEST snd;
1291         CORE_ADDR addr;
1292         ULONGEST signature;
1293       }
1294     u;
1295   };
1296
1297 /* This data structure holds a complete die structure.  */
1298 struct die_info
1299   {
1300     /* DWARF-2 tag for this DIE.  */
1301     ENUM_BITFIELD(dwarf_tag) tag : 16;
1302
1303     /* Number of attributes */
1304     unsigned char num_attrs;
1305
1306     /* True if we're presently building the full type name for the
1307        type derived from this DIE.  */
1308     unsigned char building_fullname : 1;
1309
1310     /* True if this die is in process.  PR 16581.  */
1311     unsigned char in_process : 1;
1312
1313     /* Abbrev number */
1314     unsigned int abbrev;
1315
1316     /* Offset in .debug_info or .debug_types section.  */
1317     sect_offset sect_off;
1318
1319     /* The dies in a compilation unit form an n-ary tree.  PARENT
1320        points to this die's parent; CHILD points to the first child of
1321        this node; and all the children of a given node are chained
1322        together via their SIBLING fields.  */
1323     struct die_info *child;     /* Its first child, if any.  */
1324     struct die_info *sibling;   /* Its next sibling, if any.  */
1325     struct die_info *parent;    /* Its parent, if any.  */
1326
1327     /* An array of attributes, with NUM_ATTRS elements.  There may be
1328        zero, but it's not common and zero-sized arrays are not
1329        sufficiently portable C.  */
1330     struct attribute attrs[1];
1331   };
1332
1333 /* Get at parts of an attribute structure.  */
1334
1335 #define DW_STRING(attr)    ((attr)->u.str)
1336 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1337 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1338 #define DW_BLOCK(attr)     ((attr)->u.blk)
1339 #define DW_SND(attr)       ((attr)->u.snd)
1340 #define DW_ADDR(attr)      ((attr)->u.addr)
1341 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1342
1343 /* Blocks are a bunch of untyped bytes.  */
1344 struct dwarf_block
1345   {
1346     size_t size;
1347
1348     /* Valid only if SIZE is not zero.  */
1349     const gdb_byte *data;
1350   };
1351
1352 #ifndef ATTR_ALLOC_CHUNK
1353 #define ATTR_ALLOC_CHUNK 4
1354 #endif
1355
1356 /* Allocate fields for structs, unions and enums in this size.  */
1357 #ifndef DW_FIELD_ALLOC_CHUNK
1358 #define DW_FIELD_ALLOC_CHUNK 4
1359 #endif
1360
1361 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1362    but this would require a corresponding change in unpack_field_as_long
1363    and friends.  */
1364 static int bits_per_byte = 8;
1365
1366 /* When reading a variant or variant part, we track a bit more
1367    information about the field, and store it in an object of this
1368    type.  */
1369
1370 struct variant_field
1371 {
1372   /* If we see a DW_TAG_variant, then this will be the discriminant
1373      value.  */
1374   ULONGEST discriminant_value;
1375   /* If we see a DW_TAG_variant, then this will be set if this is the
1376      default branch.  */
1377   bool default_branch;
1378   /* While reading a DW_TAG_variant_part, this will be set if this
1379      field is the discriminant.  */
1380   bool is_discriminant;
1381 };
1382
1383 struct nextfield
1384 {
1385   int accessibility = 0;
1386   int virtuality = 0;
1387   /* Extra information to describe a variant or variant part.  */
1388   struct variant_field variant {};
1389   struct field field {};
1390 };
1391
1392 struct fnfieldlist
1393 {
1394   const char *name = nullptr;
1395   std::vector<struct fn_field> fnfields;
1396 };
1397
1398 /* The routines that read and process dies for a C struct or C++ class
1399    pass lists of data member fields and lists of member function fields
1400    in an instance of a field_info structure, as defined below.  */
1401 struct field_info
1402   {
1403     /* List of data member and baseclasses fields.  */
1404     std::vector<struct nextfield> fields;
1405     std::vector<struct nextfield> baseclasses;
1406
1407     /* Number of fields (including baseclasses).  */
1408     int nfields = 0;
1409
1410     /* Set if the accesibility of one of the fields is not public.  */
1411     int non_public_fields = 0;
1412
1413     /* Member function fieldlist array, contains name of possibly overloaded
1414        member function, number of overloaded member functions and a pointer
1415        to the head of the member function field chain.  */
1416     std::vector<struct fnfieldlist> fnfieldlists;
1417
1418     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1419        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1420     std::vector<struct decl_field> typedef_field_list;
1421
1422     /* Nested types defined by this class and the number of elements in this
1423        list.  */
1424     std::vector<struct decl_field> nested_types_list;
1425   };
1426
1427 /* One item on the queue of compilation units to read in full symbols
1428    for.  */
1429 struct dwarf2_queue_item
1430 {
1431   struct dwarf2_per_cu_data *per_cu;
1432   enum language pretend_language;
1433   struct dwarf2_queue_item *next;
1434 };
1435
1436 /* The current queue.  */
1437 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1438
1439 /* Loaded secondary compilation units are kept in memory until they
1440    have not been referenced for the processing of this many
1441    compilation units.  Set this to zero to disable caching.  Cache
1442    sizes of up to at least twenty will improve startup time for
1443    typical inter-CU-reference binaries, at an obvious memory cost.  */
1444 static int dwarf_max_cache_age = 5;
1445 static void
1446 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1447                           struct cmd_list_element *c, const char *value)
1448 {
1449   fprintf_filtered (file, _("The upper bound on the age of cached "
1450                             "DWARF compilation units is %s.\n"),
1451                     value);
1452 }
1453 \f
1454 /* local function prototypes */
1455
1456 static const char *get_section_name (const struct dwarf2_section_info *);
1457
1458 static const char *get_section_file_name (const struct dwarf2_section_info *);
1459
1460 static void dwarf2_find_base_address (struct die_info *die,
1461                                       struct dwarf2_cu *cu);
1462
1463 static struct partial_symtab *create_partial_symtab
1464   (struct dwarf2_per_cu_data *per_cu, const char *name);
1465
1466 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1467                                         const gdb_byte *info_ptr,
1468                                         struct die_info *type_unit_die,
1469                                         int has_children, void *data);
1470
1471 static void dwarf2_build_psymtabs_hard
1472   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1473
1474 static void scan_partial_symbols (struct partial_die_info *,
1475                                   CORE_ADDR *, CORE_ADDR *,
1476                                   int, struct dwarf2_cu *);
1477
1478 static void add_partial_symbol (struct partial_die_info *,
1479                                 struct dwarf2_cu *);
1480
1481 static void add_partial_namespace (struct partial_die_info *pdi,
1482                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1483                                    int set_addrmap, struct dwarf2_cu *cu);
1484
1485 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1486                                 CORE_ADDR *highpc, int set_addrmap,
1487                                 struct dwarf2_cu *cu);
1488
1489 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1490                                      struct dwarf2_cu *cu);
1491
1492 static void add_partial_subprogram (struct partial_die_info *pdi,
1493                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1494                                     int need_pc, struct dwarf2_cu *cu);
1495
1496 static void dwarf2_read_symtab (struct partial_symtab *,
1497                                 struct objfile *);
1498
1499 static void psymtab_to_symtab_1 (struct partial_symtab *);
1500
1501 static abbrev_table_up abbrev_table_read_table
1502   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1503    sect_offset);
1504
1505 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1506
1507 static struct partial_die_info *load_partial_dies
1508   (const struct die_reader_specs *, const gdb_byte *, int);
1509
1510 static struct partial_die_info *find_partial_die (sect_offset, int,
1511                                                   struct dwarf2_cu *);
1512
1513 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1514                                        struct attribute *, struct attr_abbrev *,
1515                                        const gdb_byte *);
1516
1517 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1518
1519 static int read_1_signed_byte (bfd *, const gdb_byte *);
1520
1521 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1522
1523 /* Read the next three bytes (little-endian order) as an unsigned integer.  */
1524 static unsigned int read_3_bytes (bfd *, const gdb_byte *);
1525
1526 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1527
1528 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1529
1530 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1531                                unsigned int *);
1532
1533 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1534
1535 static LONGEST read_checked_initial_length_and_offset
1536   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1537    unsigned int *, unsigned int *);
1538
1539 static LONGEST read_offset (bfd *, const gdb_byte *,
1540                             const struct comp_unit_head *,
1541                             unsigned int *);
1542
1543 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1544
1545 static sect_offset read_abbrev_offset
1546   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1547    struct dwarf2_section_info *, sect_offset);
1548
1549 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1550
1551 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1552
1553 static const char *read_indirect_string
1554   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1555    const struct comp_unit_head *, unsigned int *);
1556
1557 static const char *read_indirect_line_string
1558   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1559    const struct comp_unit_head *, unsigned int *);
1560
1561 static const char *read_indirect_string_at_offset
1562   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1563    LONGEST str_offset);
1564
1565 static const char *read_indirect_string_from_dwz
1566   (struct objfile *objfile, struct dwz_file *, LONGEST);
1567
1568 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1569
1570 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1571                                               const gdb_byte *,
1572                                               unsigned int *);
1573
1574 static const char *read_str_index (const struct die_reader_specs *reader,
1575                                    ULONGEST str_index);
1576
1577 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1578
1579 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1580                                       struct dwarf2_cu *);
1581
1582 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1583                                                 unsigned int);
1584
1585 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1586                                        struct dwarf2_cu *cu);
1587
1588 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1589                                struct dwarf2_cu *cu);
1590
1591 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1592
1593 static struct die_info *die_specification (struct die_info *die,
1594                                            struct dwarf2_cu **);
1595
1596 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1597                                                 struct dwarf2_cu *cu);
1598
1599 static void dwarf_decode_lines (struct line_header *, const char *,
1600                                 struct dwarf2_cu *, struct partial_symtab *,
1601                                 CORE_ADDR, int decode_mapping);
1602
1603 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1604                                   const char *);
1605
1606 static struct symbol *new_symbol (struct die_info *, struct type *,
1607                                   struct dwarf2_cu *, struct symbol * = NULL);
1608
1609 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1610                                 struct dwarf2_cu *);
1611
1612 static void dwarf2_const_value_attr (const struct attribute *attr,
1613                                      struct type *type,
1614                                      const char *name,
1615                                      struct obstack *obstack,
1616                                      struct dwarf2_cu *cu, LONGEST *value,
1617                                      const gdb_byte **bytes,
1618                                      struct dwarf2_locexpr_baton **baton);
1619
1620 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1621
1622 static int need_gnat_info (struct dwarf2_cu *);
1623
1624 static struct type *die_descriptive_type (struct die_info *,
1625                                           struct dwarf2_cu *);
1626
1627 static void set_descriptive_type (struct type *, struct die_info *,
1628                                   struct dwarf2_cu *);
1629
1630 static struct type *die_containing_type (struct die_info *,
1631                                          struct dwarf2_cu *);
1632
1633 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1634                                      struct dwarf2_cu *);
1635
1636 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1637
1638 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1639
1640 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1641
1642 static char *typename_concat (struct obstack *obs, const char *prefix,
1643                               const char *suffix, int physname,
1644                               struct dwarf2_cu *cu);
1645
1646 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1647
1648 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1649
1650 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1651
1652 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1653
1654 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1655
1656 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1657
1658 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1659                                struct dwarf2_cu *, struct partial_symtab *);
1660
1661 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1662    values.  Keep the items ordered with increasing constraints compliance.  */
1663 enum pc_bounds_kind
1664 {
1665   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1666   PC_BOUNDS_NOT_PRESENT,
1667
1668   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1669      were present but they do not form a valid range of PC addresses.  */
1670   PC_BOUNDS_INVALID,
1671
1672   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1673   PC_BOUNDS_RANGES,
1674
1675   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1676   PC_BOUNDS_HIGH_LOW,
1677 };
1678
1679 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1680                                                  CORE_ADDR *, CORE_ADDR *,
1681                                                  struct dwarf2_cu *,
1682                                                  struct partial_symtab *);
1683
1684 static void get_scope_pc_bounds (struct die_info *,
1685                                  CORE_ADDR *, CORE_ADDR *,
1686                                  struct dwarf2_cu *);
1687
1688 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1689                                         CORE_ADDR, struct dwarf2_cu *);
1690
1691 static void dwarf2_add_field (struct field_info *, struct die_info *,
1692                               struct dwarf2_cu *);
1693
1694 static void dwarf2_attach_fields_to_type (struct field_info *,
1695                                           struct type *, struct dwarf2_cu *);
1696
1697 static void dwarf2_add_member_fn (struct field_info *,
1698                                   struct die_info *, struct type *,
1699                                   struct dwarf2_cu *);
1700
1701 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1702                                              struct type *,
1703                                              struct dwarf2_cu *);
1704
1705 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1706
1707 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1708
1709 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1710
1711 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1712
1713 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1714
1715 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1716
1717 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1718
1719 static struct type *read_module_type (struct die_info *die,
1720                                       struct dwarf2_cu *cu);
1721
1722 static const char *namespace_name (struct die_info *die,
1723                                    int *is_anonymous, struct dwarf2_cu *);
1724
1725 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1726
1727 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1728
1729 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1730                                                        struct dwarf2_cu *);
1731
1732 static struct die_info *read_die_and_siblings_1
1733   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1734    struct die_info *);
1735
1736 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1737                                                const gdb_byte *info_ptr,
1738                                                const gdb_byte **new_info_ptr,
1739                                                struct die_info *parent);
1740
1741 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1742                                         struct die_info **, const gdb_byte *,
1743                                         int *, int);
1744
1745 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1746                                       struct die_info **, const gdb_byte *,
1747                                       int *);
1748
1749 static void process_die (struct die_info *, struct dwarf2_cu *);
1750
1751 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1752                                              struct obstack *);
1753
1754 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1755
1756 static const char *dwarf2_full_name (const char *name,
1757                                      struct die_info *die,
1758                                      struct dwarf2_cu *cu);
1759
1760 static const char *dwarf2_physname (const char *name, struct die_info *die,
1761                                     struct dwarf2_cu *cu);
1762
1763 static struct die_info *dwarf2_extension (struct die_info *die,
1764                                           struct dwarf2_cu **);
1765
1766 static const char *dwarf_tag_name (unsigned int);
1767
1768 static const char *dwarf_attr_name (unsigned int);
1769
1770 static const char *dwarf_form_name (unsigned int);
1771
1772 static const char *dwarf_bool_name (unsigned int);
1773
1774 static const char *dwarf_type_encoding_name (unsigned int);
1775
1776 static struct die_info *sibling_die (struct die_info *);
1777
1778 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1779
1780 static void dump_die_for_error (struct die_info *);
1781
1782 static void dump_die_1 (struct ui_file *, int level, int max_level,
1783                         struct die_info *);
1784
1785 /*static*/ void dump_die (struct die_info *, int max_level);
1786
1787 static void store_in_ref_table (struct die_info *,
1788                                 struct dwarf2_cu *);
1789
1790 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1791
1792 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1793
1794 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1795                                                const struct attribute *,
1796                                                struct dwarf2_cu **);
1797
1798 static struct die_info *follow_die_ref (struct die_info *,
1799                                         const struct attribute *,
1800                                         struct dwarf2_cu **);
1801
1802 static struct die_info *follow_die_sig (struct die_info *,
1803                                         const struct attribute *,
1804                                         struct dwarf2_cu **);
1805
1806 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1807                                          struct dwarf2_cu *);
1808
1809 static struct type *get_DW_AT_signature_type (struct die_info *,
1810                                               const struct attribute *,
1811                                               struct dwarf2_cu *);
1812
1813 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1814
1815 static void read_signatured_type (struct signatured_type *);
1816
1817 static int attr_to_dynamic_prop (const struct attribute *attr,
1818                                  struct die_info *die, struct dwarf2_cu *cu,
1819                                  struct dynamic_prop *prop);
1820
1821 /* memory allocation interface */
1822
1823 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1824
1825 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1826
1827 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1828
1829 static int attr_form_is_block (const struct attribute *);
1830
1831 static int attr_form_is_section_offset (const struct attribute *);
1832
1833 static int attr_form_is_constant (const struct attribute *);
1834
1835 static int attr_form_is_ref (const struct attribute *);
1836
1837 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1838                                    struct dwarf2_loclist_baton *baton,
1839                                    const struct attribute *attr);
1840
1841 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1842                                          struct symbol *sym,
1843                                          struct dwarf2_cu *cu,
1844                                          int is_block);
1845
1846 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1847                                      const gdb_byte *info_ptr,
1848                                      struct abbrev_info *abbrev);
1849
1850 static hashval_t partial_die_hash (const void *item);
1851
1852 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1853
1854 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1855   (sect_offset sect_off, unsigned int offset_in_dwz,
1856    struct dwarf2_per_objfile *dwarf2_per_objfile);
1857
1858 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1859                                    struct die_info *comp_unit_die,
1860                                    enum language pretend_language);
1861
1862 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1863
1864 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1865
1866 static struct type *set_die_type (struct die_info *, struct type *,
1867                                   struct dwarf2_cu *);
1868
1869 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1870
1871 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1872
1873 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1874                                  enum language);
1875
1876 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1877                                     enum language);
1878
1879 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1880                                     enum language);
1881
1882 static void dwarf2_add_dependence (struct dwarf2_cu *,
1883                                    struct dwarf2_per_cu_data *);
1884
1885 static void dwarf2_mark (struct dwarf2_cu *);
1886
1887 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1888
1889 static struct type *get_die_type_at_offset (sect_offset,
1890                                             struct dwarf2_per_cu_data *);
1891
1892 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1893
1894 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1895                              enum language pretend_language);
1896
1897 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1898
1899 /* Class, the destructor of which frees all allocated queue entries.  This
1900    will only have work to do if an error was thrown while processing the
1901    dwarf.  If no error was thrown then the queue entries should have all
1902    been processed, and freed, as we went along.  */
1903
1904 class dwarf2_queue_guard
1905 {
1906 public:
1907   dwarf2_queue_guard () = default;
1908
1909   /* Free any entries remaining on the queue.  There should only be
1910      entries left if we hit an error while processing the dwarf.  */
1911   ~dwarf2_queue_guard ()
1912   {
1913     struct dwarf2_queue_item *item, *last;
1914
1915     item = dwarf2_queue;
1916     while (item)
1917       {
1918         /* Anything still marked queued is likely to be in an
1919            inconsistent state, so discard it.  */
1920         if (item->per_cu->queued)
1921           {
1922             if (item->per_cu->cu != NULL)
1923               free_one_cached_comp_unit (item->per_cu);
1924             item->per_cu->queued = 0;
1925           }
1926
1927         last = item;
1928         item = item->next;
1929         xfree (last);
1930       }
1931
1932     dwarf2_queue = dwarf2_queue_tail = NULL;
1933   }
1934 };
1935
1936 /* The return type of find_file_and_directory.  Note, the enclosed
1937    string pointers are only valid while this object is valid.  */
1938
1939 struct file_and_directory
1940 {
1941   /* The filename.  This is never NULL.  */
1942   const char *name;
1943
1944   /* The compilation directory.  NULL if not known.  If we needed to
1945      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1946      points directly to the DW_AT_comp_dir string attribute owned by
1947      the obstack that owns the DIE.  */
1948   const char *comp_dir;
1949
1950   /* If we needed to build a new string for comp_dir, this is what
1951      owns the storage.  */
1952   std::string comp_dir_storage;
1953 };
1954
1955 static file_and_directory find_file_and_directory (struct die_info *die,
1956                                                    struct dwarf2_cu *cu);
1957
1958 static char *file_full_name (int file, struct line_header *lh,
1959                              const char *comp_dir);
1960
1961 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1962 enum class rcuh_kind { COMPILE, TYPE };
1963
1964 static const gdb_byte *read_and_check_comp_unit_head
1965   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1966    struct comp_unit_head *header,
1967    struct dwarf2_section_info *section,
1968    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1969    rcuh_kind section_kind);
1970
1971 static void init_cutu_and_read_dies
1972   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1973    int use_existing_cu, int keep, bool skip_partial,
1974    die_reader_func_ftype *die_reader_func, void *data);
1975
1976 static void init_cutu_and_read_dies_simple
1977   (struct dwarf2_per_cu_data *this_cu,
1978    die_reader_func_ftype *die_reader_func, void *data);
1979
1980 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1981
1982 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1983
1984 static struct dwo_unit *lookup_dwo_unit_in_dwp
1985   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1986    struct dwp_file *dwp_file, const char *comp_dir,
1987    ULONGEST signature, int is_debug_types);
1988
1989 static struct dwp_file *get_dwp_file
1990   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1991
1992 static struct dwo_unit *lookup_dwo_comp_unit
1993   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1994
1995 static struct dwo_unit *lookup_dwo_type_unit
1996   (struct signatured_type *, const char *, const char *);
1997
1998 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1999
2000 static void free_dwo_file (struct dwo_file *);
2001
2002 /* A unique_ptr helper to free a dwo_file.  */
2003
2004 struct dwo_file_deleter
2005 {
2006   void operator() (struct dwo_file *df) const
2007   {
2008     free_dwo_file (df);
2009   }
2010 };
2011
2012 /* A unique pointer to a dwo_file.  */
2013
2014 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
2015
2016 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2017
2018 static void check_producer (struct dwarf2_cu *cu);
2019
2020 static void free_line_header_voidp (void *arg);
2021 \f
2022 /* Various complaints about symbol reading that don't abort the process.  */
2023
2024 static void
2025 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2026 {
2027   complaint (_("statement list doesn't fit in .debug_line section"));
2028 }
2029
2030 static void
2031 dwarf2_debug_line_missing_file_complaint (void)
2032 {
2033   complaint (_(".debug_line section has line data without a file"));
2034 }
2035
2036 static void
2037 dwarf2_debug_line_missing_end_sequence_complaint (void)
2038 {
2039   complaint (_(".debug_line section has line "
2040                "program sequence without an end"));
2041 }
2042
2043 static void
2044 dwarf2_complex_location_expr_complaint (void)
2045 {
2046   complaint (_("location expression too complex"));
2047 }
2048
2049 static void
2050 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2051                                               int arg3)
2052 {
2053   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2054              arg1, arg2, arg3);
2055 }
2056
2057 static void
2058 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2059 {
2060   complaint (_("debug info runs off end of %s section"
2061                " [in module %s]"),
2062              get_section_name (section),
2063              get_section_file_name (section));
2064 }
2065
2066 static void
2067 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2068 {
2069   complaint (_("macro debug info contains a "
2070                "malformed macro definition:\n`%s'"),
2071              arg1);
2072 }
2073
2074 static void
2075 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2076 {
2077   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2078              arg1, arg2);
2079 }
2080
2081 /* Hash function for line_header_hash.  */
2082
2083 static hashval_t
2084 line_header_hash (const struct line_header *ofs)
2085 {
2086   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2087 }
2088
2089 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2090
2091 static hashval_t
2092 line_header_hash_voidp (const void *item)
2093 {
2094   const struct line_header *ofs = (const struct line_header *) item;
2095
2096   return line_header_hash (ofs);
2097 }
2098
2099 /* Equality function for line_header_hash.  */
2100
2101 static int
2102 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2103 {
2104   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2105   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2106
2107   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2108           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2109 }
2110
2111 \f
2112
2113 /* Read the given attribute value as an address, taking the attribute's
2114    form into account.  */
2115
2116 static CORE_ADDR
2117 attr_value_as_address (struct attribute *attr)
2118 {
2119   CORE_ADDR addr;
2120
2121   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_addrx
2122       && attr->form != DW_FORM_GNU_addr_index)
2123     {
2124       /* Aside from a few clearly defined exceptions, attributes that
2125          contain an address must always be in DW_FORM_addr form.
2126          Unfortunately, some compilers happen to be violating this
2127          requirement by encoding addresses using other forms, such
2128          as DW_FORM_data4 for example.  For those broken compilers,
2129          we try to do our best, without any guarantee of success,
2130          to interpret the address correctly.  It would also be nice
2131          to generate a complaint, but that would require us to maintain
2132          a list of legitimate cases where a non-address form is allowed,
2133          as well as update callers to pass in at least the CU's DWARF
2134          version.  This is more overhead than what we're willing to
2135          expand for a pretty rare case.  */
2136       addr = DW_UNSND (attr);
2137     }
2138   else
2139     addr = DW_ADDR (attr);
2140
2141   return addr;
2142 }
2143
2144 /* See declaration.  */
2145
2146 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2147                                         const dwarf2_debug_sections *names)
2148   : objfile (objfile_)
2149 {
2150   if (names == NULL)
2151     names = &dwarf2_elf_names;
2152
2153   bfd *obfd = objfile->obfd;
2154
2155   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2156     locate_sections (obfd, sec, *names);
2157 }
2158
2159 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2160
2161 dwarf2_per_objfile::~dwarf2_per_objfile ()
2162 {
2163   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2164   free_cached_comp_units ();
2165
2166   if (quick_file_names_table)
2167     htab_delete (quick_file_names_table);
2168
2169   if (line_header_hash)
2170     htab_delete (line_header_hash);
2171
2172   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2173     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2174
2175   for (signatured_type *sig_type : all_type_units)
2176     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2177
2178   VEC_free (dwarf2_section_info_def, types);
2179
2180   if (dwo_files != NULL)
2181     free_dwo_files (dwo_files, objfile);
2182
2183   /* Everything else should be on the objfile obstack.  */
2184 }
2185
2186 /* See declaration.  */
2187
2188 void
2189 dwarf2_per_objfile::free_cached_comp_units ()
2190 {
2191   dwarf2_per_cu_data *per_cu = read_in_chain;
2192   dwarf2_per_cu_data **last_chain = &read_in_chain;
2193   while (per_cu != NULL)
2194     {
2195       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2196
2197       delete per_cu->cu;
2198       *last_chain = next_cu;
2199       per_cu = next_cu;
2200     }
2201 }
2202
2203 /* A helper class that calls free_cached_comp_units on
2204    destruction.  */
2205
2206 class free_cached_comp_units
2207 {
2208 public:
2209
2210   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2211     : m_per_objfile (per_objfile)
2212   {
2213   }
2214
2215   ~free_cached_comp_units ()
2216   {
2217     m_per_objfile->free_cached_comp_units ();
2218   }
2219
2220   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2221
2222 private:
2223
2224   dwarf2_per_objfile *m_per_objfile;
2225 };
2226
2227 /* Try to locate the sections we need for DWARF 2 debugging
2228    information and return true if we have enough to do something.
2229    NAMES points to the dwarf2 section names, or is NULL if the standard
2230    ELF names are used.  */
2231
2232 int
2233 dwarf2_has_info (struct objfile *objfile,
2234                  const struct dwarf2_debug_sections *names)
2235 {
2236   if (objfile->flags & OBJF_READNEVER)
2237     return 0;
2238
2239   struct dwarf2_per_objfile *dwarf2_per_objfile
2240     = get_dwarf2_per_objfile (objfile);
2241
2242   if (dwarf2_per_objfile == NULL)
2243     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
2244                                                           names);
2245
2246   return (!dwarf2_per_objfile->info.is_virtual
2247           && dwarf2_per_objfile->info.s.section != NULL
2248           && !dwarf2_per_objfile->abbrev.is_virtual
2249           && dwarf2_per_objfile->abbrev.s.section != NULL);
2250 }
2251
2252 /* Return the containing section of virtual section SECTION.  */
2253
2254 static struct dwarf2_section_info *
2255 get_containing_section (const struct dwarf2_section_info *section)
2256 {
2257   gdb_assert (section->is_virtual);
2258   return section->s.containing_section;
2259 }
2260
2261 /* Return the bfd owner of SECTION.  */
2262
2263 static struct bfd *
2264 get_section_bfd_owner (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->owner;
2272 }
2273
2274 /* Return the bfd section of SECTION.
2275    Returns NULL if the section is not present.  */
2276
2277 static asection *
2278 get_section_bfd_section (const struct dwarf2_section_info *section)
2279 {
2280   if (section->is_virtual)
2281     {
2282       section = get_containing_section (section);
2283       gdb_assert (!section->is_virtual);
2284     }
2285   return section->s.section;
2286 }
2287
2288 /* Return the name of SECTION.  */
2289
2290 static const char *
2291 get_section_name (const struct dwarf2_section_info *section)
2292 {
2293   asection *sectp = get_section_bfd_section (section);
2294
2295   gdb_assert (sectp != NULL);
2296   return bfd_section_name (get_section_bfd_owner (section), sectp);
2297 }
2298
2299 /* Return the name of the file SECTION is in.  */
2300
2301 static const char *
2302 get_section_file_name (const struct dwarf2_section_info *section)
2303 {
2304   bfd *abfd = get_section_bfd_owner (section);
2305
2306   return bfd_get_filename (abfd);
2307 }
2308
2309 /* Return the id of SECTION.
2310    Returns 0 if SECTION doesn't exist.  */
2311
2312 static int
2313 get_section_id (const struct dwarf2_section_info *section)
2314 {
2315   asection *sectp = get_section_bfd_section (section);
2316
2317   if (sectp == NULL)
2318     return 0;
2319   return sectp->id;
2320 }
2321
2322 /* Return the flags of SECTION.
2323    SECTION (or containing section if this is a virtual section) must exist.  */
2324
2325 static int
2326 get_section_flags (const struct dwarf2_section_info *section)
2327 {
2328   asection *sectp = get_section_bfd_section (section);
2329
2330   gdb_assert (sectp != NULL);
2331   return bfd_get_section_flags (sectp->owner, sectp);
2332 }
2333
2334 /* When loading sections, we look either for uncompressed section or for
2335    compressed section names.  */
2336
2337 static int
2338 section_is_p (const char *section_name,
2339               const struct dwarf2_section_names *names)
2340 {
2341   if (names->normal != NULL
2342       && strcmp (section_name, names->normal) == 0)
2343     return 1;
2344   if (names->compressed != NULL
2345       && strcmp (section_name, names->compressed) == 0)
2346     return 1;
2347   return 0;
2348 }
2349
2350 /* See declaration.  */
2351
2352 void
2353 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2354                                      const dwarf2_debug_sections &names)
2355 {
2356   flagword aflag = bfd_get_section_flags (abfd, sectp);
2357
2358   if ((aflag & SEC_HAS_CONTENTS) == 0)
2359     {
2360     }
2361   else if (section_is_p (sectp->name, &names.info))
2362     {
2363       this->info.s.section = sectp;
2364       this->info.size = bfd_get_section_size (sectp);
2365     }
2366   else if (section_is_p (sectp->name, &names.abbrev))
2367     {
2368       this->abbrev.s.section = sectp;
2369       this->abbrev.size = bfd_get_section_size (sectp);
2370     }
2371   else if (section_is_p (sectp->name, &names.line))
2372     {
2373       this->line.s.section = sectp;
2374       this->line.size = bfd_get_section_size (sectp);
2375     }
2376   else if (section_is_p (sectp->name, &names.loc))
2377     {
2378       this->loc.s.section = sectp;
2379       this->loc.size = bfd_get_section_size (sectp);
2380     }
2381   else if (section_is_p (sectp->name, &names.loclists))
2382     {
2383       this->loclists.s.section = sectp;
2384       this->loclists.size = bfd_get_section_size (sectp);
2385     }
2386   else if (section_is_p (sectp->name, &names.macinfo))
2387     {
2388       this->macinfo.s.section = sectp;
2389       this->macinfo.size = bfd_get_section_size (sectp);
2390     }
2391   else if (section_is_p (sectp->name, &names.macro))
2392     {
2393       this->macro.s.section = sectp;
2394       this->macro.size = bfd_get_section_size (sectp);
2395     }
2396   else if (section_is_p (sectp->name, &names.str))
2397     {
2398       this->str.s.section = sectp;
2399       this->str.size = bfd_get_section_size (sectp);
2400     }
2401   else if (section_is_p (sectp->name, &names.line_str))
2402     {
2403       this->line_str.s.section = sectp;
2404       this->line_str.size = bfd_get_section_size (sectp);
2405     }
2406   else if (section_is_p (sectp->name, &names.addr))
2407     {
2408       this->addr.s.section = sectp;
2409       this->addr.size = bfd_get_section_size (sectp);
2410     }
2411   else if (section_is_p (sectp->name, &names.frame))
2412     {
2413       this->frame.s.section = sectp;
2414       this->frame.size = bfd_get_section_size (sectp);
2415     }
2416   else if (section_is_p (sectp->name, &names.eh_frame))
2417     {
2418       this->eh_frame.s.section = sectp;
2419       this->eh_frame.size = bfd_get_section_size (sectp);
2420     }
2421   else if (section_is_p (sectp->name, &names.ranges))
2422     {
2423       this->ranges.s.section = sectp;
2424       this->ranges.size = bfd_get_section_size (sectp);
2425     }
2426   else if (section_is_p (sectp->name, &names.rnglists))
2427     {
2428       this->rnglists.s.section = sectp;
2429       this->rnglists.size = bfd_get_section_size (sectp);
2430     }
2431   else if (section_is_p (sectp->name, &names.types))
2432     {
2433       struct dwarf2_section_info type_section;
2434
2435       memset (&type_section, 0, sizeof (type_section));
2436       type_section.s.section = sectp;
2437       type_section.size = bfd_get_section_size (sectp);
2438
2439       VEC_safe_push (dwarf2_section_info_def, this->types,
2440                      &type_section);
2441     }
2442   else if (section_is_p (sectp->name, &names.gdb_index))
2443     {
2444       this->gdb_index.s.section = sectp;
2445       this->gdb_index.size = bfd_get_section_size (sectp);
2446     }
2447   else if (section_is_p (sectp->name, &names.debug_names))
2448     {
2449       this->debug_names.s.section = sectp;
2450       this->debug_names.size = bfd_get_section_size (sectp);
2451     }
2452   else if (section_is_p (sectp->name, &names.debug_aranges))
2453     {
2454       this->debug_aranges.s.section = sectp;
2455       this->debug_aranges.size = bfd_get_section_size (sectp);
2456     }
2457
2458   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2459       && bfd_section_vma (abfd, sectp) == 0)
2460     this->has_section_at_zero = true;
2461 }
2462
2463 /* A helper function that decides whether a section is empty,
2464    or not present.  */
2465
2466 static int
2467 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2468 {
2469   if (section->is_virtual)
2470     return section->size == 0;
2471   return section->s.section == NULL || section->size == 0;
2472 }
2473
2474 /* See dwarf2read.h.  */
2475
2476 void
2477 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2478 {
2479   asection *sectp;
2480   bfd *abfd;
2481   gdb_byte *buf, *retbuf;
2482
2483   if (info->readin)
2484     return;
2485   info->buffer = NULL;
2486   info->readin = 1;
2487
2488   if (dwarf2_section_empty_p (info))
2489     return;
2490
2491   sectp = get_section_bfd_section (info);
2492
2493   /* If this is a virtual section we need to read in the real one first.  */
2494   if (info->is_virtual)
2495     {
2496       struct dwarf2_section_info *containing_section =
2497         get_containing_section (info);
2498
2499       gdb_assert (sectp != NULL);
2500       if ((sectp->flags & SEC_RELOC) != 0)
2501         {
2502           error (_("Dwarf Error: DWP format V2 with relocations is not"
2503                    " supported in section %s [in module %s]"),
2504                  get_section_name (info), get_section_file_name (info));
2505         }
2506       dwarf2_read_section (objfile, containing_section);
2507       /* Other code should have already caught virtual sections that don't
2508          fit.  */
2509       gdb_assert (info->virtual_offset + info->size
2510                   <= containing_section->size);
2511       /* If the real section is empty or there was a problem reading the
2512          section we shouldn't get here.  */
2513       gdb_assert (containing_section->buffer != NULL);
2514       info->buffer = containing_section->buffer + info->virtual_offset;
2515       return;
2516     }
2517
2518   /* If the section has relocations, we must read it ourselves.
2519      Otherwise we attach it to the BFD.  */
2520   if ((sectp->flags & SEC_RELOC) == 0)
2521     {
2522       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2523       return;
2524     }
2525
2526   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2527   info->buffer = buf;
2528
2529   /* When debugging .o files, we may need to apply relocations; see
2530      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2531      We never compress sections in .o files, so we only need to
2532      try this when the section is not compressed.  */
2533   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2534   if (retbuf != NULL)
2535     {
2536       info->buffer = retbuf;
2537       return;
2538     }
2539
2540   abfd = get_section_bfd_owner (info);
2541   gdb_assert (abfd != NULL);
2542
2543   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2544       || bfd_bread (buf, info->size, abfd) != info->size)
2545     {
2546       error (_("Dwarf Error: Can't read DWARF data"
2547                " in section %s [in module %s]"),
2548              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2549     }
2550 }
2551
2552 /* A helper function that returns the size of a section in a safe way.
2553    If you are positive that the section has been read before using the
2554    size, then it is safe to refer to the dwarf2_section_info object's
2555    "size" field directly.  In other cases, you must call this
2556    function, because for compressed sections the size field is not set
2557    correctly until the section has been read.  */
2558
2559 static bfd_size_type
2560 dwarf2_section_size (struct objfile *objfile,
2561                      struct dwarf2_section_info *info)
2562 {
2563   if (!info->readin)
2564     dwarf2_read_section (objfile, info);
2565   return info->size;
2566 }
2567
2568 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2569    SECTION_NAME.  */
2570
2571 void
2572 dwarf2_get_section_info (struct objfile *objfile,
2573                          enum dwarf2_section_enum sect,
2574                          asection **sectp, const gdb_byte **bufp,
2575                          bfd_size_type *sizep)
2576 {
2577   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2578   struct dwarf2_section_info *info;
2579
2580   /* We may see an objfile without any DWARF, in which case we just
2581      return nothing.  */
2582   if (data == NULL)
2583     {
2584       *sectp = NULL;
2585       *bufp = NULL;
2586       *sizep = 0;
2587       return;
2588     }
2589   switch (sect)
2590     {
2591     case DWARF2_DEBUG_FRAME:
2592       info = &data->frame;
2593       break;
2594     case DWARF2_EH_FRAME:
2595       info = &data->eh_frame;
2596       break;
2597     default:
2598       gdb_assert_not_reached ("unexpected section");
2599     }
2600
2601   dwarf2_read_section (objfile, info);
2602
2603   *sectp = get_section_bfd_section (info);
2604   *bufp = info->buffer;
2605   *sizep = info->size;
2606 }
2607
2608 /* A helper function to find the sections for a .dwz file.  */
2609
2610 static void
2611 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2612 {
2613   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2614
2615   /* Note that we only support the standard ELF names, because .dwz
2616      is ELF-only (at the time of writing).  */
2617   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2618     {
2619       dwz_file->abbrev.s.section = sectp;
2620       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2621     }
2622   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2623     {
2624       dwz_file->info.s.section = sectp;
2625       dwz_file->info.size = bfd_get_section_size (sectp);
2626     }
2627   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2628     {
2629       dwz_file->str.s.section = sectp;
2630       dwz_file->str.size = bfd_get_section_size (sectp);
2631     }
2632   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2633     {
2634       dwz_file->line.s.section = sectp;
2635       dwz_file->line.size = bfd_get_section_size (sectp);
2636     }
2637   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2638     {
2639       dwz_file->macro.s.section = sectp;
2640       dwz_file->macro.size = bfd_get_section_size (sectp);
2641     }
2642   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2643     {
2644       dwz_file->gdb_index.s.section = sectp;
2645       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2646     }
2647   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2648     {
2649       dwz_file->debug_names.s.section = sectp;
2650       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2651     }
2652 }
2653
2654 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2655    there is no .gnu_debugaltlink section in the file.  Error if there
2656    is such a section but the file cannot be found.  */
2657
2658 static struct dwz_file *
2659 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2660 {
2661   const char *filename;
2662   bfd_size_type buildid_len_arg;
2663   size_t buildid_len;
2664   bfd_byte *buildid;
2665
2666   if (dwarf2_per_objfile->dwz_file != NULL)
2667     return dwarf2_per_objfile->dwz_file.get ();
2668
2669   bfd_set_error (bfd_error_no_error);
2670   gdb::unique_xmalloc_ptr<char> data
2671     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2672                                   &buildid_len_arg, &buildid));
2673   if (data == NULL)
2674     {
2675       if (bfd_get_error () == bfd_error_no_error)
2676         return NULL;
2677       error (_("could not read '.gnu_debugaltlink' section: %s"),
2678              bfd_errmsg (bfd_get_error ()));
2679     }
2680
2681   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2682
2683   buildid_len = (size_t) buildid_len_arg;
2684
2685   filename = data.get ();
2686
2687   std::string abs_storage;
2688   if (!IS_ABSOLUTE_PATH (filename))
2689     {
2690       gdb::unique_xmalloc_ptr<char> abs
2691         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2692
2693       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2694       filename = abs_storage.c_str ();
2695     }
2696
2697   /* First try the file name given in the section.  If that doesn't
2698      work, try to use the build-id instead.  */
2699   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2700   if (dwz_bfd != NULL)
2701     {
2702       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2703         dwz_bfd.reset (nullptr);
2704     }
2705
2706   if (dwz_bfd == NULL)
2707     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2708
2709   if (dwz_bfd == NULL)
2710     error (_("could not find '.gnu_debugaltlink' file for %s"),
2711            objfile_name (dwarf2_per_objfile->objfile));
2712
2713   std::unique_ptr<struct dwz_file> result
2714     (new struct dwz_file (std::move (dwz_bfd)));
2715
2716   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2717                          result.get ());
2718
2719   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2720                             result->dwz_bfd.get ());
2721   dwarf2_per_objfile->dwz_file = std::move (result);
2722   return dwarf2_per_objfile->dwz_file.get ();
2723 }
2724 \f
2725 /* DWARF quick_symbols_functions support.  */
2726
2727 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2728    unique line tables, so we maintain a separate table of all .debug_line
2729    derived entries to support the sharing.
2730    All the quick functions need is the list of file names.  We discard the
2731    line_header when we're done and don't need to record it here.  */
2732 struct quick_file_names
2733 {
2734   /* The data used to construct the hash key.  */
2735   struct stmt_list_hash hash;
2736
2737   /* The number of entries in file_names, real_names.  */
2738   unsigned int num_file_names;
2739
2740   /* The file names from the line table, after being run through
2741      file_full_name.  */
2742   const char **file_names;
2743
2744   /* The file names from the line table after being run through
2745      gdb_realpath.  These are computed lazily.  */
2746   const char **real_names;
2747 };
2748
2749 /* When using the index (and thus not using psymtabs), each CU has an
2750    object of this type.  This is used to hold information needed by
2751    the various "quick" methods.  */
2752 struct dwarf2_per_cu_quick_data
2753 {
2754   /* The file table.  This can be NULL if there was no file table
2755      or it's currently not read in.
2756      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2757   struct quick_file_names *file_names;
2758
2759   /* The corresponding symbol table.  This is NULL if symbols for this
2760      CU have not yet been read.  */
2761   struct compunit_symtab *compunit_symtab;
2762
2763   /* A temporary mark bit used when iterating over all CUs in
2764      expand_symtabs_matching.  */
2765   unsigned int mark : 1;
2766
2767   /* True if we've tried to read the file table and found there isn't one.
2768      There will be no point in trying to read it again next time.  */
2769   unsigned int no_file_data : 1;
2770 };
2771
2772 /* Utility hash function for a stmt_list_hash.  */
2773
2774 static hashval_t
2775 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2776 {
2777   hashval_t v = 0;
2778
2779   if (stmt_list_hash->dwo_unit != NULL)
2780     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2781   v += to_underlying (stmt_list_hash->line_sect_off);
2782   return v;
2783 }
2784
2785 /* Utility equality function for a stmt_list_hash.  */
2786
2787 static int
2788 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2789                     const struct stmt_list_hash *rhs)
2790 {
2791   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2792     return 0;
2793   if (lhs->dwo_unit != NULL
2794       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2795     return 0;
2796
2797   return lhs->line_sect_off == rhs->line_sect_off;
2798 }
2799
2800 /* Hash function for a quick_file_names.  */
2801
2802 static hashval_t
2803 hash_file_name_entry (const void *e)
2804 {
2805   const struct quick_file_names *file_data
2806     = (const struct quick_file_names *) e;
2807
2808   return hash_stmt_list_entry (&file_data->hash);
2809 }
2810
2811 /* Equality function for a quick_file_names.  */
2812
2813 static int
2814 eq_file_name_entry (const void *a, const void *b)
2815 {
2816   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2817   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2818
2819   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2820 }
2821
2822 /* Delete function for a quick_file_names.  */
2823
2824 static void
2825 delete_file_name_entry (void *e)
2826 {
2827   struct quick_file_names *file_data = (struct quick_file_names *) e;
2828   int i;
2829
2830   for (i = 0; i < file_data->num_file_names; ++i)
2831     {
2832       xfree ((void*) file_data->file_names[i]);
2833       if (file_data->real_names)
2834         xfree ((void*) file_data->real_names[i]);
2835     }
2836
2837   /* The space for the struct itself lives on objfile_obstack,
2838      so we don't free it here.  */
2839 }
2840
2841 /* Create a quick_file_names hash table.  */
2842
2843 static htab_t
2844 create_quick_file_names_table (unsigned int nr_initial_entries)
2845 {
2846   return htab_create_alloc (nr_initial_entries,
2847                             hash_file_name_entry, eq_file_name_entry,
2848                             delete_file_name_entry, xcalloc, xfree);
2849 }
2850
2851 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2852    have to be created afterwards.  You should call age_cached_comp_units after
2853    processing PER_CU->CU.  dw2_setup must have been already called.  */
2854
2855 static void
2856 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2857 {
2858   if (per_cu->is_debug_types)
2859     load_full_type_unit (per_cu);
2860   else
2861     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2862
2863   if (per_cu->cu == NULL)
2864     return;  /* Dummy CU.  */
2865
2866   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2867 }
2868
2869 /* Read in the symbols for PER_CU.  */
2870
2871 static void
2872 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2873 {
2874   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2875
2876   /* Skip type_unit_groups, reading the type units they contain
2877      is handled elsewhere.  */
2878   if (IS_TYPE_UNIT_GROUP (per_cu))
2879     return;
2880
2881   /* The destructor of dwarf2_queue_guard frees any entries left on
2882      the queue.  After this point we're guaranteed to leave this function
2883      with the dwarf queue empty.  */
2884   dwarf2_queue_guard q_guard;
2885
2886   if (dwarf2_per_objfile->using_index
2887       ? per_cu->v.quick->compunit_symtab == NULL
2888       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2889     {
2890       queue_comp_unit (per_cu, language_minimal);
2891       load_cu (per_cu, skip_partial);
2892
2893       /* If we just loaded a CU from a DWO, and we're working with an index
2894          that may badly handle TUs, load all the TUs in that DWO as well.
2895          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2896       if (!per_cu->is_debug_types
2897           && per_cu->cu != NULL
2898           && per_cu->cu->dwo_unit != NULL
2899           && dwarf2_per_objfile->index_table != NULL
2900           && dwarf2_per_objfile->index_table->version <= 7
2901           /* DWP files aren't supported yet.  */
2902           && get_dwp_file (dwarf2_per_objfile) == NULL)
2903         queue_and_load_all_dwo_tus (per_cu);
2904     }
2905
2906   process_queue (dwarf2_per_objfile);
2907
2908   /* Age the cache, releasing compilation units that have not
2909      been used recently.  */
2910   age_cached_comp_units (dwarf2_per_objfile);
2911 }
2912
2913 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2914    the objfile from which this CU came.  Returns the resulting symbol
2915    table.  */
2916
2917 static struct compunit_symtab *
2918 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2919 {
2920   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2921
2922   gdb_assert (dwarf2_per_objfile->using_index);
2923   if (!per_cu->v.quick->compunit_symtab)
2924     {
2925       free_cached_comp_units freer (dwarf2_per_objfile);
2926       scoped_restore decrementer = increment_reading_symtab ();
2927       dw2_do_instantiate_symtab (per_cu, skip_partial);
2928       process_cu_includes (dwarf2_per_objfile);
2929     }
2930
2931   return per_cu->v.quick->compunit_symtab;
2932 }
2933
2934 /* See declaration.  */
2935
2936 dwarf2_per_cu_data *
2937 dwarf2_per_objfile::get_cutu (int index)
2938 {
2939   if (index >= this->all_comp_units.size ())
2940     {
2941       index -= this->all_comp_units.size ();
2942       gdb_assert (index < this->all_type_units.size ());
2943       return &this->all_type_units[index]->per_cu;
2944     }
2945
2946   return this->all_comp_units[index];
2947 }
2948
2949 /* See declaration.  */
2950
2951 dwarf2_per_cu_data *
2952 dwarf2_per_objfile::get_cu (int index)
2953 {
2954   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2955
2956   return this->all_comp_units[index];
2957 }
2958
2959 /* See declaration.  */
2960
2961 signatured_type *
2962 dwarf2_per_objfile::get_tu (int index)
2963 {
2964   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2965
2966   return this->all_type_units[index];
2967 }
2968
2969 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2970    objfile_obstack, and constructed with the specified field
2971    values.  */
2972
2973 static dwarf2_per_cu_data *
2974 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2975                           struct dwarf2_section_info *section,
2976                           int is_dwz,
2977                           sect_offset sect_off, ULONGEST length)
2978 {
2979   struct objfile *objfile = dwarf2_per_objfile->objfile;
2980   dwarf2_per_cu_data *the_cu
2981     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2982                      struct dwarf2_per_cu_data);
2983   the_cu->sect_off = sect_off;
2984   the_cu->length = length;
2985   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2986   the_cu->section = section;
2987   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2988                                    struct dwarf2_per_cu_quick_data);
2989   the_cu->is_dwz = is_dwz;
2990   return the_cu;
2991 }
2992
2993 /* A helper for create_cus_from_index that handles a given list of
2994    CUs.  */
2995
2996 static void
2997 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2998                             const gdb_byte *cu_list, offset_type n_elements,
2999                             struct dwarf2_section_info *section,
3000                             int is_dwz)
3001 {
3002   for (offset_type i = 0; i < n_elements; i += 2)
3003     {
3004       gdb_static_assert (sizeof (ULONGEST) >= 8);
3005
3006       sect_offset sect_off
3007         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3008       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3009       cu_list += 2 * 8;
3010
3011       dwarf2_per_cu_data *per_cu
3012         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3013                                      sect_off, length);
3014       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
3015     }
3016 }
3017
3018 /* Read the CU list from the mapped index, and use it to create all
3019    the CU objects for this objfile.  */
3020
3021 static void
3022 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3023                        const gdb_byte *cu_list, offset_type cu_list_elements,
3024                        const gdb_byte *dwz_list, offset_type dwz_elements)
3025 {
3026   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3027   dwarf2_per_objfile->all_comp_units.reserve
3028     ((cu_list_elements + dwz_elements) / 2);
3029
3030   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3031                               &dwarf2_per_objfile->info, 0);
3032
3033   if (dwz_elements == 0)
3034     return;
3035
3036   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3037   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3038                               &dwz->info, 1);
3039 }
3040
3041 /* Create the signatured type hash table from the index.  */
3042
3043 static void
3044 create_signatured_type_table_from_index
3045   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3046    struct dwarf2_section_info *section,
3047    const gdb_byte *bytes,
3048    offset_type elements)
3049 {
3050   struct objfile *objfile = dwarf2_per_objfile->objfile;
3051
3052   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3053   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3054
3055   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3056
3057   for (offset_type i = 0; i < elements; i += 3)
3058     {
3059       struct signatured_type *sig_type;
3060       ULONGEST signature;
3061       void **slot;
3062       cu_offset type_offset_in_tu;
3063
3064       gdb_static_assert (sizeof (ULONGEST) >= 8);
3065       sect_offset sect_off
3066         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3067       type_offset_in_tu
3068         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3069                                                 BFD_ENDIAN_LITTLE);
3070       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3071       bytes += 3 * 8;
3072
3073       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3074                                  struct signatured_type);
3075       sig_type->signature = signature;
3076       sig_type->type_offset_in_tu = type_offset_in_tu;
3077       sig_type->per_cu.is_debug_types = 1;
3078       sig_type->per_cu.section = section;
3079       sig_type->per_cu.sect_off = sect_off;
3080       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3081       sig_type->per_cu.v.quick
3082         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3083                           struct dwarf2_per_cu_quick_data);
3084
3085       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3086       *slot = sig_type;
3087
3088       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3089     }
3090
3091   dwarf2_per_objfile->signatured_types = sig_types_hash;
3092 }
3093
3094 /* Create the signatured type hash table from .debug_names.  */
3095
3096 static void
3097 create_signatured_type_table_from_debug_names
3098   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3099    const mapped_debug_names &map,
3100    struct dwarf2_section_info *section,
3101    struct dwarf2_section_info *abbrev_section)
3102 {
3103   struct objfile *objfile = dwarf2_per_objfile->objfile;
3104
3105   dwarf2_read_section (objfile, section);
3106   dwarf2_read_section (objfile, abbrev_section);
3107
3108   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3109   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3110
3111   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3112
3113   for (uint32_t i = 0; i < map.tu_count; ++i)
3114     {
3115       struct signatured_type *sig_type;
3116       void **slot;
3117
3118       sect_offset sect_off
3119         = (sect_offset) (extract_unsigned_integer
3120                          (map.tu_table_reordered + i * map.offset_size,
3121                           map.offset_size,
3122                           map.dwarf5_byte_order));
3123
3124       comp_unit_head cu_header;
3125       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3126                                      abbrev_section,
3127                                      section->buffer + to_underlying (sect_off),
3128                                      rcuh_kind::TYPE);
3129
3130       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3131                                  struct signatured_type);
3132       sig_type->signature = cu_header.signature;
3133       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3134       sig_type->per_cu.is_debug_types = 1;
3135       sig_type->per_cu.section = section;
3136       sig_type->per_cu.sect_off = sect_off;
3137       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3138       sig_type->per_cu.v.quick
3139         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3140                           struct dwarf2_per_cu_quick_data);
3141
3142       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3143       *slot = sig_type;
3144
3145       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3146     }
3147
3148   dwarf2_per_objfile->signatured_types = sig_types_hash;
3149 }
3150
3151 /* Read the address map data from the mapped index, and use it to
3152    populate the objfile's psymtabs_addrmap.  */
3153
3154 static void
3155 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3156                            struct mapped_index *index)
3157 {
3158   struct objfile *objfile = dwarf2_per_objfile->objfile;
3159   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3160   const gdb_byte *iter, *end;
3161   struct addrmap *mutable_map;
3162   CORE_ADDR baseaddr;
3163
3164   auto_obstack temp_obstack;
3165
3166   mutable_map = addrmap_create_mutable (&temp_obstack);
3167
3168   iter = index->address_table.data ();
3169   end = iter + index->address_table.size ();
3170
3171   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3172
3173   while (iter < end)
3174     {
3175       ULONGEST hi, lo, cu_index;
3176       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3177       iter += 8;
3178       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3179       iter += 8;
3180       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3181       iter += 4;
3182
3183       if (lo > hi)
3184         {
3185           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3186                      hex_string (lo), hex_string (hi));
3187           continue;
3188         }
3189
3190       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3191         {
3192           complaint (_(".gdb_index address table has invalid CU number %u"),
3193                      (unsigned) cu_index);
3194           continue;
3195         }
3196
3197       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
3198       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
3199       addrmap_set_empty (mutable_map, lo, hi - 1,
3200                          dwarf2_per_objfile->get_cu (cu_index));
3201     }
3202
3203   objfile->partial_symtabs->psymtabs_addrmap
3204     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3205 }
3206
3207 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3208    populate the objfile's psymtabs_addrmap.  */
3209
3210 static void
3211 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3212                              struct dwarf2_section_info *section)
3213 {
3214   struct objfile *objfile = dwarf2_per_objfile->objfile;
3215   bfd *abfd = objfile->obfd;
3216   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3217   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3218                                        SECT_OFF_TEXT (objfile));
3219
3220   auto_obstack temp_obstack;
3221   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3222
3223   std::unordered_map<sect_offset,
3224                      dwarf2_per_cu_data *,
3225                      gdb::hash_enum<sect_offset>>
3226     debug_info_offset_to_per_cu;
3227   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3228     {
3229       const auto insertpair
3230         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3231       if (!insertpair.second)
3232         {
3233           warning (_("Section .debug_aranges in %s has duplicate "
3234                      "debug_info_offset %s, ignoring .debug_aranges."),
3235                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3236           return;
3237         }
3238     }
3239
3240   dwarf2_read_section (objfile, section);
3241
3242   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3243
3244   const gdb_byte *addr = section->buffer;
3245
3246   while (addr < section->buffer + section->size)
3247     {
3248       const gdb_byte *const entry_addr = addr;
3249       unsigned int bytes_read;
3250
3251       const LONGEST entry_length = read_initial_length (abfd, addr,
3252                                                         &bytes_read);
3253       addr += bytes_read;
3254
3255       const gdb_byte *const entry_end = addr + entry_length;
3256       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3257       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3258       if (addr + entry_length > section->buffer + section->size)
3259         {
3260           warning (_("Section .debug_aranges in %s entry at offset %zu "
3261                      "length %s exceeds section length %s, "
3262                      "ignoring .debug_aranges."),
3263                    objfile_name (objfile), entry_addr - section->buffer,
3264                    plongest (bytes_read + entry_length),
3265                    pulongest (section->size));
3266           return;
3267         }
3268
3269       /* The version number.  */
3270       const uint16_t version = read_2_bytes (abfd, addr);
3271       addr += 2;
3272       if (version != 2)
3273         {
3274           warning (_("Section .debug_aranges in %s entry at offset %zu "
3275                      "has unsupported version %d, ignoring .debug_aranges."),
3276                    objfile_name (objfile), entry_addr - section->buffer,
3277                    version);
3278           return;
3279         }
3280
3281       const uint64_t debug_info_offset
3282         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3283       addr += offset_size;
3284       const auto per_cu_it
3285         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3286       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3287         {
3288           warning (_("Section .debug_aranges in %s entry at offset %zu "
3289                      "debug_info_offset %s does not exists, "
3290                      "ignoring .debug_aranges."),
3291                    objfile_name (objfile), entry_addr - section->buffer,
3292                    pulongest (debug_info_offset));
3293           return;
3294         }
3295       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3296
3297       const uint8_t address_size = *addr++;
3298       if (address_size < 1 || address_size > 8)
3299         {
3300           warning (_("Section .debug_aranges in %s entry at offset %zu "
3301                      "address_size %u is invalid, ignoring .debug_aranges."),
3302                    objfile_name (objfile), entry_addr - section->buffer,
3303                    address_size);
3304           return;
3305         }
3306
3307       const uint8_t segment_selector_size = *addr++;
3308       if (segment_selector_size != 0)
3309         {
3310           warning (_("Section .debug_aranges in %s entry at offset %zu "
3311                      "segment_selector_size %u is not supported, "
3312                      "ignoring .debug_aranges."),
3313                    objfile_name (objfile), entry_addr - section->buffer,
3314                    segment_selector_size);
3315           return;
3316         }
3317
3318       /* Must pad to an alignment boundary that is twice the address
3319          size.  It is undocumented by the DWARF standard but GCC does
3320          use it.  */
3321       for (size_t padding = ((-(addr - section->buffer))
3322                              & (2 * address_size - 1));
3323            padding > 0; padding--)
3324         if (*addr++ != 0)
3325           {
3326             warning (_("Section .debug_aranges in %s entry at offset %zu "
3327                        "padding is not zero, ignoring .debug_aranges."),
3328                      objfile_name (objfile), entry_addr - section->buffer);
3329             return;
3330           }
3331
3332       for (;;)
3333         {
3334           if (addr + 2 * address_size > entry_end)
3335             {
3336               warning (_("Section .debug_aranges in %s entry at offset %zu "
3337                          "address list is not properly terminated, "
3338                          "ignoring .debug_aranges."),
3339                        objfile_name (objfile), entry_addr - section->buffer);
3340               return;
3341             }
3342           ULONGEST start = extract_unsigned_integer (addr, address_size,
3343                                                      dwarf5_byte_order);
3344           addr += address_size;
3345           ULONGEST length = extract_unsigned_integer (addr, address_size,
3346                                                       dwarf5_byte_order);
3347           addr += address_size;
3348           if (start == 0 && length == 0)
3349             break;
3350           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3351             {
3352               /* Symbol was eliminated due to a COMDAT group.  */
3353               continue;
3354             }
3355           ULONGEST end = start + length;
3356           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3357                    - baseaddr);
3358           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3359                  - baseaddr);
3360           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3361         }
3362     }
3363
3364   objfile->partial_symtabs->psymtabs_addrmap
3365     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3366 }
3367
3368 /* Find a slot in the mapped index INDEX for the object named NAME.
3369    If NAME is found, set *VEC_OUT to point to the CU vector in the
3370    constant pool and return true.  If NAME cannot be found, return
3371    false.  */
3372
3373 static bool
3374 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3375                           offset_type **vec_out)
3376 {
3377   offset_type hash;
3378   offset_type slot, step;
3379   int (*cmp) (const char *, const char *);
3380
3381   gdb::unique_xmalloc_ptr<char> without_params;
3382   if (current_language->la_language == language_cplus
3383       || current_language->la_language == language_fortran
3384       || current_language->la_language == language_d)
3385     {
3386       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3387          not contain any.  */
3388
3389       if (strchr (name, '(') != NULL)
3390         {
3391           without_params = cp_remove_params (name);
3392
3393           if (without_params != NULL)
3394             name = without_params.get ();
3395         }
3396     }
3397
3398   /* Index version 4 did not support case insensitive searches.  But the
3399      indices for case insensitive languages are built in lowercase, therefore
3400      simulate our NAME being searched is also lowercased.  */
3401   hash = mapped_index_string_hash ((index->version == 4
3402                                     && case_sensitivity == case_sensitive_off
3403                                     ? 5 : index->version),
3404                                    name);
3405
3406   slot = hash & (index->symbol_table.size () - 1);
3407   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3408   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3409
3410   for (;;)
3411     {
3412       const char *str;
3413
3414       const auto &bucket = index->symbol_table[slot];
3415       if (bucket.name == 0 && bucket.vec == 0)
3416         return false;
3417
3418       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3419       if (!cmp (name, str))
3420         {
3421           *vec_out = (offset_type *) (index->constant_pool
3422                                       + MAYBE_SWAP (bucket.vec));
3423           return true;
3424         }
3425
3426       slot = (slot + step) & (index->symbol_table.size () - 1);
3427     }
3428 }
3429
3430 /* A helper function that reads the .gdb_index from BUFFER and fills
3431    in MAP.  FILENAME is the name of the file containing the data;
3432    it is used for error reporting.  DEPRECATED_OK is true if it is
3433    ok to use deprecated sections.
3434
3435    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3436    out parameters that are filled in with information about the CU and
3437    TU lists in the section.
3438
3439    Returns true if all went well, false otherwise.  */
3440
3441 static bool
3442 read_gdb_index_from_buffer (struct objfile *objfile,
3443                             const char *filename,
3444                             bool deprecated_ok,
3445                             gdb::array_view<const gdb_byte> buffer,
3446                             struct mapped_index *map,
3447                             const gdb_byte **cu_list,
3448                             offset_type *cu_list_elements,
3449                             const gdb_byte **types_list,
3450                             offset_type *types_list_elements)
3451 {
3452   const gdb_byte *addr = &buffer[0];
3453
3454   /* Version check.  */
3455   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3456   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3457      causes the index to behave very poorly for certain requests.  Version 3
3458      contained incomplete addrmap.  So, it seems better to just ignore such
3459      indices.  */
3460   if (version < 4)
3461     {
3462       static int warning_printed = 0;
3463       if (!warning_printed)
3464         {
3465           warning (_("Skipping obsolete .gdb_index section in %s."),
3466                    filename);
3467           warning_printed = 1;
3468         }
3469       return 0;
3470     }
3471   /* Index version 4 uses a different hash function than index version
3472      5 and later.
3473
3474      Versions earlier than 6 did not emit psymbols for inlined
3475      functions.  Using these files will cause GDB not to be able to
3476      set breakpoints on inlined functions by name, so we ignore these
3477      indices unless the user has done
3478      "set use-deprecated-index-sections on".  */
3479   if (version < 6 && !deprecated_ok)
3480     {
3481       static int warning_printed = 0;
3482       if (!warning_printed)
3483         {
3484           warning (_("\
3485 Skipping deprecated .gdb_index section in %s.\n\
3486 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3487 to use the section anyway."),
3488                    filename);
3489           warning_printed = 1;
3490         }
3491       return 0;
3492     }
3493   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3494      of the TU (for symbols coming from TUs),
3495      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3496      Plus gold-generated indices can have duplicate entries for global symbols,
3497      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3498      These are just performance bugs, and we can't distinguish gdb-generated
3499      indices from gold-generated ones, so issue no warning here.  */
3500
3501   /* Indexes with higher version than the one supported by GDB may be no
3502      longer backward compatible.  */
3503   if (version > 8)
3504     return 0;
3505
3506   map->version = version;
3507
3508   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3509
3510   int i = 0;
3511   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3512   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3513                        / 8);
3514   ++i;
3515
3516   *types_list = addr + MAYBE_SWAP (metadata[i]);
3517   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3518                            - MAYBE_SWAP (metadata[i]))
3519                           / 8);
3520   ++i;
3521
3522   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3523   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3524   map->address_table
3525     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3526   ++i;
3527
3528   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3529   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3530   map->symbol_table
3531     = gdb::array_view<mapped_index::symbol_table_slot>
3532        ((mapped_index::symbol_table_slot *) symbol_table,
3533         (mapped_index::symbol_table_slot *) symbol_table_end);
3534
3535   ++i;
3536   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3537
3538   return 1;
3539 }
3540
3541 /* Callback types for dwarf2_read_gdb_index.  */
3542
3543 typedef gdb::function_view
3544     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3545     get_gdb_index_contents_ftype;
3546 typedef gdb::function_view
3547     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3548     get_gdb_index_contents_dwz_ftype;
3549
3550 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3551    elements of all the CUs and return 1.  Otherwise, return 0.  */
3552
3553 static int
3554 dwarf2_read_gdb_index
3555   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3556    get_gdb_index_contents_ftype get_gdb_index_contents,
3557    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3558 {
3559   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3560   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3561   struct dwz_file *dwz;
3562   struct objfile *objfile = dwarf2_per_objfile->objfile;
3563
3564   gdb::array_view<const gdb_byte> main_index_contents
3565     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3566
3567   if (main_index_contents.empty ())
3568     return 0;
3569
3570   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3571   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3572                                    use_deprecated_index_sections,
3573                                    main_index_contents, map.get (), &cu_list,
3574                                    &cu_list_elements, &types_list,
3575                                    &types_list_elements))
3576     return 0;
3577
3578   /* Don't use the index if it's empty.  */
3579   if (map->symbol_table.empty ())
3580     return 0;
3581
3582   /* If there is a .dwz file, read it so we can get its CU list as
3583      well.  */
3584   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3585   if (dwz != NULL)
3586     {
3587       struct mapped_index dwz_map;
3588       const gdb_byte *dwz_types_ignore;
3589       offset_type dwz_types_elements_ignore;
3590
3591       gdb::array_view<const gdb_byte> dwz_index_content
3592         = get_gdb_index_contents_dwz (objfile, dwz);
3593
3594       if (dwz_index_content.empty ())
3595         return 0;
3596
3597       if (!read_gdb_index_from_buffer (objfile,
3598                                        bfd_get_filename (dwz->dwz_bfd), 1,
3599                                        dwz_index_content, &dwz_map,
3600                                        &dwz_list, &dwz_list_elements,
3601                                        &dwz_types_ignore,
3602                                        &dwz_types_elements_ignore))
3603         {
3604           warning (_("could not read '.gdb_index' section from %s; skipping"),
3605                    bfd_get_filename (dwz->dwz_bfd));
3606           return 0;
3607         }
3608     }
3609
3610   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3611                          dwz_list, dwz_list_elements);
3612
3613   if (types_list_elements)
3614     {
3615       struct dwarf2_section_info *section;
3616
3617       /* We can only handle a single .debug_types when we have an
3618          index.  */
3619       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3620         return 0;
3621
3622       section = VEC_index (dwarf2_section_info_def,
3623                            dwarf2_per_objfile->types, 0);
3624
3625       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3626                                                types_list, types_list_elements);
3627     }
3628
3629   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3630
3631   dwarf2_per_objfile->index_table = std::move (map);
3632   dwarf2_per_objfile->using_index = 1;
3633   dwarf2_per_objfile->quick_file_names_table =
3634     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3635
3636   return 1;
3637 }
3638
3639 /* die_reader_func for dw2_get_file_names.  */
3640
3641 static void
3642 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3643                            const gdb_byte *info_ptr,
3644                            struct die_info *comp_unit_die,
3645                            int has_children,
3646                            void *data)
3647 {
3648   struct dwarf2_cu *cu = reader->cu;
3649   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3650   struct dwarf2_per_objfile *dwarf2_per_objfile
3651     = cu->per_cu->dwarf2_per_objfile;
3652   struct objfile *objfile = dwarf2_per_objfile->objfile;
3653   struct dwarf2_per_cu_data *lh_cu;
3654   struct attribute *attr;
3655   int i;
3656   void **slot;
3657   struct quick_file_names *qfn;
3658
3659   gdb_assert (! this_cu->is_debug_types);
3660
3661   /* Our callers never want to match partial units -- instead they
3662      will match the enclosing full CU.  */
3663   if (comp_unit_die->tag == DW_TAG_partial_unit)
3664     {
3665       this_cu->v.quick->no_file_data = 1;
3666       return;
3667     }
3668
3669   lh_cu = this_cu;
3670   slot = NULL;
3671
3672   line_header_up lh;
3673   sect_offset line_offset {};
3674
3675   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3676   if (attr)
3677     {
3678       struct quick_file_names find_entry;
3679
3680       line_offset = (sect_offset) DW_UNSND (attr);
3681
3682       /* We may have already read in this line header (TU line header sharing).
3683          If we have we're done.  */
3684       find_entry.hash.dwo_unit = cu->dwo_unit;
3685       find_entry.hash.line_sect_off = line_offset;
3686       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3687                              &find_entry, INSERT);
3688       if (*slot != NULL)
3689         {
3690           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3691           return;
3692         }
3693
3694       lh = dwarf_decode_line_header (line_offset, cu);
3695     }
3696   if (lh == NULL)
3697     {
3698       lh_cu->v.quick->no_file_data = 1;
3699       return;
3700     }
3701
3702   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3703   qfn->hash.dwo_unit = cu->dwo_unit;
3704   qfn->hash.line_sect_off = line_offset;
3705   gdb_assert (slot != NULL);
3706   *slot = qfn;
3707
3708   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3709
3710   qfn->num_file_names = lh->file_names.size ();
3711   qfn->file_names =
3712     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3713   for (i = 0; i < lh->file_names.size (); ++i)
3714     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3715   qfn->real_names = NULL;
3716
3717   lh_cu->v.quick->file_names = qfn;
3718 }
3719
3720 /* A helper for the "quick" functions which attempts to read the line
3721    table for THIS_CU.  */
3722
3723 static struct quick_file_names *
3724 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3725 {
3726   /* This should never be called for TUs.  */
3727   gdb_assert (! this_cu->is_debug_types);
3728   /* Nor type unit groups.  */
3729   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3730
3731   if (this_cu->v.quick->file_names != NULL)
3732     return this_cu->v.quick->file_names;
3733   /* If we know there is no line data, no point in looking again.  */
3734   if (this_cu->v.quick->no_file_data)
3735     return NULL;
3736
3737   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3738
3739   if (this_cu->v.quick->no_file_data)
3740     return NULL;
3741   return this_cu->v.quick->file_names;
3742 }
3743
3744 /* A helper for the "quick" functions which computes and caches the
3745    real path for a given file name from the line table.  */
3746
3747 static const char *
3748 dw2_get_real_path (struct objfile *objfile,
3749                    struct quick_file_names *qfn, int index)
3750 {
3751   if (qfn->real_names == NULL)
3752     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3753                                       qfn->num_file_names, const char *);
3754
3755   if (qfn->real_names[index] == NULL)
3756     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3757
3758   return qfn->real_names[index];
3759 }
3760
3761 static struct symtab *
3762 dw2_find_last_source_symtab (struct objfile *objfile)
3763 {
3764   struct dwarf2_per_objfile *dwarf2_per_objfile
3765     = get_dwarf2_per_objfile (objfile);
3766   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3767   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3768
3769   if (cust == NULL)
3770     return NULL;
3771
3772   return compunit_primary_filetab (cust);
3773 }
3774
3775 /* Traversal function for dw2_forget_cached_source_info.  */
3776
3777 static int
3778 dw2_free_cached_file_names (void **slot, void *info)
3779 {
3780   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3781
3782   if (file_data->real_names)
3783     {
3784       int i;
3785
3786       for (i = 0; i < file_data->num_file_names; ++i)
3787         {
3788           xfree ((void*) file_data->real_names[i]);
3789           file_data->real_names[i] = NULL;
3790         }
3791     }
3792
3793   return 1;
3794 }
3795
3796 static void
3797 dw2_forget_cached_source_info (struct objfile *objfile)
3798 {
3799   struct dwarf2_per_objfile *dwarf2_per_objfile
3800     = get_dwarf2_per_objfile (objfile);
3801
3802   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3803                           dw2_free_cached_file_names, NULL);
3804 }
3805
3806 /* Helper function for dw2_map_symtabs_matching_filename that expands
3807    the symtabs and calls the iterator.  */
3808
3809 static int
3810 dw2_map_expand_apply (struct objfile *objfile,
3811                       struct dwarf2_per_cu_data *per_cu,
3812                       const char *name, const char *real_path,
3813                       gdb::function_view<bool (symtab *)> callback)
3814 {
3815   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3816
3817   /* Don't visit already-expanded CUs.  */
3818   if (per_cu->v.quick->compunit_symtab)
3819     return 0;
3820
3821   /* This may expand more than one symtab, and we want to iterate over
3822      all of them.  */
3823   dw2_instantiate_symtab (per_cu, false);
3824
3825   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3826                                     last_made, callback);
3827 }
3828
3829 /* Implementation of the map_symtabs_matching_filename method.  */
3830
3831 static bool
3832 dw2_map_symtabs_matching_filename
3833   (struct objfile *objfile, const char *name, const char *real_path,
3834    gdb::function_view<bool (symtab *)> callback)
3835 {
3836   const char *name_basename = lbasename (name);
3837   struct dwarf2_per_objfile *dwarf2_per_objfile
3838     = get_dwarf2_per_objfile (objfile);
3839
3840   /* The rule is CUs specify all the files, including those used by
3841      any TU, so there's no need to scan TUs here.  */
3842
3843   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3844     {
3845       /* We only need to look at symtabs not already expanded.  */
3846       if (per_cu->v.quick->compunit_symtab)
3847         continue;
3848
3849       quick_file_names *file_data = dw2_get_file_names (per_cu);
3850       if (file_data == NULL)
3851         continue;
3852
3853       for (int j = 0; j < file_data->num_file_names; ++j)
3854         {
3855           const char *this_name = file_data->file_names[j];
3856           const char *this_real_name;
3857
3858           if (compare_filenames_for_search (this_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           /* Before we invoke realpath, which can get expensive when many
3867              files are involved, do a quick comparison of the basenames.  */
3868           if (! basenames_may_differ
3869               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3870             continue;
3871
3872           this_real_name = dw2_get_real_path (objfile, file_data, j);
3873           if (compare_filenames_for_search (this_real_name, name))
3874             {
3875               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3876                                         callback))
3877                 return true;
3878               continue;
3879             }
3880
3881           if (real_path != NULL)
3882             {
3883               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3884               gdb_assert (IS_ABSOLUTE_PATH (name));
3885               if (this_real_name != NULL
3886                   && FILENAME_CMP (real_path, this_real_name) == 0)
3887                 {
3888                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3889                                             callback))
3890                     return true;
3891                   continue;
3892                 }
3893             }
3894         }
3895     }
3896
3897   return false;
3898 }
3899
3900 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3901
3902 struct dw2_symtab_iterator
3903 {
3904   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3905   struct dwarf2_per_objfile *dwarf2_per_objfile;
3906   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3907   int want_specific_block;
3908   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3909      Unused if !WANT_SPECIFIC_BLOCK.  */
3910   int block_index;
3911   /* The kind of symbol we're looking for.  */
3912   domain_enum domain;
3913   /* The list of CUs from the index entry of the symbol,
3914      or NULL if not found.  */
3915   offset_type *vec;
3916   /* The next element in VEC to look at.  */
3917   int next;
3918   /* The number of elements in VEC, or zero if there is no match.  */
3919   int length;
3920   /* Have we seen a global version of the symbol?
3921      If so we can ignore all further global instances.
3922      This is to work around gold/15646, inefficient gold-generated
3923      indices.  */
3924   int global_seen;
3925 };
3926
3927 /* Initialize the index symtab iterator ITER.
3928    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3929    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3930
3931 static void
3932 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3933                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3934                       int want_specific_block,
3935                       int block_index,
3936                       domain_enum domain,
3937                       const char *name)
3938 {
3939   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3940   iter->want_specific_block = want_specific_block;
3941   iter->block_index = block_index;
3942   iter->domain = domain;
3943   iter->next = 0;
3944   iter->global_seen = 0;
3945
3946   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3947
3948   /* index is NULL if OBJF_READNOW.  */
3949   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3950     iter->length = MAYBE_SWAP (*iter->vec);
3951   else
3952     {
3953       iter->vec = NULL;
3954       iter->length = 0;
3955     }
3956 }
3957
3958 /* Return the next matching CU or NULL if there are no more.  */
3959
3960 static struct dwarf2_per_cu_data *
3961 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3962 {
3963   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3964
3965   for ( ; iter->next < iter->length; ++iter->next)
3966     {
3967       offset_type cu_index_and_attrs =
3968         MAYBE_SWAP (iter->vec[iter->next + 1]);
3969       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3970       int want_static = iter->block_index != GLOBAL_BLOCK;
3971       /* This value is only valid for index versions >= 7.  */
3972       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3973       gdb_index_symbol_kind symbol_kind =
3974         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3975       /* Only check the symbol attributes if they're present.
3976          Indices prior to version 7 don't record them,
3977          and indices >= 7 may elide them for certain symbols
3978          (gold does this).  */
3979       int attrs_valid =
3980         (dwarf2_per_objfile->index_table->version >= 7
3981          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3982
3983       /* Don't crash on bad data.  */
3984       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3985                        + dwarf2_per_objfile->all_type_units.size ()))
3986         {
3987           complaint (_(".gdb_index entry has bad CU index"
3988                        " [in module %s]"),
3989                      objfile_name (dwarf2_per_objfile->objfile));
3990           continue;
3991         }
3992
3993       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3994
3995       /* Skip if already read in.  */
3996       if (per_cu->v.quick->compunit_symtab)
3997         continue;
3998
3999       /* Check static vs global.  */
4000       if (attrs_valid)
4001         {
4002           if (iter->want_specific_block
4003               && want_static != is_static)
4004             continue;
4005           /* Work around gold/15646.  */
4006           if (!is_static && iter->global_seen)
4007             continue;
4008           if (!is_static)
4009             iter->global_seen = 1;
4010         }
4011
4012       /* Only check the symbol's kind if it has one.  */
4013       if (attrs_valid)
4014         {
4015           switch (iter->domain)
4016             {
4017             case VAR_DOMAIN:
4018               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4019                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4020                   /* Some types are also in VAR_DOMAIN.  */
4021                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4022                 continue;
4023               break;
4024             case STRUCT_DOMAIN:
4025               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4026                 continue;
4027               break;
4028             case LABEL_DOMAIN:
4029               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4030                 continue;
4031               break;
4032             default:
4033               break;
4034             }
4035         }
4036
4037       ++iter->next;
4038       return per_cu;
4039     }
4040
4041   return NULL;
4042 }
4043
4044 static struct compunit_symtab *
4045 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4046                    const char *name, domain_enum domain)
4047 {
4048   struct compunit_symtab *stab_best = NULL;
4049   struct dwarf2_per_objfile *dwarf2_per_objfile
4050     = get_dwarf2_per_objfile (objfile);
4051
4052   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4053
4054   struct dw2_symtab_iterator iter;
4055   struct dwarf2_per_cu_data *per_cu;
4056
4057   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4058
4059   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4060     {
4061       struct symbol *sym, *with_opaque = NULL;
4062       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4063       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4064       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4065
4066       sym = block_find_symbol (block, name, domain,
4067                                block_find_non_opaque_type_preferred,
4068                                &with_opaque);
4069
4070       /* Some caution must be observed with overloaded functions
4071          and methods, since the index will not contain any overload
4072          information (but NAME might contain it).  */
4073
4074       if (sym != NULL
4075           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4076         return stab;
4077       if (with_opaque != NULL
4078           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4079         stab_best = stab;
4080
4081       /* Keep looking through other CUs.  */
4082     }
4083
4084   return stab_best;
4085 }
4086
4087 static void
4088 dw2_print_stats (struct objfile *objfile)
4089 {
4090   struct dwarf2_per_objfile *dwarf2_per_objfile
4091     = get_dwarf2_per_objfile (objfile);
4092   int total = (dwarf2_per_objfile->all_comp_units.size ()
4093                + dwarf2_per_objfile->all_type_units.size ());
4094   int count = 0;
4095
4096   for (int i = 0; i < total; ++i)
4097     {
4098       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4099
4100       if (!per_cu->v.quick->compunit_symtab)
4101         ++count;
4102     }
4103   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4104   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4105 }
4106
4107 /* This dumps minimal information about the index.
4108    It is called via "mt print objfiles".
4109    One use is to verify .gdb_index has been loaded by the
4110    gdb.dwarf2/gdb-index.exp testcase.  */
4111
4112 static void
4113 dw2_dump (struct objfile *objfile)
4114 {
4115   struct dwarf2_per_objfile *dwarf2_per_objfile
4116     = get_dwarf2_per_objfile (objfile);
4117
4118   gdb_assert (dwarf2_per_objfile->using_index);
4119   printf_filtered (".gdb_index:");
4120   if (dwarf2_per_objfile->index_table != NULL)
4121     {
4122       printf_filtered (" version %d\n",
4123                        dwarf2_per_objfile->index_table->version);
4124     }
4125   else
4126     printf_filtered (" faked for \"readnow\"\n");
4127   printf_filtered ("\n");
4128 }
4129
4130 static void
4131 dw2_expand_symtabs_for_function (struct objfile *objfile,
4132                                  const char *func_name)
4133 {
4134   struct dwarf2_per_objfile *dwarf2_per_objfile
4135     = get_dwarf2_per_objfile (objfile);
4136
4137   struct dw2_symtab_iterator iter;
4138   struct dwarf2_per_cu_data *per_cu;
4139
4140   /* Note: It doesn't matter what we pass for block_index here.  */
4141   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4142                         func_name);
4143
4144   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4145     dw2_instantiate_symtab (per_cu, false);
4146
4147 }
4148
4149 static void
4150 dw2_expand_all_symtabs (struct objfile *objfile)
4151 {
4152   struct dwarf2_per_objfile *dwarf2_per_objfile
4153     = get_dwarf2_per_objfile (objfile);
4154   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4155                      + dwarf2_per_objfile->all_type_units.size ());
4156
4157   for (int i = 0; i < total_units; ++i)
4158     {
4159       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4160
4161       /* We don't want to directly expand a partial CU, because if we
4162          read it with the wrong language, then assertion failures can
4163          be triggered later on.  See PR symtab/23010.  So, tell
4164          dw2_instantiate_symtab to skip partial CUs -- any important
4165          partial CU will be read via DW_TAG_imported_unit anyway.  */
4166       dw2_instantiate_symtab (per_cu, true);
4167     }
4168 }
4169
4170 static void
4171 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4172                                   const char *fullname)
4173 {
4174   struct dwarf2_per_objfile *dwarf2_per_objfile
4175     = get_dwarf2_per_objfile (objfile);
4176
4177   /* We don't need to consider type units here.
4178      This is only called for examining code, e.g. expand_line_sal.
4179      There can be an order of magnitude (or more) more type units
4180      than comp units, and we avoid them if we can.  */
4181
4182   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4183     {
4184       /* We only need to look at symtabs not already expanded.  */
4185       if (per_cu->v.quick->compunit_symtab)
4186         continue;
4187
4188       quick_file_names *file_data = dw2_get_file_names (per_cu);
4189       if (file_data == NULL)
4190         continue;
4191
4192       for (int j = 0; j < file_data->num_file_names; ++j)
4193         {
4194           const char *this_fullname = file_data->file_names[j];
4195
4196           if (filename_cmp (this_fullname, fullname) == 0)
4197             {
4198               dw2_instantiate_symtab (per_cu, false);
4199               break;
4200             }
4201         }
4202     }
4203 }
4204
4205 static void
4206 dw2_map_matching_symbols (struct objfile *objfile,
4207                           const char * name, domain_enum domain,
4208                           int global,
4209                           int (*callback) (const struct block *,
4210                                            struct symbol *, void *),
4211                           void *data, symbol_name_match_type match,
4212                           symbol_compare_ftype *ordered_compare)
4213 {
4214   /* Currently unimplemented; used for Ada.  The function can be called if the
4215      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4216      does not look for non-Ada symbols this function should just return.  */
4217 }
4218
4219 /* Symbol name matcher for .gdb_index names.
4220
4221    Symbol names in .gdb_index have a few particularities:
4222
4223    - There's no indication of which is the language of each symbol.
4224
4225      Since each language has its own symbol name matching algorithm,
4226      and we don't know which language is the right one, we must match
4227      each symbol against all languages.  This would be a potential
4228      performance problem if it were not mitigated by the
4229      mapped_index::name_components lookup table, which significantly
4230      reduces the number of times we need to call into this matcher,
4231      making it a non-issue.
4232
4233    - Symbol names in the index have no overload (parameter)
4234      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4235      appear as "foo" in the index, for example.
4236
4237      This means that the lookup names passed to the symbol name
4238      matcher functions must have no parameter information either
4239      because (e.g.) symbol search name "foo" does not match
4240      lookup-name "foo(int)" [while swapping search name for lookup
4241      name would match].
4242 */
4243 class gdb_index_symbol_name_matcher
4244 {
4245 public:
4246   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4247   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4248
4249   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4250      Returns true if any matcher matches.  */
4251   bool matches (const char *symbol_name);
4252
4253 private:
4254   /* A reference to the lookup name we're matching against.  */
4255   const lookup_name_info &m_lookup_name;
4256
4257   /* A vector holding all the different symbol name matchers, for all
4258      languages.  */
4259   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4260 };
4261
4262 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4263   (const lookup_name_info &lookup_name)
4264     : m_lookup_name (lookup_name)
4265 {
4266   /* Prepare the vector of comparison functions upfront, to avoid
4267      doing the same work for each symbol.  Care is taken to avoid
4268      matching with the same matcher more than once if/when multiple
4269      languages use the same matcher function.  */
4270   auto &matchers = m_symbol_name_matcher_funcs;
4271   matchers.reserve (nr_languages);
4272
4273   matchers.push_back (default_symbol_name_matcher);
4274
4275   for (int i = 0; i < nr_languages; i++)
4276     {
4277       const language_defn *lang = language_def ((enum language) i);
4278       symbol_name_matcher_ftype *name_matcher
4279         = get_symbol_name_matcher (lang, m_lookup_name);
4280
4281       /* Don't insert the same comparison routine more than once.
4282          Note that we do this linear walk instead of a seemingly
4283          cheaper sorted insert, or use a std::set or something like
4284          that, because relative order of function addresses is not
4285          stable.  This is not a problem in practice because the number
4286          of supported languages is low, and the cost here is tiny
4287          compared to the number of searches we'll do afterwards using
4288          this object.  */
4289       if (name_matcher != default_symbol_name_matcher
4290           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4291               == matchers.end ()))
4292         matchers.push_back (name_matcher);
4293     }
4294 }
4295
4296 bool
4297 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4298 {
4299   for (auto matches_name : m_symbol_name_matcher_funcs)
4300     if (matches_name (symbol_name, m_lookup_name, NULL))
4301       return true;
4302
4303   return false;
4304 }
4305
4306 /* Starting from a search name, return the string that finds the upper
4307    bound of all strings that start with SEARCH_NAME in a sorted name
4308    list.  Returns the empty string to indicate that the upper bound is
4309    the end of the list.  */
4310
4311 static std::string
4312 make_sort_after_prefix_name (const char *search_name)
4313 {
4314   /* When looking to complete "func", we find the upper bound of all
4315      symbols that start with "func" by looking for where we'd insert
4316      the closest string that would follow "func" in lexicographical
4317      order.  Usually, that's "func"-with-last-character-incremented,
4318      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4319      will be UTF-8 multi-byte sequences, but we can't be certain.
4320      Especially mind the 0xff character, which is a valid character in
4321      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4322      rule out compilers allowing it in identifiers.  Note that
4323      conveniently, strcmp/strcasecmp are specified to compare
4324      characters interpreted as unsigned char.  So what we do is treat
4325      the whole string as a base 256 number composed of a sequence of
4326      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4327      to 0, and carries 1 to the following more-significant position.
4328      If the very first character in SEARCH_NAME ends up incremented
4329      and carries/overflows, then the upper bound is the end of the
4330      list.  The string after the empty string is also the empty
4331      string.
4332
4333      Some examples of this operation:
4334
4335        SEARCH_NAME  => "+1" RESULT
4336
4337        "abc"              => "abd"
4338        "ab\xff"           => "ac"
4339        "\xff" "a" "\xff"  => "\xff" "b"
4340        "\xff"             => ""
4341        "\xff\xff"         => ""
4342        ""                 => ""
4343
4344      Then, with these symbols for example:
4345
4346       func
4347       func1
4348       fund
4349
4350      completing "func" looks for symbols between "func" and
4351      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4352      which finds "func" and "func1", but not "fund".
4353
4354      And with:
4355
4356       funcÿ     (Latin1 'ÿ' [0xff])
4357       funcÿ1
4358       fund
4359
4360      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4361      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4362
4363      And with:
4364
4365       ÿÿ        (Latin1 'ÿ' [0xff])
4366       ÿÿ1
4367
4368      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4369      the end of the list.
4370   */
4371   std::string after = search_name;
4372   while (!after.empty () && (unsigned char) after.back () == 0xff)
4373     after.pop_back ();
4374   if (!after.empty ())
4375     after.back () = (unsigned char) after.back () + 1;
4376   return after;
4377 }
4378
4379 /* See declaration.  */
4380
4381 std::pair<std::vector<name_component>::const_iterator,
4382           std::vector<name_component>::const_iterator>
4383 mapped_index_base::find_name_components_bounds
4384   (const lookup_name_info &lookup_name_without_params) const
4385 {
4386   auto *name_cmp
4387     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4388
4389   const char *cplus
4390     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4391
4392   /* Comparison function object for lower_bound that matches against a
4393      given symbol name.  */
4394   auto lookup_compare_lower = [&] (const name_component &elem,
4395                                    const char *name)
4396     {
4397       const char *elem_qualified = this->symbol_name_at (elem.idx);
4398       const char *elem_name = elem_qualified + elem.name_offset;
4399       return name_cmp (elem_name, name) < 0;
4400     };
4401
4402   /* Comparison function object for upper_bound that matches against a
4403      given symbol name.  */
4404   auto lookup_compare_upper = [&] (const char *name,
4405                                    const name_component &elem)
4406     {
4407       const char *elem_qualified = this->symbol_name_at (elem.idx);
4408       const char *elem_name = elem_qualified + elem.name_offset;
4409       return name_cmp (name, elem_name) < 0;
4410     };
4411
4412   auto begin = this->name_components.begin ();
4413   auto end = this->name_components.end ();
4414
4415   /* Find the lower bound.  */
4416   auto lower = [&] ()
4417     {
4418       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4419         return begin;
4420       else
4421         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4422     } ();
4423
4424   /* Find the upper bound.  */
4425   auto upper = [&] ()
4426     {
4427       if (lookup_name_without_params.completion_mode ())
4428         {
4429           /* In completion mode, we want UPPER to point past all
4430              symbols names that have the same prefix.  I.e., with
4431              these symbols, and completing "func":
4432
4433               function        << lower bound
4434               function1
4435               other_function  << upper bound
4436
4437              We find the upper bound by looking for the insertion
4438              point of "func"-with-last-character-incremented,
4439              i.e. "fund".  */
4440           std::string after = make_sort_after_prefix_name (cplus);
4441           if (after.empty ())
4442             return end;
4443           return std::lower_bound (lower, end, after.c_str (),
4444                                    lookup_compare_lower);
4445         }
4446       else
4447         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4448     } ();
4449
4450   return {lower, upper};
4451 }
4452
4453 /* See declaration.  */
4454
4455 void
4456 mapped_index_base::build_name_components ()
4457 {
4458   if (!this->name_components.empty ())
4459     return;
4460
4461   this->name_components_casing = case_sensitivity;
4462   auto *name_cmp
4463     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4464
4465   /* The code below only knows how to break apart components of C++
4466      symbol names (and other languages that use '::' as
4467      namespace/module separator).  If we add support for wild matching
4468      to some language that uses some other operator (E.g., Ada, Go and
4469      D use '.'), then we'll need to try splitting the symbol name
4470      according to that language too.  Note that Ada does support wild
4471      matching, but doesn't currently support .gdb_index.  */
4472   auto count = this->symbol_name_count ();
4473   for (offset_type idx = 0; idx < count; idx++)
4474     {
4475       if (this->symbol_name_slot_invalid (idx))
4476         continue;
4477
4478       const char *name = this->symbol_name_at (idx);
4479
4480       /* Add each name component to the name component table.  */
4481       unsigned int previous_len = 0;
4482       for (unsigned int current_len = cp_find_first_component (name);
4483            name[current_len] != '\0';
4484            current_len += cp_find_first_component (name + current_len))
4485         {
4486           gdb_assert (name[current_len] == ':');
4487           this->name_components.push_back ({previous_len, idx});
4488           /* Skip the '::'.  */
4489           current_len += 2;
4490           previous_len = current_len;
4491         }
4492       this->name_components.push_back ({previous_len, idx});
4493     }
4494
4495   /* Sort name_components elements by name.  */
4496   auto name_comp_compare = [&] (const name_component &left,
4497                                 const name_component &right)
4498     {
4499       const char *left_qualified = this->symbol_name_at (left.idx);
4500       const char *right_qualified = this->symbol_name_at (right.idx);
4501
4502       const char *left_name = left_qualified + left.name_offset;
4503       const char *right_name = right_qualified + right.name_offset;
4504
4505       return name_cmp (left_name, right_name) < 0;
4506     };
4507
4508   std::sort (this->name_components.begin (),
4509              this->name_components.end (),
4510              name_comp_compare);
4511 }
4512
4513 /* Helper for dw2_expand_symtabs_matching that works with a
4514    mapped_index_base instead of the containing objfile.  This is split
4515    to a separate function in order to be able to unit test the
4516    name_components matching using a mock mapped_index_base.  For each
4517    symbol name that matches, calls MATCH_CALLBACK, passing it the
4518    symbol's index in the mapped_index_base symbol table.  */
4519
4520 static void
4521 dw2_expand_symtabs_matching_symbol
4522   (mapped_index_base &index,
4523    const lookup_name_info &lookup_name_in,
4524    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4525    enum search_domain kind,
4526    gdb::function_view<void (offset_type)> match_callback)
4527 {
4528   lookup_name_info lookup_name_without_params
4529     = lookup_name_in.make_ignore_params ();
4530   gdb_index_symbol_name_matcher lookup_name_matcher
4531     (lookup_name_without_params);
4532
4533   /* Build the symbol name component sorted vector, if we haven't
4534      yet.  */
4535   index.build_name_components ();
4536
4537   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4538
4539   /* Now for each symbol name in range, check to see if we have a name
4540      match, and if so, call the MATCH_CALLBACK callback.  */
4541
4542   /* The same symbol may appear more than once in the range though.
4543      E.g., if we're looking for symbols that complete "w", and we have
4544      a symbol named "w1::w2", we'll find the two name components for
4545      that same symbol in the range.  To be sure we only call the
4546      callback once per symbol, we first collect the symbol name
4547      indexes that matched in a temporary vector and ignore
4548      duplicates.  */
4549   std::vector<offset_type> matches;
4550   matches.reserve (std::distance (bounds.first, bounds.second));
4551
4552   for (; bounds.first != bounds.second; ++bounds.first)
4553     {
4554       const char *qualified = index.symbol_name_at (bounds.first->idx);
4555
4556       if (!lookup_name_matcher.matches (qualified)
4557           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4558         continue;
4559
4560       matches.push_back (bounds.first->idx);
4561     }
4562
4563   std::sort (matches.begin (), matches.end ());
4564
4565   /* Finally call the callback, once per match.  */
4566   ULONGEST prev = -1;
4567   for (offset_type idx : matches)
4568     {
4569       if (prev != idx)
4570         {
4571           match_callback (idx);
4572           prev = idx;
4573         }
4574     }
4575
4576   /* Above we use a type wider than idx's for 'prev', since 0 and
4577      (offset_type)-1 are both possible values.  */
4578   static_assert (sizeof (prev) > sizeof (offset_type), "");
4579 }
4580
4581 #if GDB_SELF_TEST
4582
4583 namespace selftests { namespace dw2_expand_symtabs_matching {
4584
4585 /* A mock .gdb_index/.debug_names-like name index table, enough to
4586    exercise dw2_expand_symtabs_matching_symbol, which works with the
4587    mapped_index_base interface.  Builds an index from the symbol list
4588    passed as parameter to the constructor.  */
4589 class mock_mapped_index : public mapped_index_base
4590 {
4591 public:
4592   mock_mapped_index (gdb::array_view<const char *> symbols)
4593     : m_symbol_table (symbols)
4594   {}
4595
4596   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4597
4598   /* Return the number of names in the symbol table.  */
4599   size_t symbol_name_count () const override
4600   {
4601     return m_symbol_table.size ();
4602   }
4603
4604   /* Get the name of the symbol at IDX in the symbol table.  */
4605   const char *symbol_name_at (offset_type idx) const override
4606   {
4607     return m_symbol_table[idx];
4608   }
4609
4610 private:
4611   gdb::array_view<const char *> m_symbol_table;
4612 };
4613
4614 /* Convenience function that converts a NULL pointer to a "<null>"
4615    string, to pass to print routines.  */
4616
4617 static const char *
4618 string_or_null (const char *str)
4619 {
4620   return str != NULL ? str : "<null>";
4621 }
4622
4623 /* Check if a lookup_name_info built from
4624    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4625    index.  EXPECTED_LIST is the list of expected matches, in expected
4626    matching order.  If no match expected, then an empty list is
4627    specified.  Returns true on success.  On failure prints a warning
4628    indicating the file:line that failed, and returns false.  */
4629
4630 static bool
4631 check_match (const char *file, int line,
4632              mock_mapped_index &mock_index,
4633              const char *name, symbol_name_match_type match_type,
4634              bool completion_mode,
4635              std::initializer_list<const char *> expected_list)
4636 {
4637   lookup_name_info lookup_name (name, match_type, completion_mode);
4638
4639   bool matched = true;
4640
4641   auto mismatch = [&] (const char *expected_str,
4642                        const char *got)
4643   {
4644     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4645                "expected=\"%s\", got=\"%s\"\n"),
4646              file, line,
4647              (match_type == symbol_name_match_type::FULL
4648               ? "FULL" : "WILD"),
4649              name, string_or_null (expected_str), string_or_null (got));
4650     matched = false;
4651   };
4652
4653   auto expected_it = expected_list.begin ();
4654   auto expected_end = expected_list.end ();
4655
4656   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4657                                       NULL, ALL_DOMAIN,
4658                                       [&] (offset_type idx)
4659   {
4660     const char *matched_name = mock_index.symbol_name_at (idx);
4661     const char *expected_str
4662       = expected_it == expected_end ? NULL : *expected_it++;
4663
4664     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4665       mismatch (expected_str, matched_name);
4666   });
4667
4668   const char *expected_str
4669   = expected_it == expected_end ? NULL : *expected_it++;
4670   if (expected_str != NULL)
4671     mismatch (expected_str, NULL);
4672
4673   return matched;
4674 }
4675
4676 /* The symbols added to the mock mapped_index for testing (in
4677    canonical form).  */
4678 static const char *test_symbols[] = {
4679   "function",
4680   "std::bar",
4681   "std::zfunction",
4682   "std::zfunction2",
4683   "w1::w2",
4684   "ns::foo<char*>",
4685   "ns::foo<int>",
4686   "ns::foo<long>",
4687   "ns2::tmpl<int>::foo2",
4688   "(anonymous namespace)::A::B::C",
4689
4690   /* These are used to check that the increment-last-char in the
4691      matching algorithm for completion doesn't match "t1_fund" when
4692      completing "t1_func".  */
4693   "t1_func",
4694   "t1_func1",
4695   "t1_fund",
4696   "t1_fund1",
4697
4698   /* A UTF-8 name with multi-byte sequences to make sure that
4699      cp-name-parser understands this as a single identifier ("função"
4700      is "function" in PT).  */
4701   u8"u8função",
4702
4703   /* \377 (0xff) is Latin1 'ÿ'.  */
4704   "yfunc\377",
4705
4706   /* \377 (0xff) is Latin1 'ÿ'.  */
4707   "\377",
4708   "\377\377123",
4709
4710   /* A name with all sorts of complications.  Starts with "z" to make
4711      it easier for the completion tests below.  */
4712 #define Z_SYM_NAME \
4713   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4714     "::tuple<(anonymous namespace)::ui*, " \
4715     "std::default_delete<(anonymous namespace)::ui>, void>"
4716
4717   Z_SYM_NAME
4718 };
4719
4720 /* Returns true if the mapped_index_base::find_name_component_bounds
4721    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4722    in completion mode.  */
4723
4724 static bool
4725 check_find_bounds_finds (mapped_index_base &index,
4726                          const char *search_name,
4727                          gdb::array_view<const char *> expected_syms)
4728 {
4729   lookup_name_info lookup_name (search_name,
4730                                 symbol_name_match_type::FULL, true);
4731
4732   auto bounds = index.find_name_components_bounds (lookup_name);
4733
4734   size_t distance = std::distance (bounds.first, bounds.second);
4735   if (distance != expected_syms.size ())
4736     return false;
4737
4738   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4739     {
4740       auto nc_elem = bounds.first + exp_elem;
4741       const char *qualified = index.symbol_name_at (nc_elem->idx);
4742       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4743         return false;
4744     }
4745
4746   return true;
4747 }
4748
4749 /* Test the lower-level mapped_index::find_name_component_bounds
4750    method.  */
4751
4752 static void
4753 test_mapped_index_find_name_component_bounds ()
4754 {
4755   mock_mapped_index mock_index (test_symbols);
4756
4757   mock_index.build_name_components ();
4758
4759   /* Test the lower-level mapped_index::find_name_component_bounds
4760      method in completion mode.  */
4761   {
4762     static const char *expected_syms[] = {
4763       "t1_func",
4764       "t1_func1",
4765     };
4766
4767     SELF_CHECK (check_find_bounds_finds (mock_index,
4768                                          "t1_func", expected_syms));
4769   }
4770
4771   /* Check that the increment-last-char in the name matching algorithm
4772      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4773   {
4774     static const char *expected_syms1[] = {
4775       "\377",
4776       "\377\377123",
4777     };
4778     SELF_CHECK (check_find_bounds_finds (mock_index,
4779                                          "\377", expected_syms1));
4780
4781     static const char *expected_syms2[] = {
4782       "\377\377123",
4783     };
4784     SELF_CHECK (check_find_bounds_finds (mock_index,
4785                                          "\377\377", expected_syms2));
4786   }
4787 }
4788
4789 /* Test dw2_expand_symtabs_matching_symbol.  */
4790
4791 static void
4792 test_dw2_expand_symtabs_matching_symbol ()
4793 {
4794   mock_mapped_index mock_index (test_symbols);
4795
4796   /* We let all tests run until the end even if some fails, for debug
4797      convenience.  */
4798   bool any_mismatch = false;
4799
4800   /* Create the expected symbols list (an initializer_list).  Needed
4801      because lists have commas, and we need to pass them to CHECK,
4802      which is a macro.  */
4803 #define EXPECT(...) { __VA_ARGS__ }
4804
4805   /* Wrapper for check_match that passes down the current
4806      __FILE__/__LINE__.  */
4807 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4808   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4809                                 mock_index,                             \
4810                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4811                                 EXPECTED_LIST)
4812
4813   /* Identity checks.  */
4814   for (const char *sym : test_symbols)
4815     {
4816       /* Should be able to match all existing symbols.  */
4817       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4818                    EXPECT (sym));
4819
4820       /* Should be able to match all existing symbols with
4821          parameters.  */
4822       std::string with_params = std::string (sym) + "(int)";
4823       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4824                    EXPECT (sym));
4825
4826       /* Should be able to match all existing symbols with
4827          parameters and qualifiers.  */
4828       with_params = std::string (sym) + " ( int ) const";
4829       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4830                    EXPECT (sym));
4831
4832       /* This should really find sym, but cp-name-parser.y doesn't
4833          know about lvalue/rvalue qualifiers yet.  */
4834       with_params = std::string (sym) + " ( int ) &&";
4835       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4836                    {});
4837     }
4838
4839   /* Check that the name matching algorithm for completion doesn't get
4840      confused with Latin1 'ÿ' / 0xff.  */
4841   {
4842     static const char str[] = "\377";
4843     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4844                  EXPECT ("\377", "\377\377123"));
4845   }
4846
4847   /* Check that the increment-last-char in the matching algorithm for
4848      completion doesn't match "t1_fund" when completing "t1_func".  */
4849   {
4850     static const char str[] = "t1_func";
4851     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4852                  EXPECT ("t1_func", "t1_func1"));
4853   }
4854
4855   /* Check that completion mode works at each prefix of the expected
4856      symbol name.  */
4857   {
4858     static const char str[] = "function(int)";
4859     size_t len = strlen (str);
4860     std::string lookup;
4861
4862     for (size_t i = 1; i < len; i++)
4863       {
4864         lookup.assign (str, i);
4865         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4866                      EXPECT ("function"));
4867       }
4868   }
4869
4870   /* While "w" is a prefix of both components, the match function
4871      should still only be called once.  */
4872   {
4873     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4874                  EXPECT ("w1::w2"));
4875     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4876                  EXPECT ("w1::w2"));
4877   }
4878
4879   /* Same, with a "complicated" symbol.  */
4880   {
4881     static const char str[] = Z_SYM_NAME;
4882     size_t len = strlen (str);
4883     std::string lookup;
4884
4885     for (size_t i = 1; i < len; i++)
4886       {
4887         lookup.assign (str, i);
4888         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4889                      EXPECT (Z_SYM_NAME));
4890       }
4891   }
4892
4893   /* In FULL mode, an incomplete symbol doesn't match.  */
4894   {
4895     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4896                  {});
4897   }
4898
4899   /* A complete symbol with parameters matches any overload, since the
4900      index has no overload info.  */
4901   {
4902     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4903                  EXPECT ("std::zfunction", "std::zfunction2"));
4904     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4905                  EXPECT ("std::zfunction", "std::zfunction2"));
4906     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4907                  EXPECT ("std::zfunction", "std::zfunction2"));
4908   }
4909
4910   /* Check that whitespace is ignored appropriately.  A symbol with a
4911      template argument list. */
4912   {
4913     static const char expected[] = "ns::foo<int>";
4914     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4915                  EXPECT (expected));
4916     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4917                  EXPECT (expected));
4918   }
4919
4920   /* Check that whitespace is ignored appropriately.  A symbol with a
4921      template argument list that includes a pointer.  */
4922   {
4923     static const char expected[] = "ns::foo<char*>";
4924     /* Try both completion and non-completion modes.  */
4925     static const bool completion_mode[2] = {false, true};
4926     for (size_t i = 0; i < 2; i++)
4927       {
4928         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4929                      completion_mode[i], EXPECT (expected));
4930         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4931                      completion_mode[i], EXPECT (expected));
4932
4933         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4934                      completion_mode[i], EXPECT (expected));
4935         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4936                      completion_mode[i], EXPECT (expected));
4937       }
4938   }
4939
4940   {
4941     /* Check method qualifiers are ignored.  */
4942     static const char expected[] = "ns::foo<char*>";
4943     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4944                  symbol_name_match_type::FULL, true, EXPECT (expected));
4945     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4946                  symbol_name_match_type::FULL, true, EXPECT (expected));
4947     CHECK_MATCH ("foo < char * >  ( int ) const",
4948                  symbol_name_match_type::WILD, true, EXPECT (expected));
4949     CHECK_MATCH ("foo < char * >  ( int ) &&",
4950                  symbol_name_match_type::WILD, true, EXPECT (expected));
4951   }
4952
4953   /* Test lookup names that don't match anything.  */
4954   {
4955     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4956                  {});
4957
4958     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4959                  {});
4960   }
4961
4962   /* Some wild matching tests, exercising "(anonymous namespace)",
4963      which should not be confused with a parameter list.  */
4964   {
4965     static const char *syms[] = {
4966       "A::B::C",
4967       "B::C",
4968       "C",
4969       "A :: B :: C ( int )",
4970       "B :: C ( int )",
4971       "C ( int )",
4972     };
4973
4974     for (const char *s : syms)
4975       {
4976         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4977                      EXPECT ("(anonymous namespace)::A::B::C"));
4978       }
4979   }
4980
4981   {
4982     static const char expected[] = "ns2::tmpl<int>::foo2";
4983     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4984                  EXPECT (expected));
4985     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4986                  EXPECT (expected));
4987   }
4988
4989   SELF_CHECK (!any_mismatch);
4990
4991 #undef EXPECT
4992 #undef CHECK_MATCH
4993 }
4994
4995 static void
4996 run_test ()
4997 {
4998   test_mapped_index_find_name_component_bounds ();
4999   test_dw2_expand_symtabs_matching_symbol ();
5000 }
5001
5002 }} // namespace selftests::dw2_expand_symtabs_matching
5003
5004 #endif /* GDB_SELF_TEST */
5005
5006 /* If FILE_MATCHER is NULL or if PER_CU has
5007    dwarf2_per_cu_quick_data::MARK set (see
5008    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5009    EXPANSION_NOTIFY on it.  */
5010
5011 static void
5012 dw2_expand_symtabs_matching_one
5013   (struct dwarf2_per_cu_data *per_cu,
5014    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5015    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5016 {
5017   if (file_matcher == NULL || per_cu->v.quick->mark)
5018     {
5019       bool symtab_was_null
5020         = (per_cu->v.quick->compunit_symtab == NULL);
5021
5022       dw2_instantiate_symtab (per_cu, false);
5023
5024       if (expansion_notify != NULL
5025           && symtab_was_null
5026           && per_cu->v.quick->compunit_symtab != NULL)
5027         expansion_notify (per_cu->v.quick->compunit_symtab);
5028     }
5029 }
5030
5031 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5032    matched, to expand corresponding CUs that were marked.  IDX is the
5033    index of the symbol name that matched.  */
5034
5035 static void
5036 dw2_expand_marked_cus
5037   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5038    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5039    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5040    search_domain kind)
5041 {
5042   offset_type *vec, vec_len, vec_idx;
5043   bool global_seen = false;
5044   mapped_index &index = *dwarf2_per_objfile->index_table;
5045
5046   vec = (offset_type *) (index.constant_pool
5047                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5048   vec_len = MAYBE_SWAP (vec[0]);
5049   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5050     {
5051       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5052       /* This value is only valid for index versions >= 7.  */
5053       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5054       gdb_index_symbol_kind symbol_kind =
5055         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5056       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5057       /* Only check the symbol attributes if they're present.
5058          Indices prior to version 7 don't record them,
5059          and indices >= 7 may elide them for certain symbols
5060          (gold does this).  */
5061       int attrs_valid =
5062         (index.version >= 7
5063          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5064
5065       /* Work around gold/15646.  */
5066       if (attrs_valid)
5067         {
5068           if (!is_static && global_seen)
5069             continue;
5070           if (!is_static)
5071             global_seen = true;
5072         }
5073
5074       /* Only check the symbol's kind if it has one.  */
5075       if (attrs_valid)
5076         {
5077           switch (kind)
5078             {
5079             case VARIABLES_DOMAIN:
5080               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5081                 continue;
5082               break;
5083             case FUNCTIONS_DOMAIN:
5084               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5085                 continue;
5086               break;
5087             case TYPES_DOMAIN:
5088               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5089                 continue;
5090               break;
5091             default:
5092               break;
5093             }
5094         }
5095
5096       /* Don't crash on bad data.  */
5097       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5098                        + dwarf2_per_objfile->all_type_units.size ()))
5099         {
5100           complaint (_(".gdb_index entry has bad CU index"
5101                        " [in module %s]"),
5102                        objfile_name (dwarf2_per_objfile->objfile));
5103           continue;
5104         }
5105
5106       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5107       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5108                                        expansion_notify);
5109     }
5110 }
5111
5112 /* If FILE_MATCHER is non-NULL, set all the
5113    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5114    that match FILE_MATCHER.  */
5115
5116 static void
5117 dw_expand_symtabs_matching_file_matcher
5118   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5119    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5120 {
5121   if (file_matcher == NULL)
5122     return;
5123
5124   objfile *const objfile = dwarf2_per_objfile->objfile;
5125
5126   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5127                                             htab_eq_pointer,
5128                                             NULL, xcalloc, xfree));
5129   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5130                                                 htab_eq_pointer,
5131                                                 NULL, xcalloc, xfree));
5132
5133   /* The rule is CUs specify all the files, including those used by
5134      any TU, so there's no need to scan TUs here.  */
5135
5136   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5137     {
5138       QUIT;
5139
5140       per_cu->v.quick->mark = 0;
5141
5142       /* We only need to look at symtabs not already expanded.  */
5143       if (per_cu->v.quick->compunit_symtab)
5144         continue;
5145
5146       quick_file_names *file_data = dw2_get_file_names (per_cu);
5147       if (file_data == NULL)
5148         continue;
5149
5150       if (htab_find (visited_not_found.get (), file_data) != NULL)
5151         continue;
5152       else if (htab_find (visited_found.get (), file_data) != NULL)
5153         {
5154           per_cu->v.quick->mark = 1;
5155           continue;
5156         }
5157
5158       for (int j = 0; j < file_data->num_file_names; ++j)
5159         {
5160           const char *this_real_name;
5161
5162           if (file_matcher (file_data->file_names[j], false))
5163             {
5164               per_cu->v.quick->mark = 1;
5165               break;
5166             }
5167
5168           /* Before we invoke realpath, which can get expensive when many
5169              files are involved, do a quick comparison of the basenames.  */
5170           if (!basenames_may_differ
5171               && !file_matcher (lbasename (file_data->file_names[j]),
5172                                 true))
5173             continue;
5174
5175           this_real_name = dw2_get_real_path (objfile, file_data, j);
5176           if (file_matcher (this_real_name, false))
5177             {
5178               per_cu->v.quick->mark = 1;
5179               break;
5180             }
5181         }
5182
5183       void **slot = htab_find_slot (per_cu->v.quick->mark
5184                                     ? visited_found.get ()
5185                                     : visited_not_found.get (),
5186                                     file_data, INSERT);
5187       *slot = file_data;
5188     }
5189 }
5190
5191 static void
5192 dw2_expand_symtabs_matching
5193   (struct objfile *objfile,
5194    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5195    const lookup_name_info &lookup_name,
5196    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5197    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5198    enum search_domain kind)
5199 {
5200   struct dwarf2_per_objfile *dwarf2_per_objfile
5201     = get_dwarf2_per_objfile (objfile);
5202
5203   /* index_table is NULL if OBJF_READNOW.  */
5204   if (!dwarf2_per_objfile->index_table)
5205     return;
5206
5207   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5208
5209   mapped_index &index = *dwarf2_per_objfile->index_table;
5210
5211   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5212                                       symbol_matcher,
5213                                       kind, [&] (offset_type idx)
5214     {
5215       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5216                              expansion_notify, kind);
5217     });
5218 }
5219
5220 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5221    symtab.  */
5222
5223 static struct compunit_symtab *
5224 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5225                                           CORE_ADDR pc)
5226 {
5227   int i;
5228
5229   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5230       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5231     return cust;
5232
5233   if (cust->includes == NULL)
5234     return NULL;
5235
5236   for (i = 0; cust->includes[i]; ++i)
5237     {
5238       struct compunit_symtab *s = cust->includes[i];
5239
5240       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5241       if (s != NULL)
5242         return s;
5243     }
5244
5245   return NULL;
5246 }
5247
5248 static struct compunit_symtab *
5249 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5250                                   struct bound_minimal_symbol msymbol,
5251                                   CORE_ADDR pc,
5252                                   struct obj_section *section,
5253                                   int warn_if_readin)
5254 {
5255   struct dwarf2_per_cu_data *data;
5256   struct compunit_symtab *result;
5257
5258   if (!objfile->partial_symtabs->psymtabs_addrmap)
5259     return NULL;
5260
5261   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5262                                  SECT_OFF_TEXT (objfile));
5263   data = (struct dwarf2_per_cu_data *) addrmap_find
5264     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
5265   if (!data)
5266     return NULL;
5267
5268   if (warn_if_readin && data->v.quick->compunit_symtab)
5269     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5270              paddress (get_objfile_arch (objfile), pc));
5271
5272   result
5273     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5274                                                                         false),
5275                                                 pc);
5276   gdb_assert (result != NULL);
5277   return result;
5278 }
5279
5280 static void
5281 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5282                           void *data, int need_fullname)
5283 {
5284   struct dwarf2_per_objfile *dwarf2_per_objfile
5285     = get_dwarf2_per_objfile (objfile);
5286
5287   if (!dwarf2_per_objfile->filenames_cache)
5288     {
5289       dwarf2_per_objfile->filenames_cache.emplace ();
5290
5291       htab_up visited (htab_create_alloc (10,
5292                                           htab_hash_pointer, htab_eq_pointer,
5293                                           NULL, xcalloc, xfree));
5294
5295       /* The rule is CUs specify all the files, including those used
5296          by any TU, so there's no need to scan TUs here.  We can
5297          ignore file names coming from already-expanded CUs.  */
5298
5299       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5300         {
5301           if (per_cu->v.quick->compunit_symtab)
5302             {
5303               void **slot = htab_find_slot (visited.get (),
5304                                             per_cu->v.quick->file_names,
5305                                             INSERT);
5306
5307               *slot = per_cu->v.quick->file_names;
5308             }
5309         }
5310
5311       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5312         {
5313           /* We only need to look at symtabs not already expanded.  */
5314           if (per_cu->v.quick->compunit_symtab)
5315             continue;
5316
5317           quick_file_names *file_data = dw2_get_file_names (per_cu);
5318           if (file_data == NULL)
5319             continue;
5320
5321           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5322           if (*slot)
5323             {
5324               /* Already visited.  */
5325               continue;
5326             }
5327           *slot = file_data;
5328
5329           for (int j = 0; j < file_data->num_file_names; ++j)
5330             {
5331               const char *filename = file_data->file_names[j];
5332               dwarf2_per_objfile->filenames_cache->seen (filename);
5333             }
5334         }
5335     }
5336
5337   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5338     {
5339       gdb::unique_xmalloc_ptr<char> this_real_name;
5340
5341       if (need_fullname)
5342         this_real_name = gdb_realpath (filename);
5343       (*fun) (filename, this_real_name.get (), data);
5344     });
5345 }
5346
5347 static int
5348 dw2_has_symbols (struct objfile *objfile)
5349 {
5350   return 1;
5351 }
5352
5353 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5354 {
5355   dw2_has_symbols,
5356   dw2_find_last_source_symtab,
5357   dw2_forget_cached_source_info,
5358   dw2_map_symtabs_matching_filename,
5359   dw2_lookup_symbol,
5360   dw2_print_stats,
5361   dw2_dump,
5362   dw2_expand_symtabs_for_function,
5363   dw2_expand_all_symtabs,
5364   dw2_expand_symtabs_with_fullname,
5365   dw2_map_matching_symbols,
5366   dw2_expand_symtabs_matching,
5367   dw2_find_pc_sect_compunit_symtab,
5368   NULL,
5369   dw2_map_symbol_filenames
5370 };
5371
5372 /* DWARF-5 debug_names reader.  */
5373
5374 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5375 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5376
5377 /* A helper function that reads the .debug_names section in SECTION
5378    and fills in MAP.  FILENAME is the name of the file containing the
5379    section; it is used for error reporting.
5380
5381    Returns true if all went well, false otherwise.  */
5382
5383 static bool
5384 read_debug_names_from_section (struct objfile *objfile,
5385                                const char *filename,
5386                                struct dwarf2_section_info *section,
5387                                mapped_debug_names &map)
5388 {
5389   if (dwarf2_section_empty_p (section))
5390     return false;
5391
5392   /* Older elfutils strip versions could keep the section in the main
5393      executable while splitting it for the separate debug info file.  */
5394   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5395     return false;
5396
5397   dwarf2_read_section (objfile, section);
5398
5399   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5400
5401   const gdb_byte *addr = section->buffer;
5402
5403   bfd *const abfd = get_section_bfd_owner (section);
5404
5405   unsigned int bytes_read;
5406   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5407   addr += bytes_read;
5408
5409   map.dwarf5_is_dwarf64 = bytes_read != 4;
5410   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5411   if (bytes_read + length != section->size)
5412     {
5413       /* There may be multiple per-CU indices.  */
5414       warning (_("Section .debug_names in %s length %s does not match "
5415                  "section length %s, ignoring .debug_names."),
5416                filename, plongest (bytes_read + length),
5417                pulongest (section->size));
5418       return false;
5419     }
5420
5421   /* The version number.  */
5422   uint16_t version = read_2_bytes (abfd, addr);
5423   addr += 2;
5424   if (version != 5)
5425     {
5426       warning (_("Section .debug_names in %s has unsupported version %d, "
5427                  "ignoring .debug_names."),
5428                filename, version);
5429       return false;
5430     }
5431
5432   /* Padding.  */
5433   uint16_t padding = read_2_bytes (abfd, addr);
5434   addr += 2;
5435   if (padding != 0)
5436     {
5437       warning (_("Section .debug_names in %s has unsupported padding %d, "
5438                  "ignoring .debug_names."),
5439                filename, padding);
5440       return false;
5441     }
5442
5443   /* comp_unit_count - The number of CUs in the CU list.  */
5444   map.cu_count = read_4_bytes (abfd, addr);
5445   addr += 4;
5446
5447   /* local_type_unit_count - The number of TUs in the local TU
5448      list.  */
5449   map.tu_count = read_4_bytes (abfd, addr);
5450   addr += 4;
5451
5452   /* foreign_type_unit_count - The number of TUs in the foreign TU
5453      list.  */
5454   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5455   addr += 4;
5456   if (foreign_tu_count != 0)
5457     {
5458       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5459                  "ignoring .debug_names."),
5460                filename, static_cast<unsigned long> (foreign_tu_count));
5461       return false;
5462     }
5463
5464   /* bucket_count - The number of hash buckets in the hash lookup
5465      table.  */
5466   map.bucket_count = read_4_bytes (abfd, addr);
5467   addr += 4;
5468
5469   /* name_count - The number of unique names in the index.  */
5470   map.name_count = read_4_bytes (abfd, addr);
5471   addr += 4;
5472
5473   /* abbrev_table_size - The size in bytes of the abbreviations
5474      table.  */
5475   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5476   addr += 4;
5477
5478   /* augmentation_string_size - The size in bytes of the augmentation
5479      string.  This value is rounded up to a multiple of 4.  */
5480   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5481   addr += 4;
5482   map.augmentation_is_gdb = ((augmentation_string_size
5483                               == sizeof (dwarf5_augmentation))
5484                              && memcmp (addr, dwarf5_augmentation,
5485                                         sizeof (dwarf5_augmentation)) == 0);
5486   augmentation_string_size += (-augmentation_string_size) & 3;
5487   addr += augmentation_string_size;
5488
5489   /* List of CUs */
5490   map.cu_table_reordered = addr;
5491   addr += map.cu_count * map.offset_size;
5492
5493   /* List of Local TUs */
5494   map.tu_table_reordered = addr;
5495   addr += map.tu_count * map.offset_size;
5496
5497   /* Hash Lookup Table */
5498   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5499   addr += map.bucket_count * 4;
5500   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5501   addr += map.name_count * 4;
5502
5503   /* Name Table */
5504   map.name_table_string_offs_reordered = addr;
5505   addr += map.name_count * map.offset_size;
5506   map.name_table_entry_offs_reordered = addr;
5507   addr += map.name_count * map.offset_size;
5508
5509   const gdb_byte *abbrev_table_start = addr;
5510   for (;;)
5511     {
5512       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5513       addr += bytes_read;
5514       if (index_num == 0)
5515         break;
5516
5517       const auto insertpair
5518         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5519       if (!insertpair.second)
5520         {
5521           warning (_("Section .debug_names in %s has duplicate index %s, "
5522                      "ignoring .debug_names."),
5523                    filename, pulongest (index_num));
5524           return false;
5525         }
5526       mapped_debug_names::index_val &indexval = insertpair.first->second;
5527       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5528       addr += bytes_read;
5529
5530       for (;;)
5531         {
5532           mapped_debug_names::index_val::attr attr;
5533           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5534           addr += bytes_read;
5535           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5536           addr += bytes_read;
5537           if (attr.form == DW_FORM_implicit_const)
5538             {
5539               attr.implicit_const = read_signed_leb128 (abfd, addr,
5540                                                         &bytes_read);
5541               addr += bytes_read;
5542             }
5543           if (attr.dw_idx == 0 && attr.form == 0)
5544             break;
5545           indexval.attr_vec.push_back (std::move (attr));
5546         }
5547     }
5548   if (addr != abbrev_table_start + abbrev_table_size)
5549     {
5550       warning (_("Section .debug_names in %s has abbreviation_table "
5551                  "of size %zu vs. written as %u, ignoring .debug_names."),
5552                filename, addr - abbrev_table_start, abbrev_table_size);
5553       return false;
5554     }
5555   map.entry_pool = addr;
5556
5557   return true;
5558 }
5559
5560 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5561    list.  */
5562
5563 static void
5564 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5565                                   const mapped_debug_names &map,
5566                                   dwarf2_section_info &section,
5567                                   bool is_dwz)
5568 {
5569   sect_offset sect_off_prev;
5570   for (uint32_t i = 0; i <= map.cu_count; ++i)
5571     {
5572       sect_offset sect_off_next;
5573       if (i < map.cu_count)
5574         {
5575           sect_off_next
5576             = (sect_offset) (extract_unsigned_integer
5577                              (map.cu_table_reordered + i * map.offset_size,
5578                               map.offset_size,
5579                               map.dwarf5_byte_order));
5580         }
5581       else
5582         sect_off_next = (sect_offset) section.size;
5583       if (i >= 1)
5584         {
5585           const ULONGEST length = sect_off_next - sect_off_prev;
5586           dwarf2_per_cu_data *per_cu
5587             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5588                                          sect_off_prev, length);
5589           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5590         }
5591       sect_off_prev = sect_off_next;
5592     }
5593 }
5594
5595 /* Read the CU list from the mapped index, and use it to create all
5596    the CU objects for this dwarf2_per_objfile.  */
5597
5598 static void
5599 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5600                              const mapped_debug_names &map,
5601                              const mapped_debug_names &dwz_map)
5602 {
5603   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5604   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5605
5606   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5607                                     dwarf2_per_objfile->info,
5608                                     false /* is_dwz */);
5609
5610   if (dwz_map.cu_count == 0)
5611     return;
5612
5613   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5614   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5615                                     true /* is_dwz */);
5616 }
5617
5618 /* Read .debug_names.  If everything went ok, initialize the "quick"
5619    elements of all the CUs and return true.  Otherwise, return false.  */
5620
5621 static bool
5622 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5623 {
5624   std::unique_ptr<mapped_debug_names> map
5625     (new mapped_debug_names (dwarf2_per_objfile));
5626   mapped_debug_names dwz_map (dwarf2_per_objfile);
5627   struct objfile *objfile = dwarf2_per_objfile->objfile;
5628
5629   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5630                                       &dwarf2_per_objfile->debug_names,
5631                                       *map))
5632     return false;
5633
5634   /* Don't use the index if it's empty.  */
5635   if (map->name_count == 0)
5636     return false;
5637
5638   /* If there is a .dwz file, read it so we can get its CU list as
5639      well.  */
5640   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5641   if (dwz != NULL)
5642     {
5643       if (!read_debug_names_from_section (objfile,
5644                                           bfd_get_filename (dwz->dwz_bfd),
5645                                           &dwz->debug_names, dwz_map))
5646         {
5647           warning (_("could not read '.debug_names' section from %s; skipping"),
5648                    bfd_get_filename (dwz->dwz_bfd));
5649           return false;
5650         }
5651     }
5652
5653   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5654
5655   if (map->tu_count != 0)
5656     {
5657       /* We can only handle a single .debug_types when we have an
5658          index.  */
5659       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5660         return false;
5661
5662       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5663                                                 dwarf2_per_objfile->types, 0);
5664
5665       create_signatured_type_table_from_debug_names
5666         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5667     }
5668
5669   create_addrmap_from_aranges (dwarf2_per_objfile,
5670                                &dwarf2_per_objfile->debug_aranges);
5671
5672   dwarf2_per_objfile->debug_names_table = std::move (map);
5673   dwarf2_per_objfile->using_index = 1;
5674   dwarf2_per_objfile->quick_file_names_table =
5675     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5676
5677   return true;
5678 }
5679
5680 /* Type used to manage iterating over all CUs looking for a symbol for
5681    .debug_names.  */
5682
5683 class dw2_debug_names_iterator
5684 {
5685 public:
5686   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5687      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5688   dw2_debug_names_iterator (const mapped_debug_names &map,
5689                             bool want_specific_block,
5690                             block_enum block_index, domain_enum domain,
5691                             const char *name)
5692     : m_map (map), m_want_specific_block (want_specific_block),
5693       m_block_index (block_index), m_domain (domain),
5694       m_addr (find_vec_in_debug_names (map, name))
5695   {}
5696
5697   dw2_debug_names_iterator (const mapped_debug_names &map,
5698                             search_domain search, uint32_t namei)
5699     : m_map (map),
5700       m_search (search),
5701       m_addr (find_vec_in_debug_names (map, namei))
5702   {}
5703
5704   /* Return the next matching CU or NULL if there are no more.  */
5705   dwarf2_per_cu_data *next ();
5706
5707 private:
5708   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5709                                                   const char *name);
5710   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5711                                                   uint32_t namei);
5712
5713   /* The internalized form of .debug_names.  */
5714   const mapped_debug_names &m_map;
5715
5716   /* If true, only look for symbols that match BLOCK_INDEX.  */
5717   const bool m_want_specific_block = false;
5718
5719   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5720      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5721      value.  */
5722   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5723
5724   /* The kind of symbol we're looking for.  */
5725   const domain_enum m_domain = UNDEF_DOMAIN;
5726   const search_domain m_search = ALL_DOMAIN;
5727
5728   /* The list of CUs from the index entry of the symbol, or NULL if
5729      not found.  */
5730   const gdb_byte *m_addr;
5731 };
5732
5733 const char *
5734 mapped_debug_names::namei_to_name (uint32_t namei) const
5735 {
5736   const ULONGEST namei_string_offs
5737     = extract_unsigned_integer ((name_table_string_offs_reordered
5738                                  + namei * offset_size),
5739                                 offset_size,
5740                                 dwarf5_byte_order);
5741   return read_indirect_string_at_offset
5742     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5743 }
5744
5745 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5746    found, return pointer to its pool data.  If NAME cannot be found,
5747    return NULL.  */
5748
5749 const gdb_byte *
5750 dw2_debug_names_iterator::find_vec_in_debug_names
5751   (const mapped_debug_names &map, const char *name)
5752 {
5753   int (*cmp) (const char *, const char *);
5754
5755   if (current_language->la_language == language_cplus
5756       || current_language->la_language == language_fortran
5757       || current_language->la_language == language_d)
5758     {
5759       /* NAME is already canonical.  Drop any qualifiers as
5760          .debug_names does not contain any.  */
5761
5762       if (strchr (name, '(') != NULL)
5763         {
5764           gdb::unique_xmalloc_ptr<char> without_params
5765             = cp_remove_params (name);
5766
5767           if (without_params != NULL)
5768             {
5769               name = without_params.get();
5770             }
5771         }
5772     }
5773
5774   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5775
5776   const uint32_t full_hash = dwarf5_djb_hash (name);
5777   uint32_t namei
5778     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5779                                 (map.bucket_table_reordered
5780                                  + (full_hash % map.bucket_count)), 4,
5781                                 map.dwarf5_byte_order);
5782   if (namei == 0)
5783     return NULL;
5784   --namei;
5785   if (namei >= map.name_count)
5786     {
5787       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5788                    "[in module %s]"),
5789                  namei, map.name_count,
5790                  objfile_name (map.dwarf2_per_objfile->objfile));
5791       return NULL;
5792     }
5793
5794   for (;;)
5795     {
5796       const uint32_t namei_full_hash
5797         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5798                                     (map.hash_table_reordered + namei), 4,
5799                                     map.dwarf5_byte_order);
5800       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5801         return NULL;
5802
5803       if (full_hash == namei_full_hash)
5804         {
5805           const char *const namei_string = map.namei_to_name (namei);
5806
5807 #if 0 /* An expensive sanity check.  */
5808           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5809             {
5810               complaint (_("Wrong .debug_names hash for string at index %u "
5811                            "[in module %s]"),
5812                          namei, objfile_name (dwarf2_per_objfile->objfile));
5813               return NULL;
5814             }
5815 #endif
5816
5817           if (cmp (namei_string, name) == 0)
5818             {
5819               const ULONGEST namei_entry_offs
5820                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5821                                              + namei * map.offset_size),
5822                                             map.offset_size, map.dwarf5_byte_order);
5823               return map.entry_pool + namei_entry_offs;
5824             }
5825         }
5826
5827       ++namei;
5828       if (namei >= map.name_count)
5829         return NULL;
5830     }
5831 }
5832
5833 const gdb_byte *
5834 dw2_debug_names_iterator::find_vec_in_debug_names
5835   (const mapped_debug_names &map, uint32_t namei)
5836 {
5837   if (namei >= map.name_count)
5838     {
5839       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5840                    "[in module %s]"),
5841                  namei, map.name_count,
5842                  objfile_name (map.dwarf2_per_objfile->objfile));
5843       return NULL;
5844     }
5845
5846   const ULONGEST namei_entry_offs
5847     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5848                                  + namei * map.offset_size),
5849                                 map.offset_size, map.dwarf5_byte_order);
5850   return map.entry_pool + namei_entry_offs;
5851 }
5852
5853 /* See dw2_debug_names_iterator.  */
5854
5855 dwarf2_per_cu_data *
5856 dw2_debug_names_iterator::next ()
5857 {
5858   if (m_addr == NULL)
5859     return NULL;
5860
5861   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5862   struct objfile *objfile = dwarf2_per_objfile->objfile;
5863   bfd *const abfd = objfile->obfd;
5864
5865  again:
5866
5867   unsigned int bytes_read;
5868   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5869   m_addr += bytes_read;
5870   if (abbrev == 0)
5871     return NULL;
5872
5873   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5874   if (indexval_it == m_map.abbrev_map.cend ())
5875     {
5876       complaint (_("Wrong .debug_names undefined abbrev code %s "
5877                    "[in module %s]"),
5878                  pulongest (abbrev), objfile_name (objfile));
5879       return NULL;
5880     }
5881   const mapped_debug_names::index_val &indexval = indexval_it->second;
5882   bool have_is_static = false;
5883   bool is_static;
5884   dwarf2_per_cu_data *per_cu = NULL;
5885   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5886     {
5887       ULONGEST ull;
5888       switch (attr.form)
5889         {
5890         case DW_FORM_implicit_const:
5891           ull = attr.implicit_const;
5892           break;
5893         case DW_FORM_flag_present:
5894           ull = 1;
5895           break;
5896         case DW_FORM_udata:
5897           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5898           m_addr += bytes_read;
5899           break;
5900         default:
5901           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5902                      dwarf_form_name (attr.form),
5903                      objfile_name (objfile));
5904           return NULL;
5905         }
5906       switch (attr.dw_idx)
5907         {
5908         case DW_IDX_compile_unit:
5909           /* Don't crash on bad data.  */
5910           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5911             {
5912               complaint (_(".debug_names entry has bad CU index %s"
5913                            " [in module %s]"),
5914                          pulongest (ull),
5915                          objfile_name (dwarf2_per_objfile->objfile));
5916               continue;
5917             }
5918           per_cu = dwarf2_per_objfile->get_cutu (ull);
5919           break;
5920         case DW_IDX_type_unit:
5921           /* Don't crash on bad data.  */
5922           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5923             {
5924               complaint (_(".debug_names entry has bad TU index %s"
5925                            " [in module %s]"),
5926                          pulongest (ull),
5927                          objfile_name (dwarf2_per_objfile->objfile));
5928               continue;
5929             }
5930           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5931           break;
5932         case DW_IDX_GNU_internal:
5933           if (!m_map.augmentation_is_gdb)
5934             break;
5935           have_is_static = true;
5936           is_static = true;
5937           break;
5938         case DW_IDX_GNU_external:
5939           if (!m_map.augmentation_is_gdb)
5940             break;
5941           have_is_static = true;
5942           is_static = false;
5943           break;
5944         }
5945     }
5946
5947   /* Skip if already read in.  */
5948   if (per_cu->v.quick->compunit_symtab)
5949     goto again;
5950
5951   /* Check static vs global.  */
5952   if (have_is_static)
5953     {
5954       const bool want_static = m_block_index != GLOBAL_BLOCK;
5955       if (m_want_specific_block && want_static != is_static)
5956         goto again;
5957     }
5958
5959   /* Match dw2_symtab_iter_next, symbol_kind
5960      and debug_names::psymbol_tag.  */
5961   switch (m_domain)
5962     {
5963     case VAR_DOMAIN:
5964       switch (indexval.dwarf_tag)
5965         {
5966         case DW_TAG_variable:
5967         case DW_TAG_subprogram:
5968         /* Some types are also in VAR_DOMAIN.  */
5969         case DW_TAG_typedef:
5970         case DW_TAG_structure_type:
5971           break;
5972         default:
5973           goto again;
5974         }
5975       break;
5976     case STRUCT_DOMAIN:
5977       switch (indexval.dwarf_tag)
5978         {
5979         case DW_TAG_typedef:
5980         case DW_TAG_structure_type:
5981           break;
5982         default:
5983           goto again;
5984         }
5985       break;
5986     case LABEL_DOMAIN:
5987       switch (indexval.dwarf_tag)
5988         {
5989         case 0:
5990         case DW_TAG_variable:
5991           break;
5992         default:
5993           goto again;
5994         }
5995       break;
5996     default:
5997       break;
5998     }
5999
6000   /* Match dw2_expand_symtabs_matching, symbol_kind and
6001      debug_names::psymbol_tag.  */
6002   switch (m_search)
6003     {
6004     case VARIABLES_DOMAIN:
6005       switch (indexval.dwarf_tag)
6006         {
6007         case DW_TAG_variable:
6008           break;
6009         default:
6010           goto again;
6011         }
6012       break;
6013     case FUNCTIONS_DOMAIN:
6014       switch (indexval.dwarf_tag)
6015         {
6016         case DW_TAG_subprogram:
6017           break;
6018         default:
6019           goto again;
6020         }
6021       break;
6022     case TYPES_DOMAIN:
6023       switch (indexval.dwarf_tag)
6024         {
6025         case DW_TAG_typedef:
6026         case DW_TAG_structure_type:
6027           break;
6028         default:
6029           goto again;
6030         }
6031       break;
6032     default:
6033       break;
6034     }
6035
6036   return per_cu;
6037 }
6038
6039 static struct compunit_symtab *
6040 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6041                                const char *name, domain_enum domain)
6042 {
6043   const block_enum block_index = static_cast<block_enum> (block_index_int);
6044   struct dwarf2_per_objfile *dwarf2_per_objfile
6045     = get_dwarf2_per_objfile (objfile);
6046
6047   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6048   if (!mapp)
6049     {
6050       /* index is NULL if OBJF_READNOW.  */
6051       return NULL;
6052     }
6053   const auto &map = *mapp;
6054
6055   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6056                                  block_index, domain, name);
6057
6058   struct compunit_symtab *stab_best = NULL;
6059   struct dwarf2_per_cu_data *per_cu;
6060   while ((per_cu = iter.next ()) != NULL)
6061     {
6062       struct symbol *sym, *with_opaque = NULL;
6063       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6064       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6065       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6066
6067       sym = block_find_symbol (block, name, domain,
6068                                block_find_non_opaque_type_preferred,
6069                                &with_opaque);
6070
6071       /* Some caution must be observed with overloaded functions and
6072          methods, since the index will not contain any overload
6073          information (but NAME might contain it).  */
6074
6075       if (sym != NULL
6076           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6077         return stab;
6078       if (with_opaque != NULL
6079           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6080         stab_best = stab;
6081
6082       /* Keep looking through other CUs.  */
6083     }
6084
6085   return stab_best;
6086 }
6087
6088 /* This dumps minimal information about .debug_names.  It is called
6089    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6090    uses this to verify that .debug_names has been loaded.  */
6091
6092 static void
6093 dw2_debug_names_dump (struct objfile *objfile)
6094 {
6095   struct dwarf2_per_objfile *dwarf2_per_objfile
6096     = get_dwarf2_per_objfile (objfile);
6097
6098   gdb_assert (dwarf2_per_objfile->using_index);
6099   printf_filtered (".debug_names:");
6100   if (dwarf2_per_objfile->debug_names_table)
6101     printf_filtered (" exists\n");
6102   else
6103     printf_filtered (" faked for \"readnow\"\n");
6104   printf_filtered ("\n");
6105 }
6106
6107 static void
6108 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6109                                              const char *func_name)
6110 {
6111   struct dwarf2_per_objfile *dwarf2_per_objfile
6112     = get_dwarf2_per_objfile (objfile);
6113
6114   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6115   if (dwarf2_per_objfile->debug_names_table)
6116     {
6117       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6118
6119       /* Note: It doesn't matter what we pass for block_index here.  */
6120       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6121                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6122
6123       struct dwarf2_per_cu_data *per_cu;
6124       while ((per_cu = iter.next ()) != NULL)
6125         dw2_instantiate_symtab (per_cu, false);
6126     }
6127 }
6128
6129 static void
6130 dw2_debug_names_expand_symtabs_matching
6131   (struct objfile *objfile,
6132    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6133    const lookup_name_info &lookup_name,
6134    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6135    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6136    enum search_domain kind)
6137 {
6138   struct dwarf2_per_objfile *dwarf2_per_objfile
6139     = get_dwarf2_per_objfile (objfile);
6140
6141   /* debug_names_table is NULL if OBJF_READNOW.  */
6142   if (!dwarf2_per_objfile->debug_names_table)
6143     return;
6144
6145   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6146
6147   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6148
6149   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6150                                       symbol_matcher,
6151                                       kind, [&] (offset_type namei)
6152     {
6153       /* The name was matched, now expand corresponding CUs that were
6154          marked.  */
6155       dw2_debug_names_iterator iter (map, kind, namei);
6156
6157       struct dwarf2_per_cu_data *per_cu;
6158       while ((per_cu = iter.next ()) != NULL)
6159         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6160                                          expansion_notify);
6161     });
6162 }
6163
6164 const struct quick_symbol_functions dwarf2_debug_names_functions =
6165 {
6166   dw2_has_symbols,
6167   dw2_find_last_source_symtab,
6168   dw2_forget_cached_source_info,
6169   dw2_map_symtabs_matching_filename,
6170   dw2_debug_names_lookup_symbol,
6171   dw2_print_stats,
6172   dw2_debug_names_dump,
6173   dw2_debug_names_expand_symtabs_for_function,
6174   dw2_expand_all_symtabs,
6175   dw2_expand_symtabs_with_fullname,
6176   dw2_map_matching_symbols,
6177   dw2_debug_names_expand_symtabs_matching,
6178   dw2_find_pc_sect_compunit_symtab,
6179   NULL,
6180   dw2_map_symbol_filenames
6181 };
6182
6183 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
6184    to either a dwarf2_per_objfile or dwz_file object.  */
6185
6186 template <typename T>
6187 static gdb::array_view<const gdb_byte>
6188 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
6189 {
6190   dwarf2_section_info *section = &section_owner->gdb_index;
6191
6192   if (dwarf2_section_empty_p (section))
6193     return {};
6194
6195   /* Older elfutils strip versions could keep the section in the main
6196      executable while splitting it for the separate debug info file.  */
6197   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
6198     return {};
6199
6200   dwarf2_read_section (obj, section);
6201
6202   /* dwarf2_section_info::size is a bfd_size_type, while
6203      gdb::array_view works with size_t.  On 32-bit hosts, with
6204      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
6205      is 32-bit.  So we need an explicit narrowing conversion here.
6206      This is fine, because it's impossible to allocate or mmap an
6207      array/buffer larger than what size_t can represent.  */
6208   return gdb::make_array_view (section->buffer, section->size);
6209 }
6210
6211 /* Lookup the index cache for the contents of the index associated to
6212    DWARF2_OBJ.  */
6213
6214 static gdb::array_view<const gdb_byte>
6215 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
6216 {
6217   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
6218   if (build_id == nullptr)
6219     return {};
6220
6221   return global_index_cache.lookup_gdb_index (build_id,
6222                                               &dwarf2_obj->index_cache_res);
6223 }
6224
6225 /* Same as the above, but for DWZ.  */
6226
6227 static gdb::array_view<const gdb_byte>
6228 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
6229 {
6230   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
6231   if (build_id == nullptr)
6232     return {};
6233
6234   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
6235 }
6236
6237 /* See symfile.h.  */
6238
6239 bool
6240 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6241 {
6242   struct dwarf2_per_objfile *dwarf2_per_objfile
6243     = get_dwarf2_per_objfile (objfile);
6244
6245   /* If we're about to read full symbols, don't bother with the
6246      indices.  In this case we also don't care if some other debug
6247      format is making psymtabs, because they are all about to be
6248      expanded anyway.  */
6249   if ((objfile->flags & OBJF_READNOW))
6250     {
6251       dwarf2_per_objfile->using_index = 1;
6252       create_all_comp_units (dwarf2_per_objfile);
6253       create_all_type_units (dwarf2_per_objfile);
6254       dwarf2_per_objfile->quick_file_names_table
6255         = create_quick_file_names_table
6256             (dwarf2_per_objfile->all_comp_units.size ());
6257
6258       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6259                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6260         {
6261           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6262
6263           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6264                                             struct dwarf2_per_cu_quick_data);
6265         }
6266
6267       /* Return 1 so that gdb sees the "quick" functions.  However,
6268          these functions will be no-ops because we will have expanded
6269          all symtabs.  */
6270       *index_kind = dw_index_kind::GDB_INDEX;
6271       return true;
6272     }
6273
6274   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6275     {
6276       *index_kind = dw_index_kind::DEBUG_NAMES;
6277       return true;
6278     }
6279
6280   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6281                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6282                              get_gdb_index_contents_from_section<dwz_file>))
6283     {
6284       *index_kind = dw_index_kind::GDB_INDEX;
6285       return true;
6286     }
6287
6288   /* ... otherwise, try to find the index in the index cache.  */
6289   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6290                              get_gdb_index_contents_from_cache,
6291                              get_gdb_index_contents_from_cache_dwz))
6292     {
6293       global_index_cache.hit ();
6294       *index_kind = dw_index_kind::GDB_INDEX;
6295       return true;
6296     }
6297
6298   global_index_cache.miss ();
6299   return false;
6300 }
6301
6302 \f
6303
6304 /* Build a partial symbol table.  */
6305
6306 void
6307 dwarf2_build_psymtabs (struct objfile *objfile)
6308 {
6309   struct dwarf2_per_objfile *dwarf2_per_objfile
6310     = get_dwarf2_per_objfile (objfile);
6311
6312   init_psymbol_list (objfile, 1024);
6313
6314   try
6315     {
6316       /* This isn't really ideal: all the data we allocate on the
6317          objfile's obstack is still uselessly kept around.  However,
6318          freeing it seems unsafe.  */
6319       psymtab_discarder psymtabs (objfile);
6320       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6321       psymtabs.keep ();
6322
6323       /* (maybe) store an index in the cache.  */
6324       global_index_cache.store (dwarf2_per_objfile);
6325     }
6326   catch (const gdb_exception_error &except)
6327     {
6328       exception_print (gdb_stderr, except);
6329     }
6330 }
6331
6332 /* Return the total length of the CU described by HEADER.  */
6333
6334 static unsigned int
6335 get_cu_length (const struct comp_unit_head *header)
6336 {
6337   return header->initial_length_size + header->length;
6338 }
6339
6340 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6341
6342 static inline bool
6343 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6344 {
6345   sect_offset bottom = cu_header->sect_off;
6346   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6347
6348   return sect_off >= bottom && sect_off < top;
6349 }
6350
6351 /* Find the base address of the compilation unit for range lists and
6352    location lists.  It will normally be specified by DW_AT_low_pc.
6353    In DWARF-3 draft 4, the base address could be overridden by
6354    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6355    compilation units with discontinuous ranges.  */
6356
6357 static void
6358 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6359 {
6360   struct attribute *attr;
6361
6362   cu->base_known = 0;
6363   cu->base_address = 0;
6364
6365   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6366   if (attr)
6367     {
6368       cu->base_address = attr_value_as_address (attr);
6369       cu->base_known = 1;
6370     }
6371   else
6372     {
6373       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6374       if (attr)
6375         {
6376           cu->base_address = attr_value_as_address (attr);
6377           cu->base_known = 1;
6378         }
6379     }
6380 }
6381
6382 /* Read in the comp unit header information from the debug_info at info_ptr.
6383    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6384    NOTE: This leaves members offset, first_die_offset to be filled in
6385    by the caller.  */
6386
6387 static const gdb_byte *
6388 read_comp_unit_head (struct comp_unit_head *cu_header,
6389                      const gdb_byte *info_ptr,
6390                      struct dwarf2_section_info *section,
6391                      rcuh_kind section_kind)
6392 {
6393   int signed_addr;
6394   unsigned int bytes_read;
6395   const char *filename = get_section_file_name (section);
6396   bfd *abfd = get_section_bfd_owner (section);
6397
6398   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6399   cu_header->initial_length_size = bytes_read;
6400   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6401   info_ptr += bytes_read;
6402   cu_header->version = read_2_bytes (abfd, info_ptr);
6403   if (cu_header->version < 2 || cu_header->version > 5)
6404     error (_("Dwarf Error: wrong version in compilation unit header "
6405            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6406            cu_header->version, filename);
6407   info_ptr += 2;
6408   if (cu_header->version < 5)
6409     switch (section_kind)
6410       {
6411       case rcuh_kind::COMPILE:
6412         cu_header->unit_type = DW_UT_compile;
6413         break;
6414       case rcuh_kind::TYPE:
6415         cu_header->unit_type = DW_UT_type;
6416         break;
6417       default:
6418         internal_error (__FILE__, __LINE__,
6419                         _("read_comp_unit_head: invalid section_kind"));
6420       }
6421   else
6422     {
6423       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6424                                                  (read_1_byte (abfd, info_ptr));
6425       info_ptr += 1;
6426       switch (cu_header->unit_type)
6427         {
6428         case DW_UT_compile:
6429           if (section_kind != rcuh_kind::COMPILE)
6430             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6431                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6432                    filename);
6433           break;
6434         case DW_UT_type:
6435           section_kind = rcuh_kind::TYPE;
6436           break;
6437         default:
6438           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6439                  "(is %d, should be %d or %d) [in module %s]"),
6440                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6441         }
6442
6443       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6444       info_ptr += 1;
6445     }
6446   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6447                                                           cu_header,
6448                                                           &bytes_read);
6449   info_ptr += bytes_read;
6450   if (cu_header->version < 5)
6451     {
6452       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6453       info_ptr += 1;
6454     }
6455   signed_addr = bfd_get_sign_extend_vma (abfd);
6456   if (signed_addr < 0)
6457     internal_error (__FILE__, __LINE__,
6458                     _("read_comp_unit_head: dwarf from non elf file"));
6459   cu_header->signed_addr_p = signed_addr;
6460
6461   if (section_kind == rcuh_kind::TYPE)
6462     {
6463       LONGEST type_offset;
6464
6465       cu_header->signature = read_8_bytes (abfd, info_ptr);
6466       info_ptr += 8;
6467
6468       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6469       info_ptr += bytes_read;
6470       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6471       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6472         error (_("Dwarf Error: Too big type_offset in compilation unit "
6473                "header (is %s) [in module %s]"), plongest (type_offset),
6474                filename);
6475     }
6476
6477   return info_ptr;
6478 }
6479
6480 /* Helper function that returns the proper abbrev section for
6481    THIS_CU.  */
6482
6483 static struct dwarf2_section_info *
6484 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6485 {
6486   struct dwarf2_section_info *abbrev;
6487   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6488
6489   if (this_cu->is_dwz)
6490     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6491   else
6492     abbrev = &dwarf2_per_objfile->abbrev;
6493
6494   return abbrev;
6495 }
6496
6497 /* Subroutine of read_and_check_comp_unit_head and
6498    read_and_check_type_unit_head to simplify them.
6499    Perform various error checking on the header.  */
6500
6501 static void
6502 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6503                             struct comp_unit_head *header,
6504                             struct dwarf2_section_info *section,
6505                             struct dwarf2_section_info *abbrev_section)
6506 {
6507   const char *filename = get_section_file_name (section);
6508
6509   if (to_underlying (header->abbrev_sect_off)
6510       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6511     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6512            "(offset %s + 6) [in module %s]"),
6513            sect_offset_str (header->abbrev_sect_off),
6514            sect_offset_str (header->sect_off),
6515            filename);
6516
6517   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6518      avoid potential 32-bit overflow.  */
6519   if (((ULONGEST) header->sect_off + get_cu_length (header))
6520       > section->size)
6521     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6522            "(offset %s + 0) [in module %s]"),
6523            header->length, sect_offset_str (header->sect_off),
6524            filename);
6525 }
6526
6527 /* Read in a CU/TU header and perform some basic error checking.
6528    The contents of the header are stored in HEADER.
6529    The result is a pointer to the start of the first DIE.  */
6530
6531 static const gdb_byte *
6532 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6533                                struct comp_unit_head *header,
6534                                struct dwarf2_section_info *section,
6535                                struct dwarf2_section_info *abbrev_section,
6536                                const gdb_byte *info_ptr,
6537                                rcuh_kind section_kind)
6538 {
6539   const gdb_byte *beg_of_comp_unit = info_ptr;
6540
6541   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6542
6543   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6544
6545   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6546
6547   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6548                               abbrev_section);
6549
6550   return info_ptr;
6551 }
6552
6553 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6554
6555 static sect_offset
6556 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6557                     struct dwarf2_section_info *section,
6558                     sect_offset sect_off)
6559 {
6560   bfd *abfd = get_section_bfd_owner (section);
6561   const gdb_byte *info_ptr;
6562   unsigned int initial_length_size, offset_size;
6563   uint16_t version;
6564
6565   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6566   info_ptr = section->buffer + to_underlying (sect_off);
6567   read_initial_length (abfd, info_ptr, &initial_length_size);
6568   offset_size = initial_length_size == 4 ? 4 : 8;
6569   info_ptr += initial_length_size;
6570
6571   version = read_2_bytes (abfd, info_ptr);
6572   info_ptr += 2;
6573   if (version >= 5)
6574     {
6575       /* Skip unit type and address size.  */
6576       info_ptr += 2;
6577     }
6578
6579   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6580 }
6581
6582 /* Allocate a new partial symtab for file named NAME and mark this new
6583    partial symtab as being an include of PST.  */
6584
6585 static void
6586 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6587                                struct objfile *objfile)
6588 {
6589   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6590
6591   if (!IS_ABSOLUTE_PATH (subpst->filename))
6592     {
6593       /* It shares objfile->objfile_obstack.  */
6594       subpst->dirname = pst->dirname;
6595     }
6596
6597   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
6598   subpst->dependencies[0] = pst;
6599   subpst->number_of_dependencies = 1;
6600
6601   subpst->read_symtab = pst->read_symtab;
6602
6603   /* No private part is necessary for include psymtabs.  This property
6604      can be used to differentiate between such include psymtabs and
6605      the regular ones.  */
6606   subpst->read_symtab_private = NULL;
6607 }
6608
6609 /* Read the Line Number Program data and extract the list of files
6610    included by the source file represented by PST.  Build an include
6611    partial symtab for each of these included files.  */
6612
6613 static void
6614 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6615                                struct die_info *die,
6616                                struct partial_symtab *pst)
6617 {
6618   line_header_up lh;
6619   struct attribute *attr;
6620
6621   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6622   if (attr)
6623     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6624   if (lh == NULL)
6625     return;  /* No linetable, so no includes.  */
6626
6627   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6628      that we pass in the raw text_low here; that is ok because we're
6629      only decoding the line table to make include partial symtabs, and
6630      so the addresses aren't really used.  */
6631   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6632                       pst->raw_text_low (), 1);
6633 }
6634
6635 static hashval_t
6636 hash_signatured_type (const void *item)
6637 {
6638   const struct signatured_type *sig_type
6639     = (const struct signatured_type *) item;
6640
6641   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6642   return sig_type->signature;
6643 }
6644
6645 static int
6646 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6647 {
6648   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6649   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6650
6651   return lhs->signature == rhs->signature;
6652 }
6653
6654 /* Allocate a hash table for signatured types.  */
6655
6656 static htab_t
6657 allocate_signatured_type_table (struct objfile *objfile)
6658 {
6659   return htab_create_alloc_ex (41,
6660                                hash_signatured_type,
6661                                eq_signatured_type,
6662                                NULL,
6663                                &objfile->objfile_obstack,
6664                                hashtab_obstack_allocate,
6665                                dummy_obstack_deallocate);
6666 }
6667
6668 /* A helper function to add a signatured type CU to a table.  */
6669
6670 static int
6671 add_signatured_type_cu_to_table (void **slot, void *datum)
6672 {
6673   struct signatured_type *sigt = (struct signatured_type *) *slot;
6674   std::vector<signatured_type *> *all_type_units
6675     = (std::vector<signatured_type *> *) datum;
6676
6677   all_type_units->push_back (sigt);
6678
6679   return 1;
6680 }
6681
6682 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6683    and fill them into TYPES_HTAB.  It will process only type units,
6684    therefore DW_UT_type.  */
6685
6686 static void
6687 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6688                               struct dwo_file *dwo_file,
6689                               dwarf2_section_info *section, htab_t &types_htab,
6690                               rcuh_kind section_kind)
6691 {
6692   struct objfile *objfile = dwarf2_per_objfile->objfile;
6693   struct dwarf2_section_info *abbrev_section;
6694   bfd *abfd;
6695   const gdb_byte *info_ptr, *end_ptr;
6696
6697   abbrev_section = (dwo_file != NULL
6698                     ? &dwo_file->sections.abbrev
6699                     : &dwarf2_per_objfile->abbrev);
6700
6701   if (dwarf_read_debug)
6702     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6703                         get_section_name (section),
6704                         get_section_file_name (abbrev_section));
6705
6706   dwarf2_read_section (objfile, section);
6707   info_ptr = section->buffer;
6708
6709   if (info_ptr == NULL)
6710     return;
6711
6712   /* We can't set abfd until now because the section may be empty or
6713      not present, in which case the bfd is unknown.  */
6714   abfd = get_section_bfd_owner (section);
6715
6716   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6717      because we don't need to read any dies: the signature is in the
6718      header.  */
6719
6720   end_ptr = info_ptr + section->size;
6721   while (info_ptr < end_ptr)
6722     {
6723       struct signatured_type *sig_type;
6724       struct dwo_unit *dwo_tu;
6725       void **slot;
6726       const gdb_byte *ptr = info_ptr;
6727       struct comp_unit_head header;
6728       unsigned int length;
6729
6730       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6731
6732       /* Initialize it due to a false compiler warning.  */
6733       header.signature = -1;
6734       header.type_cu_offset_in_tu = (cu_offset) -1;
6735
6736       /* We need to read the type's signature in order to build the hash
6737          table, but we don't need anything else just yet.  */
6738
6739       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6740                                            abbrev_section, ptr, section_kind);
6741
6742       length = get_cu_length (&header);
6743
6744       /* Skip dummy type units.  */
6745       if (ptr >= info_ptr + length
6746           || peek_abbrev_code (abfd, ptr) == 0
6747           || header.unit_type != DW_UT_type)
6748         {
6749           info_ptr += length;
6750           continue;
6751         }
6752
6753       if (types_htab == NULL)
6754         {
6755           if (dwo_file)
6756             types_htab = allocate_dwo_unit_table (objfile);
6757           else
6758             types_htab = allocate_signatured_type_table (objfile);
6759         }
6760
6761       if (dwo_file)
6762         {
6763           sig_type = NULL;
6764           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6765                                    struct dwo_unit);
6766           dwo_tu->dwo_file = dwo_file;
6767           dwo_tu->signature = header.signature;
6768           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6769           dwo_tu->section = section;
6770           dwo_tu->sect_off = sect_off;
6771           dwo_tu->length = length;
6772         }
6773       else
6774         {
6775           /* N.B.: type_offset is not usable if this type uses a DWO file.
6776              The real type_offset is in the DWO file.  */
6777           dwo_tu = NULL;
6778           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6779                                      struct signatured_type);
6780           sig_type->signature = header.signature;
6781           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6782           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6783           sig_type->per_cu.is_debug_types = 1;
6784           sig_type->per_cu.section = section;
6785           sig_type->per_cu.sect_off = sect_off;
6786           sig_type->per_cu.length = length;
6787         }
6788
6789       slot = htab_find_slot (types_htab,
6790                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6791                              INSERT);
6792       gdb_assert (slot != NULL);
6793       if (*slot != NULL)
6794         {
6795           sect_offset dup_sect_off;
6796
6797           if (dwo_file)
6798             {
6799               const struct dwo_unit *dup_tu
6800                 = (const struct dwo_unit *) *slot;
6801
6802               dup_sect_off = dup_tu->sect_off;
6803             }
6804           else
6805             {
6806               const struct signatured_type *dup_tu
6807                 = (const struct signatured_type *) *slot;
6808
6809               dup_sect_off = dup_tu->per_cu.sect_off;
6810             }
6811
6812           complaint (_("debug type entry at offset %s is duplicate to"
6813                        " the entry at offset %s, signature %s"),
6814                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6815                      hex_string (header.signature));
6816         }
6817       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6818
6819       if (dwarf_read_debug > 1)
6820         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6821                             sect_offset_str (sect_off),
6822                             hex_string (header.signature));
6823
6824       info_ptr += length;
6825     }
6826 }
6827
6828 /* Create the hash table of all entries in the .debug_types
6829    (or .debug_types.dwo) section(s).
6830    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6831    otherwise it is NULL.
6832
6833    The result is a pointer to the hash table or NULL if there are no types.
6834
6835    Note: This function processes DWO files only, not DWP files.  */
6836
6837 static void
6838 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6839                                struct dwo_file *dwo_file,
6840                                VEC (dwarf2_section_info_def) *types,
6841                                htab_t &types_htab)
6842 {
6843   int ix;
6844   struct dwarf2_section_info *section;
6845
6846   if (VEC_empty (dwarf2_section_info_def, types))
6847     return;
6848
6849   for (ix = 0;
6850        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6851        ++ix)
6852     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6853                                   types_htab, rcuh_kind::TYPE);
6854 }
6855
6856 /* Create the hash table of all entries in the .debug_types section,
6857    and initialize all_type_units.
6858    The result is zero if there is an error (e.g. missing .debug_types section),
6859    otherwise non-zero.  */
6860
6861 static int
6862 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6863 {
6864   htab_t types_htab = NULL;
6865
6866   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6867                                 &dwarf2_per_objfile->info, types_htab,
6868                                 rcuh_kind::COMPILE);
6869   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6870                                  dwarf2_per_objfile->types, types_htab);
6871   if (types_htab == NULL)
6872     {
6873       dwarf2_per_objfile->signatured_types = NULL;
6874       return 0;
6875     }
6876
6877   dwarf2_per_objfile->signatured_types = types_htab;
6878
6879   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6880   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6881
6882   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6883                           &dwarf2_per_objfile->all_type_units);
6884
6885   return 1;
6886 }
6887
6888 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6889    If SLOT is non-NULL, it is the entry to use in the hash table.
6890    Otherwise we find one.  */
6891
6892 static struct signatured_type *
6893 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6894                void **slot)
6895 {
6896   struct objfile *objfile = dwarf2_per_objfile->objfile;
6897
6898   if (dwarf2_per_objfile->all_type_units.size ()
6899       == dwarf2_per_objfile->all_type_units.capacity ())
6900     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6901
6902   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6903                                               struct signatured_type);
6904
6905   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6906   sig_type->signature = sig;
6907   sig_type->per_cu.is_debug_types = 1;
6908   if (dwarf2_per_objfile->using_index)
6909     {
6910       sig_type->per_cu.v.quick =
6911         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6912                         struct dwarf2_per_cu_quick_data);
6913     }
6914
6915   if (slot == NULL)
6916     {
6917       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6918                              sig_type, INSERT);
6919     }
6920   gdb_assert (*slot == NULL);
6921   *slot = sig_type;
6922   /* The rest of sig_type must be filled in by the caller.  */
6923   return sig_type;
6924 }
6925
6926 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6927    Fill in SIG_ENTRY with DWO_ENTRY.  */
6928
6929 static void
6930 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6931                                   struct signatured_type *sig_entry,
6932                                   struct dwo_unit *dwo_entry)
6933 {
6934   /* Make sure we're not clobbering something we don't expect to.  */
6935   gdb_assert (! sig_entry->per_cu.queued);
6936   gdb_assert (sig_entry->per_cu.cu == NULL);
6937   if (dwarf2_per_objfile->using_index)
6938     {
6939       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6940       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6941     }
6942   else
6943       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6944   gdb_assert (sig_entry->signature == dwo_entry->signature);
6945   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6946   gdb_assert (sig_entry->type_unit_group == NULL);
6947   gdb_assert (sig_entry->dwo_unit == NULL);
6948
6949   sig_entry->per_cu.section = dwo_entry->section;
6950   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6951   sig_entry->per_cu.length = dwo_entry->length;
6952   sig_entry->per_cu.reading_dwo_directly = 1;
6953   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6954   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6955   sig_entry->dwo_unit = dwo_entry;
6956 }
6957
6958 /* Subroutine of lookup_signatured_type.
6959    If we haven't read the TU yet, create the signatured_type data structure
6960    for a TU to be read in directly from a DWO file, bypassing the stub.
6961    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6962    using .gdb_index, then when reading a CU we want to stay in the DWO file
6963    containing that CU.  Otherwise we could end up reading several other DWO
6964    files (due to comdat folding) to process the transitive closure of all the
6965    mentioned TUs, and that can be slow.  The current DWO file will have every
6966    type signature that it needs.
6967    We only do this for .gdb_index because in the psymtab case we already have
6968    to read all the DWOs to build the type unit groups.  */
6969
6970 static struct signatured_type *
6971 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6972 {
6973   struct dwarf2_per_objfile *dwarf2_per_objfile
6974     = cu->per_cu->dwarf2_per_objfile;
6975   struct objfile *objfile = dwarf2_per_objfile->objfile;
6976   struct dwo_file *dwo_file;
6977   struct dwo_unit find_dwo_entry, *dwo_entry;
6978   struct signatured_type find_sig_entry, *sig_entry;
6979   void **slot;
6980
6981   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6982
6983   /* If TU skeletons have been removed then we may not have read in any
6984      TUs yet.  */
6985   if (dwarf2_per_objfile->signatured_types == NULL)
6986     {
6987       dwarf2_per_objfile->signatured_types
6988         = allocate_signatured_type_table (objfile);
6989     }
6990
6991   /* We only ever need to read in one copy of a signatured type.
6992      Use the global signatured_types array to do our own comdat-folding
6993      of types.  If this is the first time we're reading this TU, and
6994      the TU has an entry in .gdb_index, replace the recorded data from
6995      .gdb_index with this TU.  */
6996
6997   find_sig_entry.signature = sig;
6998   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6999                          &find_sig_entry, INSERT);
7000   sig_entry = (struct signatured_type *) *slot;
7001
7002   /* We can get here with the TU already read, *or* in the process of being
7003      read.  Don't reassign the global entry to point to this DWO if that's
7004      the case.  Also note that if the TU is already being read, it may not
7005      have come from a DWO, the program may be a mix of Fission-compiled
7006      code and non-Fission-compiled code.  */
7007
7008   /* Have we already tried to read this TU?
7009      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7010      needn't exist in the global table yet).  */
7011   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7012     return sig_entry;
7013
7014   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7015      dwo_unit of the TU itself.  */
7016   dwo_file = cu->dwo_unit->dwo_file;
7017
7018   /* Ok, this is the first time we're reading this TU.  */
7019   if (dwo_file->tus == NULL)
7020     return NULL;
7021   find_dwo_entry.signature = sig;
7022   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7023   if (dwo_entry == NULL)
7024     return NULL;
7025
7026   /* If the global table doesn't have an entry for this TU, add one.  */
7027   if (sig_entry == NULL)
7028     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7029
7030   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7031   sig_entry->per_cu.tu_read = 1;
7032   return sig_entry;
7033 }
7034
7035 /* Subroutine of lookup_signatured_type.
7036    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7037    then try the DWP file.  If the TU stub (skeleton) has been removed then
7038    it won't be in .gdb_index.  */
7039
7040 static struct signatured_type *
7041 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7042 {
7043   struct dwarf2_per_objfile *dwarf2_per_objfile
7044     = cu->per_cu->dwarf2_per_objfile;
7045   struct objfile *objfile = dwarf2_per_objfile->objfile;
7046   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7047   struct dwo_unit *dwo_entry;
7048   struct signatured_type find_sig_entry, *sig_entry;
7049   void **slot;
7050
7051   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7052   gdb_assert (dwp_file != NULL);
7053
7054   /* If TU skeletons have been removed then we may not have read in any
7055      TUs yet.  */
7056   if (dwarf2_per_objfile->signatured_types == NULL)
7057     {
7058       dwarf2_per_objfile->signatured_types
7059         = allocate_signatured_type_table (objfile);
7060     }
7061
7062   find_sig_entry.signature = sig;
7063   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7064                          &find_sig_entry, INSERT);
7065   sig_entry = (struct signatured_type *) *slot;
7066
7067   /* Have we already tried to read this TU?
7068      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7069      needn't exist in the global table yet).  */
7070   if (sig_entry != NULL)
7071     return sig_entry;
7072
7073   if (dwp_file->tus == NULL)
7074     return NULL;
7075   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7076                                       sig, 1 /* is_debug_types */);
7077   if (dwo_entry == NULL)
7078     return NULL;
7079
7080   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7081   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7082
7083   return sig_entry;
7084 }
7085
7086 /* Lookup a signature based type for DW_FORM_ref_sig8.
7087    Returns NULL if signature SIG is not present in the table.
7088    It is up to the caller to complain about this.  */
7089
7090 static struct signatured_type *
7091 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7092 {
7093   struct dwarf2_per_objfile *dwarf2_per_objfile
7094     = cu->per_cu->dwarf2_per_objfile;
7095
7096   if (cu->dwo_unit
7097       && dwarf2_per_objfile->using_index)
7098     {
7099       /* We're in a DWO/DWP file, and we're using .gdb_index.
7100          These cases require special processing.  */
7101       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7102         return lookup_dwo_signatured_type (cu, sig);
7103       else
7104         return lookup_dwp_signatured_type (cu, sig);
7105     }
7106   else
7107     {
7108       struct signatured_type find_entry, *entry;
7109
7110       if (dwarf2_per_objfile->signatured_types == NULL)
7111         return NULL;
7112       find_entry.signature = sig;
7113       entry = ((struct signatured_type *)
7114                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7115       return entry;
7116     }
7117 }
7118 \f
7119 /* Low level DIE reading support.  */
7120
7121 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7122
7123 static void
7124 init_cu_die_reader (struct die_reader_specs *reader,
7125                     struct dwarf2_cu *cu,
7126                     struct dwarf2_section_info *section,
7127                     struct dwo_file *dwo_file,
7128                     struct abbrev_table *abbrev_table)
7129 {
7130   gdb_assert (section->readin && section->buffer != NULL);
7131   reader->abfd = get_section_bfd_owner (section);
7132   reader->cu = cu;
7133   reader->dwo_file = dwo_file;
7134   reader->die_section = section;
7135   reader->buffer = section->buffer;
7136   reader->buffer_end = section->buffer + section->size;
7137   reader->comp_dir = NULL;
7138   reader->abbrev_table = abbrev_table;
7139 }
7140
7141 /* Subroutine of init_cutu_and_read_dies to simplify it.
7142    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7143    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7144    already.
7145
7146    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7147    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7148    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7149    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7150    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7151    STUB_COMP_DIR may be non-NULL.
7152    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7153    are filled in with the info of the DIE from the DWO file.
7154    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7155    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7156    kept around for at least as long as *RESULT_READER.
7157
7158    The result is non-zero if a valid (non-dummy) DIE was found.  */
7159
7160 static int
7161 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7162                         struct dwo_unit *dwo_unit,
7163                         struct die_info *stub_comp_unit_die,
7164                         const char *stub_comp_dir,
7165                         struct die_reader_specs *result_reader,
7166                         const gdb_byte **result_info_ptr,
7167                         struct die_info **result_comp_unit_die,
7168                         int *result_has_children,
7169                         abbrev_table_up *result_dwo_abbrev_table)
7170 {
7171   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7172   struct objfile *objfile = dwarf2_per_objfile->objfile;
7173   struct dwarf2_cu *cu = this_cu->cu;
7174   bfd *abfd;
7175   const gdb_byte *begin_info_ptr, *info_ptr;
7176   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7177   int i,num_extra_attrs;
7178   struct dwarf2_section_info *dwo_abbrev_section;
7179   struct attribute *attr;
7180   struct die_info *comp_unit_die;
7181
7182   /* At most one of these may be provided.  */
7183   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7184
7185   /* These attributes aren't processed until later:
7186      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7187      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7188      referenced later.  However, these attributes are found in the stub
7189      which we won't have later.  In order to not impose this complication
7190      on the rest of the code, we read them here and copy them to the
7191      DWO CU/TU die.  */
7192
7193   stmt_list = NULL;
7194   low_pc = NULL;
7195   high_pc = NULL;
7196   ranges = NULL;
7197   comp_dir = NULL;
7198
7199   if (stub_comp_unit_die != NULL)
7200     {
7201       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7202          DWO file.  */
7203       if (! this_cu->is_debug_types)
7204         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7205       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7206       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7207       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7208       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7209
7210       /* There should be a DW_AT_addr_base attribute here (if needed).
7211          We need the value before we can process DW_FORM_GNU_addr_index
7212          or DW_FORM_addrx.  */
7213       cu->addr_base = 0;
7214       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7215       if (attr)
7216         cu->addr_base = DW_UNSND (attr);
7217
7218       /* There should be a DW_AT_ranges_base attribute here (if needed).
7219          We need the value before we can process DW_AT_ranges.  */
7220       cu->ranges_base = 0;
7221       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7222       if (attr)
7223         cu->ranges_base = DW_UNSND (attr);
7224     }
7225   else if (stub_comp_dir != NULL)
7226     {
7227       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7228       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7229       comp_dir->name = DW_AT_comp_dir;
7230       comp_dir->form = DW_FORM_string;
7231       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7232       DW_STRING (comp_dir) = stub_comp_dir;
7233     }
7234
7235   /* Set up for reading the DWO CU/TU.  */
7236   cu->dwo_unit = dwo_unit;
7237   dwarf2_section_info *section = dwo_unit->section;
7238   dwarf2_read_section (objfile, section);
7239   abfd = get_section_bfd_owner (section);
7240   begin_info_ptr = info_ptr = (section->buffer
7241                                + to_underlying (dwo_unit->sect_off));
7242   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7243
7244   if (this_cu->is_debug_types)
7245     {
7246       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7247
7248       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7249                                                 &cu->header, section,
7250                                                 dwo_abbrev_section,
7251                                                 info_ptr, rcuh_kind::TYPE);
7252       /* This is not an assert because it can be caused by bad debug info.  */
7253       if (sig_type->signature != cu->header.signature)
7254         {
7255           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7256                    " TU at offset %s [in module %s]"),
7257                  hex_string (sig_type->signature),
7258                  hex_string (cu->header.signature),
7259                  sect_offset_str (dwo_unit->sect_off),
7260                  bfd_get_filename (abfd));
7261         }
7262       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7263       /* For DWOs coming from DWP files, we don't know the CU length
7264          nor the type's offset in the TU until now.  */
7265       dwo_unit->length = get_cu_length (&cu->header);
7266       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7267
7268       /* Establish the type offset that can be used to lookup the type.
7269          For DWO files, we don't know it until now.  */
7270       sig_type->type_offset_in_section
7271         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7272     }
7273   else
7274     {
7275       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7276                                                 &cu->header, section,
7277                                                 dwo_abbrev_section,
7278                                                 info_ptr, rcuh_kind::COMPILE);
7279       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7280       /* For DWOs coming from DWP files, we don't know the CU length
7281          until now.  */
7282       dwo_unit->length = get_cu_length (&cu->header);
7283     }
7284
7285   *result_dwo_abbrev_table
7286     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7287                                cu->header.abbrev_sect_off);
7288   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7289                       result_dwo_abbrev_table->get ());
7290
7291   /* Read in the die, but leave space to copy over the attributes
7292      from the stub.  This has the benefit of simplifying the rest of
7293      the code - all the work to maintain the illusion of a single
7294      DW_TAG_{compile,type}_unit DIE is done here.  */
7295   num_extra_attrs = ((stmt_list != NULL)
7296                      + (low_pc != NULL)
7297                      + (high_pc != NULL)
7298                      + (ranges != NULL)
7299                      + (comp_dir != NULL));
7300   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7301                               result_has_children, num_extra_attrs);
7302
7303   /* Copy over the attributes from the stub to the DIE we just read in.  */
7304   comp_unit_die = *result_comp_unit_die;
7305   i = comp_unit_die->num_attrs;
7306   if (stmt_list != NULL)
7307     comp_unit_die->attrs[i++] = *stmt_list;
7308   if (low_pc != NULL)
7309     comp_unit_die->attrs[i++] = *low_pc;
7310   if (high_pc != NULL)
7311     comp_unit_die->attrs[i++] = *high_pc;
7312   if (ranges != NULL)
7313     comp_unit_die->attrs[i++] = *ranges;
7314   if (comp_dir != NULL)
7315     comp_unit_die->attrs[i++] = *comp_dir;
7316   comp_unit_die->num_attrs += num_extra_attrs;
7317
7318   if (dwarf_die_debug)
7319     {
7320       fprintf_unfiltered (gdb_stdlog,
7321                           "Read die from %s@0x%x of %s:\n",
7322                           get_section_name (section),
7323                           (unsigned) (begin_info_ptr - section->buffer),
7324                           bfd_get_filename (abfd));
7325       dump_die (comp_unit_die, dwarf_die_debug);
7326     }
7327
7328   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7329      TUs by skipping the stub and going directly to the entry in the DWO file.
7330      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7331      to get it via circuitous means.  Blech.  */
7332   if (comp_dir != NULL)
7333     result_reader->comp_dir = DW_STRING (comp_dir);
7334
7335   /* Skip dummy compilation units.  */
7336   if (info_ptr >= begin_info_ptr + dwo_unit->length
7337       || peek_abbrev_code (abfd, info_ptr) == 0)
7338     return 0;
7339
7340   *result_info_ptr = info_ptr;
7341   return 1;
7342 }
7343
7344 /* Subroutine of init_cutu_and_read_dies to simplify it.
7345    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7346    Returns NULL if the specified DWO unit cannot be found.  */
7347
7348 static struct dwo_unit *
7349 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7350                  struct die_info *comp_unit_die)
7351 {
7352   struct dwarf2_cu *cu = this_cu->cu;
7353   ULONGEST signature;
7354   struct dwo_unit *dwo_unit;
7355   const char *comp_dir, *dwo_name;
7356
7357   gdb_assert (cu != NULL);
7358
7359   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7360   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7361   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7362
7363   if (this_cu->is_debug_types)
7364     {
7365       struct signatured_type *sig_type;
7366
7367       /* Since this_cu is the first member of struct signatured_type,
7368          we can go from a pointer to one to a pointer to the other.  */
7369       sig_type = (struct signatured_type *) this_cu;
7370       signature = sig_type->signature;
7371       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7372     }
7373   else
7374     {
7375       struct attribute *attr;
7376
7377       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7378       if (! attr)
7379         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7380                  " [in module %s]"),
7381                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7382       signature = DW_UNSND (attr);
7383       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7384                                        signature);
7385     }
7386
7387   return dwo_unit;
7388 }
7389
7390 /* Subroutine of init_cutu_and_read_dies to simplify it.
7391    See it for a description of the parameters.
7392    Read a TU directly from a DWO file, bypassing the stub.  */
7393
7394 static void
7395 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7396                            int use_existing_cu, int keep,
7397                            die_reader_func_ftype *die_reader_func,
7398                            void *data)
7399 {
7400   std::unique_ptr<dwarf2_cu> new_cu;
7401   struct signatured_type *sig_type;
7402   struct die_reader_specs reader;
7403   const gdb_byte *info_ptr;
7404   struct die_info *comp_unit_die;
7405   int has_children;
7406   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7407
7408   /* Verify we can do the following downcast, and that we have the
7409      data we need.  */
7410   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7411   sig_type = (struct signatured_type *) this_cu;
7412   gdb_assert (sig_type->dwo_unit != NULL);
7413
7414   if (use_existing_cu && this_cu->cu != NULL)
7415     {
7416       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7417       /* There's no need to do the rereading_dwo_cu handling that
7418          init_cutu_and_read_dies does since we don't read the stub.  */
7419     }
7420   else
7421     {
7422       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7423       gdb_assert (this_cu->cu == NULL);
7424       new_cu.reset (new dwarf2_cu (this_cu));
7425     }
7426
7427   /* A future optimization, if needed, would be to use an existing
7428      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7429      could share abbrev tables.  */
7430
7431   /* The abbreviation table used by READER, this must live at least as long as
7432      READER.  */
7433   abbrev_table_up dwo_abbrev_table;
7434
7435   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7436                               NULL /* stub_comp_unit_die */,
7437                               sig_type->dwo_unit->dwo_file->comp_dir,
7438                               &reader, &info_ptr,
7439                               &comp_unit_die, &has_children,
7440                               &dwo_abbrev_table) == 0)
7441     {
7442       /* Dummy die.  */
7443       return;
7444     }
7445
7446   /* All the "real" work is done here.  */
7447   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7448
7449   /* This duplicates the code in init_cutu_and_read_dies,
7450      but the alternative is making the latter more complex.
7451      This function is only for the special case of using DWO files directly:
7452      no point in overly complicating the general case just to handle this.  */
7453   if (new_cu != NULL && keep)
7454     {
7455       /* Link this CU into read_in_chain.  */
7456       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7457       dwarf2_per_objfile->read_in_chain = this_cu;
7458       /* The chain owns it now.  */
7459       new_cu.release ();
7460     }
7461 }
7462
7463 /* Initialize a CU (or TU) and read its DIEs.
7464    If the CU defers to a DWO file, read the DWO file as well.
7465
7466    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7467    Otherwise the table specified in the comp unit header is read in and used.
7468    This is an optimization for when we already have the abbrev table.
7469
7470    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7471    Otherwise, a new CU is allocated with xmalloc.
7472
7473    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7474    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7475
7476    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7477    linker) then DIE_READER_FUNC will not get called.  */
7478
7479 static void
7480 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7481                          struct abbrev_table *abbrev_table,
7482                          int use_existing_cu, int keep,
7483                          bool skip_partial,
7484                          die_reader_func_ftype *die_reader_func,
7485                          void *data)
7486 {
7487   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7488   struct objfile *objfile = dwarf2_per_objfile->objfile;
7489   struct dwarf2_section_info *section = this_cu->section;
7490   bfd *abfd = get_section_bfd_owner (section);
7491   struct dwarf2_cu *cu;
7492   const gdb_byte *begin_info_ptr, *info_ptr;
7493   struct die_reader_specs reader;
7494   struct die_info *comp_unit_die;
7495   int has_children;
7496   struct attribute *attr;
7497   struct signatured_type *sig_type = NULL;
7498   struct dwarf2_section_info *abbrev_section;
7499   /* Non-zero if CU currently points to a DWO file and we need to
7500      reread it.  When this happens we need to reread the skeleton die
7501      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7502   int rereading_dwo_cu = 0;
7503
7504   if (dwarf_die_debug)
7505     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7506                         this_cu->is_debug_types ? "type" : "comp",
7507                         sect_offset_str (this_cu->sect_off));
7508
7509   if (use_existing_cu)
7510     gdb_assert (keep);
7511
7512   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7513      file (instead of going through the stub), short-circuit all of this.  */
7514   if (this_cu->reading_dwo_directly)
7515     {
7516       /* Narrow down the scope of possibilities to have to understand.  */
7517       gdb_assert (this_cu->is_debug_types);
7518       gdb_assert (abbrev_table == NULL);
7519       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7520                                  die_reader_func, data);
7521       return;
7522     }
7523
7524   /* This is cheap if the section is already read in.  */
7525   dwarf2_read_section (objfile, section);
7526
7527   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7528
7529   abbrev_section = get_abbrev_section_for_cu (this_cu);
7530
7531   std::unique_ptr<dwarf2_cu> new_cu;
7532   if (use_existing_cu && this_cu->cu != NULL)
7533     {
7534       cu = this_cu->cu;
7535       /* If this CU is from a DWO file we need to start over, we need to
7536          refetch the attributes from the skeleton CU.
7537          This could be optimized by retrieving those attributes from when we
7538          were here the first time: the previous comp_unit_die was stored in
7539          comp_unit_obstack.  But there's no data yet that we need this
7540          optimization.  */
7541       if (cu->dwo_unit != NULL)
7542         rereading_dwo_cu = 1;
7543     }
7544   else
7545     {
7546       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7547       gdb_assert (this_cu->cu == NULL);
7548       new_cu.reset (new dwarf2_cu (this_cu));
7549       cu = new_cu.get ();
7550     }
7551
7552   /* Get the header.  */
7553   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7554     {
7555       /* We already have the header, there's no need to read it in again.  */
7556       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7557     }
7558   else
7559     {
7560       if (this_cu->is_debug_types)
7561         {
7562           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7563                                                     &cu->header, section,
7564                                                     abbrev_section, info_ptr,
7565                                                     rcuh_kind::TYPE);
7566
7567           /* Since per_cu is the first member of struct signatured_type,
7568              we can go from a pointer to one to a pointer to the other.  */
7569           sig_type = (struct signatured_type *) this_cu;
7570           gdb_assert (sig_type->signature == cu->header.signature);
7571           gdb_assert (sig_type->type_offset_in_tu
7572                       == cu->header.type_cu_offset_in_tu);
7573           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7574
7575           /* LENGTH has not been set yet for type units if we're
7576              using .gdb_index.  */
7577           this_cu->length = get_cu_length (&cu->header);
7578
7579           /* Establish the type offset that can be used to lookup the type.  */
7580           sig_type->type_offset_in_section =
7581             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7582
7583           this_cu->dwarf_version = cu->header.version;
7584         }
7585       else
7586         {
7587           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7588                                                     &cu->header, section,
7589                                                     abbrev_section,
7590                                                     info_ptr,
7591                                                     rcuh_kind::COMPILE);
7592
7593           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7594           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7595           this_cu->dwarf_version = cu->header.version;
7596         }
7597     }
7598
7599   /* Skip dummy compilation units.  */
7600   if (info_ptr >= begin_info_ptr + this_cu->length
7601       || peek_abbrev_code (abfd, info_ptr) == 0)
7602     return;
7603
7604   /* If we don't have them yet, read the abbrevs for this compilation unit.
7605      And if we need to read them now, make sure they're freed when we're
7606      done (own the table through ABBREV_TABLE_HOLDER).  */
7607   abbrev_table_up abbrev_table_holder;
7608   if (abbrev_table != NULL)
7609     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7610   else
7611     {
7612       abbrev_table_holder
7613         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7614                                    cu->header.abbrev_sect_off);
7615       abbrev_table = abbrev_table_holder.get ();
7616     }
7617
7618   /* Read the top level CU/TU die.  */
7619   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7620   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7621
7622   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7623     return;
7624
7625   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7626      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7627      table from the DWO file and pass the ownership over to us.  It will be
7628      referenced from READER, so we must make sure to free it after we're done
7629      with READER.
7630
7631      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7632      DWO CU, that this test will fail (the attribute will not be present).  */
7633   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7634   abbrev_table_up dwo_abbrev_table;
7635   if (attr)
7636     {
7637       struct dwo_unit *dwo_unit;
7638       struct die_info *dwo_comp_unit_die;
7639
7640       if (has_children)
7641         {
7642           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7643                        " has children (offset %s) [in module %s]"),
7644                      sect_offset_str (this_cu->sect_off),
7645                      bfd_get_filename (abfd));
7646         }
7647       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7648       if (dwo_unit != NULL)
7649         {
7650           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7651                                       comp_unit_die, NULL,
7652                                       &reader, &info_ptr,
7653                                       &dwo_comp_unit_die, &has_children,
7654                                       &dwo_abbrev_table) == 0)
7655             {
7656               /* Dummy die.  */
7657               return;
7658             }
7659           comp_unit_die = dwo_comp_unit_die;
7660         }
7661       else
7662         {
7663           /* Yikes, we couldn't find the rest of the DIE, we only have
7664              the stub.  A complaint has already been logged.  There's
7665              not much more we can do except pass on the stub DIE to
7666              die_reader_func.  We don't want to throw an error on bad
7667              debug info.  */
7668         }
7669     }
7670
7671   /* All of the above is setup for this call.  Yikes.  */
7672   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7673
7674   /* Done, clean up.  */
7675   if (new_cu != NULL && keep)
7676     {
7677       /* Link this CU into read_in_chain.  */
7678       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7679       dwarf2_per_objfile->read_in_chain = this_cu;
7680       /* The chain owns it now.  */
7681       new_cu.release ();
7682     }
7683 }
7684
7685 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7686    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7687    to have already done the lookup to find the DWO file).
7688
7689    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7690    THIS_CU->is_debug_types, but nothing else.
7691
7692    We fill in THIS_CU->length.
7693
7694    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7695    linker) then DIE_READER_FUNC will not get called.
7696
7697    THIS_CU->cu is always freed when done.
7698    This is done in order to not leave THIS_CU->cu in a state where we have
7699    to care whether it refers to the "main" CU or the DWO CU.  */
7700
7701 static void
7702 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7703                                    struct dwo_file *dwo_file,
7704                                    die_reader_func_ftype *die_reader_func,
7705                                    void *data)
7706 {
7707   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7708   struct objfile *objfile = dwarf2_per_objfile->objfile;
7709   struct dwarf2_section_info *section = this_cu->section;
7710   bfd *abfd = get_section_bfd_owner (section);
7711   struct dwarf2_section_info *abbrev_section;
7712   const gdb_byte *begin_info_ptr, *info_ptr;
7713   struct die_reader_specs reader;
7714   struct die_info *comp_unit_die;
7715   int has_children;
7716
7717   if (dwarf_die_debug)
7718     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7719                         this_cu->is_debug_types ? "type" : "comp",
7720                         sect_offset_str (this_cu->sect_off));
7721
7722   gdb_assert (this_cu->cu == NULL);
7723
7724   abbrev_section = (dwo_file != NULL
7725                     ? &dwo_file->sections.abbrev
7726                     : get_abbrev_section_for_cu (this_cu));
7727
7728   /* This is cheap if the section is already read in.  */
7729   dwarf2_read_section (objfile, section);
7730
7731   struct dwarf2_cu cu (this_cu);
7732
7733   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7734   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7735                                             &cu.header, section,
7736                                             abbrev_section, info_ptr,
7737                                             (this_cu->is_debug_types
7738                                              ? rcuh_kind::TYPE
7739                                              : rcuh_kind::COMPILE));
7740
7741   this_cu->length = get_cu_length (&cu.header);
7742
7743   /* Skip dummy compilation units.  */
7744   if (info_ptr >= begin_info_ptr + this_cu->length
7745       || peek_abbrev_code (abfd, info_ptr) == 0)
7746     return;
7747
7748   abbrev_table_up abbrev_table
7749     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7750                                cu.header.abbrev_sect_off);
7751
7752   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7753   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7754
7755   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7756 }
7757
7758 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7759    does not lookup the specified DWO file.
7760    This cannot be used to read DWO files.
7761
7762    THIS_CU->cu is always freed when done.
7763    This is done in order to not leave THIS_CU->cu in a state where we have
7764    to care whether it refers to the "main" CU or the DWO CU.
7765    We can revisit this if the data shows there's a performance issue.  */
7766
7767 static void
7768 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7769                                 die_reader_func_ftype *die_reader_func,
7770                                 void *data)
7771 {
7772   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7773 }
7774 \f
7775 /* Type Unit Groups.
7776
7777    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7778    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7779    so that all types coming from the same compilation (.o file) are grouped
7780    together.  A future step could be to put the types in the same symtab as
7781    the CU the types ultimately came from.  */
7782
7783 static hashval_t
7784 hash_type_unit_group (const void *item)
7785 {
7786   const struct type_unit_group *tu_group
7787     = (const struct type_unit_group *) item;
7788
7789   return hash_stmt_list_entry (&tu_group->hash);
7790 }
7791
7792 static int
7793 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7794 {
7795   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7796   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7797
7798   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7799 }
7800
7801 /* Allocate a hash table for type unit groups.  */
7802
7803 static htab_t
7804 allocate_type_unit_groups_table (struct objfile *objfile)
7805 {
7806   return htab_create_alloc_ex (3,
7807                                hash_type_unit_group,
7808                                eq_type_unit_group,
7809                                NULL,
7810                                &objfile->objfile_obstack,
7811                                hashtab_obstack_allocate,
7812                                dummy_obstack_deallocate);
7813 }
7814
7815 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7816    partial symtabs.  We combine several TUs per psymtab to not let the size
7817    of any one psymtab grow too big.  */
7818 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7819 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7820
7821 /* Helper routine for get_type_unit_group.
7822    Create the type_unit_group object used to hold one or more TUs.  */
7823
7824 static struct type_unit_group *
7825 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7826 {
7827   struct dwarf2_per_objfile *dwarf2_per_objfile
7828     = cu->per_cu->dwarf2_per_objfile;
7829   struct objfile *objfile = dwarf2_per_objfile->objfile;
7830   struct dwarf2_per_cu_data *per_cu;
7831   struct type_unit_group *tu_group;
7832
7833   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7834                              struct type_unit_group);
7835   per_cu = &tu_group->per_cu;
7836   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7837
7838   if (dwarf2_per_objfile->using_index)
7839     {
7840       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7841                                         struct dwarf2_per_cu_quick_data);
7842     }
7843   else
7844     {
7845       unsigned int line_offset = to_underlying (line_offset_struct);
7846       struct partial_symtab *pst;
7847       std::string name;
7848
7849       /* Give the symtab a useful name for debug purposes.  */
7850       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7851         name = string_printf ("<type_units_%d>",
7852                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7853       else
7854         name = string_printf ("<type_units_at_0x%x>", line_offset);
7855
7856       pst = create_partial_symtab (per_cu, name.c_str ());
7857       pst->anonymous = 1;
7858     }
7859
7860   tu_group->hash.dwo_unit = cu->dwo_unit;
7861   tu_group->hash.line_sect_off = line_offset_struct;
7862
7863   return tu_group;
7864 }
7865
7866 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7867    STMT_LIST is a DW_AT_stmt_list attribute.  */
7868
7869 static struct type_unit_group *
7870 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7871 {
7872   struct dwarf2_per_objfile *dwarf2_per_objfile
7873     = cu->per_cu->dwarf2_per_objfile;
7874   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7875   struct type_unit_group *tu_group;
7876   void **slot;
7877   unsigned int line_offset;
7878   struct type_unit_group type_unit_group_for_lookup;
7879
7880   if (dwarf2_per_objfile->type_unit_groups == NULL)
7881     {
7882       dwarf2_per_objfile->type_unit_groups =
7883         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7884     }
7885
7886   /* Do we need to create a new group, or can we use an existing one?  */
7887
7888   if (stmt_list)
7889     {
7890       line_offset = DW_UNSND (stmt_list);
7891       ++tu_stats->nr_symtab_sharers;
7892     }
7893   else
7894     {
7895       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7896          We can do various things here like create one group per TU or
7897          spread them over multiple groups to split up the expansion work.
7898          To avoid worst case scenarios (too many groups or too large groups)
7899          we, umm, group them in bunches.  */
7900       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7901                      | (tu_stats->nr_stmt_less_type_units
7902                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7903       ++tu_stats->nr_stmt_less_type_units;
7904     }
7905
7906   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7907   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7908   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7909                          &type_unit_group_for_lookup, INSERT);
7910   if (*slot != NULL)
7911     {
7912       tu_group = (struct type_unit_group *) *slot;
7913       gdb_assert (tu_group != NULL);
7914     }
7915   else
7916     {
7917       sect_offset line_offset_struct = (sect_offset) line_offset;
7918       tu_group = create_type_unit_group (cu, line_offset_struct);
7919       *slot = tu_group;
7920       ++tu_stats->nr_symtabs;
7921     }
7922
7923   return tu_group;
7924 }
7925 \f
7926 /* Partial symbol tables.  */
7927
7928 /* Create a psymtab named NAME and assign it to PER_CU.
7929
7930    The caller must fill in the following details:
7931    dirname, textlow, texthigh.  */
7932
7933 static struct partial_symtab *
7934 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7935 {
7936   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7937   struct partial_symtab *pst;
7938
7939   pst = start_psymtab_common (objfile, name, 0);
7940
7941   pst->psymtabs_addrmap_supported = 1;
7942
7943   /* This is the glue that links PST into GDB's symbol API.  */
7944   pst->read_symtab_private = per_cu;
7945   pst->read_symtab = dwarf2_read_symtab;
7946   per_cu->v.psymtab = pst;
7947
7948   return pst;
7949 }
7950
7951 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7952    type.  */
7953
7954 struct process_psymtab_comp_unit_data
7955 {
7956   /* True if we are reading a DW_TAG_partial_unit.  */
7957
7958   int want_partial_unit;
7959
7960   /* The "pretend" language that is used if the CU doesn't declare a
7961      language.  */
7962
7963   enum language pretend_language;
7964 };
7965
7966 /* die_reader_func for process_psymtab_comp_unit.  */
7967
7968 static void
7969 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7970                                   const gdb_byte *info_ptr,
7971                                   struct die_info *comp_unit_die,
7972                                   int has_children,
7973                                   void *data)
7974 {
7975   struct dwarf2_cu *cu = reader->cu;
7976   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7977   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7978   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7979   CORE_ADDR baseaddr;
7980   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7981   struct partial_symtab *pst;
7982   enum pc_bounds_kind cu_bounds_kind;
7983   const char *filename;
7984   struct process_psymtab_comp_unit_data *info
7985     = (struct process_psymtab_comp_unit_data *) data;
7986
7987   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7988     return;
7989
7990   gdb_assert (! per_cu->is_debug_types);
7991
7992   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7993
7994   /* Allocate a new partial symbol table structure.  */
7995   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7996   if (filename == NULL)
7997     filename = "";
7998
7999   pst = create_partial_symtab (per_cu, filename);
8000
8001   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8002   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8003
8004   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8005
8006   dwarf2_find_base_address (comp_unit_die, cu);
8007
8008   /* Possibly set the default values of LOWPC and HIGHPC from
8009      `DW_AT_ranges'.  */
8010   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8011                                          &best_highpc, cu, pst);
8012   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8013     {
8014       CORE_ADDR low
8015         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
8016            - baseaddr);
8017       CORE_ADDR high
8018         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
8019            - baseaddr - 1);
8020       /* Store the contiguous range if it is not empty; it can be
8021          empty for CUs with no code.  */
8022       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8023                          low, high, pst);
8024     }
8025
8026   /* Check if comp unit has_children.
8027      If so, read the rest of the partial symbols from this comp unit.
8028      If not, there's no more debug_info for this comp unit.  */
8029   if (has_children)
8030     {
8031       struct partial_die_info *first_die;
8032       CORE_ADDR lowpc, highpc;
8033
8034       lowpc = ((CORE_ADDR) -1);
8035       highpc = ((CORE_ADDR) 0);
8036
8037       first_die = load_partial_dies (reader, info_ptr, 1);
8038
8039       scan_partial_symbols (first_die, &lowpc, &highpc,
8040                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8041
8042       /* If we didn't find a lowpc, set it to highpc to avoid
8043          complaints from `maint check'.  */
8044       if (lowpc == ((CORE_ADDR) -1))
8045         lowpc = highpc;
8046
8047       /* If the compilation unit didn't have an explicit address range,
8048          then use the information extracted from its child dies.  */
8049       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8050         {
8051           best_lowpc = lowpc;
8052           best_highpc = highpc;
8053         }
8054     }
8055   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
8056                                                  best_lowpc + baseaddr)
8057                      - baseaddr);
8058   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
8059                                                   best_highpc + baseaddr)
8060                       - baseaddr);
8061
8062   end_psymtab_common (objfile, pst);
8063
8064   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8065     {
8066       int i;
8067       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8068       struct dwarf2_per_cu_data *iter;
8069
8070       /* Fill in 'dependencies' here; we fill in 'users' in a
8071          post-pass.  */
8072       pst->number_of_dependencies = len;
8073       pst->dependencies
8074         = objfile->partial_symtabs->allocate_dependencies (len);
8075       for (i = 0;
8076            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8077                         i, iter);
8078            ++i)
8079         pst->dependencies[i] = iter->v.psymtab;
8080
8081       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8082     }
8083
8084   /* Get the list of files included in the current compilation unit,
8085      and build a psymtab for each of them.  */
8086   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8087
8088   if (dwarf_read_debug)
8089     fprintf_unfiltered (gdb_stdlog,
8090                         "Psymtab for %s unit @%s: %s - %s"
8091                         ", %d global, %d static syms\n",
8092                         per_cu->is_debug_types ? "type" : "comp",
8093                         sect_offset_str (per_cu->sect_off),
8094                         paddress (gdbarch, pst->text_low (objfile)),
8095                         paddress (gdbarch, pst->text_high (objfile)),
8096                         pst->n_global_syms, pst->n_static_syms);
8097 }
8098
8099 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8100    Process compilation unit THIS_CU for a psymtab.  */
8101
8102 static void
8103 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8104                            int want_partial_unit,
8105                            enum language pretend_language)
8106 {
8107   /* If this compilation unit was already read in, free the
8108      cached copy in order to read it in again.  This is
8109      necessary because we skipped some symbols when we first
8110      read in the compilation unit (see load_partial_dies).
8111      This problem could be avoided, but the benefit is unclear.  */
8112   if (this_cu->cu != NULL)
8113     free_one_cached_comp_unit (this_cu);
8114
8115   if (this_cu->is_debug_types)
8116     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8117                              build_type_psymtabs_reader, NULL);
8118   else
8119     {
8120       process_psymtab_comp_unit_data info;
8121       info.want_partial_unit = want_partial_unit;
8122       info.pretend_language = pretend_language;
8123       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8124                                process_psymtab_comp_unit_reader, &info);
8125     }
8126
8127   /* Age out any secondary CUs.  */
8128   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8129 }
8130
8131 /* Reader function for build_type_psymtabs.  */
8132
8133 static void
8134 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8135                             const gdb_byte *info_ptr,
8136                             struct die_info *type_unit_die,
8137                             int has_children,
8138                             void *data)
8139 {
8140   struct dwarf2_per_objfile *dwarf2_per_objfile
8141     = reader->cu->per_cu->dwarf2_per_objfile;
8142   struct objfile *objfile = dwarf2_per_objfile->objfile;
8143   struct dwarf2_cu *cu = reader->cu;
8144   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8145   struct signatured_type *sig_type;
8146   struct type_unit_group *tu_group;
8147   struct attribute *attr;
8148   struct partial_die_info *first_die;
8149   CORE_ADDR lowpc, highpc;
8150   struct partial_symtab *pst;
8151
8152   gdb_assert (data == NULL);
8153   gdb_assert (per_cu->is_debug_types);
8154   sig_type = (struct signatured_type *) per_cu;
8155
8156   if (! has_children)
8157     return;
8158
8159   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8160   tu_group = get_type_unit_group (cu, attr);
8161
8162   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8163
8164   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8165   pst = create_partial_symtab (per_cu, "");
8166   pst->anonymous = 1;
8167
8168   first_die = load_partial_dies (reader, info_ptr, 1);
8169
8170   lowpc = (CORE_ADDR) -1;
8171   highpc = (CORE_ADDR) 0;
8172   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8173
8174   end_psymtab_common (objfile, pst);
8175 }
8176
8177 /* Struct used to sort TUs by their abbreviation table offset.  */
8178
8179 struct tu_abbrev_offset
8180 {
8181   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8182   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8183   {}
8184
8185   signatured_type *sig_type;
8186   sect_offset abbrev_offset;
8187 };
8188
8189 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8190
8191 static bool
8192 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8193                           const struct tu_abbrev_offset &b)
8194 {
8195   return a.abbrev_offset < b.abbrev_offset;
8196 }
8197
8198 /* Efficiently read all the type units.
8199    This does the bulk of the work for build_type_psymtabs.
8200
8201    The efficiency is because we sort TUs by the abbrev table they use and
8202    only read each abbrev table once.  In one program there are 200K TUs
8203    sharing 8K abbrev tables.
8204
8205    The main purpose of this function is to support building the
8206    dwarf2_per_objfile->type_unit_groups table.
8207    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8208    can collapse the search space by grouping them by stmt_list.
8209    The savings can be significant, in the same program from above the 200K TUs
8210    share 8K stmt_list tables.
8211
8212    FUNC is expected to call get_type_unit_group, which will create the
8213    struct type_unit_group if necessary and add it to
8214    dwarf2_per_objfile->type_unit_groups.  */
8215
8216 static void
8217 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8218 {
8219   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8220   abbrev_table_up abbrev_table;
8221   sect_offset abbrev_offset;
8222
8223   /* It's up to the caller to not call us multiple times.  */
8224   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8225
8226   if (dwarf2_per_objfile->all_type_units.empty ())
8227     return;
8228
8229   /* TUs typically share abbrev tables, and there can be way more TUs than
8230      abbrev tables.  Sort by abbrev table to reduce the number of times we
8231      read each abbrev table in.
8232      Alternatives are to punt or to maintain a cache of abbrev tables.
8233      This is simpler and efficient enough for now.
8234
8235      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8236      symtab to use).  Typically TUs with the same abbrev offset have the same
8237      stmt_list value too so in practice this should work well.
8238
8239      The basic algorithm here is:
8240
8241       sort TUs by abbrev table
8242       for each TU with same abbrev table:
8243         read abbrev table if first user
8244         read TU top level DIE
8245           [IWBN if DWO skeletons had DW_AT_stmt_list]
8246         call FUNC  */
8247
8248   if (dwarf_read_debug)
8249     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8250
8251   /* Sort in a separate table to maintain the order of all_type_units
8252      for .gdb_index: TU indices directly index all_type_units.  */
8253   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8254   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8255
8256   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8257     sorted_by_abbrev.emplace_back
8258       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8259                                      sig_type->per_cu.section,
8260                                      sig_type->per_cu.sect_off));
8261
8262   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8263              sort_tu_by_abbrev_offset);
8264
8265   abbrev_offset = (sect_offset) ~(unsigned) 0;
8266
8267   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8268     {
8269       /* Switch to the next abbrev table if necessary.  */
8270       if (abbrev_table == NULL
8271           || tu.abbrev_offset != abbrev_offset)
8272         {
8273           abbrev_offset = tu.abbrev_offset;
8274           abbrev_table =
8275             abbrev_table_read_table (dwarf2_per_objfile,
8276                                      &dwarf2_per_objfile->abbrev,
8277                                      abbrev_offset);
8278           ++tu_stats->nr_uniq_abbrev_tables;
8279         }
8280
8281       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8282                                0, 0, false, build_type_psymtabs_reader, NULL);
8283     }
8284 }
8285
8286 /* Print collected type unit statistics.  */
8287
8288 static void
8289 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8290 {
8291   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8292
8293   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8294   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8295                       dwarf2_per_objfile->all_type_units.size ());
8296   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8297                       tu_stats->nr_uniq_abbrev_tables);
8298   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8299                       tu_stats->nr_symtabs);
8300   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8301                       tu_stats->nr_symtab_sharers);
8302   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8303                       tu_stats->nr_stmt_less_type_units);
8304   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8305                       tu_stats->nr_all_type_units_reallocs);
8306 }
8307
8308 /* Traversal function for build_type_psymtabs.  */
8309
8310 static int
8311 build_type_psymtab_dependencies (void **slot, void *info)
8312 {
8313   struct dwarf2_per_objfile *dwarf2_per_objfile
8314     = (struct dwarf2_per_objfile *) info;
8315   struct objfile *objfile = dwarf2_per_objfile->objfile;
8316   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8317   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8318   struct partial_symtab *pst = per_cu->v.psymtab;
8319   int len = VEC_length (sig_type_ptr, tu_group->tus);
8320   struct signatured_type *iter;
8321   int i;
8322
8323   gdb_assert (len > 0);
8324   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8325
8326   pst->number_of_dependencies = len;
8327   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
8328   for (i = 0;
8329        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8330        ++i)
8331     {
8332       gdb_assert (iter->per_cu.is_debug_types);
8333       pst->dependencies[i] = iter->per_cu.v.psymtab;
8334       iter->type_unit_group = tu_group;
8335     }
8336
8337   VEC_free (sig_type_ptr, tu_group->tus);
8338
8339   return 1;
8340 }
8341
8342 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8343    Build partial symbol tables for the .debug_types comp-units.  */
8344
8345 static void
8346 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8347 {
8348   if (! create_all_type_units (dwarf2_per_objfile))
8349     return;
8350
8351   build_type_psymtabs_1 (dwarf2_per_objfile);
8352 }
8353
8354 /* Traversal function for process_skeletonless_type_unit.
8355    Read a TU in a DWO file and build partial symbols for it.  */
8356
8357 static int
8358 process_skeletonless_type_unit (void **slot, void *info)
8359 {
8360   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8361   struct dwarf2_per_objfile *dwarf2_per_objfile
8362     = (struct dwarf2_per_objfile *) info;
8363   struct signatured_type find_entry, *entry;
8364
8365   /* If this TU doesn't exist in the global table, add it and read it in.  */
8366
8367   if (dwarf2_per_objfile->signatured_types == NULL)
8368     {
8369       dwarf2_per_objfile->signatured_types
8370         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8371     }
8372
8373   find_entry.signature = dwo_unit->signature;
8374   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8375                          INSERT);
8376   /* If we've already seen this type there's nothing to do.  What's happening
8377      is we're doing our own version of comdat-folding here.  */
8378   if (*slot != NULL)
8379     return 1;
8380
8381   /* This does the job that create_all_type_units would have done for
8382      this TU.  */
8383   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8384   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8385   *slot = entry;
8386
8387   /* This does the job that build_type_psymtabs_1 would have done.  */
8388   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8389                            build_type_psymtabs_reader, NULL);
8390
8391   return 1;
8392 }
8393
8394 /* Traversal function for process_skeletonless_type_units.  */
8395
8396 static int
8397 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8398 {
8399   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8400
8401   if (dwo_file->tus != NULL)
8402     {
8403       htab_traverse_noresize (dwo_file->tus,
8404                               process_skeletonless_type_unit, info);
8405     }
8406
8407   return 1;
8408 }
8409
8410 /* Scan all TUs of DWO files, verifying we've processed them.
8411    This is needed in case a TU was emitted without its skeleton.
8412    Note: This can't be done until we know what all the DWO files are.  */
8413
8414 static void
8415 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8416 {
8417   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8418   if (get_dwp_file (dwarf2_per_objfile) == NULL
8419       && dwarf2_per_objfile->dwo_files != NULL)
8420     {
8421       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8422                               process_dwo_file_for_skeletonless_type_units,
8423                               dwarf2_per_objfile);
8424     }
8425 }
8426
8427 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8428
8429 static void
8430 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8431 {
8432   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8433     {
8434       struct partial_symtab *pst = per_cu->v.psymtab;
8435
8436       if (pst == NULL)
8437         continue;
8438
8439       for (int j = 0; j < pst->number_of_dependencies; ++j)
8440         {
8441           /* Set the 'user' field only if it is not already set.  */
8442           if (pst->dependencies[j]->user == NULL)
8443             pst->dependencies[j]->user = pst;
8444         }
8445     }
8446 }
8447
8448 /* Build the partial symbol table by doing a quick pass through the
8449    .debug_info and .debug_abbrev sections.  */
8450
8451 static void
8452 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8453 {
8454   struct objfile *objfile = dwarf2_per_objfile->objfile;
8455
8456   if (dwarf_read_debug)
8457     {
8458       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8459                           objfile_name (objfile));
8460     }
8461
8462   dwarf2_per_objfile->reading_partial_symbols = 1;
8463
8464   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8465
8466   /* Any cached compilation units will be linked by the per-objfile
8467      read_in_chain.  Make sure to free them when we're done.  */
8468   free_cached_comp_units freer (dwarf2_per_objfile);
8469
8470   build_type_psymtabs (dwarf2_per_objfile);
8471
8472   create_all_comp_units (dwarf2_per_objfile);
8473
8474   /* Create a temporary address map on a temporary obstack.  We later
8475      copy this to the final obstack.  */
8476   auto_obstack temp_obstack;
8477
8478   scoped_restore save_psymtabs_addrmap
8479     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
8480                            addrmap_create_mutable (&temp_obstack));
8481
8482   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8483     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8484
8485   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8486   process_skeletonless_type_units (dwarf2_per_objfile);
8487
8488   /* Now that all TUs have been processed we can fill in the dependencies.  */
8489   if (dwarf2_per_objfile->type_unit_groups != NULL)
8490     {
8491       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8492                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8493     }
8494
8495   if (dwarf_read_debug)
8496     print_tu_stats (dwarf2_per_objfile);
8497
8498   set_partial_user (dwarf2_per_objfile);
8499
8500   objfile->partial_symtabs->psymtabs_addrmap
8501     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
8502                             objfile->partial_symtabs->obstack ());
8503   /* At this point we want to keep the address map.  */
8504   save_psymtabs_addrmap.release ();
8505
8506   if (dwarf_read_debug)
8507     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8508                         objfile_name (objfile));
8509 }
8510
8511 /* die_reader_func for load_partial_comp_unit.  */
8512
8513 static void
8514 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8515                                const gdb_byte *info_ptr,
8516                                struct die_info *comp_unit_die,
8517                                int has_children,
8518                                void *data)
8519 {
8520   struct dwarf2_cu *cu = reader->cu;
8521
8522   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8523
8524   /* Check if comp unit has_children.
8525      If so, read the rest of the partial symbols from this comp unit.
8526      If not, there's no more debug_info for this comp unit.  */
8527   if (has_children)
8528     load_partial_dies (reader, info_ptr, 0);
8529 }
8530
8531 /* Load the partial DIEs for a secondary CU into memory.
8532    This is also used when rereading a primary CU with load_all_dies.  */
8533
8534 static void
8535 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8536 {
8537   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8538                            load_partial_comp_unit_reader, NULL);
8539 }
8540
8541 static void
8542 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8543                               struct dwarf2_section_info *section,
8544                               struct dwarf2_section_info *abbrev_section,
8545                               unsigned int is_dwz)
8546 {
8547   const gdb_byte *info_ptr;
8548   struct objfile *objfile = dwarf2_per_objfile->objfile;
8549
8550   if (dwarf_read_debug)
8551     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8552                         get_section_name (section),
8553                         get_section_file_name (section));
8554
8555   dwarf2_read_section (objfile, section);
8556
8557   info_ptr = section->buffer;
8558
8559   while (info_ptr < section->buffer + section->size)
8560     {
8561       struct dwarf2_per_cu_data *this_cu;
8562
8563       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8564
8565       comp_unit_head cu_header;
8566       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8567                                      abbrev_section, info_ptr,
8568                                      rcuh_kind::COMPILE);
8569
8570       /* Save the compilation unit for later lookup.  */
8571       if (cu_header.unit_type != DW_UT_type)
8572         {
8573           this_cu = XOBNEW (&objfile->objfile_obstack,
8574                             struct dwarf2_per_cu_data);
8575           memset (this_cu, 0, sizeof (*this_cu));
8576         }
8577       else
8578         {
8579           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8580                                   struct signatured_type);
8581           memset (sig_type, 0, sizeof (*sig_type));
8582           sig_type->signature = cu_header.signature;
8583           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8584           this_cu = &sig_type->per_cu;
8585         }
8586       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8587       this_cu->sect_off = sect_off;
8588       this_cu->length = cu_header.length + cu_header.initial_length_size;
8589       this_cu->is_dwz = is_dwz;
8590       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8591       this_cu->section = section;
8592
8593       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8594
8595       info_ptr = info_ptr + this_cu->length;
8596     }
8597 }
8598
8599 /* Create a list of all compilation units in OBJFILE.
8600    This is only done for -readnow and building partial symtabs.  */
8601
8602 static void
8603 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8604 {
8605   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8606   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8607                                 &dwarf2_per_objfile->abbrev, 0);
8608
8609   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8610   if (dwz != NULL)
8611     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8612                                   1);
8613 }
8614
8615 /* Process all loaded DIEs for compilation unit CU, starting at
8616    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8617    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8618    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8619    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8620
8621 static void
8622 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8623                       CORE_ADDR *highpc, int set_addrmap,
8624                       struct dwarf2_cu *cu)
8625 {
8626   struct partial_die_info *pdi;
8627
8628   /* Now, march along the PDI's, descending into ones which have
8629      interesting children but skipping the children of the other ones,
8630      until we reach the end of the compilation unit.  */
8631
8632   pdi = first_die;
8633
8634   while (pdi != NULL)
8635     {
8636       pdi->fixup (cu);
8637
8638       /* Anonymous namespaces or modules have no name but have interesting
8639          children, so we need to look at them.  Ditto for anonymous
8640          enums.  */
8641
8642       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8643           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8644           || pdi->tag == DW_TAG_imported_unit
8645           || pdi->tag == DW_TAG_inlined_subroutine)
8646         {
8647           switch (pdi->tag)
8648             {
8649             case DW_TAG_subprogram:
8650             case DW_TAG_inlined_subroutine:
8651               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8652               break;
8653             case DW_TAG_constant:
8654             case DW_TAG_variable:
8655             case DW_TAG_typedef:
8656             case DW_TAG_union_type:
8657               if (!pdi->is_declaration)
8658                 {
8659                   add_partial_symbol (pdi, cu);
8660                 }
8661               break;
8662             case DW_TAG_class_type:
8663             case DW_TAG_interface_type:
8664             case DW_TAG_structure_type:
8665               if (!pdi->is_declaration)
8666                 {
8667                   add_partial_symbol (pdi, cu);
8668                 }
8669               if ((cu->language == language_rust
8670                    || cu->language == language_cplus) && pdi->has_children)
8671                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8672                                       set_addrmap, cu);
8673               break;
8674             case DW_TAG_enumeration_type:
8675               if (!pdi->is_declaration)
8676                 add_partial_enumeration (pdi, cu);
8677               break;
8678             case DW_TAG_base_type:
8679             case DW_TAG_subrange_type:
8680               /* File scope base type definitions are added to the partial
8681                  symbol table.  */
8682               add_partial_symbol (pdi, cu);
8683               break;
8684             case DW_TAG_namespace:
8685               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8686               break;
8687             case DW_TAG_module:
8688               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8689               break;
8690             case DW_TAG_imported_unit:
8691               {
8692                 struct dwarf2_per_cu_data *per_cu;
8693
8694                 /* For now we don't handle imported units in type units.  */
8695                 if (cu->per_cu->is_debug_types)
8696                   {
8697                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8698                              " supported in type units [in module %s]"),
8699                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8700                   }
8701
8702                 per_cu = dwarf2_find_containing_comp_unit
8703                            (pdi->d.sect_off, pdi->is_dwz,
8704                             cu->per_cu->dwarf2_per_objfile);
8705
8706                 /* Go read the partial unit, if needed.  */
8707                 if (per_cu->v.psymtab == NULL)
8708                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8709
8710                 VEC_safe_push (dwarf2_per_cu_ptr,
8711                                cu->per_cu->imported_symtabs, per_cu);
8712               }
8713               break;
8714             case DW_TAG_imported_declaration:
8715               add_partial_symbol (pdi, cu);
8716               break;
8717             default:
8718               break;
8719             }
8720         }
8721
8722       /* If the die has a sibling, skip to the sibling.  */
8723
8724       pdi = pdi->die_sibling;
8725     }
8726 }
8727
8728 /* Functions used to compute the fully scoped name of a partial DIE.
8729
8730    Normally, this is simple.  For C++, the parent DIE's fully scoped
8731    name is concatenated with "::" and the partial DIE's name.
8732    Enumerators are an exception; they use the scope of their parent
8733    enumeration type, i.e. the name of the enumeration type is not
8734    prepended to the enumerator.
8735
8736    There are two complexities.  One is DW_AT_specification; in this
8737    case "parent" means the parent of the target of the specification,
8738    instead of the direct parent of the DIE.  The other is compilers
8739    which do not emit DW_TAG_namespace; in this case we try to guess
8740    the fully qualified name of structure types from their members'
8741    linkage names.  This must be done using the DIE's children rather
8742    than the children of any DW_AT_specification target.  We only need
8743    to do this for structures at the top level, i.e. if the target of
8744    any DW_AT_specification (if any; otherwise the DIE itself) does not
8745    have a parent.  */
8746
8747 /* Compute the scope prefix associated with PDI's parent, in
8748    compilation unit CU.  The result will be allocated on CU's
8749    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8750    field.  NULL is returned if no prefix is necessary.  */
8751 static const char *
8752 partial_die_parent_scope (struct partial_die_info *pdi,
8753                           struct dwarf2_cu *cu)
8754 {
8755   const char *grandparent_scope;
8756   struct partial_die_info *parent, *real_pdi;
8757
8758   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8759      then this means the parent of the specification DIE.  */
8760
8761   real_pdi = pdi;
8762   while (real_pdi->has_specification)
8763     real_pdi = find_partial_die (real_pdi->spec_offset,
8764                                  real_pdi->spec_is_dwz, cu);
8765
8766   parent = real_pdi->die_parent;
8767   if (parent == NULL)
8768     return NULL;
8769
8770   if (parent->scope_set)
8771     return parent->scope;
8772
8773   parent->fixup (cu);
8774
8775   grandparent_scope = partial_die_parent_scope (parent, cu);
8776
8777   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8778      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8779      Work around this problem here.  */
8780   if (cu->language == language_cplus
8781       && parent->tag == DW_TAG_namespace
8782       && strcmp (parent->name, "::") == 0
8783       && grandparent_scope == NULL)
8784     {
8785       parent->scope = NULL;
8786       parent->scope_set = 1;
8787       return NULL;
8788     }
8789
8790   if (pdi->tag == DW_TAG_enumerator)
8791     /* Enumerators should not get the name of the enumeration as a prefix.  */
8792     parent->scope = grandparent_scope;
8793   else if (parent->tag == DW_TAG_namespace
8794       || parent->tag == DW_TAG_module
8795       || parent->tag == DW_TAG_structure_type
8796       || parent->tag == DW_TAG_class_type
8797       || parent->tag == DW_TAG_interface_type
8798       || parent->tag == DW_TAG_union_type
8799       || parent->tag == DW_TAG_enumeration_type)
8800     {
8801       if (grandparent_scope == NULL)
8802         parent->scope = parent->name;
8803       else
8804         parent->scope = typename_concat (&cu->comp_unit_obstack,
8805                                          grandparent_scope,
8806                                          parent->name, 0, cu);
8807     }
8808   else
8809     {
8810       /* FIXME drow/2004-04-01: What should we be doing with
8811          function-local names?  For partial symbols, we should probably be
8812          ignoring them.  */
8813       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8814                  parent->tag, sect_offset_str (pdi->sect_off));
8815       parent->scope = grandparent_scope;
8816     }
8817
8818   parent->scope_set = 1;
8819   return parent->scope;
8820 }
8821
8822 /* Return the fully scoped name associated with PDI, from compilation unit
8823    CU.  The result will be allocated with malloc.  */
8824
8825 static char *
8826 partial_die_full_name (struct partial_die_info *pdi,
8827                        struct dwarf2_cu *cu)
8828 {
8829   const char *parent_scope;
8830
8831   /* If this is a template instantiation, we can not work out the
8832      template arguments from partial DIEs.  So, unfortunately, we have
8833      to go through the full DIEs.  At least any work we do building
8834      types here will be reused if full symbols are loaded later.  */
8835   if (pdi->has_template_arguments)
8836     {
8837       pdi->fixup (cu);
8838
8839       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8840         {
8841           struct die_info *die;
8842           struct attribute attr;
8843           struct dwarf2_cu *ref_cu = cu;
8844
8845           /* DW_FORM_ref_addr is using section offset.  */
8846           attr.name = (enum dwarf_attribute) 0;
8847           attr.form = DW_FORM_ref_addr;
8848           attr.u.unsnd = to_underlying (pdi->sect_off);
8849           die = follow_die_ref (NULL, &attr, &ref_cu);
8850
8851           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8852         }
8853     }
8854
8855   parent_scope = partial_die_parent_scope (pdi, cu);
8856   if (parent_scope == NULL)
8857     return NULL;
8858   else
8859     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8860 }
8861
8862 static void
8863 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8864 {
8865   struct dwarf2_per_objfile *dwarf2_per_objfile
8866     = cu->per_cu->dwarf2_per_objfile;
8867   struct objfile *objfile = dwarf2_per_objfile->objfile;
8868   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8869   CORE_ADDR addr = 0;
8870   const char *actual_name = NULL;
8871   CORE_ADDR baseaddr;
8872   char *built_actual_name;
8873
8874   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8875
8876   built_actual_name = partial_die_full_name (pdi, cu);
8877   if (built_actual_name != NULL)
8878     actual_name = built_actual_name;
8879
8880   if (actual_name == NULL)
8881     actual_name = pdi->name;
8882
8883   switch (pdi->tag)
8884     {
8885     case DW_TAG_inlined_subroutine:
8886     case DW_TAG_subprogram:
8887       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8888               - baseaddr);
8889       if (pdi->is_external || cu->language == language_ada)
8890         {
8891           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8892              of the global scope.  But in Ada, we want to be able to access
8893              nested procedures globally.  So all Ada subprograms are stored
8894              in the global scope.  */
8895           add_psymbol_to_list (actual_name, strlen (actual_name),
8896                                built_actual_name != NULL,
8897                                VAR_DOMAIN, LOC_BLOCK,
8898                                SECT_OFF_TEXT (objfile),
8899                                psymbol_placement::GLOBAL,
8900                                addr,
8901                                cu->language, objfile);
8902         }
8903       else
8904         {
8905           add_psymbol_to_list (actual_name, strlen (actual_name),
8906                                built_actual_name != NULL,
8907                                VAR_DOMAIN, LOC_BLOCK,
8908                                SECT_OFF_TEXT (objfile),
8909                                psymbol_placement::STATIC,
8910                                addr, cu->language, objfile);
8911         }
8912
8913       if (pdi->main_subprogram && actual_name != NULL)
8914         set_objfile_main_name (objfile, actual_name, cu->language);
8915       break;
8916     case DW_TAG_constant:
8917       add_psymbol_to_list (actual_name, strlen (actual_name),
8918                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8919                            -1, (pdi->is_external
8920                                 ? psymbol_placement::GLOBAL
8921                                 : psymbol_placement::STATIC),
8922                            0, cu->language, objfile);
8923       break;
8924     case DW_TAG_variable:
8925       if (pdi->d.locdesc)
8926         addr = decode_locdesc (pdi->d.locdesc, cu);
8927
8928       if (pdi->d.locdesc
8929           && addr == 0
8930           && !dwarf2_per_objfile->has_section_at_zero)
8931         {
8932           /* A global or static variable may also have been stripped
8933              out by the linker if unused, in which case its address
8934              will be nullified; do not add such variables into partial
8935              symbol table then.  */
8936         }
8937       else if (pdi->is_external)
8938         {
8939           /* Global Variable.
8940              Don't enter into the minimal symbol tables as there is
8941              a minimal symbol table entry from the ELF symbols already.
8942              Enter into partial symbol table if it has a location
8943              descriptor or a type.
8944              If the location descriptor is missing, new_symbol will create
8945              a LOC_UNRESOLVED symbol, the address of the variable will then
8946              be determined from the minimal symbol table whenever the variable
8947              is referenced.
8948              The address for the partial symbol table entry is not
8949              used by GDB, but it comes in handy for debugging partial symbol
8950              table building.  */
8951
8952           if (pdi->d.locdesc || pdi->has_type)
8953             add_psymbol_to_list (actual_name, strlen (actual_name),
8954                                  built_actual_name != NULL,
8955                                  VAR_DOMAIN, LOC_STATIC,
8956                                  SECT_OFF_TEXT (objfile),
8957                                  psymbol_placement::GLOBAL,
8958                                  addr, cu->language, objfile);
8959         }
8960       else
8961         {
8962           int has_loc = pdi->d.locdesc != NULL;
8963
8964           /* Static Variable.  Skip symbols whose value we cannot know (those
8965              without location descriptors or constant values).  */
8966           if (!has_loc && !pdi->has_const_value)
8967             {
8968               xfree (built_actual_name);
8969               return;
8970             }
8971
8972           add_psymbol_to_list (actual_name, strlen (actual_name),
8973                                built_actual_name != NULL,
8974                                VAR_DOMAIN, LOC_STATIC,
8975                                SECT_OFF_TEXT (objfile),
8976                                psymbol_placement::STATIC,
8977                                has_loc ? addr : 0,
8978                                cu->language, objfile);
8979         }
8980       break;
8981     case DW_TAG_typedef:
8982     case DW_TAG_base_type:
8983     case DW_TAG_subrange_type:
8984       add_psymbol_to_list (actual_name, strlen (actual_name),
8985                            built_actual_name != NULL,
8986                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8987                            psymbol_placement::STATIC,
8988                            0, cu->language, objfile);
8989       break;
8990     case DW_TAG_imported_declaration:
8991     case DW_TAG_namespace:
8992       add_psymbol_to_list (actual_name, strlen (actual_name),
8993                            built_actual_name != NULL,
8994                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8995                            psymbol_placement::GLOBAL,
8996                            0, cu->language, objfile);
8997       break;
8998     case DW_TAG_module:
8999       add_psymbol_to_list (actual_name, strlen (actual_name),
9000                            built_actual_name != NULL,
9001                            MODULE_DOMAIN, LOC_TYPEDEF, -1,
9002                            psymbol_placement::GLOBAL,
9003                            0, cu->language, objfile);
9004       break;
9005     case DW_TAG_class_type:
9006     case DW_TAG_interface_type:
9007     case DW_TAG_structure_type:
9008     case DW_TAG_union_type:
9009     case DW_TAG_enumeration_type:
9010       /* Skip external references.  The DWARF standard says in the section
9011          about "Structure, Union, and Class Type Entries": "An incomplete
9012          structure, union or class type is represented by a structure,
9013          union or class entry that does not have a byte size attribute
9014          and that has a DW_AT_declaration attribute."  */
9015       if (!pdi->has_byte_size && pdi->is_declaration)
9016         {
9017           xfree (built_actual_name);
9018           return;
9019         }
9020
9021       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9022          static vs. global.  */
9023       add_psymbol_to_list (actual_name, strlen (actual_name),
9024                            built_actual_name != NULL,
9025                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
9026                            cu->language == language_cplus
9027                            ? psymbol_placement::GLOBAL
9028                            : psymbol_placement::STATIC,
9029                            0, cu->language, objfile);
9030
9031       break;
9032     case DW_TAG_enumerator:
9033       add_psymbol_to_list (actual_name, strlen (actual_name),
9034                            built_actual_name != NULL,
9035                            VAR_DOMAIN, LOC_CONST, -1,
9036                            cu->language == language_cplus
9037                            ? psymbol_placement::GLOBAL
9038                            : psymbol_placement::STATIC,
9039                            0, cu->language, objfile);
9040       break;
9041     default:
9042       break;
9043     }
9044
9045   xfree (built_actual_name);
9046 }
9047
9048 /* Read a partial die corresponding to a namespace; also, add a symbol
9049    corresponding to that namespace to the symbol table.  NAMESPACE is
9050    the name of the enclosing namespace.  */
9051
9052 static void
9053 add_partial_namespace (struct partial_die_info *pdi,
9054                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9055                        int set_addrmap, struct dwarf2_cu *cu)
9056 {
9057   /* Add a symbol for the namespace.  */
9058
9059   add_partial_symbol (pdi, cu);
9060
9061   /* Now scan partial symbols in that namespace.  */
9062
9063   if (pdi->has_children)
9064     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9065 }
9066
9067 /* Read a partial die corresponding to a Fortran module.  */
9068
9069 static void
9070 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9071                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9072 {
9073   /* Add a symbol for the namespace.  */
9074
9075   add_partial_symbol (pdi, cu);
9076
9077   /* Now scan partial symbols in that module.  */
9078
9079   if (pdi->has_children)
9080     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9081 }
9082
9083 /* Read a partial die corresponding to a subprogram or an inlined
9084    subprogram and create a partial symbol for that subprogram.
9085    When the CU language allows it, this routine also defines a partial
9086    symbol for each nested subprogram that this subprogram contains.
9087    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9088    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9089
9090    PDI may also be a lexical block, in which case we simply search
9091    recursively for subprograms defined inside that lexical block.
9092    Again, this is only performed when the CU language allows this
9093    type of definitions.  */
9094
9095 static void
9096 add_partial_subprogram (struct partial_die_info *pdi,
9097                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9098                         int set_addrmap, struct dwarf2_cu *cu)
9099 {
9100   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9101     {
9102       if (pdi->has_pc_info)
9103         {
9104           if (pdi->lowpc < *lowpc)
9105             *lowpc = pdi->lowpc;
9106           if (pdi->highpc > *highpc)
9107             *highpc = pdi->highpc;
9108           if (set_addrmap)
9109             {
9110               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9111               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9112               CORE_ADDR baseaddr;
9113               CORE_ADDR this_highpc;
9114               CORE_ADDR this_lowpc;
9115
9116               baseaddr = ANOFFSET (objfile->section_offsets,
9117                                    SECT_OFF_TEXT (objfile));
9118               this_lowpc
9119                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9120                                                pdi->lowpc + baseaddr)
9121                    - baseaddr);
9122               this_highpc
9123                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9124                                                pdi->highpc + baseaddr)
9125                    - baseaddr);
9126               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
9127                                  this_lowpc, this_highpc - 1,
9128                                  cu->per_cu->v.psymtab);
9129             }
9130         }
9131
9132       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9133         {
9134           if (!pdi->is_declaration)
9135             /* Ignore subprogram DIEs that do not have a name, they are
9136                illegal.  Do not emit a complaint at this point, we will
9137                do so when we convert this psymtab into a symtab.  */
9138             if (pdi->name)
9139               add_partial_symbol (pdi, cu);
9140         }
9141     }
9142
9143   if (! pdi->has_children)
9144     return;
9145
9146   if (cu->language == language_ada)
9147     {
9148       pdi = pdi->die_child;
9149       while (pdi != NULL)
9150         {
9151           pdi->fixup (cu);
9152           if (pdi->tag == DW_TAG_subprogram
9153               || pdi->tag == DW_TAG_inlined_subroutine
9154               || pdi->tag == DW_TAG_lexical_block)
9155             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9156           pdi = pdi->die_sibling;
9157         }
9158     }
9159 }
9160
9161 /* Read a partial die corresponding to an enumeration type.  */
9162
9163 static void
9164 add_partial_enumeration (struct partial_die_info *enum_pdi,
9165                          struct dwarf2_cu *cu)
9166 {
9167   struct partial_die_info *pdi;
9168
9169   if (enum_pdi->name != NULL)
9170     add_partial_symbol (enum_pdi, cu);
9171
9172   pdi = enum_pdi->die_child;
9173   while (pdi)
9174     {
9175       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9176         complaint (_("malformed enumerator DIE ignored"));
9177       else
9178         add_partial_symbol (pdi, cu);
9179       pdi = pdi->die_sibling;
9180     }
9181 }
9182
9183 /* Return the initial uleb128 in the die at INFO_PTR.  */
9184
9185 static unsigned int
9186 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9187 {
9188   unsigned int bytes_read;
9189
9190   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9191 }
9192
9193 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9194    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9195
9196    Return the corresponding abbrev, or NULL if the number is zero (indicating
9197    an empty DIE).  In either case *BYTES_READ will be set to the length of
9198    the initial number.  */
9199
9200 static struct abbrev_info *
9201 peek_die_abbrev (const die_reader_specs &reader,
9202                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9203 {
9204   dwarf2_cu *cu = reader.cu;
9205   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9206   unsigned int abbrev_number
9207     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9208
9209   if (abbrev_number == 0)
9210     return NULL;
9211
9212   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9213   if (!abbrev)
9214     {
9215       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9216                " at offset %s [in module %s]"),
9217              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9218              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9219     }
9220
9221   return abbrev;
9222 }
9223
9224 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9225    Returns a pointer to the end of a series of DIEs, terminated by an empty
9226    DIE.  Any children of the skipped DIEs will also be skipped.  */
9227
9228 static const gdb_byte *
9229 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9230 {
9231   while (1)
9232     {
9233       unsigned int bytes_read;
9234       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9235
9236       if (abbrev == NULL)
9237         return info_ptr + bytes_read;
9238       else
9239         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9240     }
9241 }
9242
9243 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9244    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9245    abbrev corresponding to that skipped uleb128 should be passed in
9246    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9247    children.  */
9248
9249 static const gdb_byte *
9250 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9251               struct abbrev_info *abbrev)
9252 {
9253   unsigned int bytes_read;
9254   struct attribute attr;
9255   bfd *abfd = reader->abfd;
9256   struct dwarf2_cu *cu = reader->cu;
9257   const gdb_byte *buffer = reader->buffer;
9258   const gdb_byte *buffer_end = reader->buffer_end;
9259   unsigned int form, i;
9260
9261   for (i = 0; i < abbrev->num_attrs; i++)
9262     {
9263       /* The only abbrev we care about is DW_AT_sibling.  */
9264       if (abbrev->attrs[i].name == DW_AT_sibling)
9265         {
9266           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9267           if (attr.form == DW_FORM_ref_addr)
9268             complaint (_("ignoring absolute DW_AT_sibling"));
9269           else
9270             {
9271               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9272               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9273
9274               if (sibling_ptr < info_ptr)
9275                 complaint (_("DW_AT_sibling points backwards"));
9276               else if (sibling_ptr > reader->buffer_end)
9277                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9278               else
9279                 return sibling_ptr;
9280             }
9281         }
9282
9283       /* If it isn't DW_AT_sibling, skip this attribute.  */
9284       form = abbrev->attrs[i].form;
9285     skip_attribute:
9286       switch (form)
9287         {
9288         case DW_FORM_ref_addr:
9289           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9290              and later it is offset sized.  */
9291           if (cu->header.version == 2)
9292             info_ptr += cu->header.addr_size;
9293           else
9294             info_ptr += cu->header.offset_size;
9295           break;
9296         case DW_FORM_GNU_ref_alt:
9297           info_ptr += cu->header.offset_size;
9298           break;
9299         case DW_FORM_addr:
9300           info_ptr += cu->header.addr_size;
9301           break;
9302         case DW_FORM_data1:
9303         case DW_FORM_ref1:
9304         case DW_FORM_flag:
9305           info_ptr += 1;
9306           break;
9307         case DW_FORM_flag_present:
9308         case DW_FORM_implicit_const:
9309           break;
9310         case DW_FORM_data2:
9311         case DW_FORM_ref2:
9312           info_ptr += 2;
9313           break;
9314         case DW_FORM_data4:
9315         case DW_FORM_ref4:
9316           info_ptr += 4;
9317           break;
9318         case DW_FORM_data8:
9319         case DW_FORM_ref8:
9320         case DW_FORM_ref_sig8:
9321           info_ptr += 8;
9322           break;
9323         case DW_FORM_data16:
9324           info_ptr += 16;
9325           break;
9326         case DW_FORM_string:
9327           read_direct_string (abfd, info_ptr, &bytes_read);
9328           info_ptr += bytes_read;
9329           break;
9330         case DW_FORM_sec_offset:
9331         case DW_FORM_strp:
9332         case DW_FORM_GNU_strp_alt:
9333           info_ptr += cu->header.offset_size;
9334           break;
9335         case DW_FORM_exprloc:
9336         case DW_FORM_block:
9337           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9338           info_ptr += bytes_read;
9339           break;
9340         case DW_FORM_block1:
9341           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9342           break;
9343         case DW_FORM_block2:
9344           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9345           break;
9346         case DW_FORM_block4:
9347           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9348           break;
9349         case DW_FORM_addrx:
9350         case DW_FORM_strx:
9351         case DW_FORM_sdata:
9352         case DW_FORM_udata:
9353         case DW_FORM_ref_udata:
9354         case DW_FORM_GNU_addr_index:
9355         case DW_FORM_GNU_str_index:
9356           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9357           break;
9358         case DW_FORM_indirect:
9359           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9360           info_ptr += bytes_read;
9361           /* We need to continue parsing from here, so just go back to
9362              the top.  */
9363           goto skip_attribute;
9364
9365         default:
9366           error (_("Dwarf Error: Cannot handle %s "
9367                    "in DWARF reader [in module %s]"),
9368                  dwarf_form_name (form),
9369                  bfd_get_filename (abfd));
9370         }
9371     }
9372
9373   if (abbrev->has_children)
9374     return skip_children (reader, info_ptr);
9375   else
9376     return info_ptr;
9377 }
9378
9379 /* Locate ORIG_PDI's sibling.
9380    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9381
9382 static const gdb_byte *
9383 locate_pdi_sibling (const struct die_reader_specs *reader,
9384                     struct partial_die_info *orig_pdi,
9385                     const gdb_byte *info_ptr)
9386 {
9387   /* Do we know the sibling already?  */
9388
9389   if (orig_pdi->sibling)
9390     return orig_pdi->sibling;
9391
9392   /* Are there any children to deal with?  */
9393
9394   if (!orig_pdi->has_children)
9395     return info_ptr;
9396
9397   /* Skip the children the long way.  */
9398
9399   return skip_children (reader, info_ptr);
9400 }
9401
9402 /* Expand this partial symbol table into a full symbol table.  SELF is
9403    not NULL.  */
9404
9405 static void
9406 dwarf2_read_symtab (struct partial_symtab *self,
9407                     struct objfile *objfile)
9408 {
9409   struct dwarf2_per_objfile *dwarf2_per_objfile
9410     = get_dwarf2_per_objfile (objfile);
9411
9412   if (self->readin)
9413     {
9414       warning (_("bug: psymtab for %s is already read in."),
9415                self->filename);
9416     }
9417   else
9418     {
9419       if (info_verbose)
9420         {
9421           printf_filtered (_("Reading in symbols for %s..."),
9422                            self->filename);
9423           gdb_flush (gdb_stdout);
9424         }
9425
9426       /* If this psymtab is constructed from a debug-only objfile, the
9427          has_section_at_zero flag will not necessarily be correct.  We
9428          can get the correct value for this flag by looking at the data
9429          associated with the (presumably stripped) associated objfile.  */
9430       if (objfile->separate_debug_objfile_backlink)
9431         {
9432           struct dwarf2_per_objfile *dpo_backlink
9433             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9434
9435           dwarf2_per_objfile->has_section_at_zero
9436             = dpo_backlink->has_section_at_zero;
9437         }
9438
9439       dwarf2_per_objfile->reading_partial_symbols = 0;
9440
9441       psymtab_to_symtab_1 (self);
9442
9443       /* Finish up the debug error message.  */
9444       if (info_verbose)
9445         printf_filtered (_("done.\n"));
9446     }
9447
9448   process_cu_includes (dwarf2_per_objfile);
9449 }
9450 \f
9451 /* Reading in full CUs.  */
9452
9453 /* Add PER_CU to the queue.  */
9454
9455 static void
9456 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9457                  enum language pretend_language)
9458 {
9459   struct dwarf2_queue_item *item;
9460
9461   per_cu->queued = 1;
9462   item = XNEW (struct dwarf2_queue_item);
9463   item->per_cu = per_cu;
9464   item->pretend_language = pretend_language;
9465   item->next = NULL;
9466
9467   if (dwarf2_queue == NULL)
9468     dwarf2_queue = item;
9469   else
9470     dwarf2_queue_tail->next = item;
9471
9472   dwarf2_queue_tail = item;
9473 }
9474
9475 /* If PER_CU is not yet queued, add it to the queue.
9476    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9477    dependency.
9478    The result is non-zero if PER_CU was queued, otherwise the result is zero
9479    meaning either PER_CU is already queued or it is already loaded.
9480
9481    N.B. There is an invariant here that if a CU is queued then it is loaded.
9482    The caller is required to load PER_CU if we return non-zero.  */
9483
9484 static int
9485 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9486                        struct dwarf2_per_cu_data *per_cu,
9487                        enum language pretend_language)
9488 {
9489   /* We may arrive here during partial symbol reading, if we need full
9490      DIEs to process an unusual case (e.g. template arguments).  Do
9491      not queue PER_CU, just tell our caller to load its DIEs.  */
9492   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9493     {
9494       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9495         return 1;
9496       return 0;
9497     }
9498
9499   /* Mark the dependence relation so that we don't flush PER_CU
9500      too early.  */
9501   if (dependent_cu != NULL)
9502     dwarf2_add_dependence (dependent_cu, per_cu);
9503
9504   /* If it's already on the queue, we have nothing to do.  */
9505   if (per_cu->queued)
9506     return 0;
9507
9508   /* If the compilation unit is already loaded, just mark it as
9509      used.  */
9510   if (per_cu->cu != NULL)
9511     {
9512       per_cu->cu->last_used = 0;
9513       return 0;
9514     }
9515
9516   /* Add it to the queue.  */
9517   queue_comp_unit (per_cu, pretend_language);
9518
9519   return 1;
9520 }
9521
9522 /* Process the queue.  */
9523
9524 static void
9525 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9526 {
9527   struct dwarf2_queue_item *item, *next_item;
9528
9529   if (dwarf_read_debug)
9530     {
9531       fprintf_unfiltered (gdb_stdlog,
9532                           "Expanding one or more symtabs of objfile %s ...\n",
9533                           objfile_name (dwarf2_per_objfile->objfile));
9534     }
9535
9536   /* The queue starts out with one item, but following a DIE reference
9537      may load a new CU, adding it to the end of the queue.  */
9538   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9539     {
9540       if ((dwarf2_per_objfile->using_index
9541            ? !item->per_cu->v.quick->compunit_symtab
9542            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9543           /* Skip dummy CUs.  */
9544           && item->per_cu->cu != NULL)
9545         {
9546           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9547           unsigned int debug_print_threshold;
9548           char buf[100];
9549
9550           if (per_cu->is_debug_types)
9551             {
9552               struct signatured_type *sig_type =
9553                 (struct signatured_type *) per_cu;
9554
9555               sprintf (buf, "TU %s at offset %s",
9556                        hex_string (sig_type->signature),
9557                        sect_offset_str (per_cu->sect_off));
9558               /* There can be 100s of TUs.
9559                  Only print them in verbose mode.  */
9560               debug_print_threshold = 2;
9561             }
9562           else
9563             {
9564               sprintf (buf, "CU at offset %s",
9565                        sect_offset_str (per_cu->sect_off));
9566               debug_print_threshold = 1;
9567             }
9568
9569           if (dwarf_read_debug >= debug_print_threshold)
9570             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9571
9572           if (per_cu->is_debug_types)
9573             process_full_type_unit (per_cu, item->pretend_language);
9574           else
9575             process_full_comp_unit (per_cu, item->pretend_language);
9576
9577           if (dwarf_read_debug >= debug_print_threshold)
9578             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9579         }
9580
9581       item->per_cu->queued = 0;
9582       next_item = item->next;
9583       xfree (item);
9584     }
9585
9586   dwarf2_queue_tail = NULL;
9587
9588   if (dwarf_read_debug)
9589     {
9590       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9591                           objfile_name (dwarf2_per_objfile->objfile));
9592     }
9593 }
9594
9595 /* Read in full symbols for PST, and anything it depends on.  */
9596
9597 static void
9598 psymtab_to_symtab_1 (struct partial_symtab *pst)
9599 {
9600   struct dwarf2_per_cu_data *per_cu;
9601   int i;
9602
9603   if (pst->readin)
9604     return;
9605
9606   for (i = 0; i < pst->number_of_dependencies; i++)
9607     if (!pst->dependencies[i]->readin
9608         && pst->dependencies[i]->user == NULL)
9609       {
9610         /* Inform about additional files that need to be read in.  */
9611         if (info_verbose)
9612           {
9613             /* FIXME: i18n: Need to make this a single string.  */
9614             fputs_filtered (" ", gdb_stdout);
9615             wrap_here ("");
9616             fputs_filtered ("and ", gdb_stdout);
9617             wrap_here ("");
9618             printf_filtered ("%s...", pst->dependencies[i]->filename);
9619             wrap_here ("");     /* Flush output.  */
9620             gdb_flush (gdb_stdout);
9621           }
9622         psymtab_to_symtab_1 (pst->dependencies[i]);
9623       }
9624
9625   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9626
9627   if (per_cu == NULL)
9628     {
9629       /* It's an include file, no symbols to read for it.
9630          Everything is in the parent symtab.  */
9631       pst->readin = 1;
9632       return;
9633     }
9634
9635   dw2_do_instantiate_symtab (per_cu, false);
9636 }
9637
9638 /* Trivial hash function for die_info: the hash value of a DIE
9639    is its offset in .debug_info for this objfile.  */
9640
9641 static hashval_t
9642 die_hash (const void *item)
9643 {
9644   const struct die_info *die = (const struct die_info *) item;
9645
9646   return to_underlying (die->sect_off);
9647 }
9648
9649 /* Trivial comparison function for die_info structures: two DIEs
9650    are equal if they have the same offset.  */
9651
9652 static int
9653 die_eq (const void *item_lhs, const void *item_rhs)
9654 {
9655   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9656   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9657
9658   return die_lhs->sect_off == die_rhs->sect_off;
9659 }
9660
9661 /* die_reader_func for load_full_comp_unit.
9662    This is identical to read_signatured_type_reader,
9663    but is kept separate for now.  */
9664
9665 static void
9666 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9667                             const gdb_byte *info_ptr,
9668                             struct die_info *comp_unit_die,
9669                             int has_children,
9670                             void *data)
9671 {
9672   struct dwarf2_cu *cu = reader->cu;
9673   enum language *language_ptr = (enum language *) data;
9674
9675   gdb_assert (cu->die_hash == NULL);
9676   cu->die_hash =
9677     htab_create_alloc_ex (cu->header.length / 12,
9678                           die_hash,
9679                           die_eq,
9680                           NULL,
9681                           &cu->comp_unit_obstack,
9682                           hashtab_obstack_allocate,
9683                           dummy_obstack_deallocate);
9684
9685   if (has_children)
9686     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9687                                                   &info_ptr, comp_unit_die);
9688   cu->dies = comp_unit_die;
9689   /* comp_unit_die is not stored in die_hash, no need.  */
9690
9691   /* We try not to read any attributes in this function, because not
9692      all CUs needed for references have been loaded yet, and symbol
9693      table processing isn't initialized.  But we have to set the CU language,
9694      or we won't be able to build types correctly.
9695      Similarly, if we do not read the producer, we can not apply
9696      producer-specific interpretation.  */
9697   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9698 }
9699
9700 /* Load the DIEs associated with PER_CU into memory.  */
9701
9702 static void
9703 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9704                      bool skip_partial,
9705                      enum language pretend_language)
9706 {
9707   gdb_assert (! this_cu->is_debug_types);
9708
9709   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9710                            load_full_comp_unit_reader, &pretend_language);
9711 }
9712
9713 /* Add a DIE to the delayed physname list.  */
9714
9715 static void
9716 add_to_method_list (struct type *type, int fnfield_index, int index,
9717                     const char *name, struct die_info *die,
9718                     struct dwarf2_cu *cu)
9719 {
9720   struct delayed_method_info mi;
9721   mi.type = type;
9722   mi.fnfield_index = fnfield_index;
9723   mi.index = index;
9724   mi.name = name;
9725   mi.die = die;
9726   cu->method_list.push_back (mi);
9727 }
9728
9729 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9730    "const" / "volatile".  If so, decrements LEN by the length of the
9731    modifier and return true.  Otherwise return false.  */
9732
9733 template<size_t N>
9734 static bool
9735 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9736 {
9737   size_t mod_len = sizeof (mod) - 1;
9738   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9739     {
9740       len -= mod_len;
9741       return true;
9742     }
9743   return false;
9744 }
9745
9746 /* Compute the physnames of any methods on the CU's method list.
9747
9748    The computation of method physnames is delayed in order to avoid the
9749    (bad) condition that one of the method's formal parameters is of an as yet
9750    incomplete type.  */
9751
9752 static void
9753 compute_delayed_physnames (struct dwarf2_cu *cu)
9754 {
9755   /* Only C++ delays computing physnames.  */
9756   if (cu->method_list.empty ())
9757     return;
9758   gdb_assert (cu->language == language_cplus);
9759
9760   for (const delayed_method_info &mi : cu->method_list)
9761     {
9762       const char *physname;
9763       struct fn_fieldlist *fn_flp
9764         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9765       physname = dwarf2_physname (mi.name, mi.die, cu);
9766       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9767         = physname ? physname : "";
9768
9769       /* Since there's no tag to indicate whether a method is a
9770          const/volatile overload, extract that information out of the
9771          demangled name.  */
9772       if (physname != NULL)
9773         {
9774           size_t len = strlen (physname);
9775
9776           while (1)
9777             {
9778               if (physname[len] == ')') /* shortcut */
9779                 break;
9780               else if (check_modifier (physname, len, " const"))
9781                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9782               else if (check_modifier (physname, len, " volatile"))
9783                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9784               else
9785                 break;
9786             }
9787         }
9788     }
9789
9790   /* The list is no longer needed.  */
9791   cu->method_list.clear ();
9792 }
9793
9794 /* Go objects should be embedded in a DW_TAG_module DIE,
9795    and it's not clear if/how imported objects will appear.
9796    To keep Go support simple until that's worked out,
9797    go back through what we've read and create something usable.
9798    We could do this while processing each DIE, and feels kinda cleaner,
9799    but that way is more invasive.
9800    This is to, for example, allow the user to type "p var" or "b main"
9801    without having to specify the package name, and allow lookups
9802    of module.object to work in contexts that use the expression
9803    parser.  */
9804
9805 static void
9806 fixup_go_packaging (struct dwarf2_cu *cu)
9807 {
9808   char *package_name = NULL;
9809   struct pending *list;
9810   int i;
9811
9812   for (list = *cu->get_builder ()->get_global_symbols ();
9813        list != NULL;
9814        list = list->next)
9815     {
9816       for (i = 0; i < list->nsyms; ++i)
9817         {
9818           struct symbol *sym = list->symbol[i];
9819
9820           if (SYMBOL_LANGUAGE (sym) == language_go
9821               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9822             {
9823               char *this_package_name = go_symbol_package_name (sym);
9824
9825               if (this_package_name == NULL)
9826                 continue;
9827               if (package_name == NULL)
9828                 package_name = this_package_name;
9829               else
9830                 {
9831                   struct objfile *objfile
9832                     = cu->per_cu->dwarf2_per_objfile->objfile;
9833                   if (strcmp (package_name, this_package_name) != 0)
9834                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9835                                (symbol_symtab (sym) != NULL
9836                                 ? symtab_to_filename_for_display
9837                                     (symbol_symtab (sym))
9838                                 : objfile_name (objfile)),
9839                                this_package_name, package_name);
9840                   xfree (this_package_name);
9841                 }
9842             }
9843         }
9844     }
9845
9846   if (package_name != NULL)
9847     {
9848       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9849       const char *saved_package_name
9850         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9851                                         package_name,
9852                                         strlen (package_name));
9853       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9854                                      saved_package_name);
9855       struct symbol *sym;
9856
9857       sym = allocate_symbol (objfile);
9858       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9859       SYMBOL_SET_NAMES (sym, saved_package_name,
9860                         strlen (saved_package_name), 0, objfile);
9861       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9862          e.g., "main" finds the "main" module and not C's main().  */
9863       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9864       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9865       SYMBOL_TYPE (sym) = type;
9866
9867       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9868
9869       xfree (package_name);
9870     }
9871 }
9872
9873 /* Allocate a fully-qualified name consisting of the two parts on the
9874    obstack.  */
9875
9876 static const char *
9877 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9878 {
9879   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9880 }
9881
9882 /* A helper that allocates a struct discriminant_info to attach to a
9883    union type.  */
9884
9885 static struct discriminant_info *
9886 alloc_discriminant_info (struct type *type, int discriminant_index,
9887                          int default_index)
9888 {
9889   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9890   gdb_assert (discriminant_index == -1
9891               || (discriminant_index >= 0
9892                   && discriminant_index < TYPE_NFIELDS (type)));
9893   gdb_assert (default_index == -1
9894               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9895
9896   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9897
9898   struct discriminant_info *disc
9899     = ((struct discriminant_info *)
9900        TYPE_ZALLOC (type,
9901                     offsetof (struct discriminant_info, discriminants)
9902                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9903   disc->default_index = default_index;
9904   disc->discriminant_index = discriminant_index;
9905
9906   struct dynamic_prop prop;
9907   prop.kind = PROP_UNDEFINED;
9908   prop.data.baton = disc;
9909
9910   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9911
9912   return disc;
9913 }
9914
9915 /* Some versions of rustc emitted enums in an unusual way.
9916
9917    Ordinary enums were emitted as unions.  The first element of each
9918    structure in the union was named "RUST$ENUM$DISR".  This element
9919    held the discriminant.
9920
9921    These versions of Rust also implemented the "non-zero"
9922    optimization.  When the enum had two values, and one is empty and
9923    the other holds a pointer that cannot be zero, the pointer is used
9924    as the discriminant, with a zero value meaning the empty variant.
9925    Here, the union's first member is of the form
9926    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9927    where the fieldnos are the indices of the fields that should be
9928    traversed in order to find the field (which may be several fields deep)
9929    and the variantname is the name of the variant of the case when the
9930    field is zero.
9931
9932    This function recognizes whether TYPE is of one of these forms,
9933    and, if so, smashes it to be a variant type.  */
9934
9935 static void
9936 quirk_rust_enum (struct type *type, struct objfile *objfile)
9937 {
9938   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9939
9940   /* We don't need to deal with empty enums.  */
9941   if (TYPE_NFIELDS (type) == 0)
9942     return;
9943
9944 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9945   if (TYPE_NFIELDS (type) == 1
9946       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9947     {
9948       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9949
9950       /* Decode the field name to find the offset of the
9951          discriminant.  */
9952       ULONGEST bit_offset = 0;
9953       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9954       while (name[0] >= '0' && name[0] <= '9')
9955         {
9956           char *tail;
9957           unsigned long index = strtoul (name, &tail, 10);
9958           name = tail;
9959           if (*name != '$'
9960               || index >= TYPE_NFIELDS (field_type)
9961               || (TYPE_FIELD_LOC_KIND (field_type, index)
9962                   != FIELD_LOC_KIND_BITPOS))
9963             {
9964               complaint (_("Could not parse Rust enum encoding string \"%s\""
9965                            "[in module %s]"),
9966                          TYPE_FIELD_NAME (type, 0),
9967                          objfile_name (objfile));
9968               return;
9969             }
9970           ++name;
9971
9972           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9973           field_type = TYPE_FIELD_TYPE (field_type, index);
9974         }
9975
9976       /* Make a union to hold the variants.  */
9977       struct type *union_type = alloc_type (objfile);
9978       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9979       TYPE_NFIELDS (union_type) = 3;
9980       TYPE_FIELDS (union_type)
9981         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9982       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9983       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9984
9985       /* Put the discriminant must at index 0.  */
9986       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9987       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9988       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9989       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9990
9991       /* The order of fields doesn't really matter, so put the real
9992          field at index 1 and the data-less field at index 2.  */
9993       struct discriminant_info *disc
9994         = alloc_discriminant_info (union_type, 0, 1);
9995       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9996       TYPE_FIELD_NAME (union_type, 1)
9997         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9998       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9999         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10000                               TYPE_FIELD_NAME (union_type, 1));
10001
10002       const char *dataless_name
10003         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10004                               name);
10005       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10006                                               dataless_name);
10007       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10008       /* NAME points into the original discriminant name, which
10009          already has the correct lifetime.  */
10010       TYPE_FIELD_NAME (union_type, 2) = name;
10011       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10012       disc->discriminants[2] = 0;
10013
10014       /* Smash this type to be a structure type.  We have to do this
10015          because the type has already been recorded.  */
10016       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10017       TYPE_NFIELDS (type) = 1;
10018       TYPE_FIELDS (type)
10019         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10020
10021       /* Install the variant part.  */
10022       TYPE_FIELD_TYPE (type, 0) = union_type;
10023       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10024       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10025     }
10026   else if (TYPE_NFIELDS (type) == 1)
10027     {
10028       /* We assume that a union with a single field is a univariant
10029          enum.  */
10030       /* Smash this type to be a structure type.  We have to do this
10031          because the type has already been recorded.  */
10032       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10033
10034       /* Make a union to hold the variants.  */
10035       struct type *union_type = alloc_type (objfile);
10036       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10037       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10038       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10039       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10040       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10041
10042       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10043       const char *variant_name
10044         = rust_last_path_segment (TYPE_NAME (field_type));
10045       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10046       TYPE_NAME (field_type)
10047         = rust_fully_qualify (&objfile->objfile_obstack,
10048                               TYPE_NAME (type), variant_name);
10049
10050       /* Install the union in the outer struct type.  */
10051       TYPE_NFIELDS (type) = 1;
10052       TYPE_FIELDS (type)
10053         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10054       TYPE_FIELD_TYPE (type, 0) = union_type;
10055       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10056       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10057
10058       alloc_discriminant_info (union_type, -1, 0);
10059     }
10060   else
10061     {
10062       struct type *disr_type = nullptr;
10063       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10064         {
10065           disr_type = TYPE_FIELD_TYPE (type, i);
10066
10067           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10068             {
10069               /* All fields of a true enum will be structs.  */
10070               return;
10071             }
10072           else if (TYPE_NFIELDS (disr_type) == 0)
10073             {
10074               /* Could be data-less variant, so keep going.  */
10075               disr_type = nullptr;
10076             }
10077           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10078                            "RUST$ENUM$DISR") != 0)
10079             {
10080               /* Not a Rust enum.  */
10081               return;
10082             }
10083           else
10084             {
10085               /* Found one.  */
10086               break;
10087             }
10088         }
10089
10090       /* If we got here without a discriminant, then it's probably
10091          just a union.  */
10092       if (disr_type == nullptr)
10093         return;
10094
10095       /* Smash this type to be a structure type.  We have to do this
10096          because the type has already been recorded.  */
10097       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10098
10099       /* Make a union to hold the variants.  */
10100       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10101       struct type *union_type = alloc_type (objfile);
10102       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10103       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10104       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10105       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10106       TYPE_FIELDS (union_type)
10107         = (struct field *) TYPE_ZALLOC (union_type,
10108                                         (TYPE_NFIELDS (union_type)
10109                                          * sizeof (struct field)));
10110
10111       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10112               TYPE_NFIELDS (type) * sizeof (struct field));
10113
10114       /* Install the discriminant at index 0 in the union.  */
10115       TYPE_FIELD (union_type, 0) = *disr_field;
10116       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10117       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10118
10119       /* Install the union in the outer struct type.  */
10120       TYPE_FIELD_TYPE (type, 0) = union_type;
10121       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10122       TYPE_NFIELDS (type) = 1;
10123
10124       /* Set the size and offset of the union type.  */
10125       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10126
10127       /* We need a way to find the correct discriminant given a
10128          variant name.  For convenience we build a map here.  */
10129       struct type *enum_type = FIELD_TYPE (*disr_field);
10130       std::unordered_map<std::string, ULONGEST> discriminant_map;
10131       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10132         {
10133           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10134             {
10135               const char *name
10136                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10137               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10138             }
10139         }
10140
10141       int n_fields = TYPE_NFIELDS (union_type);
10142       struct discriminant_info *disc
10143         = alloc_discriminant_info (union_type, 0, -1);
10144       /* Skip the discriminant here.  */
10145       for (int i = 1; i < n_fields; ++i)
10146         {
10147           /* Find the final word in the name of this variant's type.
10148              That name can be used to look up the correct
10149              discriminant.  */
10150           const char *variant_name
10151             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10152                                                                   i)));
10153
10154           auto iter = discriminant_map.find (variant_name);
10155           if (iter != discriminant_map.end ())
10156             disc->discriminants[i] = iter->second;
10157
10158           /* Remove the discriminant field, if it exists.  */
10159           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10160           if (TYPE_NFIELDS (sub_type) > 0)
10161             {
10162               --TYPE_NFIELDS (sub_type);
10163               ++TYPE_FIELDS (sub_type);
10164             }
10165           TYPE_FIELD_NAME (union_type, i) = variant_name;
10166           TYPE_NAME (sub_type)
10167             = rust_fully_qualify (&objfile->objfile_obstack,
10168                                   TYPE_NAME (type), variant_name);
10169         }
10170     }
10171 }
10172
10173 /* Rewrite some Rust unions to be structures with variants parts.  */
10174
10175 static void
10176 rust_union_quirks (struct dwarf2_cu *cu)
10177 {
10178   gdb_assert (cu->language == language_rust);
10179   for (type *type_ : cu->rust_unions)
10180     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10181   /* We don't need this any more.  */
10182   cu->rust_unions.clear ();
10183 }
10184
10185 /* Return the symtab for PER_CU.  This works properly regardless of
10186    whether we're using the index or psymtabs.  */
10187
10188 static struct compunit_symtab *
10189 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10190 {
10191   return (per_cu->dwarf2_per_objfile->using_index
10192           ? per_cu->v.quick->compunit_symtab
10193           : per_cu->v.psymtab->compunit_symtab);
10194 }
10195
10196 /* A helper function for computing the list of all symbol tables
10197    included by PER_CU.  */
10198
10199 static void
10200 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
10201                                 htab_t all_children, htab_t all_type_symtabs,
10202                                 struct dwarf2_per_cu_data *per_cu,
10203                                 struct compunit_symtab *immediate_parent)
10204 {
10205   void **slot;
10206   int ix;
10207   struct compunit_symtab *cust;
10208   struct dwarf2_per_cu_data *iter;
10209
10210   slot = htab_find_slot (all_children, per_cu, INSERT);
10211   if (*slot != NULL)
10212     {
10213       /* This inclusion and its children have been processed.  */
10214       return;
10215     }
10216
10217   *slot = per_cu;
10218   /* Only add a CU if it has a symbol table.  */
10219   cust = get_compunit_symtab (per_cu);
10220   if (cust != NULL)
10221     {
10222       /* If this is a type unit only add its symbol table if we haven't
10223          seen it yet (type unit per_cu's can share symtabs).  */
10224       if (per_cu->is_debug_types)
10225         {
10226           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10227           if (*slot == NULL)
10228             {
10229               *slot = cust;
10230               result->push_back (cust);
10231               if (cust->user == NULL)
10232                 cust->user = immediate_parent;
10233             }
10234         }
10235       else
10236         {
10237           result->push_back (cust);
10238           if (cust->user == NULL)
10239             cust->user = immediate_parent;
10240         }
10241     }
10242
10243   for (ix = 0;
10244        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10245        ++ix)
10246     {
10247       recursively_compute_inclusions (result, all_children,
10248                                       all_type_symtabs, iter, cust);
10249     }
10250 }
10251
10252 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10253    PER_CU.  */
10254
10255 static void
10256 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10257 {
10258   gdb_assert (! per_cu->is_debug_types);
10259
10260   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10261     {
10262       int ix, len;
10263       struct dwarf2_per_cu_data *per_cu_iter;
10264       std::vector<compunit_symtab *> result_symtabs;
10265       htab_t all_children, all_type_symtabs;
10266       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10267
10268       /* If we don't have a symtab, we can just skip this case.  */
10269       if (cust == NULL)
10270         return;
10271
10272       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10273                                         NULL, xcalloc, xfree);
10274       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10275                                             NULL, xcalloc, xfree);
10276
10277       for (ix = 0;
10278            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10279                         ix, per_cu_iter);
10280            ++ix)
10281         {
10282           recursively_compute_inclusions (&result_symtabs, all_children,
10283                                           all_type_symtabs, per_cu_iter,
10284                                           cust);
10285         }
10286
10287       /* Now we have a transitive closure of all the included symtabs.  */
10288       len = result_symtabs.size ();
10289       cust->includes
10290         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10291                      struct compunit_symtab *, len + 1);
10292       memcpy (cust->includes, result_symtabs.data (),
10293               len * sizeof (compunit_symtab *));
10294       cust->includes[len] = NULL;
10295
10296       htab_delete (all_children);
10297       htab_delete (all_type_symtabs);
10298     }
10299 }
10300
10301 /* Compute the 'includes' field for the symtabs of all the CUs we just
10302    read.  */
10303
10304 static void
10305 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10306 {
10307   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10308     {
10309       if (! iter->is_debug_types)
10310         compute_compunit_symtab_includes (iter);
10311     }
10312
10313   dwarf2_per_objfile->just_read_cus.clear ();
10314 }
10315
10316 /* Generate full symbol information for PER_CU, whose DIEs have
10317    already been loaded into memory.  */
10318
10319 static void
10320 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10321                         enum language pretend_language)
10322 {
10323   struct dwarf2_cu *cu = per_cu->cu;
10324   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10325   struct objfile *objfile = dwarf2_per_objfile->objfile;
10326   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10327   CORE_ADDR lowpc, highpc;
10328   struct compunit_symtab *cust;
10329   CORE_ADDR baseaddr;
10330   struct block *static_block;
10331   CORE_ADDR addr;
10332
10333   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10334
10335   /* Clear the list here in case something was left over.  */
10336   cu->method_list.clear ();
10337
10338   cu->language = pretend_language;
10339   cu->language_defn = language_def (cu->language);
10340
10341   /* Do line number decoding in read_file_scope () */
10342   process_die (cu->dies, cu);
10343
10344   /* For now fudge the Go package.  */
10345   if (cu->language == language_go)
10346     fixup_go_packaging (cu);
10347
10348   /* Now that we have processed all the DIEs in the CU, all the types 
10349      should be complete, and it should now be safe to compute all of the
10350      physnames.  */
10351   compute_delayed_physnames (cu);
10352
10353   if (cu->language == language_rust)
10354     rust_union_quirks (cu);
10355
10356   /* Some compilers don't define a DW_AT_high_pc attribute for the
10357      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10358      it, by scanning the DIE's below the compilation unit.  */
10359   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10360
10361   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10362   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
10363
10364   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10365      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10366      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10367      addrmap to help ensure it has an accurate map of pc values belonging to
10368      this comp unit.  */
10369   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10370
10371   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10372                                                     SECT_OFF_TEXT (objfile),
10373                                                     0);
10374
10375   if (cust != NULL)
10376     {
10377       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10378
10379       /* Set symtab language to language from DW_AT_language.  If the
10380          compilation is from a C file generated by language preprocessors, do
10381          not set the language if it was already deduced by start_subfile.  */
10382       if (!(cu->language == language_c
10383             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10384         COMPUNIT_FILETABS (cust)->language = cu->language;
10385
10386       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10387          produce DW_AT_location with location lists but it can be possibly
10388          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10389          there were bugs in prologue debug info, fixed later in GCC-4.5
10390          by "unwind info for epilogues" patch (which is not directly related).
10391
10392          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10393          needed, it would be wrong due to missing DW_AT_producer there.
10394
10395          Still one can confuse GDB by using non-standard GCC compilation
10396          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10397          */ 
10398       if (cu->has_loclist && gcc_4_minor >= 5)
10399         cust->locations_valid = 1;
10400
10401       if (gcc_4_minor >= 5)
10402         cust->epilogue_unwind_valid = 1;
10403
10404       cust->call_site_htab = cu->call_site_htab;
10405     }
10406
10407   if (dwarf2_per_objfile->using_index)
10408     per_cu->v.quick->compunit_symtab = cust;
10409   else
10410     {
10411       struct partial_symtab *pst = per_cu->v.psymtab;
10412       pst->compunit_symtab = cust;
10413       pst->readin = 1;
10414     }
10415
10416   /* Push it for inclusion processing later.  */
10417   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10418
10419   /* Not needed any more.  */
10420   cu->reset_builder ();
10421 }
10422
10423 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10424    already been loaded into memory.  */
10425
10426 static void
10427 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10428                         enum language pretend_language)
10429 {
10430   struct dwarf2_cu *cu = per_cu->cu;
10431   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10432   struct objfile *objfile = dwarf2_per_objfile->objfile;
10433   struct compunit_symtab *cust;
10434   struct signatured_type *sig_type;
10435
10436   gdb_assert (per_cu->is_debug_types);
10437   sig_type = (struct signatured_type *) per_cu;
10438
10439   /* Clear the list here in case something was left over.  */
10440   cu->method_list.clear ();
10441
10442   cu->language = pretend_language;
10443   cu->language_defn = language_def (cu->language);
10444
10445   /* The symbol tables are set up in read_type_unit_scope.  */
10446   process_die (cu->dies, cu);
10447
10448   /* For now fudge the Go package.  */
10449   if (cu->language == language_go)
10450     fixup_go_packaging (cu);
10451
10452   /* Now that we have processed all the DIEs in the CU, all the types 
10453      should be complete, and it should now be safe to compute all of the
10454      physnames.  */
10455   compute_delayed_physnames (cu);
10456
10457   if (cu->language == language_rust)
10458     rust_union_quirks (cu);
10459
10460   /* TUs share symbol tables.
10461      If this is the first TU to use this symtab, complete the construction
10462      of it with end_expandable_symtab.  Otherwise, complete the addition of
10463      this TU's symbols to the existing symtab.  */
10464   if (sig_type->type_unit_group->compunit_symtab == NULL)
10465     {
10466       buildsym_compunit *builder = cu->get_builder ();
10467       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10468       sig_type->type_unit_group->compunit_symtab = cust;
10469
10470       if (cust != NULL)
10471         {
10472           /* Set symtab language to language from DW_AT_language.  If the
10473              compilation is from a C file generated by language preprocessors,
10474              do not set the language if it was already deduced by
10475              start_subfile.  */
10476           if (!(cu->language == language_c
10477                 && COMPUNIT_FILETABS (cust)->language != language_c))
10478             COMPUNIT_FILETABS (cust)->language = cu->language;
10479         }
10480     }
10481   else
10482     {
10483       cu->get_builder ()->augment_type_symtab ();
10484       cust = sig_type->type_unit_group->compunit_symtab;
10485     }
10486
10487   if (dwarf2_per_objfile->using_index)
10488     per_cu->v.quick->compunit_symtab = cust;
10489   else
10490     {
10491       struct partial_symtab *pst = per_cu->v.psymtab;
10492       pst->compunit_symtab = cust;
10493       pst->readin = 1;
10494     }
10495
10496   /* Not needed any more.  */
10497   cu->reset_builder ();
10498 }
10499
10500 /* Process an imported unit DIE.  */
10501
10502 static void
10503 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10504 {
10505   struct attribute *attr;
10506
10507   /* For now we don't handle imported units in type units.  */
10508   if (cu->per_cu->is_debug_types)
10509     {
10510       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10511                " supported in type units [in module %s]"),
10512              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10513     }
10514
10515   attr = dwarf2_attr (die, DW_AT_import, cu);
10516   if (attr != NULL)
10517     {
10518       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10519       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10520       dwarf2_per_cu_data *per_cu
10521         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10522                                             cu->per_cu->dwarf2_per_objfile);
10523
10524       /* If necessary, add it to the queue and load its DIEs.  */
10525       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10526         load_full_comp_unit (per_cu, false, cu->language);
10527
10528       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10529                      per_cu);
10530     }
10531 }
10532
10533 /* RAII object that represents a process_die scope: i.e.,
10534    starts/finishes processing a DIE.  */
10535 class process_die_scope
10536 {
10537 public:
10538   process_die_scope (die_info *die, dwarf2_cu *cu)
10539     : m_die (die), m_cu (cu)
10540   {
10541     /* We should only be processing DIEs not already in process.  */
10542     gdb_assert (!m_die->in_process);
10543     m_die->in_process = true;
10544   }
10545
10546   ~process_die_scope ()
10547   {
10548     m_die->in_process = false;
10549
10550     /* If we're done processing the DIE for the CU that owns the line
10551        header, we don't need the line header anymore.  */
10552     if (m_cu->line_header_die_owner == m_die)
10553       {
10554         delete m_cu->line_header;
10555         m_cu->line_header = NULL;
10556         m_cu->line_header_die_owner = NULL;
10557       }
10558   }
10559
10560 private:
10561   die_info *m_die;
10562   dwarf2_cu *m_cu;
10563 };
10564
10565 /* Process a die and its children.  */
10566
10567 static void
10568 process_die (struct die_info *die, struct dwarf2_cu *cu)
10569 {
10570   process_die_scope scope (die, cu);
10571
10572   switch (die->tag)
10573     {
10574     case DW_TAG_padding:
10575       break;
10576     case DW_TAG_compile_unit:
10577     case DW_TAG_partial_unit:
10578       read_file_scope (die, cu);
10579       break;
10580     case DW_TAG_type_unit:
10581       read_type_unit_scope (die, cu);
10582       break;
10583     case DW_TAG_subprogram:
10584     case DW_TAG_inlined_subroutine:
10585       read_func_scope (die, cu);
10586       break;
10587     case DW_TAG_lexical_block:
10588     case DW_TAG_try_block:
10589     case DW_TAG_catch_block:
10590       read_lexical_block_scope (die, cu);
10591       break;
10592     case DW_TAG_call_site:
10593     case DW_TAG_GNU_call_site:
10594       read_call_site_scope (die, cu);
10595       break;
10596     case DW_TAG_class_type:
10597     case DW_TAG_interface_type:
10598     case DW_TAG_structure_type:
10599     case DW_TAG_union_type:
10600       process_structure_scope (die, cu);
10601       break;
10602     case DW_TAG_enumeration_type:
10603       process_enumeration_scope (die, cu);
10604       break;
10605
10606     /* These dies have a type, but processing them does not create
10607        a symbol or recurse to process the children.  Therefore we can
10608        read them on-demand through read_type_die.  */
10609     case DW_TAG_subroutine_type:
10610     case DW_TAG_set_type:
10611     case DW_TAG_array_type:
10612     case DW_TAG_pointer_type:
10613     case DW_TAG_ptr_to_member_type:
10614     case DW_TAG_reference_type:
10615     case DW_TAG_rvalue_reference_type:
10616     case DW_TAG_string_type:
10617       break;
10618
10619     case DW_TAG_base_type:
10620     case DW_TAG_subrange_type:
10621     case DW_TAG_typedef:
10622       /* Add a typedef symbol for the type definition, if it has a
10623          DW_AT_name.  */
10624       new_symbol (die, read_type_die (die, cu), cu);
10625       break;
10626     case DW_TAG_common_block:
10627       read_common_block (die, cu);
10628       break;
10629     case DW_TAG_common_inclusion:
10630       break;
10631     case DW_TAG_namespace:
10632       cu->processing_has_namespace_info = true;
10633       read_namespace (die, cu);
10634       break;
10635     case DW_TAG_module:
10636       cu->processing_has_namespace_info = true;
10637       read_module (die, cu);
10638       break;
10639     case DW_TAG_imported_declaration:
10640       cu->processing_has_namespace_info = true;
10641       if (read_namespace_alias (die, cu))
10642         break;
10643       /* The declaration is not a global namespace alias.  */
10644       /* Fall through.  */
10645     case DW_TAG_imported_module:
10646       cu->processing_has_namespace_info = true;
10647       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10648                                  || cu->language != language_fortran))
10649         complaint (_("Tag '%s' has unexpected children"),
10650                    dwarf_tag_name (die->tag));
10651       read_import_statement (die, cu);
10652       break;
10653
10654     case DW_TAG_imported_unit:
10655       process_imported_unit_die (die, cu);
10656       break;
10657
10658     case DW_TAG_variable:
10659       read_variable (die, cu);
10660       break;
10661
10662     default:
10663       new_symbol (die, NULL, cu);
10664       break;
10665     }
10666 }
10667 \f
10668 /* DWARF name computation.  */
10669
10670 /* A helper function for dwarf2_compute_name which determines whether DIE
10671    needs to have the name of the scope prepended to the name listed in the
10672    die.  */
10673
10674 static int
10675 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10676 {
10677   struct attribute *attr;
10678
10679   switch (die->tag)
10680     {
10681     case DW_TAG_namespace:
10682     case DW_TAG_typedef:
10683     case DW_TAG_class_type:
10684     case DW_TAG_interface_type:
10685     case DW_TAG_structure_type:
10686     case DW_TAG_union_type:
10687     case DW_TAG_enumeration_type:
10688     case DW_TAG_enumerator:
10689     case DW_TAG_subprogram:
10690     case DW_TAG_inlined_subroutine:
10691     case DW_TAG_member:
10692     case DW_TAG_imported_declaration:
10693       return 1;
10694
10695     case DW_TAG_variable:
10696     case DW_TAG_constant:
10697       /* We only need to prefix "globally" visible variables.  These include
10698          any variable marked with DW_AT_external or any variable that
10699          lives in a namespace.  [Variables in anonymous namespaces
10700          require prefixing, but they are not DW_AT_external.]  */
10701
10702       if (dwarf2_attr (die, DW_AT_specification, cu))
10703         {
10704           struct dwarf2_cu *spec_cu = cu;
10705
10706           return die_needs_namespace (die_specification (die, &spec_cu),
10707                                       spec_cu);
10708         }
10709
10710       attr = dwarf2_attr (die, DW_AT_external, cu);
10711       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10712           && die->parent->tag != DW_TAG_module)
10713         return 0;
10714       /* A variable in a lexical block of some kind does not need a
10715          namespace, even though in C++ such variables may be external
10716          and have a mangled name.  */
10717       if (die->parent->tag ==  DW_TAG_lexical_block
10718           || die->parent->tag ==  DW_TAG_try_block
10719           || die->parent->tag ==  DW_TAG_catch_block
10720           || die->parent->tag == DW_TAG_subprogram)
10721         return 0;
10722       return 1;
10723
10724     default:
10725       return 0;
10726     }
10727 }
10728
10729 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10730    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10731    defined for the given DIE.  */
10732
10733 static struct attribute *
10734 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10735 {
10736   struct attribute *attr;
10737
10738   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10739   if (attr == NULL)
10740     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10741
10742   return attr;
10743 }
10744
10745 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10746    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10747    defined for the given DIE.  */
10748
10749 static const char *
10750 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10751 {
10752   const char *linkage_name;
10753
10754   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10755   if (linkage_name == NULL)
10756     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10757
10758   return linkage_name;
10759 }
10760
10761 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10762    compute the physname for the object, which include a method's:
10763    - formal parameters (C++),
10764    - receiver type (Go),
10765
10766    The term "physname" is a bit confusing.
10767    For C++, for example, it is the demangled name.
10768    For Go, for example, it's the mangled name.
10769
10770    For Ada, return the DIE's linkage name rather than the fully qualified
10771    name.  PHYSNAME is ignored..
10772
10773    The result is allocated on the objfile_obstack and canonicalized.  */
10774
10775 static const char *
10776 dwarf2_compute_name (const char *name,
10777                      struct die_info *die, struct dwarf2_cu *cu,
10778                      int physname)
10779 {
10780   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10781
10782   if (name == NULL)
10783     name = dwarf2_name (die, cu);
10784
10785   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10786      but otherwise compute it by typename_concat inside GDB.
10787      FIXME: Actually this is not really true, or at least not always true.
10788      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10789      Fortran names because there is no mangling standard.  So new_symbol
10790      will set the demangled name to the result of dwarf2_full_name, and it is
10791      the demangled name that GDB uses if it exists.  */
10792   if (cu->language == language_ada
10793       || (cu->language == language_fortran && physname))
10794     {
10795       /* For Ada unit, we prefer the linkage name over the name, as
10796          the former contains the exported name, which the user expects
10797          to be able to reference.  Ideally, we want the user to be able
10798          to reference this entity using either natural or linkage name,
10799          but we haven't started looking at this enhancement yet.  */
10800       const char *linkage_name = dw2_linkage_name (die, cu);
10801
10802       if (linkage_name != NULL)
10803         return linkage_name;
10804     }
10805
10806   /* These are the only languages we know how to qualify names in.  */
10807   if (name != NULL
10808       && (cu->language == language_cplus
10809           || cu->language == language_fortran || cu->language == language_d
10810           || cu->language == language_rust))
10811     {
10812       if (die_needs_namespace (die, cu))
10813         {
10814           const char *prefix;
10815           const char *canonical_name = NULL;
10816
10817           string_file buf;
10818
10819           prefix = determine_prefix (die, cu);
10820           if (*prefix != '\0')
10821             {
10822               char *prefixed_name = typename_concat (NULL, prefix, name,
10823                                                      physname, cu);
10824
10825               buf.puts (prefixed_name);
10826               xfree (prefixed_name);
10827             }
10828           else
10829             buf.puts (name);
10830
10831           /* Template parameters may be specified in the DIE's DW_AT_name, or
10832              as children with DW_TAG_template_type_param or
10833              DW_TAG_value_type_param.  If the latter, add them to the name
10834              here.  If the name already has template parameters, then
10835              skip this step; some versions of GCC emit both, and
10836              it is more efficient to use the pre-computed name.
10837
10838              Something to keep in mind about this process: it is very
10839              unlikely, or in some cases downright impossible, to produce
10840              something that will match the mangled name of a function.
10841              If the definition of the function has the same debug info,
10842              we should be able to match up with it anyway.  But fallbacks
10843              using the minimal symbol, for instance to find a method
10844              implemented in a stripped copy of libstdc++, will not work.
10845              If we do not have debug info for the definition, we will have to
10846              match them up some other way.
10847
10848              When we do name matching there is a related problem with function
10849              templates; two instantiated function templates are allowed to
10850              differ only by their return types, which we do not add here.  */
10851
10852           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10853             {
10854               struct attribute *attr;
10855               struct die_info *child;
10856               int first = 1;
10857
10858               die->building_fullname = 1;
10859
10860               for (child = die->child; child != NULL; child = child->sibling)
10861                 {
10862                   struct type *type;
10863                   LONGEST value;
10864                   const gdb_byte *bytes;
10865                   struct dwarf2_locexpr_baton *baton;
10866                   struct value *v;
10867
10868                   if (child->tag != DW_TAG_template_type_param
10869                       && child->tag != DW_TAG_template_value_param)
10870                     continue;
10871
10872                   if (first)
10873                     {
10874                       buf.puts ("<");
10875                       first = 0;
10876                     }
10877                   else
10878                     buf.puts (", ");
10879
10880                   attr = dwarf2_attr (child, DW_AT_type, cu);
10881                   if (attr == NULL)
10882                     {
10883                       complaint (_("template parameter missing DW_AT_type"));
10884                       buf.puts ("UNKNOWN_TYPE");
10885                       continue;
10886                     }
10887                   type = die_type (child, cu);
10888
10889                   if (child->tag == DW_TAG_template_type_param)
10890                     {
10891                       c_print_type (type, "", &buf, -1, 0, cu->language,
10892                                     &type_print_raw_options);
10893                       continue;
10894                     }
10895
10896                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10897                   if (attr == NULL)
10898                     {
10899                       complaint (_("template parameter missing "
10900                                    "DW_AT_const_value"));
10901                       buf.puts ("UNKNOWN_VALUE");
10902                       continue;
10903                     }
10904
10905                   dwarf2_const_value_attr (attr, type, name,
10906                                            &cu->comp_unit_obstack, cu,
10907                                            &value, &bytes, &baton);
10908
10909                   if (TYPE_NOSIGN (type))
10910                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10911                        changed, this can use value_print instead.  */
10912                     c_printchar (value, type, &buf);
10913                   else
10914                     {
10915                       struct value_print_options opts;
10916
10917                       if (baton != NULL)
10918                         v = dwarf2_evaluate_loc_desc (type, NULL,
10919                                                       baton->data,
10920                                                       baton->size,
10921                                                       baton->per_cu);
10922                       else if (bytes != NULL)
10923                         {
10924                           v = allocate_value (type);
10925                           memcpy (value_contents_writeable (v), bytes,
10926                                   TYPE_LENGTH (type));
10927                         }
10928                       else
10929                         v = value_from_longest (type, value);
10930
10931                       /* Specify decimal so that we do not depend on
10932                          the radix.  */
10933                       get_formatted_print_options (&opts, 'd');
10934                       opts.raw = 1;
10935                       value_print (v, &buf, &opts);
10936                       release_value (v);
10937                     }
10938                 }
10939
10940               die->building_fullname = 0;
10941
10942               if (!first)
10943                 {
10944                   /* Close the argument list, with a space if necessary
10945                      (nested templates).  */
10946                   if (!buf.empty () && buf.string ().back () == '>')
10947                     buf.puts (" >");
10948                   else
10949                     buf.puts (">");
10950                 }
10951             }
10952
10953           /* For C++ methods, append formal parameter type
10954              information, if PHYSNAME.  */
10955
10956           if (physname && die->tag == DW_TAG_subprogram
10957               && cu->language == language_cplus)
10958             {
10959               struct type *type = read_type_die (die, cu);
10960
10961               c_type_print_args (type, &buf, 1, cu->language,
10962                                  &type_print_raw_options);
10963
10964               if (cu->language == language_cplus)
10965                 {
10966                   /* Assume that an artificial first parameter is
10967                      "this", but do not crash if it is not.  RealView
10968                      marks unnamed (and thus unused) parameters as
10969                      artificial; there is no way to differentiate
10970                      the two cases.  */
10971                   if (TYPE_NFIELDS (type) > 0
10972                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10973                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10974                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10975                                                                         0))))
10976                     buf.puts (" const");
10977                 }
10978             }
10979
10980           const std::string &intermediate_name = buf.string ();
10981
10982           if (cu->language == language_cplus)
10983             canonical_name
10984               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10985                                           &objfile->per_bfd->storage_obstack);
10986
10987           /* If we only computed INTERMEDIATE_NAME, or if
10988              INTERMEDIATE_NAME is already canonical, then we need to
10989              copy it to the appropriate obstack.  */
10990           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10991             name = ((const char *)
10992                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10993                                    intermediate_name.c_str (),
10994                                    intermediate_name.length ()));
10995           else
10996             name = canonical_name;
10997         }
10998     }
10999
11000   return name;
11001 }
11002
11003 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11004    If scope qualifiers are appropriate they will be added.  The result
11005    will be allocated on the storage_obstack, or NULL if the DIE does
11006    not have a name.  NAME may either be from a previous call to
11007    dwarf2_name or NULL.
11008
11009    The output string will be canonicalized (if C++).  */
11010
11011 static const char *
11012 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11013 {
11014   return dwarf2_compute_name (name, die, cu, 0);
11015 }
11016
11017 /* Construct a physname for the given DIE in CU.  NAME may either be
11018    from a previous call to dwarf2_name or NULL.  The result will be
11019    allocated on the objfile_objstack or NULL if the DIE does not have a
11020    name.
11021
11022    The output string will be canonicalized (if C++).  */
11023
11024 static const char *
11025 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11026 {
11027   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11028   const char *retval, *mangled = NULL, *canon = NULL;
11029   int need_copy = 1;
11030
11031   /* In this case dwarf2_compute_name is just a shortcut not building anything
11032      on its own.  */
11033   if (!die_needs_namespace (die, cu))
11034     return dwarf2_compute_name (name, die, cu, 1);
11035
11036   mangled = dw2_linkage_name (die, cu);
11037
11038   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11039      See https://github.com/rust-lang/rust/issues/32925.  */
11040   if (cu->language == language_rust && mangled != NULL
11041       && strchr (mangled, '{') != NULL)
11042     mangled = NULL;
11043
11044   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11045      has computed.  */
11046   gdb::unique_xmalloc_ptr<char> demangled;
11047   if (mangled != NULL)
11048     {
11049
11050       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11051         {
11052           /* Do nothing (do not demangle the symbol name).  */
11053         }
11054       else if (cu->language == language_go)
11055         {
11056           /* This is a lie, but we already lie to the caller new_symbol.
11057              new_symbol assumes we return the mangled name.
11058              This just undoes that lie until things are cleaned up.  */
11059         }
11060       else
11061         {
11062           /* Use DMGL_RET_DROP for C++ template functions to suppress
11063              their return type.  It is easier for GDB users to search
11064              for such functions as `name(params)' than `long name(params)'.
11065              In such case the minimal symbol names do not match the full
11066              symbol names but for template functions there is never a need
11067              to look up their definition from their declaration so
11068              the only disadvantage remains the minimal symbol variant
11069              `long name(params)' does not have the proper inferior type.  */
11070           demangled.reset (gdb_demangle (mangled,
11071                                          (DMGL_PARAMS | DMGL_ANSI
11072                                           | DMGL_RET_DROP)));
11073         }
11074       if (demangled)
11075         canon = demangled.get ();
11076       else
11077         {
11078           canon = mangled;
11079           need_copy = 0;
11080         }
11081     }
11082
11083   if (canon == NULL || check_physname)
11084     {
11085       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11086
11087       if (canon != NULL && strcmp (physname, canon) != 0)
11088         {
11089           /* It may not mean a bug in GDB.  The compiler could also
11090              compute DW_AT_linkage_name incorrectly.  But in such case
11091              GDB would need to be bug-to-bug compatible.  */
11092
11093           complaint (_("Computed physname <%s> does not match demangled <%s> "
11094                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11095                      physname, canon, mangled, sect_offset_str (die->sect_off),
11096                      objfile_name (objfile));
11097
11098           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11099              is available here - over computed PHYSNAME.  It is safer
11100              against both buggy GDB and buggy compilers.  */
11101
11102           retval = canon;
11103         }
11104       else
11105         {
11106           retval = physname;
11107           need_copy = 0;
11108         }
11109     }
11110   else
11111     retval = canon;
11112
11113   if (need_copy)
11114     retval = ((const char *)
11115               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11116                              retval, strlen (retval)));
11117
11118   return retval;
11119 }
11120
11121 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11122    a new symbol for it.
11123
11124    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11125
11126 static int
11127 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11128 {
11129   struct attribute *attr;
11130
11131   /* If the die does not have a name, this is not a namespace
11132      alias.  */
11133   attr = dwarf2_attr (die, DW_AT_name, cu);
11134   if (attr != NULL)
11135     {
11136       int num;
11137       struct die_info *d = die;
11138       struct dwarf2_cu *imported_cu = cu;
11139
11140       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11141          keep inspecting DIEs until we hit the underlying import.  */
11142 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11143       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11144         {
11145           attr = dwarf2_attr (d, DW_AT_import, cu);
11146           if (attr == NULL)
11147             break;
11148
11149           d = follow_die_ref (d, attr, &imported_cu);
11150           if (d->tag != DW_TAG_imported_declaration)
11151             break;
11152         }
11153
11154       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11155         {
11156           complaint (_("DIE at %s has too many recursively imported "
11157                        "declarations"), sect_offset_str (d->sect_off));
11158           return 0;
11159         }
11160
11161       if (attr != NULL)
11162         {
11163           struct type *type;
11164           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11165
11166           type = get_die_type_at_offset (sect_off, cu->per_cu);
11167           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11168             {
11169               /* This declaration is a global namespace alias.  Add
11170                  a symbol for it whose type is the aliased namespace.  */
11171               new_symbol (die, type, cu);
11172               return 1;
11173             }
11174         }
11175     }
11176
11177   return 0;
11178 }
11179
11180 /* Return the using directives repository (global or local?) to use in the
11181    current context for CU.
11182
11183    For Ada, imported declarations can materialize renamings, which *may* be
11184    global.  However it is impossible (for now?) in DWARF to distinguish
11185    "external" imported declarations and "static" ones.  As all imported
11186    declarations seem to be static in all other languages, make them all CU-wide
11187    global only in Ada.  */
11188
11189 static struct using_direct **
11190 using_directives (struct dwarf2_cu *cu)
11191 {
11192   if (cu->language == language_ada
11193       && cu->get_builder ()->outermost_context_p ())
11194     return cu->get_builder ()->get_global_using_directives ();
11195   else
11196     return cu->get_builder ()->get_local_using_directives ();
11197 }
11198
11199 /* Read the import statement specified by the given die and record it.  */
11200
11201 static void
11202 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11203 {
11204   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11205   struct attribute *import_attr;
11206   struct die_info *imported_die, *child_die;
11207   struct dwarf2_cu *imported_cu;
11208   const char *imported_name;
11209   const char *imported_name_prefix;
11210   const char *canonical_name;
11211   const char *import_alias;
11212   const char *imported_declaration = NULL;
11213   const char *import_prefix;
11214   std::vector<const char *> excludes;
11215
11216   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11217   if (import_attr == NULL)
11218     {
11219       complaint (_("Tag '%s' has no DW_AT_import"),
11220                  dwarf_tag_name (die->tag));
11221       return;
11222     }
11223
11224   imported_cu = cu;
11225   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11226   imported_name = dwarf2_name (imported_die, imported_cu);
11227   if (imported_name == NULL)
11228     {
11229       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11230
11231         The import in the following code:
11232         namespace A
11233           {
11234             typedef int B;
11235           }
11236
11237         int main ()
11238           {
11239             using A::B;
11240             B b;
11241             return b;
11242           }
11243
11244         ...
11245          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11246             <52>   DW_AT_decl_file   : 1
11247             <53>   DW_AT_decl_line   : 6
11248             <54>   DW_AT_import      : <0x75>
11249          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11250             <59>   DW_AT_name        : B
11251             <5b>   DW_AT_decl_file   : 1
11252             <5c>   DW_AT_decl_line   : 2
11253             <5d>   DW_AT_type        : <0x6e>
11254         ...
11255          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11256             <76>   DW_AT_byte_size   : 4
11257             <77>   DW_AT_encoding    : 5        (signed)
11258
11259         imports the wrong die ( 0x75 instead of 0x58 ).
11260         This case will be ignored until the gcc bug is fixed.  */
11261       return;
11262     }
11263
11264   /* Figure out the local name after import.  */
11265   import_alias = dwarf2_name (die, cu);
11266
11267   /* Figure out where the statement is being imported to.  */
11268   import_prefix = determine_prefix (die, cu);
11269
11270   /* Figure out what the scope of the imported die is and prepend it
11271      to the name of the imported die.  */
11272   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11273
11274   if (imported_die->tag != DW_TAG_namespace
11275       && imported_die->tag != DW_TAG_module)
11276     {
11277       imported_declaration = imported_name;
11278       canonical_name = imported_name_prefix;
11279     }
11280   else if (strlen (imported_name_prefix) > 0)
11281     canonical_name = obconcat (&objfile->objfile_obstack,
11282                                imported_name_prefix,
11283                                (cu->language == language_d ? "." : "::"),
11284                                imported_name, (char *) NULL);
11285   else
11286     canonical_name = imported_name;
11287
11288   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11289     for (child_die = die->child; child_die && child_die->tag;
11290          child_die = sibling_die (child_die))
11291       {
11292         /* DWARF-4: A Fortran use statement with a “rename list” may be
11293            represented by an imported module entry with an import attribute
11294            referring to the module and owned entries corresponding to those
11295            entities that are renamed as part of being imported.  */
11296
11297         if (child_die->tag != DW_TAG_imported_declaration)
11298           {
11299             complaint (_("child DW_TAG_imported_declaration expected "
11300                          "- DIE at %s [in module %s]"),
11301                        sect_offset_str (child_die->sect_off),
11302                        objfile_name (objfile));
11303             continue;
11304           }
11305
11306         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11307         if (import_attr == NULL)
11308           {
11309             complaint (_("Tag '%s' has no DW_AT_import"),
11310                        dwarf_tag_name (child_die->tag));
11311             continue;
11312           }
11313
11314         imported_cu = cu;
11315         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11316                                               &imported_cu);
11317         imported_name = dwarf2_name (imported_die, imported_cu);
11318         if (imported_name == NULL)
11319           {
11320             complaint (_("child DW_TAG_imported_declaration has unknown "
11321                          "imported name - DIE at %s [in module %s]"),
11322                        sect_offset_str (child_die->sect_off),
11323                        objfile_name (objfile));
11324             continue;
11325           }
11326
11327         excludes.push_back (imported_name);
11328
11329         process_die (child_die, cu);
11330       }
11331
11332   add_using_directive (using_directives (cu),
11333                        import_prefix,
11334                        canonical_name,
11335                        import_alias,
11336                        imported_declaration,
11337                        excludes,
11338                        0,
11339                        &objfile->objfile_obstack);
11340 }
11341
11342 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11343    types, but gives them a size of zero.  Starting with version 14,
11344    ICC is compatible with GCC.  */
11345
11346 static bool
11347 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11348 {
11349   if (!cu->checked_producer)
11350     check_producer (cu);
11351
11352   return cu->producer_is_icc_lt_14;
11353 }
11354
11355 /* ICC generates a DW_AT_type for C void functions.  This was observed on
11356    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
11357    which says that void functions should not have a DW_AT_type.  */
11358
11359 static bool
11360 producer_is_icc (struct dwarf2_cu *cu)
11361 {
11362   if (!cu->checked_producer)
11363     check_producer (cu);
11364
11365   return cu->producer_is_icc;
11366 }
11367
11368 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11369    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11370    this, it was first present in GCC release 4.3.0.  */
11371
11372 static bool
11373 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11374 {
11375   if (!cu->checked_producer)
11376     check_producer (cu);
11377
11378   return cu->producer_is_gcc_lt_4_3;
11379 }
11380
11381 static file_and_directory
11382 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11383 {
11384   file_and_directory res;
11385
11386   /* Find the filename.  Do not use dwarf2_name here, since the filename
11387      is not a source language identifier.  */
11388   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11389   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11390
11391   if (res.comp_dir == NULL
11392       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11393       && IS_ABSOLUTE_PATH (res.name))
11394     {
11395       res.comp_dir_storage = ldirname (res.name);
11396       if (!res.comp_dir_storage.empty ())
11397         res.comp_dir = res.comp_dir_storage.c_str ();
11398     }
11399   if (res.comp_dir != NULL)
11400     {
11401       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11402          directory, get rid of it.  */
11403       const char *cp = strchr (res.comp_dir, ':');
11404
11405       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11406         res.comp_dir = cp + 1;
11407     }
11408
11409   if (res.name == NULL)
11410     res.name = "<unknown>";
11411
11412   return res;
11413 }
11414
11415 /* Handle DW_AT_stmt_list for a compilation unit.
11416    DIE is the DW_TAG_compile_unit die for CU.
11417    COMP_DIR is the compilation directory.  LOWPC is passed to
11418    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11419
11420 static void
11421 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11422                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11423 {
11424   struct dwarf2_per_objfile *dwarf2_per_objfile
11425     = cu->per_cu->dwarf2_per_objfile;
11426   struct objfile *objfile = dwarf2_per_objfile->objfile;
11427   struct attribute *attr;
11428   struct line_header line_header_local;
11429   hashval_t line_header_local_hash;
11430   void **slot;
11431   int decode_mapping;
11432
11433   gdb_assert (! cu->per_cu->is_debug_types);
11434
11435   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11436   if (attr == NULL)
11437     return;
11438
11439   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11440
11441   /* The line header hash table is only created if needed (it exists to
11442      prevent redundant reading of the line table for partial_units).
11443      If we're given a partial_unit, we'll need it.  If we're given a
11444      compile_unit, then use the line header hash table if it's already
11445      created, but don't create one just yet.  */
11446
11447   if (dwarf2_per_objfile->line_header_hash == NULL
11448       && die->tag == DW_TAG_partial_unit)
11449     {
11450       dwarf2_per_objfile->line_header_hash
11451         = htab_create_alloc_ex (127, line_header_hash_voidp,
11452                                 line_header_eq_voidp,
11453                                 free_line_header_voidp,
11454                                 &objfile->objfile_obstack,
11455                                 hashtab_obstack_allocate,
11456                                 dummy_obstack_deallocate);
11457     }
11458
11459   line_header_local.sect_off = line_offset;
11460   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11461   line_header_local_hash = line_header_hash (&line_header_local);
11462   if (dwarf2_per_objfile->line_header_hash != NULL)
11463     {
11464       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11465                                        &line_header_local,
11466                                        line_header_local_hash, NO_INSERT);
11467
11468       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11469          is not present in *SLOT (since if there is something in *SLOT then
11470          it will be for a partial_unit).  */
11471       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11472         {
11473           gdb_assert (*slot != NULL);
11474           cu->line_header = (struct line_header *) *slot;
11475           return;
11476         }
11477     }
11478
11479   /* dwarf_decode_line_header does not yet provide sufficient information.
11480      We always have to call also dwarf_decode_lines for it.  */
11481   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11482   if (lh == NULL)
11483     return;
11484
11485   cu->line_header = lh.release ();
11486   cu->line_header_die_owner = die;
11487
11488   if (dwarf2_per_objfile->line_header_hash == NULL)
11489     slot = NULL;
11490   else
11491     {
11492       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11493                                        &line_header_local,
11494                                        line_header_local_hash, INSERT);
11495       gdb_assert (slot != NULL);
11496     }
11497   if (slot != NULL && *slot == NULL)
11498     {
11499       /* This newly decoded line number information unit will be owned
11500          by line_header_hash hash table.  */
11501       *slot = cu->line_header;
11502       cu->line_header_die_owner = NULL;
11503     }
11504   else
11505     {
11506       /* We cannot free any current entry in (*slot) as that struct line_header
11507          may be already used by multiple CUs.  Create only temporary decoded
11508          line_header for this CU - it may happen at most once for each line
11509          number information unit.  And if we're not using line_header_hash
11510          then this is what we want as well.  */
11511       gdb_assert (die->tag != DW_TAG_partial_unit);
11512     }
11513   decode_mapping = (die->tag != DW_TAG_partial_unit);
11514   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11515                       decode_mapping);
11516
11517 }
11518
11519 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11520
11521 static void
11522 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11523 {
11524   struct dwarf2_per_objfile *dwarf2_per_objfile
11525     = cu->per_cu->dwarf2_per_objfile;
11526   struct objfile *objfile = dwarf2_per_objfile->objfile;
11527   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11528   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11529   CORE_ADDR highpc = ((CORE_ADDR) 0);
11530   struct attribute *attr;
11531   struct die_info *child_die;
11532   CORE_ADDR baseaddr;
11533
11534   prepare_one_comp_unit (cu, die, cu->language);
11535   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11536
11537   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11538
11539   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11540      from finish_block.  */
11541   if (lowpc == ((CORE_ADDR) -1))
11542     lowpc = highpc;
11543   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11544
11545   file_and_directory fnd = find_file_and_directory (die, cu);
11546
11547   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11548      standardised yet.  As a workaround for the language detection we fall
11549      back to the DW_AT_producer string.  */
11550   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11551     cu->language = language_opencl;
11552
11553   /* Similar hack for Go.  */
11554   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11555     set_cu_language (DW_LANG_Go, cu);
11556
11557   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11558
11559   /* Decode line number information if present.  We do this before
11560      processing child DIEs, so that the line header table is available
11561      for DW_AT_decl_file.  */
11562   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11563
11564   /* Process all dies in compilation unit.  */
11565   if (die->child != NULL)
11566     {
11567       child_die = die->child;
11568       while (child_die && child_die->tag)
11569         {
11570           process_die (child_die, cu);
11571           child_die = sibling_die (child_die);
11572         }
11573     }
11574
11575   /* Decode macro information, if present.  Dwarf 2 macro information
11576      refers to information in the line number info statement program
11577      header, so we can only read it if we've read the header
11578      successfully.  */
11579   attr = dwarf2_attr (die, DW_AT_macros, cu);
11580   if (attr == NULL)
11581     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11582   if (attr && cu->line_header)
11583     {
11584       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11585         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11586
11587       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11588     }
11589   else
11590     {
11591       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11592       if (attr && cu->line_header)
11593         {
11594           unsigned int macro_offset = DW_UNSND (attr);
11595
11596           dwarf_decode_macros (cu, macro_offset, 0);
11597         }
11598     }
11599 }
11600
11601 void
11602 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11603 {
11604   struct type_unit_group *tu_group;
11605   int first_time;
11606   struct attribute *attr;
11607   unsigned int i;
11608   struct signatured_type *sig_type;
11609
11610   gdb_assert (per_cu->is_debug_types);
11611   sig_type = (struct signatured_type *) per_cu;
11612
11613   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11614
11615   /* If we're using .gdb_index (includes -readnow) then
11616      per_cu->type_unit_group may not have been set up yet.  */
11617   if (sig_type->type_unit_group == NULL)
11618     sig_type->type_unit_group = get_type_unit_group (this, attr);
11619   tu_group = sig_type->type_unit_group;
11620
11621   /* If we've already processed this stmt_list there's no real need to
11622      do it again, we could fake it and just recreate the part we need
11623      (file name,index -> symtab mapping).  If data shows this optimization
11624      is useful we can do it then.  */
11625   first_time = tu_group->compunit_symtab == NULL;
11626
11627   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11628      debug info.  */
11629   line_header_up lh;
11630   if (attr != NULL)
11631     {
11632       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11633       lh = dwarf_decode_line_header (line_offset, this);
11634     }
11635   if (lh == NULL)
11636     {
11637       if (first_time)
11638         start_symtab ("", NULL, 0);
11639       else
11640         {
11641           gdb_assert (tu_group->symtabs == NULL);
11642           gdb_assert (m_builder == nullptr);
11643           struct compunit_symtab *cust = tu_group->compunit_symtab;
11644           m_builder.reset (new struct buildsym_compunit
11645                            (COMPUNIT_OBJFILE (cust), "",
11646                             COMPUNIT_DIRNAME (cust),
11647                             compunit_language (cust),
11648                             0, cust));
11649         }
11650       return;
11651     }
11652
11653   line_header = lh.release ();
11654   line_header_die_owner = die;
11655
11656   if (first_time)
11657     {
11658       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11659
11660       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11661          still initializing it, and our caller (a few levels up)
11662          process_full_type_unit still needs to know if this is the first
11663          time.  */
11664
11665       tu_group->num_symtabs = line_header->file_names.size ();
11666       tu_group->symtabs = XNEWVEC (struct symtab *,
11667                                    line_header->file_names.size ());
11668
11669       for (i = 0; i < line_header->file_names.size (); ++i)
11670         {
11671           file_entry &fe = line_header->file_names[i];
11672
11673           dwarf2_start_subfile (this, fe.name,
11674                                 fe.include_dir (line_header));
11675           buildsym_compunit *b = get_builder ();
11676           if (b->get_current_subfile ()->symtab == NULL)
11677             {
11678               /* NOTE: start_subfile will recognize when it's been
11679                  passed a file it has already seen.  So we can't
11680                  assume there's a simple mapping from
11681                  cu->line_header->file_names to subfiles, plus
11682                  cu->line_header->file_names may contain dups.  */
11683               b->get_current_subfile ()->symtab
11684                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11685             }
11686
11687           fe.symtab = b->get_current_subfile ()->symtab;
11688           tu_group->symtabs[i] = fe.symtab;
11689         }
11690     }
11691   else
11692     {
11693       gdb_assert (m_builder == nullptr);
11694       struct compunit_symtab *cust = tu_group->compunit_symtab;
11695       m_builder.reset (new struct buildsym_compunit
11696                        (COMPUNIT_OBJFILE (cust), "",
11697                         COMPUNIT_DIRNAME (cust),
11698                         compunit_language (cust),
11699                         0, cust));
11700
11701       for (i = 0; i < line_header->file_names.size (); ++i)
11702         {
11703           file_entry &fe = line_header->file_names[i];
11704
11705           fe.symtab = tu_group->symtabs[i];
11706         }
11707     }
11708
11709   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11710      so they don't have a "real" (so to speak) symtab anyway.
11711      There is later code that will assign the main symtab to all symbols
11712      that don't have one.  We need to handle the case of a symbol with a
11713      missing symtab (DW_AT_decl_file) anyway.  */
11714 }
11715
11716 /* Process DW_TAG_type_unit.
11717    For TUs we want to skip the first top level sibling if it's not the
11718    actual type being defined by this TU.  In this case the first top
11719    level sibling is there to provide context only.  */
11720
11721 static void
11722 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11723 {
11724   struct die_info *child_die;
11725
11726   prepare_one_comp_unit (cu, die, language_minimal);
11727
11728   /* Initialize (or reinitialize) the machinery for building symtabs.
11729      We do this before processing child DIEs, so that the line header table
11730      is available for DW_AT_decl_file.  */
11731   cu->setup_type_unit_groups (die);
11732
11733   if (die->child != NULL)
11734     {
11735       child_die = die->child;
11736       while (child_die && child_die->tag)
11737         {
11738           process_die (child_die, cu);
11739           child_die = sibling_die (child_die);
11740         }
11741     }
11742 }
11743 \f
11744 /* DWO/DWP files.
11745
11746    http://gcc.gnu.org/wiki/DebugFission
11747    http://gcc.gnu.org/wiki/DebugFissionDWP
11748
11749    To simplify handling of both DWO files ("object" files with the DWARF info)
11750    and DWP files (a file with the DWOs packaged up into one file), we treat
11751    DWP files as having a collection of virtual DWO files.  */
11752
11753 static hashval_t
11754 hash_dwo_file (const void *item)
11755 {
11756   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11757   hashval_t hash;
11758
11759   hash = htab_hash_string (dwo_file->dwo_name);
11760   if (dwo_file->comp_dir != NULL)
11761     hash += htab_hash_string (dwo_file->comp_dir);
11762   return hash;
11763 }
11764
11765 static int
11766 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11767 {
11768   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11769   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11770
11771   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11772     return 0;
11773   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11774     return lhs->comp_dir == rhs->comp_dir;
11775   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11776 }
11777
11778 /* Allocate a hash table for DWO files.  */
11779
11780 static htab_t
11781 allocate_dwo_file_hash_table (struct objfile *objfile)
11782 {
11783   return htab_create_alloc_ex (41,
11784                                hash_dwo_file,
11785                                eq_dwo_file,
11786                                NULL,
11787                                &objfile->objfile_obstack,
11788                                hashtab_obstack_allocate,
11789                                dummy_obstack_deallocate);
11790 }
11791
11792 /* Lookup DWO file DWO_NAME.  */
11793
11794 static void **
11795 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11796                       const char *dwo_name,
11797                       const char *comp_dir)
11798 {
11799   struct dwo_file find_entry;
11800   void **slot;
11801
11802   if (dwarf2_per_objfile->dwo_files == NULL)
11803     dwarf2_per_objfile->dwo_files
11804       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11805
11806   memset (&find_entry, 0, sizeof (find_entry));
11807   find_entry.dwo_name = dwo_name;
11808   find_entry.comp_dir = comp_dir;
11809   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11810
11811   return slot;
11812 }
11813
11814 static hashval_t
11815 hash_dwo_unit (const void *item)
11816 {
11817   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11818
11819   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11820   return dwo_unit->signature;
11821 }
11822
11823 static int
11824 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11825 {
11826   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11827   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11828
11829   /* The signature is assumed to be unique within the DWO file.
11830      So while object file CU dwo_id's always have the value zero,
11831      that's OK, assuming each object file DWO file has only one CU,
11832      and that's the rule for now.  */
11833   return lhs->signature == rhs->signature;
11834 }
11835
11836 /* Allocate a hash table for DWO CUs,TUs.
11837    There is one of these tables for each of CUs,TUs for each DWO file.  */
11838
11839 static htab_t
11840 allocate_dwo_unit_table (struct objfile *objfile)
11841 {
11842   /* Start out with a pretty small number.
11843      Generally DWO files contain only one CU and maybe some TUs.  */
11844   return htab_create_alloc_ex (3,
11845                                hash_dwo_unit,
11846                                eq_dwo_unit,
11847                                NULL,
11848                                &objfile->objfile_obstack,
11849                                hashtab_obstack_allocate,
11850                                dummy_obstack_deallocate);
11851 }
11852
11853 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11854
11855 struct create_dwo_cu_data
11856 {
11857   struct dwo_file *dwo_file;
11858   struct dwo_unit dwo_unit;
11859 };
11860
11861 /* die_reader_func for create_dwo_cu.  */
11862
11863 static void
11864 create_dwo_cu_reader (const struct die_reader_specs *reader,
11865                       const gdb_byte *info_ptr,
11866                       struct die_info *comp_unit_die,
11867                       int has_children,
11868                       void *datap)
11869 {
11870   struct dwarf2_cu *cu = reader->cu;
11871   sect_offset sect_off = cu->per_cu->sect_off;
11872   struct dwarf2_section_info *section = cu->per_cu->section;
11873   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11874   struct dwo_file *dwo_file = data->dwo_file;
11875   struct dwo_unit *dwo_unit = &data->dwo_unit;
11876   struct attribute *attr;
11877
11878   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11879   if (attr == NULL)
11880     {
11881       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11882                    " its dwo_id [in module %s]"),
11883                  sect_offset_str (sect_off), dwo_file->dwo_name);
11884       return;
11885     }
11886
11887   dwo_unit->dwo_file = dwo_file;
11888   dwo_unit->signature = DW_UNSND (attr);
11889   dwo_unit->section = section;
11890   dwo_unit->sect_off = sect_off;
11891   dwo_unit->length = cu->per_cu->length;
11892
11893   if (dwarf_read_debug)
11894     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11895                         sect_offset_str (sect_off),
11896                         hex_string (dwo_unit->signature));
11897 }
11898
11899 /* Create the dwo_units for the CUs in a DWO_FILE.
11900    Note: This function processes DWO files only, not DWP files.  */
11901
11902 static void
11903 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11904                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11905                        htab_t &cus_htab)
11906 {
11907   struct objfile *objfile = dwarf2_per_objfile->objfile;
11908   const gdb_byte *info_ptr, *end_ptr;
11909
11910   dwarf2_read_section (objfile, &section);
11911   info_ptr = section.buffer;
11912
11913   if (info_ptr == NULL)
11914     return;
11915
11916   if (dwarf_read_debug)
11917     {
11918       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11919                           get_section_name (&section),
11920                           get_section_file_name (&section));
11921     }
11922
11923   end_ptr = info_ptr + section.size;
11924   while (info_ptr < end_ptr)
11925     {
11926       struct dwarf2_per_cu_data per_cu;
11927       struct create_dwo_cu_data create_dwo_cu_data;
11928       struct dwo_unit *dwo_unit;
11929       void **slot;
11930       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11931
11932       memset (&create_dwo_cu_data.dwo_unit, 0,
11933               sizeof (create_dwo_cu_data.dwo_unit));
11934       memset (&per_cu, 0, sizeof (per_cu));
11935       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11936       per_cu.is_debug_types = 0;
11937       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11938       per_cu.section = &section;
11939       create_dwo_cu_data.dwo_file = &dwo_file;
11940
11941       init_cutu_and_read_dies_no_follow (
11942           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11943       info_ptr += per_cu.length;
11944
11945       // If the unit could not be parsed, skip it.
11946       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11947         continue;
11948
11949       if (cus_htab == NULL)
11950         cus_htab = allocate_dwo_unit_table (objfile);
11951
11952       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11953       *dwo_unit = create_dwo_cu_data.dwo_unit;
11954       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11955       gdb_assert (slot != NULL);
11956       if (*slot != NULL)
11957         {
11958           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11959           sect_offset dup_sect_off = dup_cu->sect_off;
11960
11961           complaint (_("debug cu entry at offset %s is duplicate to"
11962                        " the entry at offset %s, signature %s"),
11963                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11964                      hex_string (dwo_unit->signature));
11965         }
11966       *slot = (void *)dwo_unit;
11967     }
11968 }
11969
11970 /* DWP file .debug_{cu,tu}_index section format:
11971    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11972
11973    DWP Version 1:
11974
11975    Both index sections have the same format, and serve to map a 64-bit
11976    signature to a set of section numbers.  Each section begins with a header,
11977    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11978    indexes, and a pool of 32-bit section numbers.  The index sections will be
11979    aligned at 8-byte boundaries in the file.
11980
11981    The index section header consists of:
11982
11983     V, 32 bit version number
11984     -, 32 bits unused
11985     N, 32 bit number of compilation units or type units in the index
11986     M, 32 bit number of slots in the hash table
11987
11988    Numbers are recorded using the byte order of the application binary.
11989
11990    The hash table begins at offset 16 in the section, and consists of an array
11991    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11992    order of the application binary).  Unused slots in the hash table are 0.
11993    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11994
11995    The parallel table begins immediately after the hash table
11996    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11997    array of 32-bit indexes (using the byte order of the application binary),
11998    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11999    table contains a 32-bit index into the pool of section numbers.  For unused
12000    hash table slots, the corresponding entry in the parallel table will be 0.
12001
12002    The pool of section numbers begins immediately following the hash table
12003    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12004    section numbers consists of an array of 32-bit words (using the byte order
12005    of the application binary).  Each item in the array is indexed starting
12006    from 0.  The hash table entry provides the index of the first section
12007    number in the set.  Additional section numbers in the set follow, and the
12008    set is terminated by a 0 entry (section number 0 is not used in ELF).
12009
12010    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12011    section must be the first entry in the set, and the .debug_abbrev.dwo must
12012    be the second entry. Other members of the set may follow in any order.
12013
12014    ---
12015
12016    DWP Version 2:
12017
12018    DWP Version 2 combines all the .debug_info, etc. sections into one,
12019    and the entries in the index tables are now offsets into these sections.
12020    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12021    section.
12022
12023    Index Section Contents:
12024     Header
12025     Hash Table of Signatures   dwp_hash_table.hash_table
12026     Parallel Table of Indices  dwp_hash_table.unit_table
12027     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12028     Table of Section Sizes     dwp_hash_table.v2.sizes
12029
12030    The index section header consists of:
12031
12032     V, 32 bit version number
12033     L, 32 bit number of columns in the table of section offsets
12034     N, 32 bit number of compilation units or type units in the index
12035     M, 32 bit number of slots in the hash table
12036
12037    Numbers are recorded using the byte order of the application binary.
12038
12039    The hash table has the same format as version 1.
12040    The parallel table of indices has the same format as version 1,
12041    except that the entries are origin-1 indices into the table of sections
12042    offsets and the table of section sizes.
12043
12044    The table of offsets begins immediately following the parallel table
12045    (at offset 16 + 12 * M from the beginning of the section).  The table is
12046    a two-dimensional array of 32-bit words (using the byte order of the
12047    application binary), with L columns and N+1 rows, in row-major order.
12048    Each row in the array is indexed starting from 0.  The first row provides
12049    a key to the remaining rows: each column in this row provides an identifier
12050    for a debug section, and the offsets in the same column of subsequent rows
12051    refer to that section.  The section identifiers are:
12052
12053     DW_SECT_INFO         1  .debug_info.dwo
12054     DW_SECT_TYPES        2  .debug_types.dwo
12055     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12056     DW_SECT_LINE         4  .debug_line.dwo
12057     DW_SECT_LOC          5  .debug_loc.dwo
12058     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12059     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12060     DW_SECT_MACRO        8  .debug_macro.dwo
12061
12062    The offsets provided by the CU and TU index sections are the base offsets
12063    for the contributions made by each CU or TU to the corresponding section
12064    in the package file.  Each CU and TU header contains an abbrev_offset
12065    field, used to find the abbreviations table for that CU or TU within the
12066    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12067    be interpreted as relative to the base offset given in the index section.
12068    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12069    should be interpreted as relative to the base offset for .debug_line.dwo,
12070    and offsets into other debug sections obtained from DWARF attributes should
12071    also be interpreted as relative to the corresponding base offset.
12072
12073    The table of sizes begins immediately following the table of offsets.
12074    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12075    with L columns and N rows, in row-major order.  Each row in the array is
12076    indexed starting from 1 (row 0 is shared by the two tables).
12077
12078    ---
12079
12080    Hash table lookup is handled the same in version 1 and 2:
12081
12082    We assume that N and M will not exceed 2^32 - 1.
12083    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12084
12085    Given a 64-bit compilation unit signature or a type signature S, an entry
12086    in the hash table is located as follows:
12087
12088    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12089       the low-order k bits all set to 1.
12090
12091    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12092
12093    3) If the hash table entry at index H matches the signature, use that
12094       entry.  If the hash table entry at index H is unused (all zeroes),
12095       terminate the search: the signature is not present in the table.
12096
12097    4) Let H = (H + H') modulo M. Repeat at Step 3.
12098
12099    Because M > N and H' and M are relatively prime, the search is guaranteed
12100    to stop at an unused slot or find the match.  */
12101
12102 /* Create a hash table to map DWO IDs to their CU/TU entry in
12103    .debug_{info,types}.dwo in DWP_FILE.
12104    Returns NULL if there isn't one.
12105    Note: This function processes DWP files only, not DWO files.  */
12106
12107 static struct dwp_hash_table *
12108 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12109                        struct dwp_file *dwp_file, int is_debug_types)
12110 {
12111   struct objfile *objfile = dwarf2_per_objfile->objfile;
12112   bfd *dbfd = dwp_file->dbfd.get ();
12113   const gdb_byte *index_ptr, *index_end;
12114   struct dwarf2_section_info *index;
12115   uint32_t version, nr_columns, nr_units, nr_slots;
12116   struct dwp_hash_table *htab;
12117
12118   if (is_debug_types)
12119     index = &dwp_file->sections.tu_index;
12120   else
12121     index = &dwp_file->sections.cu_index;
12122
12123   if (dwarf2_section_empty_p (index))
12124     return NULL;
12125   dwarf2_read_section (objfile, index);
12126
12127   index_ptr = index->buffer;
12128   index_end = index_ptr + index->size;
12129
12130   version = read_4_bytes (dbfd, index_ptr);
12131   index_ptr += 4;
12132   if (version == 2)
12133     nr_columns = read_4_bytes (dbfd, index_ptr);
12134   else
12135     nr_columns = 0;
12136   index_ptr += 4;
12137   nr_units = read_4_bytes (dbfd, index_ptr);
12138   index_ptr += 4;
12139   nr_slots = read_4_bytes (dbfd, index_ptr);
12140   index_ptr += 4;
12141
12142   if (version != 1 && version != 2)
12143     {
12144       error (_("Dwarf Error: unsupported DWP file version (%s)"
12145                " [in module %s]"),
12146              pulongest (version), dwp_file->name);
12147     }
12148   if (nr_slots != (nr_slots & -nr_slots))
12149     {
12150       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12151                " is not power of 2 [in module %s]"),
12152              pulongest (nr_slots), dwp_file->name);
12153     }
12154
12155   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12156   htab->version = version;
12157   htab->nr_columns = nr_columns;
12158   htab->nr_units = nr_units;
12159   htab->nr_slots = nr_slots;
12160   htab->hash_table = index_ptr;
12161   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12162
12163   /* Exit early if the table is empty.  */
12164   if (nr_slots == 0 || nr_units == 0
12165       || (version == 2 && nr_columns == 0))
12166     {
12167       /* All must be zero.  */
12168       if (nr_slots != 0 || nr_units != 0
12169           || (version == 2 && nr_columns != 0))
12170         {
12171           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12172                        " all zero [in modules %s]"),
12173                      dwp_file->name);
12174         }
12175       return htab;
12176     }
12177
12178   if (version == 1)
12179     {
12180       htab->section_pool.v1.indices =
12181         htab->unit_table + sizeof (uint32_t) * nr_slots;
12182       /* It's harder to decide whether the section is too small in v1.
12183          V1 is deprecated anyway so we punt.  */
12184     }
12185   else
12186     {
12187       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12188       int *ids = htab->section_pool.v2.section_ids;
12189       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
12190       /* Reverse map for error checking.  */
12191       int ids_seen[DW_SECT_MAX + 1];
12192       int i;
12193
12194       if (nr_columns < 2)
12195         {
12196           error (_("Dwarf Error: bad DWP hash table, too few columns"
12197                    " in section table [in module %s]"),
12198                  dwp_file->name);
12199         }
12200       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12201         {
12202           error (_("Dwarf Error: bad DWP hash table, too many columns"
12203                    " in section table [in module %s]"),
12204                  dwp_file->name);
12205         }
12206       memset (ids, 255, sizeof_ids);
12207       memset (ids_seen, 255, sizeof (ids_seen));
12208       for (i = 0; i < nr_columns; ++i)
12209         {
12210           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12211
12212           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12213             {
12214               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12215                        " in section table [in module %s]"),
12216                      id, dwp_file->name);
12217             }
12218           if (ids_seen[id] != -1)
12219             {
12220               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12221                        " id %d in section table [in module %s]"),
12222                      id, dwp_file->name);
12223             }
12224           ids_seen[id] = i;
12225           ids[i] = id;
12226         }
12227       /* Must have exactly one info or types section.  */
12228       if (((ids_seen[DW_SECT_INFO] != -1)
12229            + (ids_seen[DW_SECT_TYPES] != -1))
12230           != 1)
12231         {
12232           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12233                    " DWO info/types section [in module %s]"),
12234                  dwp_file->name);
12235         }
12236       /* Must have an abbrev section.  */
12237       if (ids_seen[DW_SECT_ABBREV] == -1)
12238         {
12239           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12240                    " section [in module %s]"),
12241                  dwp_file->name);
12242         }
12243       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12244       htab->section_pool.v2.sizes =
12245         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12246                                          * nr_units * nr_columns);
12247       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12248                                           * nr_units * nr_columns))
12249           > index_end)
12250         {
12251           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12252                    " [in module %s]"),
12253                  dwp_file->name);
12254         }
12255     }
12256
12257   return htab;
12258 }
12259
12260 /* Update SECTIONS with the data from SECTP.
12261
12262    This function is like the other "locate" section routines that are
12263    passed to bfd_map_over_sections, but in this context the sections to
12264    read comes from the DWP V1 hash table, not the full ELF section table.
12265
12266    The result is non-zero for success, or zero if an error was found.  */
12267
12268 static int
12269 locate_v1_virtual_dwo_sections (asection *sectp,
12270                                 struct virtual_v1_dwo_sections *sections)
12271 {
12272   const struct dwop_section_names *names = &dwop_section_names;
12273
12274   if (section_is_p (sectp->name, &names->abbrev_dwo))
12275     {
12276       /* There can be only one.  */
12277       if (sections->abbrev.s.section != NULL)
12278         return 0;
12279       sections->abbrev.s.section = sectp;
12280       sections->abbrev.size = bfd_get_section_size (sectp);
12281     }
12282   else if (section_is_p (sectp->name, &names->info_dwo)
12283            || section_is_p (sectp->name, &names->types_dwo))
12284     {
12285       /* There can be only one.  */
12286       if (sections->info_or_types.s.section != NULL)
12287         return 0;
12288       sections->info_or_types.s.section = sectp;
12289       sections->info_or_types.size = bfd_get_section_size (sectp);
12290     }
12291   else if (section_is_p (sectp->name, &names->line_dwo))
12292     {
12293       /* There can be only one.  */
12294       if (sections->line.s.section != NULL)
12295         return 0;
12296       sections->line.s.section = sectp;
12297       sections->line.size = bfd_get_section_size (sectp);
12298     }
12299   else if (section_is_p (sectp->name, &names->loc_dwo))
12300     {
12301       /* There can be only one.  */
12302       if (sections->loc.s.section != NULL)
12303         return 0;
12304       sections->loc.s.section = sectp;
12305       sections->loc.size = bfd_get_section_size (sectp);
12306     }
12307   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12308     {
12309       /* There can be only one.  */
12310       if (sections->macinfo.s.section != NULL)
12311         return 0;
12312       sections->macinfo.s.section = sectp;
12313       sections->macinfo.size = bfd_get_section_size (sectp);
12314     }
12315   else if (section_is_p (sectp->name, &names->macro_dwo))
12316     {
12317       /* There can be only one.  */
12318       if (sections->macro.s.section != NULL)
12319         return 0;
12320       sections->macro.s.section = sectp;
12321       sections->macro.size = bfd_get_section_size (sectp);
12322     }
12323   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12324     {
12325       /* There can be only one.  */
12326       if (sections->str_offsets.s.section != NULL)
12327         return 0;
12328       sections->str_offsets.s.section = sectp;
12329       sections->str_offsets.size = bfd_get_section_size (sectp);
12330     }
12331   else
12332     {
12333       /* No other kind of section is valid.  */
12334       return 0;
12335     }
12336
12337   return 1;
12338 }
12339
12340 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12341    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12342    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12343    This is for DWP version 1 files.  */
12344
12345 static struct dwo_unit *
12346 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12347                            struct dwp_file *dwp_file,
12348                            uint32_t unit_index,
12349                            const char *comp_dir,
12350                            ULONGEST signature, int is_debug_types)
12351 {
12352   struct objfile *objfile = dwarf2_per_objfile->objfile;
12353   const struct dwp_hash_table *dwp_htab =
12354     is_debug_types ? dwp_file->tus : dwp_file->cus;
12355   bfd *dbfd = dwp_file->dbfd.get ();
12356   const char *kind = is_debug_types ? "TU" : "CU";
12357   struct dwo_file *dwo_file;
12358   struct dwo_unit *dwo_unit;
12359   struct virtual_v1_dwo_sections sections;
12360   void **dwo_file_slot;
12361   int i;
12362
12363   gdb_assert (dwp_file->version == 1);
12364
12365   if (dwarf_read_debug)
12366     {
12367       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12368                           kind,
12369                           pulongest (unit_index), hex_string (signature),
12370                           dwp_file->name);
12371     }
12372
12373   /* Fetch the sections of this DWO unit.
12374      Put a limit on the number of sections we look for so that bad data
12375      doesn't cause us to loop forever.  */
12376
12377 #define MAX_NR_V1_DWO_SECTIONS \
12378   (1 /* .debug_info or .debug_types */ \
12379    + 1 /* .debug_abbrev */ \
12380    + 1 /* .debug_line */ \
12381    + 1 /* .debug_loc */ \
12382    + 1 /* .debug_str_offsets */ \
12383    + 1 /* .debug_macro or .debug_macinfo */ \
12384    + 1 /* trailing zero */)
12385
12386   memset (&sections, 0, sizeof (sections));
12387
12388   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12389     {
12390       asection *sectp;
12391       uint32_t section_nr =
12392         read_4_bytes (dbfd,
12393                       dwp_htab->section_pool.v1.indices
12394                       + (unit_index + i) * sizeof (uint32_t));
12395
12396       if (section_nr == 0)
12397         break;
12398       if (section_nr >= dwp_file->num_sections)
12399         {
12400           error (_("Dwarf Error: bad DWP hash table, section number too large"
12401                    " [in module %s]"),
12402                  dwp_file->name);
12403         }
12404
12405       sectp = dwp_file->elf_sections[section_nr];
12406       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12407         {
12408           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12409                    " [in module %s]"),
12410                  dwp_file->name);
12411         }
12412     }
12413
12414   if (i < 2
12415       || dwarf2_section_empty_p (&sections.info_or_types)
12416       || dwarf2_section_empty_p (&sections.abbrev))
12417     {
12418       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12419                " [in module %s]"),
12420              dwp_file->name);
12421     }
12422   if (i == MAX_NR_V1_DWO_SECTIONS)
12423     {
12424       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12425                " [in module %s]"),
12426              dwp_file->name);
12427     }
12428
12429   /* It's easier for the rest of the code if we fake a struct dwo_file and
12430      have dwo_unit "live" in that.  At least for now.
12431
12432      The DWP file can be made up of a random collection of CUs and TUs.
12433      However, for each CU + set of TUs that came from the same original DWO
12434      file, we can combine them back into a virtual DWO file to save space
12435      (fewer struct dwo_file objects to allocate).  Remember that for really
12436      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12437
12438   std::string virtual_dwo_name =
12439     string_printf ("virtual-dwo/%d-%d-%d-%d",
12440                    get_section_id (&sections.abbrev),
12441                    get_section_id (&sections.line),
12442                    get_section_id (&sections.loc),
12443                    get_section_id (&sections.str_offsets));
12444   /* Can we use an existing virtual DWO file?  */
12445   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12446                                         virtual_dwo_name.c_str (),
12447                                         comp_dir);
12448   /* Create one if necessary.  */
12449   if (*dwo_file_slot == NULL)
12450     {
12451       if (dwarf_read_debug)
12452         {
12453           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12454                               virtual_dwo_name.c_str ());
12455         }
12456       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12457       dwo_file->dwo_name
12458         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12459                                         virtual_dwo_name.c_str (),
12460                                         virtual_dwo_name.size ());
12461       dwo_file->comp_dir = comp_dir;
12462       dwo_file->sections.abbrev = sections.abbrev;
12463       dwo_file->sections.line = sections.line;
12464       dwo_file->sections.loc = sections.loc;
12465       dwo_file->sections.macinfo = sections.macinfo;
12466       dwo_file->sections.macro = sections.macro;
12467       dwo_file->sections.str_offsets = sections.str_offsets;
12468       /* The "str" section is global to the entire DWP file.  */
12469       dwo_file->sections.str = dwp_file->sections.str;
12470       /* The info or types section is assigned below to dwo_unit,
12471          there's no need to record it in dwo_file.
12472          Also, we can't simply record type sections in dwo_file because
12473          we record a pointer into the vector in dwo_unit.  As we collect more
12474          types we'll grow the vector and eventually have to reallocate space
12475          for it, invalidating all copies of pointers into the previous
12476          contents.  */
12477       *dwo_file_slot = dwo_file;
12478     }
12479   else
12480     {
12481       if (dwarf_read_debug)
12482         {
12483           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12484                               virtual_dwo_name.c_str ());
12485         }
12486       dwo_file = (struct dwo_file *) *dwo_file_slot;
12487     }
12488
12489   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12490   dwo_unit->dwo_file = dwo_file;
12491   dwo_unit->signature = signature;
12492   dwo_unit->section =
12493     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12494   *dwo_unit->section = sections.info_or_types;
12495   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12496
12497   return dwo_unit;
12498 }
12499
12500 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12501    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12502    piece within that section used by a TU/CU, return a virtual section
12503    of just that piece.  */
12504
12505 static struct dwarf2_section_info
12506 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12507                        struct dwarf2_section_info *section,
12508                        bfd_size_type offset, bfd_size_type size)
12509 {
12510   struct dwarf2_section_info result;
12511   asection *sectp;
12512
12513   gdb_assert (section != NULL);
12514   gdb_assert (!section->is_virtual);
12515
12516   memset (&result, 0, sizeof (result));
12517   result.s.containing_section = section;
12518   result.is_virtual = 1;
12519
12520   if (size == 0)
12521     return result;
12522
12523   sectp = get_section_bfd_section (section);
12524
12525   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12526      bounds of the real section.  This is a pretty-rare event, so just
12527      flag an error (easier) instead of a warning and trying to cope.  */
12528   if (sectp == NULL
12529       || offset + size > bfd_get_section_size (sectp))
12530     {
12531       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12532                " in section %s [in module %s]"),
12533              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12534              objfile_name (dwarf2_per_objfile->objfile));
12535     }
12536
12537   result.virtual_offset = offset;
12538   result.size = size;
12539   return result;
12540 }
12541
12542 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12543    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12544    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12545    This is for DWP version 2 files.  */
12546
12547 static struct dwo_unit *
12548 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12549                            struct dwp_file *dwp_file,
12550                            uint32_t unit_index,
12551                            const char *comp_dir,
12552                            ULONGEST signature, int is_debug_types)
12553 {
12554   struct objfile *objfile = dwarf2_per_objfile->objfile;
12555   const struct dwp_hash_table *dwp_htab =
12556     is_debug_types ? dwp_file->tus : dwp_file->cus;
12557   bfd *dbfd = dwp_file->dbfd.get ();
12558   const char *kind = is_debug_types ? "TU" : "CU";
12559   struct dwo_file *dwo_file;
12560   struct dwo_unit *dwo_unit;
12561   struct virtual_v2_dwo_sections sections;
12562   void **dwo_file_slot;
12563   int i;
12564
12565   gdb_assert (dwp_file->version == 2);
12566
12567   if (dwarf_read_debug)
12568     {
12569       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12570                           kind,
12571                           pulongest (unit_index), hex_string (signature),
12572                           dwp_file->name);
12573     }
12574
12575   /* Fetch the section offsets of this DWO unit.  */
12576
12577   memset (&sections, 0, sizeof (sections));
12578
12579   for (i = 0; i < dwp_htab->nr_columns; ++i)
12580     {
12581       uint32_t offset = read_4_bytes (dbfd,
12582                                       dwp_htab->section_pool.v2.offsets
12583                                       + (((unit_index - 1) * dwp_htab->nr_columns
12584                                           + i)
12585                                          * sizeof (uint32_t)));
12586       uint32_t size = read_4_bytes (dbfd,
12587                                     dwp_htab->section_pool.v2.sizes
12588                                     + (((unit_index - 1) * dwp_htab->nr_columns
12589                                         + i)
12590                                        * sizeof (uint32_t)));
12591
12592       switch (dwp_htab->section_pool.v2.section_ids[i])
12593         {
12594         case DW_SECT_INFO:
12595         case DW_SECT_TYPES:
12596           sections.info_or_types_offset = offset;
12597           sections.info_or_types_size = size;
12598           break;
12599         case DW_SECT_ABBREV:
12600           sections.abbrev_offset = offset;
12601           sections.abbrev_size = size;
12602           break;
12603         case DW_SECT_LINE:
12604           sections.line_offset = offset;
12605           sections.line_size = size;
12606           break;
12607         case DW_SECT_LOC:
12608           sections.loc_offset = offset;
12609           sections.loc_size = size;
12610           break;
12611         case DW_SECT_STR_OFFSETS:
12612           sections.str_offsets_offset = offset;
12613           sections.str_offsets_size = size;
12614           break;
12615         case DW_SECT_MACINFO:
12616           sections.macinfo_offset = offset;
12617           sections.macinfo_size = size;
12618           break;
12619         case DW_SECT_MACRO:
12620           sections.macro_offset = offset;
12621           sections.macro_size = size;
12622           break;
12623         }
12624     }
12625
12626   /* It's easier for the rest of the code if we fake a struct dwo_file and
12627      have dwo_unit "live" in that.  At least for now.
12628
12629      The DWP file can be made up of a random collection of CUs and TUs.
12630      However, for each CU + set of TUs that came from the same original DWO
12631      file, we can combine them back into a virtual DWO file to save space
12632      (fewer struct dwo_file objects to allocate).  Remember that for really
12633      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12634
12635   std::string virtual_dwo_name =
12636     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12637                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12638                    (long) (sections.line_size ? sections.line_offset : 0),
12639                    (long) (sections.loc_size ? sections.loc_offset : 0),
12640                    (long) (sections.str_offsets_size
12641                            ? sections.str_offsets_offset : 0));
12642   /* Can we use an existing virtual DWO file?  */
12643   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12644                                         virtual_dwo_name.c_str (),
12645                                         comp_dir);
12646   /* Create one if necessary.  */
12647   if (*dwo_file_slot == NULL)
12648     {
12649       if (dwarf_read_debug)
12650         {
12651           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12652                               virtual_dwo_name.c_str ());
12653         }
12654       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12655       dwo_file->dwo_name
12656         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12657                                         virtual_dwo_name.c_str (),
12658                                         virtual_dwo_name.size ());
12659       dwo_file->comp_dir = comp_dir;
12660       dwo_file->sections.abbrev =
12661         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12662                                sections.abbrev_offset, sections.abbrev_size);
12663       dwo_file->sections.line =
12664         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12665                                sections.line_offset, sections.line_size);
12666       dwo_file->sections.loc =
12667         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12668                                sections.loc_offset, sections.loc_size);
12669       dwo_file->sections.macinfo =
12670         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12671                                sections.macinfo_offset, sections.macinfo_size);
12672       dwo_file->sections.macro =
12673         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12674                                sections.macro_offset, sections.macro_size);
12675       dwo_file->sections.str_offsets =
12676         create_dwp_v2_section (dwarf2_per_objfile,
12677                                &dwp_file->sections.str_offsets,
12678                                sections.str_offsets_offset,
12679                                sections.str_offsets_size);
12680       /* The "str" section is global to the entire DWP file.  */
12681       dwo_file->sections.str = dwp_file->sections.str;
12682       /* The info or types section is assigned below to dwo_unit,
12683          there's no need to record it in dwo_file.
12684          Also, we can't simply record type sections in dwo_file because
12685          we record a pointer into the vector in dwo_unit.  As we collect more
12686          types we'll grow the vector and eventually have to reallocate space
12687          for it, invalidating all copies of pointers into the previous
12688          contents.  */
12689       *dwo_file_slot = dwo_file;
12690     }
12691   else
12692     {
12693       if (dwarf_read_debug)
12694         {
12695           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12696                               virtual_dwo_name.c_str ());
12697         }
12698       dwo_file = (struct dwo_file *) *dwo_file_slot;
12699     }
12700
12701   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12702   dwo_unit->dwo_file = dwo_file;
12703   dwo_unit->signature = signature;
12704   dwo_unit->section =
12705     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12706   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12707                                               is_debug_types
12708                                               ? &dwp_file->sections.types
12709                                               : &dwp_file->sections.info,
12710                                               sections.info_or_types_offset,
12711                                               sections.info_or_types_size);
12712   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12713
12714   return dwo_unit;
12715 }
12716
12717 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12718    Returns NULL if the signature isn't found.  */
12719
12720 static struct dwo_unit *
12721 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12722                         struct dwp_file *dwp_file, const char *comp_dir,
12723                         ULONGEST signature, int is_debug_types)
12724 {
12725   const struct dwp_hash_table *dwp_htab =
12726     is_debug_types ? dwp_file->tus : dwp_file->cus;
12727   bfd *dbfd = dwp_file->dbfd.get ();
12728   uint32_t mask = dwp_htab->nr_slots - 1;
12729   uint32_t hash = signature & mask;
12730   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12731   unsigned int i;
12732   void **slot;
12733   struct dwo_unit find_dwo_cu;
12734
12735   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12736   find_dwo_cu.signature = signature;
12737   slot = htab_find_slot (is_debug_types
12738                          ? dwp_file->loaded_tus
12739                          : dwp_file->loaded_cus,
12740                          &find_dwo_cu, INSERT);
12741
12742   if (*slot != NULL)
12743     return (struct dwo_unit *) *slot;
12744
12745   /* Use a for loop so that we don't loop forever on bad debug info.  */
12746   for (i = 0; i < dwp_htab->nr_slots; ++i)
12747     {
12748       ULONGEST signature_in_table;
12749
12750       signature_in_table =
12751         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12752       if (signature_in_table == signature)
12753         {
12754           uint32_t unit_index =
12755             read_4_bytes (dbfd,
12756                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12757
12758           if (dwp_file->version == 1)
12759             {
12760               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12761                                                  dwp_file, unit_index,
12762                                                  comp_dir, signature,
12763                                                  is_debug_types);
12764             }
12765           else
12766             {
12767               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12768                                                  dwp_file, unit_index,
12769                                                  comp_dir, signature,
12770                                                  is_debug_types);
12771             }
12772           return (struct dwo_unit *) *slot;
12773         }
12774       if (signature_in_table == 0)
12775         return NULL;
12776       hash = (hash + hash2) & mask;
12777     }
12778
12779   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12780            " [in module %s]"),
12781          dwp_file->name);
12782 }
12783
12784 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12785    Open the file specified by FILE_NAME and hand it off to BFD for
12786    preliminary analysis.  Return a newly initialized bfd *, which
12787    includes a canonicalized copy of FILE_NAME.
12788    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12789    SEARCH_CWD is true if the current directory is to be searched.
12790    It will be searched before debug-file-directory.
12791    If successful, the file is added to the bfd include table of the
12792    objfile's bfd (see gdb_bfd_record_inclusion).
12793    If unable to find/open the file, return NULL.
12794    NOTE: This function is derived from symfile_bfd_open.  */
12795
12796 static gdb_bfd_ref_ptr
12797 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12798                     const char *file_name, int is_dwp, int search_cwd)
12799 {
12800   int desc;
12801   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12802      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12803      to debug_file_directory.  */
12804   const char *search_path;
12805   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12806
12807   gdb::unique_xmalloc_ptr<char> search_path_holder;
12808   if (search_cwd)
12809     {
12810       if (*debug_file_directory != '\0')
12811         {
12812           search_path_holder.reset (concat (".", dirname_separator_string,
12813                                             debug_file_directory,
12814                                             (char *) NULL));
12815           search_path = search_path_holder.get ();
12816         }
12817       else
12818         search_path = ".";
12819     }
12820   else
12821     search_path = debug_file_directory;
12822
12823   openp_flags flags = OPF_RETURN_REALPATH;
12824   if (is_dwp)
12825     flags |= OPF_SEARCH_IN_PATH;
12826
12827   gdb::unique_xmalloc_ptr<char> absolute_name;
12828   desc = openp (search_path, flags, file_name,
12829                 O_RDONLY | O_BINARY, &absolute_name);
12830   if (desc < 0)
12831     return NULL;
12832
12833   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12834                                          gnutarget, desc));
12835   if (sym_bfd == NULL)
12836     return NULL;
12837   bfd_set_cacheable (sym_bfd.get (), 1);
12838
12839   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12840     return NULL;
12841
12842   /* Success.  Record the bfd as having been included by the objfile's bfd.
12843      This is important because things like demangled_names_hash lives in the
12844      objfile's per_bfd space and may have references to things like symbol
12845      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12846   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12847
12848   return sym_bfd;
12849 }
12850
12851 /* Try to open DWO file FILE_NAME.
12852    COMP_DIR is the DW_AT_comp_dir attribute.
12853    The result is the bfd handle of the file.
12854    If there is a problem finding or opening the file, return NULL.
12855    Upon success, the canonicalized path of the file is stored in the bfd,
12856    same as symfile_bfd_open.  */
12857
12858 static gdb_bfd_ref_ptr
12859 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12860                const char *file_name, const char *comp_dir)
12861 {
12862   if (IS_ABSOLUTE_PATH (file_name))
12863     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12864                                0 /*is_dwp*/, 0 /*search_cwd*/);
12865
12866   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12867
12868   if (comp_dir != NULL)
12869     {
12870       char *path_to_try = concat (comp_dir, SLASH_STRING,
12871                                   file_name, (char *) NULL);
12872
12873       /* NOTE: If comp_dir is a relative path, this will also try the
12874          search path, which seems useful.  */
12875       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12876                                                 path_to_try,
12877                                                 0 /*is_dwp*/,
12878                                                 1 /*search_cwd*/));
12879       xfree (path_to_try);
12880       if (abfd != NULL)
12881         return abfd;
12882     }
12883
12884   /* That didn't work, try debug-file-directory, which, despite its name,
12885      is a list of paths.  */
12886
12887   if (*debug_file_directory == '\0')
12888     return NULL;
12889
12890   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12891                              0 /*is_dwp*/, 1 /*search_cwd*/);
12892 }
12893
12894 /* This function is mapped across the sections and remembers the offset and
12895    size of each of the DWO debugging sections we are interested in.  */
12896
12897 static void
12898 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12899 {
12900   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12901   const struct dwop_section_names *names = &dwop_section_names;
12902
12903   if (section_is_p (sectp->name, &names->abbrev_dwo))
12904     {
12905       dwo_sections->abbrev.s.section = sectp;
12906       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12907     }
12908   else if (section_is_p (sectp->name, &names->info_dwo))
12909     {
12910       dwo_sections->info.s.section = sectp;
12911       dwo_sections->info.size = bfd_get_section_size (sectp);
12912     }
12913   else if (section_is_p (sectp->name, &names->line_dwo))
12914     {
12915       dwo_sections->line.s.section = sectp;
12916       dwo_sections->line.size = bfd_get_section_size (sectp);
12917     }
12918   else if (section_is_p (sectp->name, &names->loc_dwo))
12919     {
12920       dwo_sections->loc.s.section = sectp;
12921       dwo_sections->loc.size = bfd_get_section_size (sectp);
12922     }
12923   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12924     {
12925       dwo_sections->macinfo.s.section = sectp;
12926       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12927     }
12928   else if (section_is_p (sectp->name, &names->macro_dwo))
12929     {
12930       dwo_sections->macro.s.section = sectp;
12931       dwo_sections->macro.size = bfd_get_section_size (sectp);
12932     }
12933   else if (section_is_p (sectp->name, &names->str_dwo))
12934     {
12935       dwo_sections->str.s.section = sectp;
12936       dwo_sections->str.size = bfd_get_section_size (sectp);
12937     }
12938   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12939     {
12940       dwo_sections->str_offsets.s.section = sectp;
12941       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12942     }
12943   else if (section_is_p (sectp->name, &names->types_dwo))
12944     {
12945       struct dwarf2_section_info type_section;
12946
12947       memset (&type_section, 0, sizeof (type_section));
12948       type_section.s.section = sectp;
12949       type_section.size = bfd_get_section_size (sectp);
12950       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12951                      &type_section);
12952     }
12953 }
12954
12955 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12956    by PER_CU.  This is for the non-DWP case.
12957    The result is NULL if DWO_NAME can't be found.  */
12958
12959 static struct dwo_file *
12960 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12961                         const char *dwo_name, const char *comp_dir)
12962 {
12963   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12964   struct objfile *objfile = dwarf2_per_objfile->objfile;
12965
12966   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12967   if (dbfd == NULL)
12968     {
12969       if (dwarf_read_debug)
12970         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12971       return NULL;
12972     }
12973
12974   /* We use a unique pointer here, despite the obstack allocation,
12975      because a dwo_file needs some cleanup if it is abandoned.  */
12976   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12977                                         struct dwo_file));
12978   dwo_file->dwo_name = dwo_name;
12979   dwo_file->comp_dir = comp_dir;
12980   dwo_file->dbfd = dbfd.release ();
12981
12982   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12983                          &dwo_file->sections);
12984
12985   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12986                          dwo_file->cus);
12987
12988   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12989                                  dwo_file->sections.types, dwo_file->tus);
12990
12991   if (dwarf_read_debug)
12992     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12993
12994   return dwo_file.release ();
12995 }
12996
12997 /* This function is mapped across the sections and remembers the offset and
12998    size of each of the DWP debugging sections common to version 1 and 2 that
12999    we are interested in.  */
13000
13001 static void
13002 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13003                                    void *dwp_file_ptr)
13004 {
13005   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13006   const struct dwop_section_names *names = &dwop_section_names;
13007   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13008
13009   /* Record the ELF section number for later lookup: this is what the
13010      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13011   gdb_assert (elf_section_nr < dwp_file->num_sections);
13012   dwp_file->elf_sections[elf_section_nr] = sectp;
13013
13014   /* Look for specific sections that we need.  */
13015   if (section_is_p (sectp->name, &names->str_dwo))
13016     {
13017       dwp_file->sections.str.s.section = sectp;
13018       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13019     }
13020   else if (section_is_p (sectp->name, &names->cu_index))
13021     {
13022       dwp_file->sections.cu_index.s.section = sectp;
13023       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13024     }
13025   else if (section_is_p (sectp->name, &names->tu_index))
13026     {
13027       dwp_file->sections.tu_index.s.section = sectp;
13028       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13029     }
13030 }
13031
13032 /* This function is mapped across the sections and remembers the offset and
13033    size of each of the DWP version 2 debugging sections that we are interested
13034    in.  This is split into a separate function because we don't know if we
13035    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13036
13037 static void
13038 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13039 {
13040   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13041   const struct dwop_section_names *names = &dwop_section_names;
13042   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13043
13044   /* Record the ELF section number for later lookup: this is what the
13045      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13046   gdb_assert (elf_section_nr < dwp_file->num_sections);
13047   dwp_file->elf_sections[elf_section_nr] = sectp;
13048
13049   /* Look for specific sections that we need.  */
13050   if (section_is_p (sectp->name, &names->abbrev_dwo))
13051     {
13052       dwp_file->sections.abbrev.s.section = sectp;
13053       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13054     }
13055   else if (section_is_p (sectp->name, &names->info_dwo))
13056     {
13057       dwp_file->sections.info.s.section = sectp;
13058       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13059     }
13060   else if (section_is_p (sectp->name, &names->line_dwo))
13061     {
13062       dwp_file->sections.line.s.section = sectp;
13063       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13064     }
13065   else if (section_is_p (sectp->name, &names->loc_dwo))
13066     {
13067       dwp_file->sections.loc.s.section = sectp;
13068       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13069     }
13070   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13071     {
13072       dwp_file->sections.macinfo.s.section = sectp;
13073       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13074     }
13075   else if (section_is_p (sectp->name, &names->macro_dwo))
13076     {
13077       dwp_file->sections.macro.s.section = sectp;
13078       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13079     }
13080   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13081     {
13082       dwp_file->sections.str_offsets.s.section = sectp;
13083       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13084     }
13085   else if (section_is_p (sectp->name, &names->types_dwo))
13086     {
13087       dwp_file->sections.types.s.section = sectp;
13088       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13089     }
13090 }
13091
13092 /* Hash function for dwp_file loaded CUs/TUs.  */
13093
13094 static hashval_t
13095 hash_dwp_loaded_cutus (const void *item)
13096 {
13097   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13098
13099   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13100   return dwo_unit->signature;
13101 }
13102
13103 /* Equality function for dwp_file loaded CUs/TUs.  */
13104
13105 static int
13106 eq_dwp_loaded_cutus (const void *a, const void *b)
13107 {
13108   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13109   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13110
13111   return dua->signature == dub->signature;
13112 }
13113
13114 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13115
13116 static htab_t
13117 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13118 {
13119   return htab_create_alloc_ex (3,
13120                                hash_dwp_loaded_cutus,
13121                                eq_dwp_loaded_cutus,
13122                                NULL,
13123                                &objfile->objfile_obstack,
13124                                hashtab_obstack_allocate,
13125                                dummy_obstack_deallocate);
13126 }
13127
13128 /* Try to open DWP file FILE_NAME.
13129    The result is the bfd handle of the file.
13130    If there is a problem finding or opening the file, return NULL.
13131    Upon success, the canonicalized path of the file is stored in the bfd,
13132    same as symfile_bfd_open.  */
13133
13134 static gdb_bfd_ref_ptr
13135 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13136                const char *file_name)
13137 {
13138   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13139                                             1 /*is_dwp*/,
13140                                             1 /*search_cwd*/));
13141   if (abfd != NULL)
13142     return abfd;
13143
13144   /* Work around upstream bug 15652.
13145      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13146      [Whether that's a "bug" is debatable, but it is getting in our way.]
13147      We have no real idea where the dwp file is, because gdb's realpath-ing
13148      of the executable's path may have discarded the needed info.
13149      [IWBN if the dwp file name was recorded in the executable, akin to
13150      .gnu_debuglink, but that doesn't exist yet.]
13151      Strip the directory from FILE_NAME and search again.  */
13152   if (*debug_file_directory != '\0')
13153     {
13154       /* Don't implicitly search the current directory here.
13155          If the user wants to search "." to handle this case,
13156          it must be added to debug-file-directory.  */
13157       return try_open_dwop_file (dwarf2_per_objfile,
13158                                  lbasename (file_name), 1 /*is_dwp*/,
13159                                  0 /*search_cwd*/);
13160     }
13161
13162   return NULL;
13163 }
13164
13165 /* Initialize the use of the DWP file for the current objfile.
13166    By convention the name of the DWP file is ${objfile}.dwp.
13167    The result is NULL if it can't be found.  */
13168
13169 static std::unique_ptr<struct dwp_file>
13170 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13171 {
13172   struct objfile *objfile = dwarf2_per_objfile->objfile;
13173
13174   /* Try to find first .dwp for the binary file before any symbolic links
13175      resolving.  */
13176
13177   /* If the objfile is a debug file, find the name of the real binary
13178      file and get the name of dwp file from there.  */
13179   std::string dwp_name;
13180   if (objfile->separate_debug_objfile_backlink != NULL)
13181     {
13182       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13183       const char *backlink_basename = lbasename (backlink->original_name);
13184
13185       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13186     }
13187   else
13188     dwp_name = objfile->original_name;
13189
13190   dwp_name += ".dwp";
13191
13192   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13193   if (dbfd == NULL
13194       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13195     {
13196       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13197       dwp_name = objfile_name (objfile);
13198       dwp_name += ".dwp";
13199       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13200     }
13201
13202   if (dbfd == NULL)
13203     {
13204       if (dwarf_read_debug)
13205         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13206       return std::unique_ptr<dwp_file> ();
13207     }
13208
13209   const char *name = bfd_get_filename (dbfd.get ());
13210   std::unique_ptr<struct dwp_file> dwp_file
13211     (new struct dwp_file (name, std::move (dbfd)));
13212
13213   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
13214   dwp_file->elf_sections =
13215     OBSTACK_CALLOC (&objfile->objfile_obstack,
13216                     dwp_file->num_sections, asection *);
13217
13218   bfd_map_over_sections (dwp_file->dbfd.get (),
13219                          dwarf2_locate_common_dwp_sections,
13220                          dwp_file.get ());
13221
13222   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13223                                          0);
13224
13225   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13226                                          1);
13227
13228   /* The DWP file version is stored in the hash table.  Oh well.  */
13229   if (dwp_file->cus && dwp_file->tus
13230       && dwp_file->cus->version != dwp_file->tus->version)
13231     {
13232       /* Technically speaking, we should try to limp along, but this is
13233          pretty bizarre.  We use pulongest here because that's the established
13234          portability solution (e.g, we cannot use %u for uint32_t).  */
13235       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13236                " TU version %s [in DWP file %s]"),
13237              pulongest (dwp_file->cus->version),
13238              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13239     }
13240
13241   if (dwp_file->cus)
13242     dwp_file->version = dwp_file->cus->version;
13243   else if (dwp_file->tus)
13244     dwp_file->version = dwp_file->tus->version;
13245   else
13246     dwp_file->version = 2;
13247
13248   if (dwp_file->version == 2)
13249     bfd_map_over_sections (dwp_file->dbfd.get (),
13250                            dwarf2_locate_v2_dwp_sections,
13251                            dwp_file.get ());
13252
13253   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13254   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13255
13256   if (dwarf_read_debug)
13257     {
13258       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13259       fprintf_unfiltered (gdb_stdlog,
13260                           "    %s CUs, %s TUs\n",
13261                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13262                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13263     }
13264
13265   return dwp_file;
13266 }
13267
13268 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13269
13270 static struct dwp_file *
13271 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13272 {
13273   if (! dwarf2_per_objfile->dwp_checked)
13274     {
13275       dwarf2_per_objfile->dwp_file
13276         = open_and_init_dwp_file (dwarf2_per_objfile);
13277       dwarf2_per_objfile->dwp_checked = 1;
13278     }
13279   return dwarf2_per_objfile->dwp_file.get ();
13280 }
13281
13282 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13283    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13284    or in the DWP file for the objfile, referenced by THIS_UNIT.
13285    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13286    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13287
13288    This is called, for example, when wanting to read a variable with a
13289    complex location.  Therefore we don't want to do file i/o for every call.
13290    Therefore we don't want to look for a DWO file on every call.
13291    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13292    then we check if we've already seen DWO_NAME, and only THEN do we check
13293    for a DWO file.
13294
13295    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13296    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13297
13298 static struct dwo_unit *
13299 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13300                  const char *dwo_name, const char *comp_dir,
13301                  ULONGEST signature, int is_debug_types)
13302 {
13303   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13304   struct objfile *objfile = dwarf2_per_objfile->objfile;
13305   const char *kind = is_debug_types ? "TU" : "CU";
13306   void **dwo_file_slot;
13307   struct dwo_file *dwo_file;
13308   struct dwp_file *dwp_file;
13309
13310   /* First see if there's a DWP file.
13311      If we have a DWP file but didn't find the DWO inside it, don't
13312      look for the original DWO file.  It makes gdb behave differently
13313      depending on whether one is debugging in the build tree.  */
13314
13315   dwp_file = get_dwp_file (dwarf2_per_objfile);
13316   if (dwp_file != NULL)
13317     {
13318       const struct dwp_hash_table *dwp_htab =
13319         is_debug_types ? dwp_file->tus : dwp_file->cus;
13320
13321       if (dwp_htab != NULL)
13322         {
13323           struct dwo_unit *dwo_cutu =
13324             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13325                                     signature, is_debug_types);
13326
13327           if (dwo_cutu != NULL)
13328             {
13329               if (dwarf_read_debug)
13330                 {
13331                   fprintf_unfiltered (gdb_stdlog,
13332                                       "Virtual DWO %s %s found: @%s\n",
13333                                       kind, hex_string (signature),
13334                                       host_address_to_string (dwo_cutu));
13335                 }
13336               return dwo_cutu;
13337             }
13338         }
13339     }
13340   else
13341     {
13342       /* No DWP file, look for the DWO file.  */
13343
13344       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13345                                             dwo_name, comp_dir);
13346       if (*dwo_file_slot == NULL)
13347         {
13348           /* Read in the file and build a table of the CUs/TUs it contains.  */
13349           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13350         }
13351       /* NOTE: This will be NULL if unable to open the file.  */
13352       dwo_file = (struct dwo_file *) *dwo_file_slot;
13353
13354       if (dwo_file != NULL)
13355         {
13356           struct dwo_unit *dwo_cutu = NULL;
13357
13358           if (is_debug_types && dwo_file->tus)
13359             {
13360               struct dwo_unit find_dwo_cutu;
13361
13362               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13363               find_dwo_cutu.signature = signature;
13364               dwo_cutu
13365                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13366             }
13367           else if (!is_debug_types && dwo_file->cus)
13368             {
13369               struct dwo_unit find_dwo_cutu;
13370
13371               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13372               find_dwo_cutu.signature = signature;
13373               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13374                                                        &find_dwo_cutu);
13375             }
13376
13377           if (dwo_cutu != NULL)
13378             {
13379               if (dwarf_read_debug)
13380                 {
13381                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13382                                       kind, dwo_name, hex_string (signature),
13383                                       host_address_to_string (dwo_cutu));
13384                 }
13385               return dwo_cutu;
13386             }
13387         }
13388     }
13389
13390   /* We didn't find it.  This could mean a dwo_id mismatch, or
13391      someone deleted the DWO/DWP file, or the search path isn't set up
13392      correctly to find the file.  */
13393
13394   if (dwarf_read_debug)
13395     {
13396       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13397                           kind, dwo_name, hex_string (signature));
13398     }
13399
13400   /* This is a warning and not a complaint because it can be caused by
13401      pilot error (e.g., user accidentally deleting the DWO).  */
13402   {
13403     /* Print the name of the DWP file if we looked there, helps the user
13404        better diagnose the problem.  */
13405     std::string dwp_text;
13406
13407     if (dwp_file != NULL)
13408       dwp_text = string_printf (" [in DWP file %s]",
13409                                 lbasename (dwp_file->name));
13410
13411     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13412                " [in module %s]"),
13413              kind, dwo_name, hex_string (signature),
13414              dwp_text.c_str (),
13415              this_unit->is_debug_types ? "TU" : "CU",
13416              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13417   }
13418   return NULL;
13419 }
13420
13421 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13422    See lookup_dwo_cutu_unit for details.  */
13423
13424 static struct dwo_unit *
13425 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13426                       const char *dwo_name, const char *comp_dir,
13427                       ULONGEST signature)
13428 {
13429   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13430 }
13431
13432 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13433    See lookup_dwo_cutu_unit for details.  */
13434
13435 static struct dwo_unit *
13436 lookup_dwo_type_unit (struct signatured_type *this_tu,
13437                       const char *dwo_name, const char *comp_dir)
13438 {
13439   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13440 }
13441
13442 /* Traversal function for queue_and_load_all_dwo_tus.  */
13443
13444 static int
13445 queue_and_load_dwo_tu (void **slot, void *info)
13446 {
13447   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13448   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13449   ULONGEST signature = dwo_unit->signature;
13450   struct signatured_type *sig_type =
13451     lookup_dwo_signatured_type (per_cu->cu, signature);
13452
13453   if (sig_type != NULL)
13454     {
13455       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13456
13457       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13458          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13459          while processing PER_CU.  */
13460       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13461         load_full_type_unit (sig_cu);
13462       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13463     }
13464
13465   return 1;
13466 }
13467
13468 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13469    The DWO may have the only definition of the type, though it may not be
13470    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13471    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13472
13473 static void
13474 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13475 {
13476   struct dwo_unit *dwo_unit;
13477   struct dwo_file *dwo_file;
13478
13479   gdb_assert (!per_cu->is_debug_types);
13480   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13481   gdb_assert (per_cu->cu != NULL);
13482
13483   dwo_unit = per_cu->cu->dwo_unit;
13484   gdb_assert (dwo_unit != NULL);
13485
13486   dwo_file = dwo_unit->dwo_file;
13487   if (dwo_file->tus != NULL)
13488     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13489 }
13490
13491 /* Free all resources associated with DWO_FILE.
13492    Close the DWO file and munmap the sections.  */
13493
13494 static void
13495 free_dwo_file (struct dwo_file *dwo_file)
13496 {
13497   /* Note: dbfd is NULL for virtual DWO files.  */
13498   gdb_bfd_unref (dwo_file->dbfd);
13499
13500   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13501 }
13502
13503 /* Traversal function for free_dwo_files.  */
13504
13505 static int
13506 free_dwo_file_from_slot (void **slot, void *info)
13507 {
13508   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13509
13510   free_dwo_file (dwo_file);
13511
13512   return 1;
13513 }
13514
13515 /* Free all resources associated with DWO_FILES.  */
13516
13517 static void
13518 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13519 {
13520   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13521 }
13522 \f
13523 /* Read in various DIEs.  */
13524
13525 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13526    Inherit only the children of the DW_AT_abstract_origin DIE not being
13527    already referenced by DW_AT_abstract_origin from the children of the
13528    current DIE.  */
13529
13530 static void
13531 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13532 {
13533   struct die_info *child_die;
13534   sect_offset *offsetp;
13535   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13536   struct die_info *origin_die;
13537   /* Iterator of the ORIGIN_DIE children.  */
13538   struct die_info *origin_child_die;
13539   struct attribute *attr;
13540   struct dwarf2_cu *origin_cu;
13541   struct pending **origin_previous_list_in_scope;
13542
13543   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13544   if (!attr)
13545     return;
13546
13547   /* Note that following die references may follow to a die in a
13548      different cu.  */
13549
13550   origin_cu = cu;
13551   origin_die = follow_die_ref (die, attr, &origin_cu);
13552
13553   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13554      symbols in.  */
13555   origin_previous_list_in_scope = origin_cu->list_in_scope;
13556   origin_cu->list_in_scope = cu->list_in_scope;
13557
13558   if (die->tag != origin_die->tag
13559       && !(die->tag == DW_TAG_inlined_subroutine
13560            && origin_die->tag == DW_TAG_subprogram))
13561     complaint (_("DIE %s and its abstract origin %s have different tags"),
13562                sect_offset_str (die->sect_off),
13563                sect_offset_str (origin_die->sect_off));
13564
13565   std::vector<sect_offset> offsets;
13566
13567   for (child_die = die->child;
13568        child_die && child_die->tag;
13569        child_die = sibling_die (child_die))
13570     {
13571       struct die_info *child_origin_die;
13572       struct dwarf2_cu *child_origin_cu;
13573
13574       /* We are trying to process concrete instance entries:
13575          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13576          it's not relevant to our analysis here. i.e. detecting DIEs that are
13577          present in the abstract instance but not referenced in the concrete
13578          one.  */
13579       if (child_die->tag == DW_TAG_call_site
13580           || child_die->tag == DW_TAG_GNU_call_site)
13581         continue;
13582
13583       /* For each CHILD_DIE, find the corresponding child of
13584          ORIGIN_DIE.  If there is more than one layer of
13585          DW_AT_abstract_origin, follow them all; there shouldn't be,
13586          but GCC versions at least through 4.4 generate this (GCC PR
13587          40573).  */
13588       child_origin_die = child_die;
13589       child_origin_cu = cu;
13590       while (1)
13591         {
13592           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13593                               child_origin_cu);
13594           if (attr == NULL)
13595             break;
13596           child_origin_die = follow_die_ref (child_origin_die, attr,
13597                                              &child_origin_cu);
13598         }
13599
13600       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13601          counterpart may exist.  */
13602       if (child_origin_die != child_die)
13603         {
13604           if (child_die->tag != child_origin_die->tag
13605               && !(child_die->tag == DW_TAG_inlined_subroutine
13606                    && child_origin_die->tag == DW_TAG_subprogram))
13607             complaint (_("Child DIE %s and its abstract origin %s have "
13608                          "different tags"),
13609                        sect_offset_str (child_die->sect_off),
13610                        sect_offset_str (child_origin_die->sect_off));
13611           if (child_origin_die->parent != origin_die)
13612             complaint (_("Child DIE %s and its abstract origin %s have "
13613                          "different parents"),
13614                        sect_offset_str (child_die->sect_off),
13615                        sect_offset_str (child_origin_die->sect_off));
13616           else
13617             offsets.push_back (child_origin_die->sect_off);
13618         }
13619     }
13620   std::sort (offsets.begin (), offsets.end ());
13621   sect_offset *offsets_end = offsets.data () + offsets.size ();
13622   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13623     if (offsetp[-1] == *offsetp)
13624       complaint (_("Multiple children of DIE %s refer "
13625                    "to DIE %s as their abstract origin"),
13626                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13627
13628   offsetp = offsets.data ();
13629   origin_child_die = origin_die->child;
13630   while (origin_child_die && origin_child_die->tag)
13631     {
13632       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13633       while (offsetp < offsets_end
13634              && *offsetp < origin_child_die->sect_off)
13635         offsetp++;
13636       if (offsetp >= offsets_end
13637           || *offsetp > origin_child_die->sect_off)
13638         {
13639           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13640              Check whether we're already processing ORIGIN_CHILD_DIE.
13641              This can happen with mutually referenced abstract_origins.
13642              PR 16581.  */
13643           if (!origin_child_die->in_process)
13644             process_die (origin_child_die, origin_cu);
13645         }
13646       origin_child_die = sibling_die (origin_child_die);
13647     }
13648   origin_cu->list_in_scope = origin_previous_list_in_scope;
13649 }
13650
13651 static void
13652 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13653 {
13654   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13655   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13656   struct context_stack *newobj;
13657   CORE_ADDR lowpc;
13658   CORE_ADDR highpc;
13659   struct die_info *child_die;
13660   struct attribute *attr, *call_line, *call_file;
13661   const char *name;
13662   CORE_ADDR baseaddr;
13663   struct block *block;
13664   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13665   std::vector<struct symbol *> template_args;
13666   struct template_symbol *templ_func = NULL;
13667
13668   if (inlined_func)
13669     {
13670       /* If we do not have call site information, we can't show the
13671          caller of this inlined function.  That's too confusing, so
13672          only use the scope for local variables.  */
13673       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13674       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13675       if (call_line == NULL || call_file == NULL)
13676         {
13677           read_lexical_block_scope (die, cu);
13678           return;
13679         }
13680     }
13681
13682   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13683
13684   name = dwarf2_name (die, cu);
13685
13686   /* Ignore functions with missing or empty names.  These are actually
13687      illegal according to the DWARF standard.  */
13688   if (name == NULL)
13689     {
13690       complaint (_("missing name for subprogram DIE at %s"),
13691                  sect_offset_str (die->sect_off));
13692       return;
13693     }
13694
13695   /* Ignore functions with missing or invalid low and high pc attributes.  */
13696   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13697       <= PC_BOUNDS_INVALID)
13698     {
13699       attr = dwarf2_attr (die, DW_AT_external, cu);
13700       if (!attr || !DW_UNSND (attr))
13701         complaint (_("cannot get low and high bounds "
13702                      "for subprogram DIE at %s"),
13703                    sect_offset_str (die->sect_off));
13704       return;
13705     }
13706
13707   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13708   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13709
13710   /* If we have any template arguments, then we must allocate a
13711      different sort of symbol.  */
13712   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13713     {
13714       if (child_die->tag == DW_TAG_template_type_param
13715           || child_die->tag == DW_TAG_template_value_param)
13716         {
13717           templ_func = allocate_template_symbol (objfile);
13718           templ_func->subclass = SYMBOL_TEMPLATE;
13719           break;
13720         }
13721     }
13722
13723   newobj = cu->get_builder ()->push_context (0, lowpc);
13724   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13725                              (struct symbol *) templ_func);
13726
13727   /* If there is a location expression for DW_AT_frame_base, record
13728      it.  */
13729   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13730   if (attr)
13731     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13732
13733   /* If there is a location for the static link, record it.  */
13734   newobj->static_link = NULL;
13735   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13736   if (attr)
13737     {
13738       newobj->static_link
13739         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13740       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13741     }
13742
13743   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13744
13745   if (die->child != NULL)
13746     {
13747       child_die = die->child;
13748       while (child_die && child_die->tag)
13749         {
13750           if (child_die->tag == DW_TAG_template_type_param
13751               || child_die->tag == DW_TAG_template_value_param)
13752             {
13753               struct symbol *arg = new_symbol (child_die, NULL, cu);
13754
13755               if (arg != NULL)
13756                 template_args.push_back (arg);
13757             }
13758           else
13759             process_die (child_die, cu);
13760           child_die = sibling_die (child_die);
13761         }
13762     }
13763
13764   inherit_abstract_dies (die, cu);
13765
13766   /* If we have a DW_AT_specification, we might need to import using
13767      directives from the context of the specification DIE.  See the
13768      comment in determine_prefix.  */
13769   if (cu->language == language_cplus
13770       && dwarf2_attr (die, DW_AT_specification, cu))
13771     {
13772       struct dwarf2_cu *spec_cu = cu;
13773       struct die_info *spec_die = die_specification (die, &spec_cu);
13774
13775       while (spec_die)
13776         {
13777           child_die = spec_die->child;
13778           while (child_die && child_die->tag)
13779             {
13780               if (child_die->tag == DW_TAG_imported_module)
13781                 process_die (child_die, spec_cu);
13782               child_die = sibling_die (child_die);
13783             }
13784
13785           /* In some cases, GCC generates specification DIEs that
13786              themselves contain DW_AT_specification attributes.  */
13787           spec_die = die_specification (spec_die, &spec_cu);
13788         }
13789     }
13790
13791   struct context_stack cstk = cu->get_builder ()->pop_context ();
13792   /* Make a block for the local symbols within.  */
13793   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13794                                      cstk.static_link, lowpc, highpc);
13795
13796   /* For C++, set the block's scope.  */
13797   if ((cu->language == language_cplus
13798        || cu->language == language_fortran
13799        || cu->language == language_d
13800        || cu->language == language_rust)
13801       && cu->processing_has_namespace_info)
13802     block_set_scope (block, determine_prefix (die, cu),
13803                      &objfile->objfile_obstack);
13804
13805   /* If we have address ranges, record them.  */
13806   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13807
13808   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13809
13810   /* Attach template arguments to function.  */
13811   if (!template_args.empty ())
13812     {
13813       gdb_assert (templ_func != NULL);
13814
13815       templ_func->n_template_arguments = template_args.size ();
13816       templ_func->template_arguments
13817         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13818                      templ_func->n_template_arguments);
13819       memcpy (templ_func->template_arguments,
13820               template_args.data (),
13821               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13822
13823       /* Make sure that the symtab is set on the new symbols.  Even
13824          though they don't appear in this symtab directly, other parts
13825          of gdb assume that symbols do, and this is reasonably
13826          true.  */
13827       for (symbol *sym : template_args)
13828         symbol_set_symtab (sym, symbol_symtab (templ_func));
13829     }
13830
13831   /* In C++, we can have functions nested inside functions (e.g., when
13832      a function declares a class that has methods).  This means that
13833      when we finish processing a function scope, we may need to go
13834      back to building a containing block's symbol lists.  */
13835   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13836   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13837
13838   /* If we've finished processing a top-level function, subsequent
13839      symbols go in the file symbol list.  */
13840   if (cu->get_builder ()->outermost_context_p ())
13841     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13842 }
13843
13844 /* Process all the DIES contained within a lexical block scope.  Start
13845    a new scope, process the dies, and then close the scope.  */
13846
13847 static void
13848 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13849 {
13850   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13851   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13852   CORE_ADDR lowpc, highpc;
13853   struct die_info *child_die;
13854   CORE_ADDR baseaddr;
13855
13856   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13857
13858   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13859   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13860      as multiple lexical blocks?  Handling children in a sane way would
13861      be nasty.  Might be easier to properly extend generic blocks to
13862      describe ranges.  */
13863   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13864     {
13865     case PC_BOUNDS_NOT_PRESENT:
13866       /* DW_TAG_lexical_block has no attributes, process its children as if
13867          there was no wrapping by that DW_TAG_lexical_block.
13868          GCC does no longer produces such DWARF since GCC r224161.  */
13869       for (child_die = die->child;
13870            child_die != NULL && child_die->tag;
13871            child_die = sibling_die (child_die))
13872         process_die (child_die, cu);
13873       return;
13874     case PC_BOUNDS_INVALID:
13875       return;
13876     }
13877   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13878   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13879
13880   cu->get_builder ()->push_context (0, lowpc);
13881   if (die->child != NULL)
13882     {
13883       child_die = die->child;
13884       while (child_die && child_die->tag)
13885         {
13886           process_die (child_die, cu);
13887           child_die = sibling_die (child_die);
13888         }
13889     }
13890   inherit_abstract_dies (die, cu);
13891   struct context_stack cstk = cu->get_builder ()->pop_context ();
13892
13893   if (*cu->get_builder ()->get_local_symbols () != NULL
13894       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13895     {
13896       struct block *block
13897         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13898                                      cstk.start_addr, highpc);
13899
13900       /* Note that recording ranges after traversing children, as we
13901          do here, means that recording a parent's ranges entails
13902          walking across all its children's ranges as they appear in
13903          the address map, which is quadratic behavior.
13904
13905          It would be nicer to record the parent's ranges before
13906          traversing its children, simply overriding whatever you find
13907          there.  But since we don't even decide whether to create a
13908          block until after we've traversed its children, that's hard
13909          to do.  */
13910       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13911     }
13912   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13913   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13914 }
13915
13916 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13917
13918 static void
13919 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13920 {
13921   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13922   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13923   CORE_ADDR pc, baseaddr;
13924   struct attribute *attr;
13925   struct call_site *call_site, call_site_local;
13926   void **slot;
13927   int nparams;
13928   struct die_info *child_die;
13929
13930   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13931
13932   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13933   if (attr == NULL)
13934     {
13935       /* This was a pre-DWARF-5 GNU extension alias
13936          for DW_AT_call_return_pc.  */
13937       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13938     }
13939   if (!attr)
13940     {
13941       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13942                    "DIE %s [in module %s]"),
13943                  sect_offset_str (die->sect_off), objfile_name (objfile));
13944       return;
13945     }
13946   pc = attr_value_as_address (attr) + baseaddr;
13947   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13948
13949   if (cu->call_site_htab == NULL)
13950     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13951                                                NULL, &objfile->objfile_obstack,
13952                                                hashtab_obstack_allocate, NULL);
13953   call_site_local.pc = pc;
13954   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13955   if (*slot != NULL)
13956     {
13957       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13958                    "DIE %s [in module %s]"),
13959                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13960                  objfile_name (objfile));
13961       return;
13962     }
13963
13964   /* Count parameters at the caller.  */
13965
13966   nparams = 0;
13967   for (child_die = die->child; child_die && child_die->tag;
13968        child_die = sibling_die (child_die))
13969     {
13970       if (child_die->tag != DW_TAG_call_site_parameter
13971           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13972         {
13973           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13974                        "DW_TAG_call_site child DIE %s [in module %s]"),
13975                      child_die->tag, sect_offset_str (child_die->sect_off),
13976                      objfile_name (objfile));
13977           continue;
13978         }
13979
13980       nparams++;
13981     }
13982
13983   call_site
13984     = ((struct call_site *)
13985        obstack_alloc (&objfile->objfile_obstack,
13986                       sizeof (*call_site)
13987                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13988   *slot = call_site;
13989   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13990   call_site->pc = pc;
13991
13992   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13993       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13994     {
13995       struct die_info *func_die;
13996
13997       /* Skip also over DW_TAG_inlined_subroutine.  */
13998       for (func_die = die->parent;
13999            func_die && func_die->tag != DW_TAG_subprogram
14000            && func_die->tag != DW_TAG_subroutine_type;
14001            func_die = func_die->parent);
14002
14003       /* DW_AT_call_all_calls is a superset
14004          of DW_AT_call_all_tail_calls.  */
14005       if (func_die
14006           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14007           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14008           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14009           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14010         {
14011           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14012              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14013              both the initial caller containing the real return address PC and
14014              the final callee containing the current PC of a chain of tail
14015              calls do not need to have the tail call list complete.  But any
14016              function candidate for a virtual tail call frame searched via
14017              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14018              determined unambiguously.  */
14019         }
14020       else
14021         {
14022           struct type *func_type = NULL;
14023
14024           if (func_die)
14025             func_type = get_die_type (func_die, cu);
14026           if (func_type != NULL)
14027             {
14028               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14029
14030               /* Enlist this call site to the function.  */
14031               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14032               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14033             }
14034           else
14035             complaint (_("Cannot find function owning DW_TAG_call_site "
14036                          "DIE %s [in module %s]"),
14037                        sect_offset_str (die->sect_off), objfile_name (objfile));
14038         }
14039     }
14040
14041   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14042   if (attr == NULL)
14043     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14044   if (attr == NULL)
14045     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14046   if (attr == NULL)
14047     {
14048       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14049       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14050     }
14051   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14052   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14053     /* Keep NULL DWARF_BLOCK.  */;
14054   else if (attr_form_is_block (attr))
14055     {
14056       struct dwarf2_locexpr_baton *dlbaton;
14057
14058       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14059       dlbaton->data = DW_BLOCK (attr)->data;
14060       dlbaton->size = DW_BLOCK (attr)->size;
14061       dlbaton->per_cu = cu->per_cu;
14062
14063       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14064     }
14065   else if (attr_form_is_ref (attr))
14066     {
14067       struct dwarf2_cu *target_cu = cu;
14068       struct die_info *target_die;
14069
14070       target_die = follow_die_ref (die, attr, &target_cu);
14071       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14072       if (die_is_declaration (target_die, target_cu))
14073         {
14074           const char *target_physname;
14075
14076           /* Prefer the mangled name; otherwise compute the demangled one.  */
14077           target_physname = dw2_linkage_name (target_die, target_cu);
14078           if (target_physname == NULL)
14079             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14080           if (target_physname == NULL)
14081             complaint (_("DW_AT_call_target target DIE has invalid "
14082                          "physname, for referencing DIE %s [in module %s]"),
14083                        sect_offset_str (die->sect_off), objfile_name (objfile));
14084           else
14085             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14086         }
14087       else
14088         {
14089           CORE_ADDR lowpc;
14090
14091           /* DW_AT_entry_pc should be preferred.  */
14092           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14093               <= PC_BOUNDS_INVALID)
14094             complaint (_("DW_AT_call_target target DIE has invalid "
14095                          "low pc, for referencing DIE %s [in module %s]"),
14096                        sect_offset_str (die->sect_off), objfile_name (objfile));
14097           else
14098             {
14099               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14100               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14101             }
14102         }
14103     }
14104   else
14105     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14106                  "block nor reference, for DIE %s [in module %s]"),
14107                sect_offset_str (die->sect_off), objfile_name (objfile));
14108
14109   call_site->per_cu = cu->per_cu;
14110
14111   for (child_die = die->child;
14112        child_die && child_die->tag;
14113        child_die = sibling_die (child_die))
14114     {
14115       struct call_site_parameter *parameter;
14116       struct attribute *loc, *origin;
14117
14118       if (child_die->tag != DW_TAG_call_site_parameter
14119           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14120         {
14121           /* Already printed the complaint above.  */
14122           continue;
14123         }
14124
14125       gdb_assert (call_site->parameter_count < nparams);
14126       parameter = &call_site->parameter[call_site->parameter_count];
14127
14128       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14129          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14130          register is contained in DW_AT_call_value.  */
14131
14132       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14133       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14134       if (origin == NULL)
14135         {
14136           /* This was a pre-DWARF-5 GNU extension alias
14137              for DW_AT_call_parameter.  */
14138           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14139         }
14140       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14141         {
14142           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14143
14144           sect_offset sect_off
14145             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14146           if (!offset_in_cu_p (&cu->header, sect_off))
14147             {
14148               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14149                  binding can be done only inside one CU.  Such referenced DIE
14150                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14151               complaint (_("DW_AT_call_parameter offset is not in CU for "
14152                            "DW_TAG_call_site child DIE %s [in module %s]"),
14153                          sect_offset_str (child_die->sect_off),
14154                          objfile_name (objfile));
14155               continue;
14156             }
14157           parameter->u.param_cu_off
14158             = (cu_offset) (sect_off - cu->header.sect_off);
14159         }
14160       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14161         {
14162           complaint (_("No DW_FORM_block* DW_AT_location for "
14163                        "DW_TAG_call_site child DIE %s [in module %s]"),
14164                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14165           continue;
14166         }
14167       else
14168         {
14169           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14170             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14171           if (parameter->u.dwarf_reg != -1)
14172             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14173           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14174                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14175                                              &parameter->u.fb_offset))
14176             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14177           else
14178             {
14179               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14180                            "for DW_FORM_block* DW_AT_location is supported for "
14181                            "DW_TAG_call_site child DIE %s "
14182                            "[in module %s]"),
14183                          sect_offset_str (child_die->sect_off),
14184                          objfile_name (objfile));
14185               continue;
14186             }
14187         }
14188
14189       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14190       if (attr == NULL)
14191         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14192       if (!attr_form_is_block (attr))
14193         {
14194           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14195                        "DW_TAG_call_site child DIE %s [in module %s]"),
14196                      sect_offset_str (child_die->sect_off),
14197                      objfile_name (objfile));
14198           continue;
14199         }
14200       parameter->value = DW_BLOCK (attr)->data;
14201       parameter->value_size = DW_BLOCK (attr)->size;
14202
14203       /* Parameters are not pre-cleared by memset above.  */
14204       parameter->data_value = NULL;
14205       parameter->data_value_size = 0;
14206       call_site->parameter_count++;
14207
14208       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14209       if (attr == NULL)
14210         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14211       if (attr)
14212         {
14213           if (!attr_form_is_block (attr))
14214             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14215                          "DW_TAG_call_site child DIE %s [in module %s]"),
14216                        sect_offset_str (child_die->sect_off),
14217                        objfile_name (objfile));
14218           else
14219             {
14220               parameter->data_value = DW_BLOCK (attr)->data;
14221               parameter->data_value_size = DW_BLOCK (attr)->size;
14222             }
14223         }
14224     }
14225 }
14226
14227 /* Helper function for read_variable.  If DIE represents a virtual
14228    table, then return the type of the concrete object that is
14229    associated with the virtual table.  Otherwise, return NULL.  */
14230
14231 static struct type *
14232 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14233 {
14234   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14235   if (attr == NULL)
14236     return NULL;
14237
14238   /* Find the type DIE.  */
14239   struct die_info *type_die = NULL;
14240   struct dwarf2_cu *type_cu = cu;
14241
14242   if (attr_form_is_ref (attr))
14243     type_die = follow_die_ref (die, attr, &type_cu);
14244   if (type_die == NULL)
14245     return NULL;
14246
14247   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14248     return NULL;
14249   return die_containing_type (type_die, type_cu);
14250 }
14251
14252 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14253
14254 static void
14255 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14256 {
14257   struct rust_vtable_symbol *storage = NULL;
14258
14259   if (cu->language == language_rust)
14260     {
14261       struct type *containing_type = rust_containing_type (die, cu);
14262
14263       if (containing_type != NULL)
14264         {
14265           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14266
14267           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14268                                     struct rust_vtable_symbol);
14269           initialize_objfile_symbol (storage);
14270           storage->concrete_type = containing_type;
14271           storage->subclass = SYMBOL_RUST_VTABLE;
14272         }
14273     }
14274
14275   struct symbol *res = new_symbol (die, NULL, cu, storage);
14276   struct attribute *abstract_origin
14277     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14278   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
14279   if (res == NULL && loc && abstract_origin)
14280     {
14281       /* We have a variable without a name, but with a location and an abstract
14282          origin.  This may be a concrete instance of an abstract variable
14283          referenced from an DW_OP_GNU_variable_value, so save it to find it back
14284          later.  */
14285       struct dwarf2_cu *origin_cu = cu;
14286       struct die_info *origin_die
14287         = follow_die_ref (die, abstract_origin, &origin_cu);
14288       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
14289       dpo->abstract_to_concrete[origin_die].push_back (die);
14290     }
14291 }
14292
14293 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14294    reading .debug_rnglists.
14295    Callback's type should be:
14296     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14297    Return true if the attributes are present and valid, otherwise,
14298    return false.  */
14299
14300 template <typename Callback>
14301 static bool
14302 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14303                          Callback &&callback)
14304 {
14305   struct dwarf2_per_objfile *dwarf2_per_objfile
14306     = cu->per_cu->dwarf2_per_objfile;
14307   struct objfile *objfile = dwarf2_per_objfile->objfile;
14308   bfd *obfd = objfile->obfd;
14309   /* Base address selection entry.  */
14310   CORE_ADDR base;
14311   int found_base;
14312   const gdb_byte *buffer;
14313   CORE_ADDR baseaddr;
14314   bool overflow = false;
14315
14316   found_base = cu->base_known;
14317   base = cu->base_address;
14318
14319   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14320   if (offset >= dwarf2_per_objfile->rnglists.size)
14321     {
14322       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14323                  offset);
14324       return false;
14325     }
14326   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14327
14328   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14329
14330   while (1)
14331     {
14332       /* Initialize it due to a false compiler warning.  */
14333       CORE_ADDR range_beginning = 0, range_end = 0;
14334       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14335                                  + dwarf2_per_objfile->rnglists.size);
14336       unsigned int bytes_read;
14337
14338       if (buffer == buf_end)
14339         {
14340           overflow = true;
14341           break;
14342         }
14343       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14344       switch (rlet)
14345         {
14346         case DW_RLE_end_of_list:
14347           break;
14348         case DW_RLE_base_address:
14349           if (buffer + cu->header.addr_size > buf_end)
14350             {
14351               overflow = true;
14352               break;
14353             }
14354           base = read_address (obfd, buffer, cu, &bytes_read);
14355           found_base = 1;
14356           buffer += bytes_read;
14357           break;
14358         case DW_RLE_start_length:
14359           if (buffer + cu->header.addr_size > buf_end)
14360             {
14361               overflow = true;
14362               break;
14363             }
14364           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14365           buffer += bytes_read;
14366           range_end = (range_beginning
14367                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14368           buffer += bytes_read;
14369           if (buffer > buf_end)
14370             {
14371               overflow = true;
14372               break;
14373             }
14374           break;
14375         case DW_RLE_offset_pair:
14376           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14377           buffer += bytes_read;
14378           if (buffer > buf_end)
14379             {
14380               overflow = true;
14381               break;
14382             }
14383           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14384           buffer += bytes_read;
14385           if (buffer > buf_end)
14386             {
14387               overflow = true;
14388               break;
14389             }
14390           break;
14391         case DW_RLE_start_end:
14392           if (buffer + 2 * cu->header.addr_size > buf_end)
14393             {
14394               overflow = true;
14395               break;
14396             }
14397           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14398           buffer += bytes_read;
14399           range_end = read_address (obfd, buffer, cu, &bytes_read);
14400           buffer += bytes_read;
14401           break;
14402         default:
14403           complaint (_("Invalid .debug_rnglists data (no base address)"));
14404           return false;
14405         }
14406       if (rlet == DW_RLE_end_of_list || overflow)
14407         break;
14408       if (rlet == DW_RLE_base_address)
14409         continue;
14410
14411       if (!found_base)
14412         {
14413           /* We have no valid base address for the ranges
14414              data.  */
14415           complaint (_("Invalid .debug_rnglists data (no base address)"));
14416           return false;
14417         }
14418
14419       if (range_beginning > range_end)
14420         {
14421           /* Inverted range entries are invalid.  */
14422           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14423           return false;
14424         }
14425
14426       /* Empty range entries have no effect.  */
14427       if (range_beginning == range_end)
14428         continue;
14429
14430       range_beginning += base;
14431       range_end += base;
14432
14433       /* A not-uncommon case of bad debug info.
14434          Don't pollute the addrmap with bad data.  */
14435       if (range_beginning + baseaddr == 0
14436           && !dwarf2_per_objfile->has_section_at_zero)
14437         {
14438           complaint (_(".debug_rnglists entry has start address of zero"
14439                        " [in module %s]"), objfile_name (objfile));
14440           continue;
14441         }
14442
14443       callback (range_beginning, range_end);
14444     }
14445
14446   if (overflow)
14447     {
14448       complaint (_("Offset %d is not terminated "
14449                    "for DW_AT_ranges attribute"),
14450                  offset);
14451       return false;
14452     }
14453
14454   return true;
14455 }
14456
14457 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14458    Callback's type should be:
14459     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14460    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14461
14462 template <typename Callback>
14463 static int
14464 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14465                        Callback &&callback)
14466 {
14467   struct dwarf2_per_objfile *dwarf2_per_objfile
14468       = cu->per_cu->dwarf2_per_objfile;
14469   struct objfile *objfile = dwarf2_per_objfile->objfile;
14470   struct comp_unit_head *cu_header = &cu->header;
14471   bfd *obfd = objfile->obfd;
14472   unsigned int addr_size = cu_header->addr_size;
14473   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14474   /* Base address selection entry.  */
14475   CORE_ADDR base;
14476   int found_base;
14477   unsigned int dummy;
14478   const gdb_byte *buffer;
14479   CORE_ADDR baseaddr;
14480
14481   if (cu_header->version >= 5)
14482     return dwarf2_rnglists_process (offset, cu, callback);
14483
14484   found_base = cu->base_known;
14485   base = cu->base_address;
14486
14487   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14488   if (offset >= dwarf2_per_objfile->ranges.size)
14489     {
14490       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14491                  offset);
14492       return 0;
14493     }
14494   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14495
14496   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14497
14498   while (1)
14499     {
14500       CORE_ADDR range_beginning, range_end;
14501
14502       range_beginning = read_address (obfd, buffer, cu, &dummy);
14503       buffer += addr_size;
14504       range_end = read_address (obfd, buffer, cu, &dummy);
14505       buffer += addr_size;
14506       offset += 2 * addr_size;
14507
14508       /* An end of list marker is a pair of zero addresses.  */
14509       if (range_beginning == 0 && range_end == 0)
14510         /* Found the end of list entry.  */
14511         break;
14512
14513       /* Each base address selection entry is a pair of 2 values.
14514          The first is the largest possible address, the second is
14515          the base address.  Check for a base address here.  */
14516       if ((range_beginning & mask) == mask)
14517         {
14518           /* If we found the largest possible address, then we already
14519              have the base address in range_end.  */
14520           base = range_end;
14521           found_base = 1;
14522           continue;
14523         }
14524
14525       if (!found_base)
14526         {
14527           /* We have no valid base address for the ranges
14528              data.  */
14529           complaint (_("Invalid .debug_ranges data (no base address)"));
14530           return 0;
14531         }
14532
14533       if (range_beginning > range_end)
14534         {
14535           /* Inverted range entries are invalid.  */
14536           complaint (_("Invalid .debug_ranges data (inverted range)"));
14537           return 0;
14538         }
14539
14540       /* Empty range entries have no effect.  */
14541       if (range_beginning == range_end)
14542         continue;
14543
14544       range_beginning += base;
14545       range_end += base;
14546
14547       /* A not-uncommon case of bad debug info.
14548          Don't pollute the addrmap with bad data.  */
14549       if (range_beginning + baseaddr == 0
14550           && !dwarf2_per_objfile->has_section_at_zero)
14551         {
14552           complaint (_(".debug_ranges entry has start address of zero"
14553                        " [in module %s]"), objfile_name (objfile));
14554           continue;
14555         }
14556
14557       callback (range_beginning, range_end);
14558     }
14559
14560   return 1;
14561 }
14562
14563 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14564    Return 1 if the attributes are present and valid, otherwise, return 0.
14565    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14566
14567 static int
14568 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14569                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14570                     struct partial_symtab *ranges_pst)
14571 {
14572   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14573   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14574   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14575                                        SECT_OFF_TEXT (objfile));
14576   int low_set = 0;
14577   CORE_ADDR low = 0;
14578   CORE_ADDR high = 0;
14579   int retval;
14580
14581   retval = dwarf2_ranges_process (offset, cu,
14582     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14583     {
14584       if (ranges_pst != NULL)
14585         {
14586           CORE_ADDR lowpc;
14587           CORE_ADDR highpc;
14588
14589           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14590                                                range_beginning + baseaddr)
14591                    - baseaddr);
14592           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14593                                                 range_end + baseaddr)
14594                     - baseaddr);
14595           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
14596                              lowpc, highpc - 1, ranges_pst);
14597         }
14598
14599       /* FIXME: This is recording everything as a low-high
14600          segment of consecutive addresses.  We should have a
14601          data structure for discontiguous block ranges
14602          instead.  */
14603       if (! low_set)
14604         {
14605           low = range_beginning;
14606           high = range_end;
14607           low_set = 1;
14608         }
14609       else
14610         {
14611           if (range_beginning < low)
14612             low = range_beginning;
14613           if (range_end > high)
14614             high = range_end;
14615         }
14616     });
14617   if (!retval)
14618     return 0;
14619
14620   if (! low_set)
14621     /* If the first entry is an end-of-list marker, the range
14622        describes an empty scope, i.e. no instructions.  */
14623     return 0;
14624
14625   if (low_return)
14626     *low_return = low;
14627   if (high_return)
14628     *high_return = high;
14629   return 1;
14630 }
14631
14632 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14633    definition for the return value.  *LOWPC and *HIGHPC are set iff
14634    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14635
14636 static enum pc_bounds_kind
14637 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14638                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14639                       struct partial_symtab *pst)
14640 {
14641   struct dwarf2_per_objfile *dwarf2_per_objfile
14642     = cu->per_cu->dwarf2_per_objfile;
14643   struct attribute *attr;
14644   struct attribute *attr_high;
14645   CORE_ADDR low = 0;
14646   CORE_ADDR high = 0;
14647   enum pc_bounds_kind ret;
14648
14649   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14650   if (attr_high)
14651     {
14652       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14653       if (attr)
14654         {
14655           low = attr_value_as_address (attr);
14656           high = attr_value_as_address (attr_high);
14657           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14658             high += low;
14659         }
14660       else
14661         /* Found high w/o low attribute.  */
14662         return PC_BOUNDS_INVALID;
14663
14664       /* Found consecutive range of addresses.  */
14665       ret = PC_BOUNDS_HIGH_LOW;
14666     }
14667   else
14668     {
14669       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14670       if (attr != NULL)
14671         {
14672           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14673              We take advantage of the fact that DW_AT_ranges does not appear
14674              in DW_TAG_compile_unit of DWO files.  */
14675           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14676           unsigned int ranges_offset = (DW_UNSND (attr)
14677                                         + (need_ranges_base
14678                                            ? cu->ranges_base
14679                                            : 0));
14680
14681           /* Value of the DW_AT_ranges attribute is the offset in the
14682              .debug_ranges section.  */
14683           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14684             return PC_BOUNDS_INVALID;
14685           /* Found discontinuous range of addresses.  */
14686           ret = PC_BOUNDS_RANGES;
14687         }
14688       else
14689         return PC_BOUNDS_NOT_PRESENT;
14690     }
14691
14692   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14693   if (high <= low)
14694     return PC_BOUNDS_INVALID;
14695
14696   /* When using the GNU linker, .gnu.linkonce. sections are used to
14697      eliminate duplicate copies of functions and vtables and such.
14698      The linker will arbitrarily choose one and discard the others.
14699      The AT_*_pc values for such functions refer to local labels in
14700      these sections.  If the section from that file was discarded, the
14701      labels are not in the output, so the relocs get a value of 0.
14702      If this is a discarded function, mark the pc bounds as invalid,
14703      so that GDB will ignore it.  */
14704   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14705     return PC_BOUNDS_INVALID;
14706
14707   *lowpc = low;
14708   if (highpc)
14709     *highpc = high;
14710   return ret;
14711 }
14712
14713 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14714    its low and high PC addresses.  Do nothing if these addresses could not
14715    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14716    and HIGHPC to the high address if greater than HIGHPC.  */
14717
14718 static void
14719 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14720                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14721                                  struct dwarf2_cu *cu)
14722 {
14723   CORE_ADDR low, high;
14724   struct die_info *child = die->child;
14725
14726   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14727     {
14728       *lowpc = std::min (*lowpc, low);
14729       *highpc = std::max (*highpc, high);
14730     }
14731
14732   /* If the language does not allow nested subprograms (either inside
14733      subprograms or lexical blocks), we're done.  */
14734   if (cu->language != language_ada)
14735     return;
14736
14737   /* Check all the children of the given DIE.  If it contains nested
14738      subprograms, then check their pc bounds.  Likewise, we need to
14739      check lexical blocks as well, as they may also contain subprogram
14740      definitions.  */
14741   while (child && child->tag)
14742     {
14743       if (child->tag == DW_TAG_subprogram
14744           || child->tag == DW_TAG_lexical_block)
14745         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14746       child = sibling_die (child);
14747     }
14748 }
14749
14750 /* Get the low and high pc's represented by the scope DIE, and store
14751    them in *LOWPC and *HIGHPC.  If the correct values can't be
14752    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14753
14754 static void
14755 get_scope_pc_bounds (struct die_info *die,
14756                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14757                      struct dwarf2_cu *cu)
14758 {
14759   CORE_ADDR best_low = (CORE_ADDR) -1;
14760   CORE_ADDR best_high = (CORE_ADDR) 0;
14761   CORE_ADDR current_low, current_high;
14762
14763   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14764       >= PC_BOUNDS_RANGES)
14765     {
14766       best_low = current_low;
14767       best_high = current_high;
14768     }
14769   else
14770     {
14771       struct die_info *child = die->child;
14772
14773       while (child && child->tag)
14774         {
14775           switch (child->tag) {
14776           case DW_TAG_subprogram:
14777             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14778             break;
14779           case DW_TAG_namespace:
14780           case DW_TAG_module:
14781             /* FIXME: carlton/2004-01-16: Should we do this for
14782                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14783                that current GCC's always emit the DIEs corresponding
14784                to definitions of methods of classes as children of a
14785                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14786                the DIEs giving the declarations, which could be
14787                anywhere).  But I don't see any reason why the
14788                standards says that they have to be there.  */
14789             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14790
14791             if (current_low != ((CORE_ADDR) -1))
14792               {
14793                 best_low = std::min (best_low, current_low);
14794                 best_high = std::max (best_high, current_high);
14795               }
14796             break;
14797           default:
14798             /* Ignore.  */
14799             break;
14800           }
14801
14802           child = sibling_die (child);
14803         }
14804     }
14805
14806   *lowpc = best_low;
14807   *highpc = best_high;
14808 }
14809
14810 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14811    in DIE.  */
14812
14813 static void
14814 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14815                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14816 {
14817   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14818   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14819   struct attribute *attr;
14820   struct attribute *attr_high;
14821
14822   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14823   if (attr_high)
14824     {
14825       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14826       if (attr)
14827         {
14828           CORE_ADDR low = attr_value_as_address (attr);
14829           CORE_ADDR high = attr_value_as_address (attr_high);
14830
14831           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14832             high += low;
14833
14834           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14835           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14836           cu->get_builder ()->record_block_range (block, low, high - 1);
14837         }
14838     }
14839
14840   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14841   if (attr)
14842     {
14843       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14844          We take advantage of the fact that DW_AT_ranges does not appear
14845          in DW_TAG_compile_unit of DWO files.  */
14846       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14847
14848       /* The value of the DW_AT_ranges attribute is the offset of the
14849          address range list in the .debug_ranges section.  */
14850       unsigned long offset = (DW_UNSND (attr)
14851                               + (need_ranges_base ? cu->ranges_base : 0));
14852
14853       std::vector<blockrange> blockvec;
14854       dwarf2_ranges_process (offset, cu,
14855         [&] (CORE_ADDR start, CORE_ADDR end)
14856         {
14857           start += baseaddr;
14858           end += baseaddr;
14859           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14860           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14861           cu->get_builder ()->record_block_range (block, start, end - 1);
14862           blockvec.emplace_back (start, end);
14863         });
14864
14865       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14866     }
14867 }
14868
14869 /* Check whether the producer field indicates either of GCC < 4.6, or the
14870    Intel C/C++ compiler, and cache the result in CU.  */
14871
14872 static void
14873 check_producer (struct dwarf2_cu *cu)
14874 {
14875   int major, minor;
14876
14877   if (cu->producer == NULL)
14878     {
14879       /* For unknown compilers expect their behavior is DWARF version
14880          compliant.
14881
14882          GCC started to support .debug_types sections by -gdwarf-4 since
14883          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14884          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14885          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14886          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14887     }
14888   else if (producer_is_gcc (cu->producer, &major, &minor))
14889     {
14890       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14891       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14892     }
14893   else if (producer_is_icc (cu->producer, &major, &minor))
14894     {
14895       cu->producer_is_icc = true;
14896       cu->producer_is_icc_lt_14 = major < 14;
14897     }
14898   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14899     cu->producer_is_codewarrior = true;
14900   else
14901     {
14902       /* For other non-GCC compilers, expect their behavior is DWARF version
14903          compliant.  */
14904     }
14905
14906   cu->checked_producer = true;
14907 }
14908
14909 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14910    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14911    during 4.6.0 experimental.  */
14912
14913 static bool
14914 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14915 {
14916   if (!cu->checked_producer)
14917     check_producer (cu);
14918
14919   return cu->producer_is_gxx_lt_4_6;
14920 }
14921
14922
14923 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14924    with incorrect is_stmt attributes.  */
14925
14926 static bool
14927 producer_is_codewarrior (struct dwarf2_cu *cu)
14928 {
14929   if (!cu->checked_producer)
14930     check_producer (cu);
14931
14932   return cu->producer_is_codewarrior;
14933 }
14934
14935 /* Return the default accessibility type if it is not overriden by
14936    DW_AT_accessibility.  */
14937
14938 static enum dwarf_access_attribute
14939 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14940 {
14941   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14942     {
14943       /* The default DWARF 2 accessibility for members is public, the default
14944          accessibility for inheritance is private.  */
14945
14946       if (die->tag != DW_TAG_inheritance)
14947         return DW_ACCESS_public;
14948       else
14949         return DW_ACCESS_private;
14950     }
14951   else
14952     {
14953       /* DWARF 3+ defines the default accessibility a different way.  The same
14954          rules apply now for DW_TAG_inheritance as for the members and it only
14955          depends on the container kind.  */
14956
14957       if (die->parent->tag == DW_TAG_class_type)
14958         return DW_ACCESS_private;
14959       else
14960         return DW_ACCESS_public;
14961     }
14962 }
14963
14964 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14965    offset.  If the attribute was not found return 0, otherwise return
14966    1.  If it was found but could not properly be handled, set *OFFSET
14967    to 0.  */
14968
14969 static int
14970 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14971                              LONGEST *offset)
14972 {
14973   struct attribute *attr;
14974
14975   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14976   if (attr != NULL)
14977     {
14978       *offset = 0;
14979
14980       /* Note that we do not check for a section offset first here.
14981          This is because DW_AT_data_member_location is new in DWARF 4,
14982          so if we see it, we can assume that a constant form is really
14983          a constant and not a section offset.  */
14984       if (attr_form_is_constant (attr))
14985         *offset = dwarf2_get_attr_constant_value (attr, 0);
14986       else if (attr_form_is_section_offset (attr))
14987         dwarf2_complex_location_expr_complaint ();
14988       else if (attr_form_is_block (attr))
14989         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14990       else
14991         dwarf2_complex_location_expr_complaint ();
14992
14993       return 1;
14994     }
14995
14996   return 0;
14997 }
14998
14999 /* Add an aggregate field to the field list.  */
15000
15001 static void
15002 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15003                   struct dwarf2_cu *cu)
15004 {
15005   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15006   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15007   struct nextfield *new_field;
15008   struct attribute *attr;
15009   struct field *fp;
15010   const char *fieldname = "";
15011
15012   if (die->tag == DW_TAG_inheritance)
15013     {
15014       fip->baseclasses.emplace_back ();
15015       new_field = &fip->baseclasses.back ();
15016     }
15017   else
15018     {
15019       fip->fields.emplace_back ();
15020       new_field = &fip->fields.back ();
15021     }
15022
15023   fip->nfields++;
15024
15025   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15026   if (attr)
15027     new_field->accessibility = DW_UNSND (attr);
15028   else
15029     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15030   if (new_field->accessibility != DW_ACCESS_public)
15031     fip->non_public_fields = 1;
15032
15033   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15034   if (attr)
15035     new_field->virtuality = DW_UNSND (attr);
15036   else
15037     new_field->virtuality = DW_VIRTUALITY_none;
15038
15039   fp = &new_field->field;
15040
15041   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15042     {
15043       LONGEST offset;
15044
15045       /* Data member other than a C++ static data member.  */
15046
15047       /* Get type of field.  */
15048       fp->type = die_type (die, cu);
15049
15050       SET_FIELD_BITPOS (*fp, 0);
15051
15052       /* Get bit size of field (zero if none).  */
15053       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15054       if (attr)
15055         {
15056           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15057         }
15058       else
15059         {
15060           FIELD_BITSIZE (*fp) = 0;
15061         }
15062
15063       /* Get bit offset of field.  */
15064       if (handle_data_member_location (die, cu, &offset))
15065         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15066       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15067       if (attr)
15068         {
15069           if (gdbarch_bits_big_endian (gdbarch))
15070             {
15071               /* For big endian bits, the DW_AT_bit_offset gives the
15072                  additional bit offset from the MSB of the containing
15073                  anonymous object to the MSB of the field.  We don't
15074                  have to do anything special since we don't need to
15075                  know the size of the anonymous object.  */
15076               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15077             }
15078           else
15079             {
15080               /* For little endian bits, compute the bit offset to the
15081                  MSB of the anonymous object, subtract off the number of
15082                  bits from the MSB of the field to the MSB of the
15083                  object, and then subtract off the number of bits of
15084                  the field itself.  The result is the bit offset of
15085                  the LSB of the field.  */
15086               int anonymous_size;
15087               int bit_offset = DW_UNSND (attr);
15088
15089               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15090               if (attr)
15091                 {
15092                   /* The size of the anonymous object containing
15093                      the bit field is explicit, so use the
15094                      indicated size (in bytes).  */
15095                   anonymous_size = DW_UNSND (attr);
15096                 }
15097               else
15098                 {
15099                   /* The size of the anonymous object containing
15100                      the bit field must be inferred from the type
15101                      attribute of the data member containing the
15102                      bit field.  */
15103                   anonymous_size = TYPE_LENGTH (fp->type);
15104                 }
15105               SET_FIELD_BITPOS (*fp,
15106                                 (FIELD_BITPOS (*fp)
15107                                  + anonymous_size * bits_per_byte
15108                                  - bit_offset - FIELD_BITSIZE (*fp)));
15109             }
15110         }
15111       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15112       if (attr != NULL)
15113         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15114                                 + dwarf2_get_attr_constant_value (attr, 0)));
15115
15116       /* Get name of field.  */
15117       fieldname = dwarf2_name (die, cu);
15118       if (fieldname == NULL)
15119         fieldname = "";
15120
15121       /* The name is already allocated along with this objfile, so we don't
15122          need to duplicate it for the type.  */
15123       fp->name = fieldname;
15124
15125       /* Change accessibility for artificial fields (e.g. virtual table
15126          pointer or virtual base class pointer) to private.  */
15127       if (dwarf2_attr (die, DW_AT_artificial, cu))
15128         {
15129           FIELD_ARTIFICIAL (*fp) = 1;
15130           new_field->accessibility = DW_ACCESS_private;
15131           fip->non_public_fields = 1;
15132         }
15133     }
15134   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15135     {
15136       /* C++ static member.  */
15137
15138       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15139          is a declaration, but all versions of G++ as of this writing
15140          (so through at least 3.2.1) incorrectly generate
15141          DW_TAG_variable tags.  */
15142
15143       const char *physname;
15144
15145       /* Get name of field.  */
15146       fieldname = dwarf2_name (die, cu);
15147       if (fieldname == NULL)
15148         return;
15149
15150       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15151       if (attr
15152           /* Only create a symbol if this is an external value.
15153              new_symbol checks this and puts the value in the global symbol
15154              table, which we want.  If it is not external, new_symbol
15155              will try to put the value in cu->list_in_scope which is wrong.  */
15156           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15157         {
15158           /* A static const member, not much different than an enum as far as
15159              we're concerned, except that we can support more types.  */
15160           new_symbol (die, NULL, cu);
15161         }
15162
15163       /* Get physical name.  */
15164       physname = dwarf2_physname (fieldname, die, cu);
15165
15166       /* The name is already allocated along with this objfile, so we don't
15167          need to duplicate it for the type.  */
15168       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15169       FIELD_TYPE (*fp) = die_type (die, cu);
15170       FIELD_NAME (*fp) = fieldname;
15171     }
15172   else if (die->tag == DW_TAG_inheritance)
15173     {
15174       LONGEST offset;
15175
15176       /* C++ base class field.  */
15177       if (handle_data_member_location (die, cu, &offset))
15178         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15179       FIELD_BITSIZE (*fp) = 0;
15180       FIELD_TYPE (*fp) = die_type (die, cu);
15181       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15182     }
15183   else if (die->tag == DW_TAG_variant_part)
15184     {
15185       /* process_structure_scope will treat this DIE as a union.  */
15186       process_structure_scope (die, cu);
15187
15188       /* The variant part is relative to the start of the enclosing
15189          structure.  */
15190       SET_FIELD_BITPOS (*fp, 0);
15191       fp->type = get_die_type (die, cu);
15192       fp->artificial = 1;
15193       fp->name = "<<variant>>";
15194
15195       /* Normally a DW_TAG_variant_part won't have a size, but our
15196          representation requires one, so set it to the maximum of the
15197          child sizes.  */
15198       if (TYPE_LENGTH (fp->type) == 0)
15199         {
15200           unsigned max = 0;
15201           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
15202             if (TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)) > max)
15203               max = TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i));
15204           TYPE_LENGTH (fp->type) = max;
15205         }
15206     }
15207   else
15208     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15209 }
15210
15211 /* Can the type given by DIE define another type?  */
15212
15213 static bool
15214 type_can_define_types (const struct die_info *die)
15215 {
15216   switch (die->tag)
15217     {
15218     case DW_TAG_typedef:
15219     case DW_TAG_class_type:
15220     case DW_TAG_structure_type:
15221     case DW_TAG_union_type:
15222     case DW_TAG_enumeration_type:
15223       return true;
15224
15225     default:
15226       return false;
15227     }
15228 }
15229
15230 /* Add a type definition defined in the scope of the FIP's class.  */
15231
15232 static void
15233 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15234                       struct dwarf2_cu *cu)
15235 {
15236   struct decl_field fp;
15237   memset (&fp, 0, sizeof (fp));
15238
15239   gdb_assert (type_can_define_types (die));
15240
15241   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15242   fp.name = dwarf2_name (die, cu);
15243   fp.type = read_type_die (die, cu);
15244
15245   /* Save accessibility.  */
15246   enum dwarf_access_attribute accessibility;
15247   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15248   if (attr != NULL)
15249     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15250   else
15251     accessibility = dwarf2_default_access_attribute (die, cu);
15252   switch (accessibility)
15253     {
15254     case DW_ACCESS_public:
15255       /* The assumed value if neither private nor protected.  */
15256       break;
15257     case DW_ACCESS_private:
15258       fp.is_private = 1;
15259       break;
15260     case DW_ACCESS_protected:
15261       fp.is_protected = 1;
15262       break;
15263     default:
15264       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15265     }
15266
15267   if (die->tag == DW_TAG_typedef)
15268     fip->typedef_field_list.push_back (fp);
15269   else
15270     fip->nested_types_list.push_back (fp);
15271 }
15272
15273 /* Create the vector of fields, and attach it to the type.  */
15274
15275 static void
15276 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15277                               struct dwarf2_cu *cu)
15278 {
15279   int nfields = fip->nfields;
15280
15281   /* Record the field count, allocate space for the array of fields,
15282      and create blank accessibility bitfields if necessary.  */
15283   TYPE_NFIELDS (type) = nfields;
15284   TYPE_FIELDS (type) = (struct field *)
15285     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15286
15287   if (fip->non_public_fields && cu->language != language_ada)
15288     {
15289       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15290
15291       TYPE_FIELD_PRIVATE_BITS (type) =
15292         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15293       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15294
15295       TYPE_FIELD_PROTECTED_BITS (type) =
15296         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15297       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15298
15299       TYPE_FIELD_IGNORE_BITS (type) =
15300         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15301       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15302     }
15303
15304   /* If the type has baseclasses, allocate and clear a bit vector for
15305      TYPE_FIELD_VIRTUAL_BITS.  */
15306   if (!fip->baseclasses.empty () && cu->language != language_ada)
15307     {
15308       int num_bytes = B_BYTES (fip->baseclasses.size ());
15309       unsigned char *pointer;
15310
15311       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15312       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15313       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15314       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15315       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15316     }
15317
15318   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15319     {
15320       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15321
15322       for (int index = 0; index < nfields; ++index)
15323         {
15324           struct nextfield &field = fip->fields[index];
15325
15326           if (field.variant.is_discriminant)
15327             di->discriminant_index = index;
15328           else if (field.variant.default_branch)
15329             di->default_index = index;
15330           else
15331             di->discriminants[index] = field.variant.discriminant_value;
15332         }
15333     }
15334
15335   /* Copy the saved-up fields into the field vector.  */
15336   for (int i = 0; i < nfields; ++i)
15337     {
15338       struct nextfield &field
15339         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15340            : fip->fields[i - fip->baseclasses.size ()]);
15341
15342       TYPE_FIELD (type, i) = field.field;
15343       switch (field.accessibility)
15344         {
15345         case DW_ACCESS_private:
15346           if (cu->language != language_ada)
15347             SET_TYPE_FIELD_PRIVATE (type, i);
15348           break;
15349
15350         case DW_ACCESS_protected:
15351           if (cu->language != language_ada)
15352             SET_TYPE_FIELD_PROTECTED (type, i);
15353           break;
15354
15355         case DW_ACCESS_public:
15356           break;
15357
15358         default:
15359           /* Unknown accessibility.  Complain and treat it as public.  */
15360           {
15361             complaint (_("unsupported accessibility %d"),
15362                        field.accessibility);
15363           }
15364           break;
15365         }
15366       if (i < fip->baseclasses.size ())
15367         {
15368           switch (field.virtuality)
15369             {
15370             case DW_VIRTUALITY_virtual:
15371             case DW_VIRTUALITY_pure_virtual:
15372               if (cu->language == language_ada)
15373                 error (_("unexpected virtuality in component of Ada type"));
15374               SET_TYPE_FIELD_VIRTUAL (type, i);
15375               break;
15376             }
15377         }
15378     }
15379 }
15380
15381 /* Return true if this member function is a constructor, false
15382    otherwise.  */
15383
15384 static int
15385 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15386 {
15387   const char *fieldname;
15388   const char *type_name;
15389   int len;
15390
15391   if (die->parent == NULL)
15392     return 0;
15393
15394   if (die->parent->tag != DW_TAG_structure_type
15395       && die->parent->tag != DW_TAG_union_type
15396       && die->parent->tag != DW_TAG_class_type)
15397     return 0;
15398
15399   fieldname = dwarf2_name (die, cu);
15400   type_name = dwarf2_name (die->parent, cu);
15401   if (fieldname == NULL || type_name == NULL)
15402     return 0;
15403
15404   len = strlen (fieldname);
15405   return (strncmp (fieldname, type_name, len) == 0
15406           && (type_name[len] == '\0' || type_name[len] == '<'));
15407 }
15408
15409 /* Add a member function to the proper fieldlist.  */
15410
15411 static void
15412 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15413                       struct type *type, struct dwarf2_cu *cu)
15414 {
15415   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15416   struct attribute *attr;
15417   int i;
15418   struct fnfieldlist *flp = nullptr;
15419   struct fn_field *fnp;
15420   const char *fieldname;
15421   struct type *this_type;
15422   enum dwarf_access_attribute accessibility;
15423
15424   if (cu->language == language_ada)
15425     error (_("unexpected member function in Ada type"));
15426
15427   /* Get name of member function.  */
15428   fieldname = dwarf2_name (die, cu);
15429   if (fieldname == NULL)
15430     return;
15431
15432   /* Look up member function name in fieldlist.  */
15433   for (i = 0; i < fip->fnfieldlists.size (); i++)
15434     {
15435       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15436         {
15437           flp = &fip->fnfieldlists[i];
15438           break;
15439         }
15440     }
15441
15442   /* Create a new fnfieldlist if necessary.  */
15443   if (flp == nullptr)
15444     {
15445       fip->fnfieldlists.emplace_back ();
15446       flp = &fip->fnfieldlists.back ();
15447       flp->name = fieldname;
15448       i = fip->fnfieldlists.size () - 1;
15449     }
15450
15451   /* Create a new member function field and add it to the vector of
15452      fnfieldlists.  */
15453   flp->fnfields.emplace_back ();
15454   fnp = &flp->fnfields.back ();
15455
15456   /* Delay processing of the physname until later.  */
15457   if (cu->language == language_cplus)
15458     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15459                         die, cu);
15460   else
15461     {
15462       const char *physname = dwarf2_physname (fieldname, die, cu);
15463       fnp->physname = physname ? physname : "";
15464     }
15465
15466   fnp->type = alloc_type (objfile);
15467   this_type = read_type_die (die, cu);
15468   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15469     {
15470       int nparams = TYPE_NFIELDS (this_type);
15471
15472       /* TYPE is the domain of this method, and THIS_TYPE is the type
15473            of the method itself (TYPE_CODE_METHOD).  */
15474       smash_to_method_type (fnp->type, type,
15475                             TYPE_TARGET_TYPE (this_type),
15476                             TYPE_FIELDS (this_type),
15477                             TYPE_NFIELDS (this_type),
15478                             TYPE_VARARGS (this_type));
15479
15480       /* Handle static member functions.
15481          Dwarf2 has no clean way to discern C++ static and non-static
15482          member functions.  G++ helps GDB by marking the first
15483          parameter for non-static member functions (which is the this
15484          pointer) as artificial.  We obtain this information from
15485          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15486       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15487         fnp->voffset = VOFFSET_STATIC;
15488     }
15489   else
15490     complaint (_("member function type missing for '%s'"),
15491                dwarf2_full_name (fieldname, die, cu));
15492
15493   /* Get fcontext from DW_AT_containing_type if present.  */
15494   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15495     fnp->fcontext = die_containing_type (die, cu);
15496
15497   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15498      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15499
15500   /* Get accessibility.  */
15501   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15502   if (attr)
15503     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15504   else
15505     accessibility = dwarf2_default_access_attribute (die, cu);
15506   switch (accessibility)
15507     {
15508     case DW_ACCESS_private:
15509       fnp->is_private = 1;
15510       break;
15511     case DW_ACCESS_protected:
15512       fnp->is_protected = 1;
15513       break;
15514     }
15515
15516   /* Check for artificial methods.  */
15517   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15518   if (attr && DW_UNSND (attr) != 0)
15519     fnp->is_artificial = 1;
15520
15521   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15522
15523   /* Get index in virtual function table if it is a virtual member
15524      function.  For older versions of GCC, this is an offset in the
15525      appropriate virtual table, as specified by DW_AT_containing_type.
15526      For everyone else, it is an expression to be evaluated relative
15527      to the object address.  */
15528
15529   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15530   if (attr)
15531     {
15532       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15533         {
15534           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15535             {
15536               /* Old-style GCC.  */
15537               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15538             }
15539           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15540                    || (DW_BLOCK (attr)->size > 1
15541                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15542                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15543             {
15544               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15545               if ((fnp->voffset % cu->header.addr_size) != 0)
15546                 dwarf2_complex_location_expr_complaint ();
15547               else
15548                 fnp->voffset /= cu->header.addr_size;
15549               fnp->voffset += 2;
15550             }
15551           else
15552             dwarf2_complex_location_expr_complaint ();
15553
15554           if (!fnp->fcontext)
15555             {
15556               /* If there is no `this' field and no DW_AT_containing_type,
15557                  we cannot actually find a base class context for the
15558                  vtable!  */
15559               if (TYPE_NFIELDS (this_type) == 0
15560                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15561                 {
15562                   complaint (_("cannot determine context for virtual member "
15563                                "function \"%s\" (offset %s)"),
15564                              fieldname, sect_offset_str (die->sect_off));
15565                 }
15566               else
15567                 {
15568                   fnp->fcontext
15569                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15570                 }
15571             }
15572         }
15573       else if (attr_form_is_section_offset (attr))
15574         {
15575           dwarf2_complex_location_expr_complaint ();
15576         }
15577       else
15578         {
15579           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15580                                                  fieldname);
15581         }
15582     }
15583   else
15584     {
15585       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15586       if (attr && DW_UNSND (attr))
15587         {
15588           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15589           complaint (_("Member function \"%s\" (offset %s) is virtual "
15590                        "but the vtable offset is not specified"),
15591                      fieldname, sect_offset_str (die->sect_off));
15592           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15593           TYPE_CPLUS_DYNAMIC (type) = 1;
15594         }
15595     }
15596 }
15597
15598 /* Create the vector of member function fields, and attach it to the type.  */
15599
15600 static void
15601 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15602                                  struct dwarf2_cu *cu)
15603 {
15604   if (cu->language == language_ada)
15605     error (_("unexpected member functions in Ada type"));
15606
15607   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15608   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15609     TYPE_ALLOC (type,
15610                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15611
15612   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15613     {
15614       struct fnfieldlist &nf = fip->fnfieldlists[i];
15615       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15616
15617       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15618       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15619       fn_flp->fn_fields = (struct fn_field *)
15620         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15621
15622       for (int k = 0; k < nf.fnfields.size (); ++k)
15623         fn_flp->fn_fields[k] = nf.fnfields[k];
15624     }
15625
15626   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15627 }
15628
15629 /* Returns non-zero if NAME is the name of a vtable member in CU's
15630    language, zero otherwise.  */
15631 static int
15632 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15633 {
15634   static const char vptr[] = "_vptr";
15635
15636   /* Look for the C++ form of the vtable.  */
15637   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15638     return 1;
15639
15640   return 0;
15641 }
15642
15643 /* GCC outputs unnamed structures that are really pointers to member
15644    functions, with the ABI-specified layout.  If TYPE describes
15645    such a structure, smash it into a member function type.
15646
15647    GCC shouldn't do this; it should just output pointer to member DIEs.
15648    This is GCC PR debug/28767.  */
15649
15650 static void
15651 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15652 {
15653   struct type *pfn_type, *self_type, *new_type;
15654
15655   /* Check for a structure with no name and two children.  */
15656   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15657     return;
15658
15659   /* Check for __pfn and __delta members.  */
15660   if (TYPE_FIELD_NAME (type, 0) == NULL
15661       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15662       || TYPE_FIELD_NAME (type, 1) == NULL
15663       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15664     return;
15665
15666   /* Find the type of the method.  */
15667   pfn_type = TYPE_FIELD_TYPE (type, 0);
15668   if (pfn_type == NULL
15669       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15670       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15671     return;
15672
15673   /* Look for the "this" argument.  */
15674   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15675   if (TYPE_NFIELDS (pfn_type) == 0
15676       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15677       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15678     return;
15679
15680   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15681   new_type = alloc_type (objfile);
15682   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15683                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15684                         TYPE_VARARGS (pfn_type));
15685   smash_to_methodptr_type (type, new_type);
15686 }
15687
15688 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15689    appropriate error checking and issuing complaints if there is a
15690    problem.  */
15691
15692 static ULONGEST
15693 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15694 {
15695   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15696
15697   if (attr == nullptr)
15698     return 0;
15699
15700   if (!attr_form_is_constant (attr))
15701     {
15702       complaint (_("DW_AT_alignment must have constant form"
15703                    " - DIE at %s [in module %s]"),
15704                  sect_offset_str (die->sect_off),
15705                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15706       return 0;
15707     }
15708
15709   ULONGEST align;
15710   if (attr->form == DW_FORM_sdata)
15711     {
15712       LONGEST val = DW_SND (attr);
15713       if (val < 0)
15714         {
15715           complaint (_("DW_AT_alignment value must not be negative"
15716                        " - DIE at %s [in module %s]"),
15717                      sect_offset_str (die->sect_off),
15718                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15719           return 0;
15720         }
15721       align = val;
15722     }
15723   else
15724     align = DW_UNSND (attr);
15725
15726   if (align == 0)
15727     {
15728       complaint (_("DW_AT_alignment value must not be zero"
15729                    " - DIE at %s [in module %s]"),
15730                  sect_offset_str (die->sect_off),
15731                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15732       return 0;
15733     }
15734   if ((align & (align - 1)) != 0)
15735     {
15736       complaint (_("DW_AT_alignment value must be a power of 2"
15737                    " - DIE at %s [in module %s]"),
15738                  sect_offset_str (die->sect_off),
15739                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15740       return 0;
15741     }
15742
15743   return align;
15744 }
15745
15746 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15747    the alignment for TYPE.  */
15748
15749 static void
15750 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15751                      struct type *type)
15752 {
15753   if (!set_type_align (type, get_alignment (cu, die)))
15754     complaint (_("DW_AT_alignment value too large"
15755                  " - DIE at %s [in module %s]"),
15756                sect_offset_str (die->sect_off),
15757                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15758 }
15759
15760 /* Called when we find the DIE that starts a structure or union scope
15761    (definition) to create a type for the structure or union.  Fill in
15762    the type's name and general properties; the members will not be
15763    processed until process_structure_scope.  A symbol table entry for
15764    the type will also not be done until process_structure_scope (assuming
15765    the type has a name).
15766
15767    NOTE: we need to call these functions regardless of whether or not the
15768    DIE has a DW_AT_name attribute, since it might be an anonymous
15769    structure or union.  This gets the type entered into our set of
15770    user defined types.  */
15771
15772 static struct type *
15773 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15774 {
15775   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15776   struct type *type;
15777   struct attribute *attr;
15778   const char *name;
15779
15780   /* If the definition of this type lives in .debug_types, read that type.
15781      Don't follow DW_AT_specification though, that will take us back up
15782      the chain and we want to go down.  */
15783   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15784   if (attr)
15785     {
15786       type = get_DW_AT_signature_type (die, attr, cu);
15787
15788       /* The type's CU may not be the same as CU.
15789          Ensure TYPE is recorded with CU in die_type_hash.  */
15790       return set_die_type (die, type, cu);
15791     }
15792
15793   type = alloc_type (objfile);
15794   INIT_CPLUS_SPECIFIC (type);
15795
15796   name = dwarf2_name (die, cu);
15797   if (name != NULL)
15798     {
15799       if (cu->language == language_cplus
15800           || cu->language == language_d
15801           || cu->language == language_rust)
15802         {
15803           const char *full_name = dwarf2_full_name (name, die, cu);
15804
15805           /* dwarf2_full_name might have already finished building the DIE's
15806              type.  If so, there is no need to continue.  */
15807           if (get_die_type (die, cu) != NULL)
15808             return get_die_type (die, cu);
15809
15810           TYPE_NAME (type) = full_name;
15811         }
15812       else
15813         {
15814           /* The name is already allocated along with this objfile, so
15815              we don't need to duplicate it for the type.  */
15816           TYPE_NAME (type) = name;
15817         }
15818     }
15819
15820   if (die->tag == DW_TAG_structure_type)
15821     {
15822       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15823     }
15824   else if (die->tag == DW_TAG_union_type)
15825     {
15826       TYPE_CODE (type) = TYPE_CODE_UNION;
15827     }
15828   else if (die->tag == DW_TAG_variant_part)
15829     {
15830       TYPE_CODE (type) = TYPE_CODE_UNION;
15831       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15832     }
15833   else
15834     {
15835       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15836     }
15837
15838   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15839     TYPE_DECLARED_CLASS (type) = 1;
15840
15841   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15842   if (attr)
15843     {
15844       if (attr_form_is_constant (attr))
15845         TYPE_LENGTH (type) = DW_UNSND (attr);
15846       else
15847         {
15848           /* For the moment, dynamic type sizes are not supported
15849              by GDB's struct type.  The actual size is determined
15850              on-demand when resolving the type of a given object,
15851              so set the type's length to zero for now.  Otherwise,
15852              we record an expression as the length, and that expression
15853              could lead to a very large value, which could eventually
15854              lead to us trying to allocate that much memory when creating
15855              a value of that type.  */
15856           TYPE_LENGTH (type) = 0;
15857         }
15858     }
15859   else
15860     {
15861       TYPE_LENGTH (type) = 0;
15862     }
15863
15864   maybe_set_alignment (cu, die, type);
15865
15866   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15867     {
15868       /* ICC<14 does not output the required DW_AT_declaration on
15869          incomplete types, but gives them a size of zero.  */
15870       TYPE_STUB (type) = 1;
15871     }
15872   else
15873     TYPE_STUB_SUPPORTED (type) = 1;
15874
15875   if (die_is_declaration (die, cu))
15876     TYPE_STUB (type) = 1;
15877   else if (attr == NULL && die->child == NULL
15878            && producer_is_realview (cu->producer))
15879     /* RealView does not output the required DW_AT_declaration
15880        on incomplete types.  */
15881     TYPE_STUB (type) = 1;
15882
15883   /* We need to add the type field to the die immediately so we don't
15884      infinitely recurse when dealing with pointers to the structure
15885      type within the structure itself.  */
15886   set_die_type (die, type, cu);
15887
15888   /* set_die_type should be already done.  */
15889   set_descriptive_type (type, die, cu);
15890
15891   return type;
15892 }
15893
15894 /* A helper for process_structure_scope that handles a single member
15895    DIE.  */
15896
15897 static void
15898 handle_struct_member_die (struct die_info *child_die, struct type *type,
15899                           struct field_info *fi,
15900                           std::vector<struct symbol *> *template_args,
15901                           struct dwarf2_cu *cu)
15902 {
15903   if (child_die->tag == DW_TAG_member
15904       || child_die->tag == DW_TAG_variable
15905       || child_die->tag == DW_TAG_variant_part)
15906     {
15907       /* NOTE: carlton/2002-11-05: A C++ static data member
15908          should be a DW_TAG_member that is a declaration, but
15909          all versions of G++ as of this writing (so through at
15910          least 3.2.1) incorrectly generate DW_TAG_variable
15911          tags for them instead.  */
15912       dwarf2_add_field (fi, child_die, cu);
15913     }
15914   else if (child_die->tag == DW_TAG_subprogram)
15915     {
15916       /* Rust doesn't have member functions in the C++ sense.
15917          However, it does emit ordinary functions as children
15918          of a struct DIE.  */
15919       if (cu->language == language_rust)
15920         read_func_scope (child_die, cu);
15921       else
15922         {
15923           /* C++ member function.  */
15924           dwarf2_add_member_fn (fi, child_die, type, cu);
15925         }
15926     }
15927   else if (child_die->tag == DW_TAG_inheritance)
15928     {
15929       /* C++ base class field.  */
15930       dwarf2_add_field (fi, child_die, cu);
15931     }
15932   else if (type_can_define_types (child_die))
15933     dwarf2_add_type_defn (fi, child_die, cu);
15934   else if (child_die->tag == DW_TAG_template_type_param
15935            || child_die->tag == DW_TAG_template_value_param)
15936     {
15937       struct symbol *arg = new_symbol (child_die, NULL, cu);
15938
15939       if (arg != NULL)
15940         template_args->push_back (arg);
15941     }
15942   else if (child_die->tag == DW_TAG_variant)
15943     {
15944       /* In a variant we want to get the discriminant and also add a
15945          field for our sole member child.  */
15946       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15947
15948       for (die_info *variant_child = child_die->child;
15949            variant_child != NULL;
15950            variant_child = sibling_die (variant_child))
15951         {
15952           if (variant_child->tag == DW_TAG_member)
15953             {
15954               handle_struct_member_die (variant_child, type, fi,
15955                                         template_args, cu);
15956               /* Only handle the one.  */
15957               break;
15958             }
15959         }
15960
15961       /* We don't handle this but we might as well report it if we see
15962          it.  */
15963       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15964           complaint (_("DW_AT_discr_list is not supported yet"
15965                        " - DIE at %s [in module %s]"),
15966                      sect_offset_str (child_die->sect_off),
15967                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15968
15969       /* The first field was just added, so we can stash the
15970          discriminant there.  */
15971       gdb_assert (!fi->fields.empty ());
15972       if (discr == NULL)
15973         fi->fields.back ().variant.default_branch = true;
15974       else
15975         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15976     }
15977 }
15978
15979 /* Finish creating a structure or union type, including filling in
15980    its members and creating a symbol for it.  */
15981
15982 static void
15983 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15984 {
15985   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15986   struct die_info *child_die;
15987   struct type *type;
15988
15989   type = get_die_type (die, cu);
15990   if (type == NULL)
15991     type = read_structure_type (die, cu);
15992
15993   /* When reading a DW_TAG_variant_part, we need to notice when we
15994      read the discriminant member, so we can record it later in the
15995      discriminant_info.  */
15996   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15997   sect_offset discr_offset;
15998   bool has_template_parameters = false;
15999
16000   if (is_variant_part)
16001     {
16002       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
16003       if (discr == NULL)
16004         {
16005           /* Maybe it's a univariant form, an extension we support.
16006              In this case arrange not to check the offset.  */
16007           is_variant_part = false;
16008         }
16009       else if (attr_form_is_ref (discr))
16010         {
16011           struct dwarf2_cu *target_cu = cu;
16012           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
16013
16014           discr_offset = target_die->sect_off;
16015         }
16016       else
16017         {
16018           complaint (_("DW_AT_discr does not have DIE reference form"
16019                        " - DIE at %s [in module %s]"),
16020                      sect_offset_str (die->sect_off),
16021                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16022           is_variant_part = false;
16023         }
16024     }
16025
16026   if (die->child != NULL && ! die_is_declaration (die, cu))
16027     {
16028       struct field_info fi;
16029       std::vector<struct symbol *> template_args;
16030
16031       child_die = die->child;
16032
16033       while (child_die && child_die->tag)
16034         {
16035           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
16036
16037           if (is_variant_part && discr_offset == child_die->sect_off)
16038             fi.fields.back ().variant.is_discriminant = true;
16039
16040           child_die = sibling_die (child_die);
16041         }
16042
16043       /* Attach template arguments to type.  */
16044       if (!template_args.empty ())
16045         {
16046           has_template_parameters = true;
16047           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16048           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16049           TYPE_TEMPLATE_ARGUMENTS (type)
16050             = XOBNEWVEC (&objfile->objfile_obstack,
16051                          struct symbol *,
16052                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16053           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16054                   template_args.data (),
16055                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16056                    * sizeof (struct symbol *)));
16057         }
16058
16059       /* Attach fields and member functions to the type.  */
16060       if (fi.nfields)
16061         dwarf2_attach_fields_to_type (&fi, type, cu);
16062       if (!fi.fnfieldlists.empty ())
16063         {
16064           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16065
16066           /* Get the type which refers to the base class (possibly this
16067              class itself) which contains the vtable pointer for the current
16068              class from the DW_AT_containing_type attribute.  This use of
16069              DW_AT_containing_type is a GNU extension.  */
16070
16071           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16072             {
16073               struct type *t = die_containing_type (die, cu);
16074
16075               set_type_vptr_basetype (type, t);
16076               if (type == t)
16077                 {
16078                   int i;
16079
16080                   /* Our own class provides vtbl ptr.  */
16081                   for (i = TYPE_NFIELDS (t) - 1;
16082                        i >= TYPE_N_BASECLASSES (t);
16083                        --i)
16084                     {
16085                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16086
16087                       if (is_vtable_name (fieldname, cu))
16088                         {
16089                           set_type_vptr_fieldno (type, i);
16090                           break;
16091                         }
16092                     }
16093
16094                   /* Complain if virtual function table field not found.  */
16095                   if (i < TYPE_N_BASECLASSES (t))
16096                     complaint (_("virtual function table pointer "
16097                                  "not found when defining class '%s'"),
16098                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
16099                 }
16100               else
16101                 {
16102                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16103                 }
16104             }
16105           else if (cu->producer
16106                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16107             {
16108               /* The IBM XLC compiler does not provide direct indication
16109                  of the containing type, but the vtable pointer is
16110                  always named __vfp.  */
16111
16112               int i;
16113
16114               for (i = TYPE_NFIELDS (type) - 1;
16115                    i >= TYPE_N_BASECLASSES (type);
16116                    --i)
16117                 {
16118                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16119                     {
16120                       set_type_vptr_fieldno (type, i);
16121                       set_type_vptr_basetype (type, type);
16122                       break;
16123                     }
16124                 }
16125             }
16126         }
16127
16128       /* Copy fi.typedef_field_list linked list elements content into the
16129          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16130       if (!fi.typedef_field_list.empty ())
16131         {
16132           int count = fi.typedef_field_list.size ();
16133
16134           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16135           TYPE_TYPEDEF_FIELD_ARRAY (type)
16136             = ((struct decl_field *)
16137                TYPE_ALLOC (type,
16138                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16139           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16140
16141           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16142             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16143         }
16144
16145       /* Copy fi.nested_types_list linked list elements content into the
16146          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16147       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16148         {
16149           int count = fi.nested_types_list.size ();
16150
16151           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16152           TYPE_NESTED_TYPES_ARRAY (type)
16153             = ((struct decl_field *)
16154                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16155           TYPE_NESTED_TYPES_COUNT (type) = count;
16156
16157           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16158             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16159         }
16160     }
16161
16162   quirk_gcc_member_function_pointer (type, objfile);
16163   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16164     cu->rust_unions.push_back (type);
16165
16166   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16167      snapshots) has been known to create a die giving a declaration
16168      for a class that has, as a child, a die giving a definition for a
16169      nested class.  So we have to process our children even if the
16170      current die is a declaration.  Normally, of course, a declaration
16171      won't have any children at all.  */
16172
16173   child_die = die->child;
16174
16175   while (child_die != NULL && child_die->tag)
16176     {
16177       if (child_die->tag == DW_TAG_member
16178           || child_die->tag == DW_TAG_variable
16179           || child_die->tag == DW_TAG_inheritance
16180           || child_die->tag == DW_TAG_template_value_param
16181           || child_die->tag == DW_TAG_template_type_param)
16182         {
16183           /* Do nothing.  */
16184         }
16185       else
16186         process_die (child_die, cu);
16187
16188       child_die = sibling_die (child_die);
16189     }
16190
16191   /* Do not consider external references.  According to the DWARF standard,
16192      these DIEs are identified by the fact that they have no byte_size
16193      attribute, and a declaration attribute.  */
16194   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16195       || !die_is_declaration (die, cu))
16196     {
16197       struct symbol *sym = new_symbol (die, type, cu);
16198
16199       if (has_template_parameters)
16200         {
16201           struct symtab *symtab;
16202           if (sym != nullptr)
16203             symtab = symbol_symtab (sym);
16204           else if (cu->line_header != nullptr)
16205             {
16206               /* Any related symtab will do.  */
16207               symtab
16208                 = cu->line_header->file_name_at (file_name_index (1))->symtab;
16209             }
16210           else
16211             {
16212               symtab = nullptr;
16213               complaint (_("could not find suitable "
16214                            "symtab for template parameter"
16215                            " - DIE at %s [in module %s]"),
16216                          sect_offset_str (die->sect_off),
16217                          objfile_name (objfile));
16218             }
16219
16220           if (symtab != nullptr)
16221             {
16222               /* Make sure that the symtab is set on the new symbols.
16223                  Even though they don't appear in this symtab directly,
16224                  other parts of gdb assume that symbols do, and this is
16225                  reasonably true.  */
16226               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16227                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
16228             }
16229         }
16230     }
16231 }
16232
16233 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16234    update TYPE using some information only available in DIE's children.  */
16235
16236 static void
16237 update_enumeration_type_from_children (struct die_info *die,
16238                                        struct type *type,
16239                                        struct dwarf2_cu *cu)
16240 {
16241   struct die_info *child_die;
16242   int unsigned_enum = 1;
16243   int flag_enum = 1;
16244   ULONGEST mask = 0;
16245
16246   auto_obstack obstack;
16247
16248   for (child_die = die->child;
16249        child_die != NULL && child_die->tag;
16250        child_die = sibling_die (child_die))
16251     {
16252       struct attribute *attr;
16253       LONGEST value;
16254       const gdb_byte *bytes;
16255       struct dwarf2_locexpr_baton *baton;
16256       const char *name;
16257
16258       if (child_die->tag != DW_TAG_enumerator)
16259         continue;
16260
16261       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16262       if (attr == NULL)
16263         continue;
16264
16265       name = dwarf2_name (child_die, cu);
16266       if (name == NULL)
16267         name = "<anonymous enumerator>";
16268
16269       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16270                                &value, &bytes, &baton);
16271       if (value < 0)
16272         {
16273           unsigned_enum = 0;
16274           flag_enum = 0;
16275         }
16276       else if ((mask & value) != 0)
16277         flag_enum = 0;
16278       else
16279         mask |= value;
16280
16281       /* If we already know that the enum type is neither unsigned, nor
16282          a flag type, no need to look at the rest of the enumerates.  */
16283       if (!unsigned_enum && !flag_enum)
16284         break;
16285     }
16286
16287   if (unsigned_enum)
16288     TYPE_UNSIGNED (type) = 1;
16289   if (flag_enum)
16290     TYPE_FLAG_ENUM (type) = 1;
16291 }
16292
16293 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16294    complete the type's fields yet, or create any symbols.  */
16295
16296 static struct type *
16297 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16298 {
16299   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16300   struct type *type;
16301   struct attribute *attr;
16302   const char *name;
16303
16304   /* If the definition of this type lives in .debug_types, read that type.
16305      Don't follow DW_AT_specification though, that will take us back up
16306      the chain and we want to go down.  */
16307   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16308   if (attr)
16309     {
16310       type = get_DW_AT_signature_type (die, attr, cu);
16311
16312       /* The type's CU may not be the same as CU.
16313          Ensure TYPE is recorded with CU in die_type_hash.  */
16314       return set_die_type (die, type, cu);
16315     }
16316
16317   type = alloc_type (objfile);
16318
16319   TYPE_CODE (type) = TYPE_CODE_ENUM;
16320   name = dwarf2_full_name (NULL, die, cu);
16321   if (name != NULL)
16322     TYPE_NAME (type) = name;
16323
16324   attr = dwarf2_attr (die, DW_AT_type, cu);
16325   if (attr != NULL)
16326     {
16327       struct type *underlying_type = die_type (die, cu);
16328
16329       TYPE_TARGET_TYPE (type) = underlying_type;
16330     }
16331
16332   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16333   if (attr)
16334     {
16335       TYPE_LENGTH (type) = DW_UNSND (attr);
16336     }
16337   else
16338     {
16339       TYPE_LENGTH (type) = 0;
16340     }
16341
16342   maybe_set_alignment (cu, die, type);
16343
16344   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16345      declared as private in the package spec, and then defined only
16346      inside the package body.  Such types are known as Taft Amendment
16347      Types.  When another package uses such a type, an incomplete DIE
16348      may be generated by the compiler.  */
16349   if (die_is_declaration (die, cu))
16350     TYPE_STUB (type) = 1;
16351
16352   /* Finish the creation of this type by using the enum's children.
16353      We must call this even when the underlying type has been provided
16354      so that we can determine if we're looking at a "flag" enum.  */
16355   update_enumeration_type_from_children (die, type, cu);
16356
16357   /* If this type has an underlying type that is not a stub, then we
16358      may use its attributes.  We always use the "unsigned" attribute
16359      in this situation, because ordinarily we guess whether the type
16360      is unsigned -- but the guess can be wrong and the underlying type
16361      can tell us the reality.  However, we defer to a local size
16362      attribute if one exists, because this lets the compiler override
16363      the underlying type if needed.  */
16364   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16365     {
16366       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16367       if (TYPE_LENGTH (type) == 0)
16368         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16369       if (TYPE_RAW_ALIGN (type) == 0
16370           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16371         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16372     }
16373
16374   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16375
16376   return set_die_type (die, type, cu);
16377 }
16378
16379 /* Given a pointer to a die which begins an enumeration, process all
16380    the dies that define the members of the enumeration, and create the
16381    symbol for the enumeration type.
16382
16383    NOTE: We reverse the order of the element list.  */
16384
16385 static void
16386 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16387 {
16388   struct type *this_type;
16389
16390   this_type = get_die_type (die, cu);
16391   if (this_type == NULL)
16392     this_type = read_enumeration_type (die, cu);
16393
16394   if (die->child != NULL)
16395     {
16396       struct die_info *child_die;
16397       struct symbol *sym;
16398       struct field *fields = NULL;
16399       int num_fields = 0;
16400       const char *name;
16401
16402       child_die = die->child;
16403       while (child_die && child_die->tag)
16404         {
16405           if (child_die->tag != DW_TAG_enumerator)
16406             {
16407               process_die (child_die, cu);
16408             }
16409           else
16410             {
16411               name = dwarf2_name (child_die, cu);
16412               if (name)
16413                 {
16414                   sym = new_symbol (child_die, this_type, cu);
16415
16416                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16417                     {
16418                       fields = (struct field *)
16419                         xrealloc (fields,
16420                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16421                                   * sizeof (struct field));
16422                     }
16423
16424                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16425                   FIELD_TYPE (fields[num_fields]) = NULL;
16426                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16427                   FIELD_BITSIZE (fields[num_fields]) = 0;
16428
16429                   num_fields++;
16430                 }
16431             }
16432
16433           child_die = sibling_die (child_die);
16434         }
16435
16436       if (num_fields)
16437         {
16438           TYPE_NFIELDS (this_type) = num_fields;
16439           TYPE_FIELDS (this_type) = (struct field *)
16440             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16441           memcpy (TYPE_FIELDS (this_type), fields,
16442                   sizeof (struct field) * num_fields);
16443           xfree (fields);
16444         }
16445     }
16446
16447   /* If we are reading an enum from a .debug_types unit, and the enum
16448      is a declaration, and the enum is not the signatured type in the
16449      unit, then we do not want to add a symbol for it.  Adding a
16450      symbol would in some cases obscure the true definition of the
16451      enum, giving users an incomplete type when the definition is
16452      actually available.  Note that we do not want to do this for all
16453      enums which are just declarations, because C++0x allows forward
16454      enum declarations.  */
16455   if (cu->per_cu->is_debug_types
16456       && die_is_declaration (die, cu))
16457     {
16458       struct signatured_type *sig_type;
16459
16460       sig_type = (struct signatured_type *) cu->per_cu;
16461       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16462       if (sig_type->type_offset_in_section != die->sect_off)
16463         return;
16464     }
16465
16466   new_symbol (die, this_type, cu);
16467 }
16468
16469 /* Extract all information from a DW_TAG_array_type DIE and put it in
16470    the DIE's type field.  For now, this only handles one dimensional
16471    arrays.  */
16472
16473 static struct type *
16474 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16475 {
16476   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16477   struct die_info *child_die;
16478   struct type *type;
16479   struct type *element_type, *range_type, *index_type;
16480   struct attribute *attr;
16481   const char *name;
16482   struct dynamic_prop *byte_stride_prop = NULL;
16483   unsigned int bit_stride = 0;
16484
16485   element_type = die_type (die, cu);
16486
16487   /* The die_type call above may have already set the type for this DIE.  */
16488   type = get_die_type (die, cu);
16489   if (type)
16490     return type;
16491
16492   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16493   if (attr != NULL)
16494     {
16495       int stride_ok;
16496
16497       byte_stride_prop
16498         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16499       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16500       if (!stride_ok)
16501         {
16502           complaint (_("unable to read array DW_AT_byte_stride "
16503                        " - DIE at %s [in module %s]"),
16504                      sect_offset_str (die->sect_off),
16505                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16506           /* Ignore this attribute.  We will likely not be able to print
16507              arrays of this type correctly, but there is little we can do
16508              to help if we cannot read the attribute's value.  */
16509           byte_stride_prop = NULL;
16510         }
16511     }
16512
16513   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16514   if (attr != NULL)
16515     bit_stride = DW_UNSND (attr);
16516
16517   /* Irix 6.2 native cc creates array types without children for
16518      arrays with unspecified length.  */
16519   if (die->child == NULL)
16520     {
16521       index_type = objfile_type (objfile)->builtin_int;
16522       range_type = create_static_range_type (NULL, index_type, 0, -1);
16523       type = create_array_type_with_stride (NULL, element_type, range_type,
16524                                             byte_stride_prop, bit_stride);
16525       return set_die_type (die, type, cu);
16526     }
16527
16528   std::vector<struct type *> range_types;
16529   child_die = die->child;
16530   while (child_die && child_die->tag)
16531     {
16532       if (child_die->tag == DW_TAG_subrange_type)
16533         {
16534           struct type *child_type = read_type_die (child_die, cu);
16535
16536           if (child_type != NULL)
16537             {
16538               /* The range type was succesfully read.  Save it for the
16539                  array type creation.  */
16540               range_types.push_back (child_type);
16541             }
16542         }
16543       child_die = sibling_die (child_die);
16544     }
16545
16546   /* Dwarf2 dimensions are output from left to right, create the
16547      necessary array types in backwards order.  */
16548
16549   type = element_type;
16550
16551   if (read_array_order (die, cu) == DW_ORD_col_major)
16552     {
16553       int i = 0;
16554
16555       while (i < range_types.size ())
16556         type = create_array_type_with_stride (NULL, type, range_types[i++],
16557                                               byte_stride_prop, bit_stride);
16558     }
16559   else
16560     {
16561       size_t ndim = range_types.size ();
16562       while (ndim-- > 0)
16563         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16564                                               byte_stride_prop, bit_stride);
16565     }
16566
16567   /* Understand Dwarf2 support for vector types (like they occur on
16568      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16569      array type.  This is not part of the Dwarf2/3 standard yet, but a
16570      custom vendor extension.  The main difference between a regular
16571      array and the vector variant is that vectors are passed by value
16572      to functions.  */
16573   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16574   if (attr)
16575     make_vector_type (type);
16576
16577   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16578      implementation may choose to implement triple vectors using this
16579      attribute.  */
16580   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16581   if (attr)
16582     {
16583       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16584         TYPE_LENGTH (type) = DW_UNSND (attr);
16585       else
16586         complaint (_("DW_AT_byte_size for array type smaller "
16587                      "than the total size of elements"));
16588     }
16589
16590   name = dwarf2_name (die, cu);
16591   if (name)
16592     TYPE_NAME (type) = name;
16593
16594   maybe_set_alignment (cu, die, type);
16595
16596   /* Install the type in the die.  */
16597   set_die_type (die, type, cu);
16598
16599   /* set_die_type should be already done.  */
16600   set_descriptive_type (type, die, cu);
16601
16602   return type;
16603 }
16604
16605 static enum dwarf_array_dim_ordering
16606 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16607 {
16608   struct attribute *attr;
16609
16610   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16611
16612   if (attr)
16613     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16614
16615   /* GNU F77 is a special case, as at 08/2004 array type info is the
16616      opposite order to the dwarf2 specification, but data is still
16617      laid out as per normal fortran.
16618
16619      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16620      version checking.  */
16621
16622   if (cu->language == language_fortran
16623       && cu->producer && strstr (cu->producer, "GNU F77"))
16624     {
16625       return DW_ORD_row_major;
16626     }
16627
16628   switch (cu->language_defn->la_array_ordering)
16629     {
16630     case array_column_major:
16631       return DW_ORD_col_major;
16632     case array_row_major:
16633     default:
16634       return DW_ORD_row_major;
16635     };
16636 }
16637
16638 /* Extract all information from a DW_TAG_set_type DIE and put it in
16639    the DIE's type field.  */
16640
16641 static struct type *
16642 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16643 {
16644   struct type *domain_type, *set_type;
16645   struct attribute *attr;
16646
16647   domain_type = die_type (die, cu);
16648
16649   /* The die_type call above may have already set the type for this DIE.  */
16650   set_type = get_die_type (die, cu);
16651   if (set_type)
16652     return set_type;
16653
16654   set_type = create_set_type (NULL, domain_type);
16655
16656   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16657   if (attr)
16658     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16659
16660   maybe_set_alignment (cu, die, set_type);
16661
16662   return set_die_type (die, set_type, cu);
16663 }
16664
16665 /* A helper for read_common_block that creates a locexpr baton.
16666    SYM is the symbol which we are marking as computed.
16667    COMMON_DIE is the DIE for the common block.
16668    COMMON_LOC is the location expression attribute for the common
16669    block itself.
16670    MEMBER_LOC is the location expression attribute for the particular
16671    member of the common block that we are processing.
16672    CU is the CU from which the above come.  */
16673
16674 static void
16675 mark_common_block_symbol_computed (struct symbol *sym,
16676                                    struct die_info *common_die,
16677                                    struct attribute *common_loc,
16678                                    struct attribute *member_loc,
16679                                    struct dwarf2_cu *cu)
16680 {
16681   struct dwarf2_per_objfile *dwarf2_per_objfile
16682     = cu->per_cu->dwarf2_per_objfile;
16683   struct objfile *objfile = dwarf2_per_objfile->objfile;
16684   struct dwarf2_locexpr_baton *baton;
16685   gdb_byte *ptr;
16686   unsigned int cu_off;
16687   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16688   LONGEST offset = 0;
16689
16690   gdb_assert (common_loc && member_loc);
16691   gdb_assert (attr_form_is_block (common_loc));
16692   gdb_assert (attr_form_is_block (member_loc)
16693               || attr_form_is_constant (member_loc));
16694
16695   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16696   baton->per_cu = cu->per_cu;
16697   gdb_assert (baton->per_cu);
16698
16699   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16700
16701   if (attr_form_is_constant (member_loc))
16702     {
16703       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16704       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16705     }
16706   else
16707     baton->size += DW_BLOCK (member_loc)->size;
16708
16709   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16710   baton->data = ptr;
16711
16712   *ptr++ = DW_OP_call4;
16713   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16714   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16715   ptr += 4;
16716
16717   if (attr_form_is_constant (member_loc))
16718     {
16719       *ptr++ = DW_OP_addr;
16720       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16721       ptr += cu->header.addr_size;
16722     }
16723   else
16724     {
16725       /* We have to copy the data here, because DW_OP_call4 will only
16726          use a DW_AT_location attribute.  */
16727       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16728       ptr += DW_BLOCK (member_loc)->size;
16729     }
16730
16731   *ptr++ = DW_OP_plus;
16732   gdb_assert (ptr - baton->data == baton->size);
16733
16734   SYMBOL_LOCATION_BATON (sym) = baton;
16735   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16736 }
16737
16738 /* Create appropriate locally-scoped variables for all the
16739    DW_TAG_common_block entries.  Also create a struct common_block
16740    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16741    is used to sepate the common blocks name namespace from regular
16742    variable names.  */
16743
16744 static void
16745 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16746 {
16747   struct attribute *attr;
16748
16749   attr = dwarf2_attr (die, DW_AT_location, cu);
16750   if (attr)
16751     {
16752       /* Support the .debug_loc offsets.  */
16753       if (attr_form_is_block (attr))
16754         {
16755           /* Ok.  */
16756         }
16757       else if (attr_form_is_section_offset (attr))
16758         {
16759           dwarf2_complex_location_expr_complaint ();
16760           attr = NULL;
16761         }
16762       else
16763         {
16764           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16765                                                  "common block member");
16766           attr = NULL;
16767         }
16768     }
16769
16770   if (die->child != NULL)
16771     {
16772       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16773       struct die_info *child_die;
16774       size_t n_entries = 0, size;
16775       struct common_block *common_block;
16776       struct symbol *sym;
16777
16778       for (child_die = die->child;
16779            child_die && child_die->tag;
16780            child_die = sibling_die (child_die))
16781         ++n_entries;
16782
16783       size = (sizeof (struct common_block)
16784               + (n_entries - 1) * sizeof (struct symbol *));
16785       common_block
16786         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16787                                                  size);
16788       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16789       common_block->n_entries = 0;
16790
16791       for (child_die = die->child;
16792            child_die && child_die->tag;
16793            child_die = sibling_die (child_die))
16794         {
16795           /* Create the symbol in the DW_TAG_common_block block in the current
16796              symbol scope.  */
16797           sym = new_symbol (child_die, NULL, cu);
16798           if (sym != NULL)
16799             {
16800               struct attribute *member_loc;
16801
16802               common_block->contents[common_block->n_entries++] = sym;
16803
16804               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16805                                         cu);
16806               if (member_loc)
16807                 {
16808                   /* GDB has handled this for a long time, but it is
16809                      not specified by DWARF.  It seems to have been
16810                      emitted by gfortran at least as recently as:
16811                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16812                   complaint (_("Variable in common block has "
16813                                "DW_AT_data_member_location "
16814                                "- DIE at %s [in module %s]"),
16815                                sect_offset_str (child_die->sect_off),
16816                              objfile_name (objfile));
16817
16818                   if (attr_form_is_section_offset (member_loc))
16819                     dwarf2_complex_location_expr_complaint ();
16820                   else if (attr_form_is_constant (member_loc)
16821                            || attr_form_is_block (member_loc))
16822                     {
16823                       if (attr)
16824                         mark_common_block_symbol_computed (sym, die, attr,
16825                                                            member_loc, cu);
16826                     }
16827                   else
16828                     dwarf2_complex_location_expr_complaint ();
16829                 }
16830             }
16831         }
16832
16833       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16834       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16835     }
16836 }
16837
16838 /* Create a type for a C++ namespace.  */
16839
16840 static struct type *
16841 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16842 {
16843   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16844   const char *previous_prefix, *name;
16845   int is_anonymous;
16846   struct type *type;
16847
16848   /* For extensions, reuse the type of the original namespace.  */
16849   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16850     {
16851       struct die_info *ext_die;
16852       struct dwarf2_cu *ext_cu = cu;
16853
16854       ext_die = dwarf2_extension (die, &ext_cu);
16855       type = read_type_die (ext_die, ext_cu);
16856
16857       /* EXT_CU may not be the same as CU.
16858          Ensure TYPE is recorded with CU in die_type_hash.  */
16859       return set_die_type (die, type, cu);
16860     }
16861
16862   name = namespace_name (die, &is_anonymous, cu);
16863
16864   /* Now build the name of the current namespace.  */
16865
16866   previous_prefix = determine_prefix (die, cu);
16867   if (previous_prefix[0] != '\0')
16868     name = typename_concat (&objfile->objfile_obstack,
16869                             previous_prefix, name, 0, cu);
16870
16871   /* Create the type.  */
16872   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16873
16874   return set_die_type (die, type, cu);
16875 }
16876
16877 /* Read a namespace scope.  */
16878
16879 static void
16880 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16881 {
16882   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16883   int is_anonymous;
16884
16885   /* Add a symbol associated to this if we haven't seen the namespace
16886      before.  Also, add a using directive if it's an anonymous
16887      namespace.  */
16888
16889   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16890     {
16891       struct type *type;
16892
16893       type = read_type_die (die, cu);
16894       new_symbol (die, type, cu);
16895
16896       namespace_name (die, &is_anonymous, cu);
16897       if (is_anonymous)
16898         {
16899           const char *previous_prefix = determine_prefix (die, cu);
16900
16901           std::vector<const char *> excludes;
16902           add_using_directive (using_directives (cu),
16903                                previous_prefix, TYPE_NAME (type), NULL,
16904                                NULL, excludes, 0, &objfile->objfile_obstack);
16905         }
16906     }
16907
16908   if (die->child != NULL)
16909     {
16910       struct die_info *child_die = die->child;
16911
16912       while (child_die && child_die->tag)
16913         {
16914           process_die (child_die, cu);
16915           child_die = sibling_die (child_die);
16916         }
16917     }
16918 }
16919
16920 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16921    imported module.  Still we need that type as local Fortran "use ... only"
16922    declaration imports depend on the created type in determine_prefix.  */
16923
16924 static struct type *
16925 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16926 {
16927   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16928   const char *module_name;
16929   struct type *type;
16930
16931   module_name = dwarf2_name (die, cu);
16932   if (!module_name)
16933     complaint (_("DW_TAG_module has no name, offset %s"),
16934                sect_offset_str (die->sect_off));
16935   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16936
16937   return set_die_type (die, type, cu);
16938 }
16939
16940 /* Read a Fortran module.  */
16941
16942 static void
16943 read_module (struct die_info *die, struct dwarf2_cu *cu)
16944 {
16945   struct die_info *child_die = die->child;
16946   struct type *type;
16947
16948   type = read_type_die (die, cu);
16949   new_symbol (die, type, cu);
16950
16951   while (child_die && child_die->tag)
16952     {
16953       process_die (child_die, cu);
16954       child_die = sibling_die (child_die);
16955     }
16956 }
16957
16958 /* Return the name of the namespace represented by DIE.  Set
16959    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16960    namespace.  */
16961
16962 static const char *
16963 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16964 {
16965   struct die_info *current_die;
16966   const char *name = NULL;
16967
16968   /* Loop through the extensions until we find a name.  */
16969
16970   for (current_die = die;
16971        current_die != NULL;
16972        current_die = dwarf2_extension (die, &cu))
16973     {
16974       /* We don't use dwarf2_name here so that we can detect the absence
16975          of a name -> anonymous namespace.  */
16976       name = dwarf2_string_attr (die, DW_AT_name, cu);
16977
16978       if (name != NULL)
16979         break;
16980     }
16981
16982   /* Is it an anonymous namespace?  */
16983
16984   *is_anonymous = (name == NULL);
16985   if (*is_anonymous)
16986     name = CP_ANONYMOUS_NAMESPACE_STR;
16987
16988   return name;
16989 }
16990
16991 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16992    the user defined type vector.  */
16993
16994 static struct type *
16995 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16996 {
16997   struct gdbarch *gdbarch
16998     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16999   struct comp_unit_head *cu_header = &cu->header;
17000   struct type *type;
17001   struct attribute *attr_byte_size;
17002   struct attribute *attr_address_class;
17003   int byte_size, addr_class;
17004   struct type *target_type;
17005
17006   target_type = die_type (die, cu);
17007
17008   /* The die_type call above may have already set the type for this DIE.  */
17009   type = get_die_type (die, cu);
17010   if (type)
17011     return type;
17012
17013   type = lookup_pointer_type (target_type);
17014
17015   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17016   if (attr_byte_size)
17017     byte_size = DW_UNSND (attr_byte_size);
17018   else
17019     byte_size = cu_header->addr_size;
17020
17021   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17022   if (attr_address_class)
17023     addr_class = DW_UNSND (attr_address_class);
17024   else
17025     addr_class = DW_ADDR_none;
17026
17027   ULONGEST alignment = get_alignment (cu, die);
17028
17029   /* If the pointer size, alignment, or address class is different
17030      than the default, create a type variant marked as such and set
17031      the length accordingly.  */
17032   if (TYPE_LENGTH (type) != byte_size
17033       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
17034           && alignment != TYPE_RAW_ALIGN (type))
17035       || addr_class != DW_ADDR_none)
17036     {
17037       if (gdbarch_address_class_type_flags_p (gdbarch))
17038         {
17039           int type_flags;
17040
17041           type_flags = gdbarch_address_class_type_flags
17042                          (gdbarch, byte_size, addr_class);
17043           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17044                       == 0);
17045           type = make_type_with_address_space (type, type_flags);
17046         }
17047       else if (TYPE_LENGTH (type) != byte_size)
17048         {
17049           complaint (_("invalid pointer size %d"), byte_size);
17050         }
17051       else if (TYPE_RAW_ALIGN (type) != alignment)
17052         {
17053           complaint (_("Invalid DW_AT_alignment"
17054                        " - DIE at %s [in module %s]"),
17055                      sect_offset_str (die->sect_off),
17056                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17057         }
17058       else
17059         {
17060           /* Should we also complain about unhandled address classes?  */
17061         }
17062     }
17063
17064   TYPE_LENGTH (type) = byte_size;
17065   set_type_align (type, alignment);
17066   return set_die_type (die, type, cu);
17067 }
17068
17069 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17070    the user defined type vector.  */
17071
17072 static struct type *
17073 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17074 {
17075   struct type *type;
17076   struct type *to_type;
17077   struct type *domain;
17078
17079   to_type = die_type (die, cu);
17080   domain = die_containing_type (die, cu);
17081
17082   /* The calls above may have already set the type for this DIE.  */
17083   type = get_die_type (die, cu);
17084   if (type)
17085     return type;
17086
17087   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17088     type = lookup_methodptr_type (to_type);
17089   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17090     {
17091       struct type *new_type
17092         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17093
17094       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17095                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17096                             TYPE_VARARGS (to_type));
17097       type = lookup_methodptr_type (new_type);
17098     }
17099   else
17100     type = lookup_memberptr_type (to_type, domain);
17101
17102   return set_die_type (die, type, cu);
17103 }
17104
17105 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17106    the user defined type vector.  */
17107
17108 static struct type *
17109 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17110                           enum type_code refcode)
17111 {
17112   struct comp_unit_head *cu_header = &cu->header;
17113   struct type *type, *target_type;
17114   struct attribute *attr;
17115
17116   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17117
17118   target_type = die_type (die, cu);
17119
17120   /* The die_type call above may have already set the type for this DIE.  */
17121   type = get_die_type (die, cu);
17122   if (type)
17123     return type;
17124
17125   type = lookup_reference_type (target_type, refcode);
17126   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17127   if (attr)
17128     {
17129       TYPE_LENGTH (type) = DW_UNSND (attr);
17130     }
17131   else
17132     {
17133       TYPE_LENGTH (type) = cu_header->addr_size;
17134     }
17135   maybe_set_alignment (cu, die, type);
17136   return set_die_type (die, type, cu);
17137 }
17138
17139 /* Add the given cv-qualifiers to the element type of the array.  GCC
17140    outputs DWARF type qualifiers that apply to an array, not the
17141    element type.  But GDB relies on the array element type to carry
17142    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17143    specification.  */
17144
17145 static struct type *
17146 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17147                    struct type *base_type, int cnst, int voltl)
17148 {
17149   struct type *el_type, *inner_array;
17150
17151   base_type = copy_type (base_type);
17152   inner_array = base_type;
17153
17154   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17155     {
17156       TYPE_TARGET_TYPE (inner_array) =
17157         copy_type (TYPE_TARGET_TYPE (inner_array));
17158       inner_array = TYPE_TARGET_TYPE (inner_array);
17159     }
17160
17161   el_type = TYPE_TARGET_TYPE (inner_array);
17162   cnst |= TYPE_CONST (el_type);
17163   voltl |= TYPE_VOLATILE (el_type);
17164   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17165
17166   return set_die_type (die, base_type, cu);
17167 }
17168
17169 static struct type *
17170 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17171 {
17172   struct type *base_type, *cv_type;
17173
17174   base_type = die_type (die, cu);
17175
17176   /* The die_type call above may have already set the type for this DIE.  */
17177   cv_type = get_die_type (die, cu);
17178   if (cv_type)
17179     return cv_type;
17180
17181   /* In case the const qualifier is applied to an array type, the element type
17182      is so qualified, not the array type (section 6.7.3 of C99).  */
17183   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17184     return add_array_cv_type (die, cu, base_type, 1, 0);
17185
17186   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17187   return set_die_type (die, cv_type, cu);
17188 }
17189
17190 static struct type *
17191 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17192 {
17193   struct type *base_type, *cv_type;
17194
17195   base_type = die_type (die, cu);
17196
17197   /* The die_type call above may have already set the type for this DIE.  */
17198   cv_type = get_die_type (die, cu);
17199   if (cv_type)
17200     return cv_type;
17201
17202   /* In case the volatile qualifier is applied to an array type, the
17203      element type is so qualified, not the array type (section 6.7.3
17204      of C99).  */
17205   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17206     return add_array_cv_type (die, cu, base_type, 0, 1);
17207
17208   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17209   return set_die_type (die, cv_type, cu);
17210 }
17211
17212 /* Handle DW_TAG_restrict_type.  */
17213
17214 static struct type *
17215 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17216 {
17217   struct type *base_type, *cv_type;
17218
17219   base_type = die_type (die, cu);
17220
17221   /* The die_type call above may have already set the type for this DIE.  */
17222   cv_type = get_die_type (die, cu);
17223   if (cv_type)
17224     return cv_type;
17225
17226   cv_type = make_restrict_type (base_type);
17227   return set_die_type (die, cv_type, cu);
17228 }
17229
17230 /* Handle DW_TAG_atomic_type.  */
17231
17232 static struct type *
17233 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17234 {
17235   struct type *base_type, *cv_type;
17236
17237   base_type = die_type (die, cu);
17238
17239   /* The die_type call above may have already set the type for this DIE.  */
17240   cv_type = get_die_type (die, cu);
17241   if (cv_type)
17242     return cv_type;
17243
17244   cv_type = make_atomic_type (base_type);
17245   return set_die_type (die, cv_type, cu);
17246 }
17247
17248 /* Extract all information from a DW_TAG_string_type DIE and add to
17249    the user defined type vector.  It isn't really a user defined type,
17250    but it behaves like one, with other DIE's using an AT_user_def_type
17251    attribute to reference it.  */
17252
17253 static struct type *
17254 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17255 {
17256   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17257   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17258   struct type *type, *range_type, *index_type, *char_type;
17259   struct attribute *attr;
17260   unsigned int length;
17261
17262   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17263   if (attr)
17264     {
17265       length = DW_UNSND (attr);
17266     }
17267   else
17268     {
17269       /* Check for the DW_AT_byte_size attribute.  */
17270       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17271       if (attr)
17272         {
17273           length = DW_UNSND (attr);
17274         }
17275       else
17276         {
17277           length = 1;
17278         }
17279     }
17280
17281   index_type = objfile_type (objfile)->builtin_int;
17282   range_type = create_static_range_type (NULL, index_type, 1, length);
17283   char_type = language_string_char_type (cu->language_defn, gdbarch);
17284   type = create_string_type (NULL, char_type, range_type);
17285
17286   return set_die_type (die, type, cu);
17287 }
17288
17289 /* Assuming that DIE corresponds to a function, returns nonzero
17290    if the function is prototyped.  */
17291
17292 static int
17293 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17294 {
17295   struct attribute *attr;
17296
17297   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17298   if (attr && (DW_UNSND (attr) != 0))
17299     return 1;
17300
17301   /* The DWARF standard implies that the DW_AT_prototyped attribute
17302      is only meaninful for C, but the concept also extends to other
17303      languages that allow unprototyped functions (Eg: Objective C).
17304      For all other languages, assume that functions are always
17305      prototyped.  */
17306   if (cu->language != language_c
17307       && cu->language != language_objc
17308       && cu->language != language_opencl)
17309     return 1;
17310
17311   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17312      prototyped and unprototyped functions; default to prototyped,
17313      since that is more common in modern code (and RealView warns
17314      about unprototyped functions).  */
17315   if (producer_is_realview (cu->producer))
17316     return 1;
17317
17318   return 0;
17319 }
17320
17321 /* Handle DIES due to C code like:
17322
17323    struct foo
17324    {
17325    int (*funcp)(int a, long l);
17326    int b;
17327    };
17328
17329    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17330
17331 static struct type *
17332 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17333 {
17334   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17335   struct type *type;            /* Type that this function returns.  */
17336   struct type *ftype;           /* Function that returns above type.  */
17337   struct attribute *attr;
17338
17339   type = die_type (die, cu);
17340
17341   /* The die_type call above may have already set the type for this DIE.  */
17342   ftype = get_die_type (die, cu);
17343   if (ftype)
17344     return ftype;
17345
17346   ftype = lookup_function_type (type);
17347
17348   if (prototyped_function_p (die, cu))
17349     TYPE_PROTOTYPED (ftype) = 1;
17350
17351   /* Store the calling convention in the type if it's available in
17352      the subroutine die.  Otherwise set the calling convention to
17353      the default value DW_CC_normal.  */
17354   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17355   if (attr)
17356     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17357   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17358     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17359   else
17360     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17361
17362   /* Record whether the function returns normally to its caller or not
17363      if the DWARF producer set that information.  */
17364   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17365   if (attr && (DW_UNSND (attr) != 0))
17366     TYPE_NO_RETURN (ftype) = 1;
17367
17368   /* We need to add the subroutine type to the die immediately so
17369      we don't infinitely recurse when dealing with parameters
17370      declared as the same subroutine type.  */
17371   set_die_type (die, ftype, cu);
17372
17373   if (die->child != NULL)
17374     {
17375       struct type *void_type = objfile_type (objfile)->builtin_void;
17376       struct die_info *child_die;
17377       int nparams, iparams;
17378
17379       /* Count the number of parameters.
17380          FIXME: GDB currently ignores vararg functions, but knows about
17381          vararg member functions.  */
17382       nparams = 0;
17383       child_die = die->child;
17384       while (child_die && child_die->tag)
17385         {
17386           if (child_die->tag == DW_TAG_formal_parameter)
17387             nparams++;
17388           else if (child_die->tag == DW_TAG_unspecified_parameters)
17389             TYPE_VARARGS (ftype) = 1;
17390           child_die = sibling_die (child_die);
17391         }
17392
17393       /* Allocate storage for parameters and fill them in.  */
17394       TYPE_NFIELDS (ftype) = nparams;
17395       TYPE_FIELDS (ftype) = (struct field *)
17396         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17397
17398       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17399          even if we error out during the parameters reading below.  */
17400       for (iparams = 0; iparams < nparams; iparams++)
17401         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17402
17403       iparams = 0;
17404       child_die = die->child;
17405       while (child_die && child_die->tag)
17406         {
17407           if (child_die->tag == DW_TAG_formal_parameter)
17408             {
17409               struct type *arg_type;
17410
17411               /* DWARF version 2 has no clean way to discern C++
17412                  static and non-static member functions.  G++ helps
17413                  GDB by marking the first parameter for non-static
17414                  member functions (which is the this pointer) as
17415                  artificial.  We pass this information to
17416                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17417
17418                  DWARF version 3 added DW_AT_object_pointer, which GCC
17419                  4.5 does not yet generate.  */
17420               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17421               if (attr)
17422                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17423               else
17424                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17425               arg_type = die_type (child_die, cu);
17426
17427               /* RealView does not mark THIS as const, which the testsuite
17428                  expects.  GCC marks THIS as const in method definitions,
17429                  but not in the class specifications (GCC PR 43053).  */
17430               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17431                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17432                 {
17433                   int is_this = 0;
17434                   struct dwarf2_cu *arg_cu = cu;
17435                   const char *name = dwarf2_name (child_die, cu);
17436
17437                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17438                   if (attr)
17439                     {
17440                       /* If the compiler emits this, use it.  */
17441                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17442                         is_this = 1;
17443                     }
17444                   else if (name && strcmp (name, "this") == 0)
17445                     /* Function definitions will have the argument names.  */
17446                     is_this = 1;
17447                   else if (name == NULL && iparams == 0)
17448                     /* Declarations may not have the names, so like
17449                        elsewhere in GDB, assume an artificial first
17450                        argument is "this".  */
17451                     is_this = 1;
17452
17453                   if (is_this)
17454                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17455                                              arg_type, 0);
17456                 }
17457
17458               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17459               iparams++;
17460             }
17461           child_die = sibling_die (child_die);
17462         }
17463     }
17464
17465   return ftype;
17466 }
17467
17468 static struct type *
17469 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17470 {
17471   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17472   const char *name = NULL;
17473   struct type *this_type, *target_type;
17474
17475   name = dwarf2_full_name (NULL, die, cu);
17476   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17477   TYPE_TARGET_STUB (this_type) = 1;
17478   set_die_type (die, this_type, cu);
17479   target_type = die_type (die, cu);
17480   if (target_type != this_type)
17481     TYPE_TARGET_TYPE (this_type) = target_type;
17482   else
17483     {
17484       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17485          spec and cause infinite loops in GDB.  */
17486       complaint (_("Self-referential DW_TAG_typedef "
17487                    "- DIE at %s [in module %s]"),
17488                  sect_offset_str (die->sect_off), objfile_name (objfile));
17489       TYPE_TARGET_TYPE (this_type) = NULL;
17490     }
17491   return this_type;
17492 }
17493
17494 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17495    (which may be different from NAME) to the architecture back-end to allow
17496    it to guess the correct format if necessary.  */
17497
17498 static struct type *
17499 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17500                         const char *name_hint)
17501 {
17502   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17503   const struct floatformat **format;
17504   struct type *type;
17505
17506   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17507   if (format)
17508     type = init_float_type (objfile, bits, name, format);
17509   else
17510     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17511
17512   return type;
17513 }
17514
17515 /* Allocate an integer type of size BITS and name NAME.  */
17516
17517 static struct type *
17518 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17519                           int bits, int unsigned_p, const char *name)
17520 {
17521   struct type *type;
17522
17523   /* Versions of Intel's C Compiler generate an integer type called "void"
17524      instead of using DW_TAG_unspecified_type.  This has been seen on
17525      at least versions 14, 17, and 18.  */
17526   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17527       && strcmp (name, "void") == 0)
17528     type = objfile_type (objfile)->builtin_void;
17529   else
17530     type = init_integer_type (objfile, bits, unsigned_p, name);
17531
17532   return type;
17533 }
17534
17535 /* Initialise and return a floating point type of size BITS suitable for
17536    use as a component of a complex number.  The NAME_HINT is passed through
17537    when initialising the floating point type and is the name of the complex
17538    type.
17539
17540    As DWARF doesn't currently provide an explicit name for the components
17541    of a complex number, but it can be helpful to have these components
17542    named, we try to select a suitable name based on the size of the
17543    component.  */
17544 static struct type *
17545 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17546                                  struct objfile *objfile,
17547                                  int bits, const char *name_hint)
17548 {
17549   gdbarch *gdbarch = get_objfile_arch (objfile);
17550   struct type *tt = nullptr;
17551
17552   /* Try to find a suitable floating point builtin type of size BITS.
17553      We're going to use the name of this type as the name for the complex
17554      target type that we are about to create.  */
17555   switch (cu->language)
17556     {
17557     case language_fortran:
17558       switch (bits)
17559         {
17560         case 32:
17561           tt = builtin_f_type (gdbarch)->builtin_real;
17562           break;
17563         case 64:
17564           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17565           break;
17566         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17567         case 128:
17568           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17569           break;
17570         }
17571       break;
17572     default:
17573       switch (bits)
17574         {
17575         case 32:
17576           tt = builtin_type (gdbarch)->builtin_float;
17577           break;
17578         case 64:
17579           tt = builtin_type (gdbarch)->builtin_double;
17580           break;
17581         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17582         case 128:
17583           tt = builtin_type (gdbarch)->builtin_long_double;
17584           break;
17585         }
17586       break;
17587     }
17588
17589   /* If the type we found doesn't match the size we were looking for, then
17590      pretend we didn't find a type at all, the complex target type we
17591      create will then be nameless.  */
17592   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17593     tt = nullptr;
17594
17595   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
17596   return dwarf2_init_float_type (objfile, bits, name, name_hint);
17597 }
17598
17599 /* Find a representation of a given base type and install
17600    it in the TYPE field of the die.  */
17601
17602 static struct type *
17603 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17604 {
17605   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17606   struct type *type;
17607   struct attribute *attr;
17608   int encoding = 0, bits = 0;
17609   const char *name;
17610
17611   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17612   if (attr)
17613     {
17614       encoding = DW_UNSND (attr);
17615     }
17616   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17617   if (attr)
17618     {
17619       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17620     }
17621   name = dwarf2_name (die, cu);
17622   if (!name)
17623     {
17624       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17625     }
17626
17627   switch (encoding)
17628     {
17629       case DW_ATE_address:
17630         /* Turn DW_ATE_address into a void * pointer.  */
17631         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17632         type = init_pointer_type (objfile, bits, name, type);
17633         break;
17634       case DW_ATE_boolean:
17635         type = init_boolean_type (objfile, bits, 1, name);
17636         break;
17637       case DW_ATE_complex_float:
17638         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name);
17639         type = init_complex_type (objfile, name, type);
17640         break;
17641       case DW_ATE_decimal_float:
17642         type = init_decfloat_type (objfile, bits, name);
17643         break;
17644       case DW_ATE_float:
17645         type = dwarf2_init_float_type (objfile, bits, name, name);
17646         break;
17647       case DW_ATE_signed:
17648         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17649         break;
17650       case DW_ATE_unsigned:
17651         if (cu->language == language_fortran
17652             && name
17653             && startswith (name, "character("))
17654           type = init_character_type (objfile, bits, 1, name);
17655         else
17656           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17657         break;
17658       case DW_ATE_signed_char:
17659         if (cu->language == language_ada || cu->language == language_m2
17660             || cu->language == language_pascal
17661             || cu->language == language_fortran)
17662           type = init_character_type (objfile, bits, 0, name);
17663         else
17664           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17665         break;
17666       case DW_ATE_unsigned_char:
17667         if (cu->language == language_ada || cu->language == language_m2
17668             || cu->language == language_pascal
17669             || cu->language == language_fortran
17670             || cu->language == language_rust)
17671           type = init_character_type (objfile, bits, 1, name);
17672         else
17673           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17674         break;
17675       case DW_ATE_UTF:
17676         {
17677           gdbarch *arch = get_objfile_arch (objfile);
17678
17679           if (bits == 16)
17680             type = builtin_type (arch)->builtin_char16;
17681           else if (bits == 32)
17682             type = builtin_type (arch)->builtin_char32;
17683           else
17684             {
17685               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17686                          bits);
17687               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17688             }
17689           return set_die_type (die, type, cu);
17690         }
17691         break;
17692
17693       default:
17694         complaint (_("unsupported DW_AT_encoding: '%s'"),
17695                    dwarf_type_encoding_name (encoding));
17696         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17697         break;
17698     }
17699
17700   if (name && strcmp (name, "char") == 0)
17701     TYPE_NOSIGN (type) = 1;
17702
17703   maybe_set_alignment (cu, die, type);
17704
17705   return set_die_type (die, type, cu);
17706 }
17707
17708 /* Parse dwarf attribute if it's a block, reference or constant and put the
17709    resulting value of the attribute into struct bound_prop.
17710    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17711
17712 static int
17713 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17714                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17715 {
17716   struct dwarf2_property_baton *baton;
17717   struct obstack *obstack
17718     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17719
17720   if (attr == NULL || prop == NULL)
17721     return 0;
17722
17723   if (attr_form_is_block (attr))
17724     {
17725       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17726       baton->referenced_type = NULL;
17727       baton->locexpr.per_cu = cu->per_cu;
17728       baton->locexpr.size = DW_BLOCK (attr)->size;
17729       baton->locexpr.data = DW_BLOCK (attr)->data;
17730       prop->data.baton = baton;
17731       prop->kind = PROP_LOCEXPR;
17732       gdb_assert (prop->data.baton != NULL);
17733     }
17734   else if (attr_form_is_ref (attr))
17735     {
17736       struct dwarf2_cu *target_cu = cu;
17737       struct die_info *target_die;
17738       struct attribute *target_attr;
17739
17740       target_die = follow_die_ref (die, attr, &target_cu);
17741       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17742       if (target_attr == NULL)
17743         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17744                                    target_cu);
17745       if (target_attr == NULL)
17746         return 0;
17747
17748       switch (target_attr->name)
17749         {
17750           case DW_AT_location:
17751             if (attr_form_is_section_offset (target_attr))
17752               {
17753                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17754                 baton->referenced_type = die_type (target_die, target_cu);
17755                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17756                 prop->data.baton = baton;
17757                 prop->kind = PROP_LOCLIST;
17758                 gdb_assert (prop->data.baton != NULL);
17759               }
17760             else if (attr_form_is_block (target_attr))
17761               {
17762                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17763                 baton->referenced_type = die_type (target_die, target_cu);
17764                 baton->locexpr.per_cu = cu->per_cu;
17765                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17766                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17767                 prop->data.baton = baton;
17768                 prop->kind = PROP_LOCEXPR;
17769                 gdb_assert (prop->data.baton != NULL);
17770               }
17771             else
17772               {
17773                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17774                                                        "dynamic property");
17775                 return 0;
17776               }
17777             break;
17778           case DW_AT_data_member_location:
17779             {
17780               LONGEST offset;
17781
17782               if (!handle_data_member_location (target_die, target_cu,
17783                                                 &offset))
17784                 return 0;
17785
17786               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17787               baton->referenced_type = read_type_die (target_die->parent,
17788                                                       target_cu);
17789               baton->offset_info.offset = offset;
17790               baton->offset_info.type = die_type (target_die, target_cu);
17791               prop->data.baton = baton;
17792               prop->kind = PROP_ADDR_OFFSET;
17793               break;
17794             }
17795         }
17796     }
17797   else if (attr_form_is_constant (attr))
17798     {
17799       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17800       prop->kind = PROP_CONST;
17801     }
17802   else
17803     {
17804       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17805                                              dwarf2_name (die, cu));
17806       return 0;
17807     }
17808
17809   return 1;
17810 }
17811
17812 /* Read the given DW_AT_subrange DIE.  */
17813
17814 static struct type *
17815 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17816 {
17817   struct type *base_type, *orig_base_type;
17818   struct type *range_type;
17819   struct attribute *attr;
17820   struct dynamic_prop low, high;
17821   int low_default_is_valid;
17822   int high_bound_is_count = 0;
17823   const char *name;
17824   ULONGEST negative_mask;
17825
17826   orig_base_type = die_type (die, cu);
17827   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17828      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17829      creating the range type, but we use the result of check_typedef
17830      when examining properties of the type.  */
17831   base_type = check_typedef (orig_base_type);
17832
17833   /* The die_type call above may have already set the type for this DIE.  */
17834   range_type = get_die_type (die, cu);
17835   if (range_type)
17836     return range_type;
17837
17838   low.kind = PROP_CONST;
17839   high.kind = PROP_CONST;
17840   high.data.const_val = 0;
17841
17842   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17843      omitting DW_AT_lower_bound.  */
17844   switch (cu->language)
17845     {
17846     case language_c:
17847     case language_cplus:
17848       low.data.const_val = 0;
17849       low_default_is_valid = 1;
17850       break;
17851     case language_fortran:
17852       low.data.const_val = 1;
17853       low_default_is_valid = 1;
17854       break;
17855     case language_d:
17856     case language_objc:
17857     case language_rust:
17858       low.data.const_val = 0;
17859       low_default_is_valid = (cu->header.version >= 4);
17860       break;
17861     case language_ada:
17862     case language_m2:
17863     case language_pascal:
17864       low.data.const_val = 1;
17865       low_default_is_valid = (cu->header.version >= 4);
17866       break;
17867     default:
17868       low.data.const_val = 0;
17869       low_default_is_valid = 0;
17870       break;
17871     }
17872
17873   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17874   if (attr)
17875     attr_to_dynamic_prop (attr, die, cu, &low);
17876   else if (!low_default_is_valid)
17877     complaint (_("Missing DW_AT_lower_bound "
17878                                       "- DIE at %s [in module %s]"),
17879                sect_offset_str (die->sect_off),
17880                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17881
17882   struct attribute *attr_ub, *attr_count;
17883   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17884   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17885     {
17886       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17887       if (attr_to_dynamic_prop (attr, die, cu, &high))
17888         {
17889           /* If bounds are constant do the final calculation here.  */
17890           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17891             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17892           else
17893             high_bound_is_count = 1;
17894         }
17895       else
17896         {
17897           if (attr_ub != NULL)
17898             complaint (_("Unresolved DW_AT_upper_bound "
17899                          "- DIE at %s [in module %s]"),
17900                        sect_offset_str (die->sect_off),
17901                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17902           if (attr_count != NULL)
17903             complaint (_("Unresolved DW_AT_count "
17904                          "- DIE at %s [in module %s]"),
17905                        sect_offset_str (die->sect_off),
17906                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17907         }
17908         
17909     }
17910
17911   /* Dwarf-2 specifications explicitly allows to create subrange types
17912      without specifying a base type.
17913      In that case, the base type must be set to the type of
17914      the lower bound, upper bound or count, in that order, if any of these
17915      three attributes references an object that has a type.
17916      If no base type is found, the Dwarf-2 specifications say that
17917      a signed integer type of size equal to the size of an address should
17918      be used.
17919      For the following C code: `extern char gdb_int [];'
17920      GCC produces an empty range DIE.
17921      FIXME: muller/2010-05-28: Possible references to object for low bound,
17922      high bound or count are not yet handled by this code.  */
17923   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17924     {
17925       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17926       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17927       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17928       struct type *int_type = objfile_type (objfile)->builtin_int;
17929
17930       /* Test "int", "long int", and "long long int" objfile types,
17931          and select the first one having a size above or equal to the
17932          architecture address size.  */
17933       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17934         base_type = int_type;
17935       else
17936         {
17937           int_type = objfile_type (objfile)->builtin_long;
17938           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17939             base_type = int_type;
17940           else
17941             {
17942               int_type = objfile_type (objfile)->builtin_long_long;
17943               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17944                 base_type = int_type;
17945             }
17946         }
17947     }
17948
17949   /* Normally, the DWARF producers are expected to use a signed
17950      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17951      But this is unfortunately not always the case, as witnessed
17952      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17953      is used instead.  To work around that ambiguity, we treat
17954      the bounds as signed, and thus sign-extend their values, when
17955      the base type is signed.  */
17956   negative_mask =
17957     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17958   if (low.kind == PROP_CONST
17959       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17960     low.data.const_val |= negative_mask;
17961   if (high.kind == PROP_CONST
17962       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17963     high.data.const_val |= negative_mask;
17964
17965   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17966
17967   if (high_bound_is_count)
17968     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17969
17970   /* Ada expects an empty array on no boundary attributes.  */
17971   if (attr == NULL && cu->language != language_ada)
17972     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17973
17974   name = dwarf2_name (die, cu);
17975   if (name)
17976     TYPE_NAME (range_type) = name;
17977
17978   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17979   if (attr)
17980     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17981
17982   maybe_set_alignment (cu, die, range_type);
17983
17984   set_die_type (die, range_type, cu);
17985
17986   /* set_die_type should be already done.  */
17987   set_descriptive_type (range_type, die, cu);
17988
17989   return range_type;
17990 }
17991
17992 static struct type *
17993 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17994 {
17995   struct type *type;
17996
17997   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17998                     NULL);
17999   TYPE_NAME (type) = dwarf2_name (die, cu);
18000
18001   /* In Ada, an unspecified type is typically used when the description
18002      of the type is defered to a different unit.  When encountering
18003      such a type, we treat it as a stub, and try to resolve it later on,
18004      when needed.  */
18005   if (cu->language == language_ada)
18006     TYPE_STUB (type) = 1;
18007
18008   return set_die_type (die, type, cu);
18009 }
18010
18011 /* Read a single die and all its descendents.  Set the die's sibling
18012    field to NULL; set other fields in the die correctly, and set all
18013    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18014    location of the info_ptr after reading all of those dies.  PARENT
18015    is the parent of the die in question.  */
18016
18017 static struct die_info *
18018 read_die_and_children (const struct die_reader_specs *reader,
18019                        const gdb_byte *info_ptr,
18020                        const gdb_byte **new_info_ptr,
18021                        struct die_info *parent)
18022 {
18023   struct die_info *die;
18024   const gdb_byte *cur_ptr;
18025   int has_children;
18026
18027   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
18028   if (die == NULL)
18029     {
18030       *new_info_ptr = cur_ptr;
18031       return NULL;
18032     }
18033   store_in_ref_table (die, reader->cu);
18034
18035   if (has_children)
18036     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18037   else
18038     {
18039       die->child = NULL;
18040       *new_info_ptr = cur_ptr;
18041     }
18042
18043   die->sibling = NULL;
18044   die->parent = parent;
18045   return die;
18046 }
18047
18048 /* Read a die, all of its descendents, and all of its siblings; set
18049    all of the fields of all of the dies correctly.  Arguments are as
18050    in read_die_and_children.  */
18051
18052 static struct die_info *
18053 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18054                          const gdb_byte *info_ptr,
18055                          const gdb_byte **new_info_ptr,
18056                          struct die_info *parent)
18057 {
18058   struct die_info *first_die, *last_sibling;
18059   const gdb_byte *cur_ptr;
18060
18061   cur_ptr = info_ptr;
18062   first_die = last_sibling = NULL;
18063
18064   while (1)
18065     {
18066       struct die_info *die
18067         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18068
18069       if (die == NULL)
18070         {
18071           *new_info_ptr = cur_ptr;
18072           return first_die;
18073         }
18074
18075       if (!first_die)
18076         first_die = die;
18077       else
18078         last_sibling->sibling = die;
18079
18080       last_sibling = die;
18081     }
18082 }
18083
18084 /* Read a die, all of its descendents, and all of its siblings; set
18085    all of the fields of all of the dies correctly.  Arguments are as
18086    in read_die_and_children.
18087    This the main entry point for reading a DIE and all its children.  */
18088
18089 static struct die_info *
18090 read_die_and_siblings (const struct die_reader_specs *reader,
18091                        const gdb_byte *info_ptr,
18092                        const gdb_byte **new_info_ptr,
18093                        struct die_info *parent)
18094 {
18095   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18096                                                   new_info_ptr, parent);
18097
18098   if (dwarf_die_debug)
18099     {
18100       fprintf_unfiltered (gdb_stdlog,
18101                           "Read die from %s@0x%x of %s:\n",
18102                           get_section_name (reader->die_section),
18103                           (unsigned) (info_ptr - reader->die_section->buffer),
18104                           bfd_get_filename (reader->abfd));
18105       dump_die (die, dwarf_die_debug);
18106     }
18107
18108   return die;
18109 }
18110
18111 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18112    attributes.
18113    The caller is responsible for filling in the extra attributes
18114    and updating (*DIEP)->num_attrs.
18115    Set DIEP to point to a newly allocated die with its information,
18116    except for its child, sibling, and parent fields.
18117    Set HAS_CHILDREN to tell whether the die has children or not.  */
18118
18119 static const gdb_byte *
18120 read_full_die_1 (const struct die_reader_specs *reader,
18121                  struct die_info **diep, const gdb_byte *info_ptr,
18122                  int *has_children, int num_extra_attrs)
18123 {
18124   unsigned int abbrev_number, bytes_read, i;
18125   struct abbrev_info *abbrev;
18126   struct die_info *die;
18127   struct dwarf2_cu *cu = reader->cu;
18128   bfd *abfd = reader->abfd;
18129
18130   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18131   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18132   info_ptr += bytes_read;
18133   if (!abbrev_number)
18134     {
18135       *diep = NULL;
18136       *has_children = 0;
18137       return info_ptr;
18138     }
18139
18140   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18141   if (!abbrev)
18142     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18143            abbrev_number,
18144            bfd_get_filename (abfd));
18145
18146   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18147   die->sect_off = sect_off;
18148   die->tag = abbrev->tag;
18149   die->abbrev = abbrev_number;
18150
18151   /* Make the result usable.
18152      The caller needs to update num_attrs after adding the extra
18153      attributes.  */
18154   die->num_attrs = abbrev->num_attrs;
18155
18156   for (i = 0; i < abbrev->num_attrs; ++i)
18157     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18158                                info_ptr);
18159
18160   *diep = die;
18161   *has_children = abbrev->has_children;
18162   return info_ptr;
18163 }
18164
18165 /* Read a die and all its attributes.
18166    Set DIEP to point to a newly allocated die with its information,
18167    except for its child, sibling, and parent fields.
18168    Set HAS_CHILDREN to tell whether the die has children or not.  */
18169
18170 static const gdb_byte *
18171 read_full_die (const struct die_reader_specs *reader,
18172                struct die_info **diep, const gdb_byte *info_ptr,
18173                int *has_children)
18174 {
18175   const gdb_byte *result;
18176
18177   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18178
18179   if (dwarf_die_debug)
18180     {
18181       fprintf_unfiltered (gdb_stdlog,
18182                           "Read die from %s@0x%x of %s:\n",
18183                           get_section_name (reader->die_section),
18184                           (unsigned) (info_ptr - reader->die_section->buffer),
18185                           bfd_get_filename (reader->abfd));
18186       dump_die (*diep, dwarf_die_debug);
18187     }
18188
18189   return result;
18190 }
18191 \f
18192 /* Abbreviation tables.
18193
18194    In DWARF version 2, the description of the debugging information is
18195    stored in a separate .debug_abbrev section.  Before we read any
18196    dies from a section we read in all abbreviations and install them
18197    in a hash table.  */
18198
18199 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18200
18201 struct abbrev_info *
18202 abbrev_table::alloc_abbrev ()
18203 {
18204   struct abbrev_info *abbrev;
18205
18206   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18207   memset (abbrev, 0, sizeof (struct abbrev_info));
18208
18209   return abbrev;
18210 }
18211
18212 /* Add an abbreviation to the table.  */
18213
18214 void
18215 abbrev_table::add_abbrev (unsigned int abbrev_number,
18216                           struct abbrev_info *abbrev)
18217 {
18218   unsigned int hash_number;
18219
18220   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18221   abbrev->next = m_abbrevs[hash_number];
18222   m_abbrevs[hash_number] = abbrev;
18223 }
18224
18225 /* Look up an abbrev in the table.
18226    Returns NULL if the abbrev is not found.  */
18227
18228 struct abbrev_info *
18229 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18230 {
18231   unsigned int hash_number;
18232   struct abbrev_info *abbrev;
18233
18234   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18235   abbrev = m_abbrevs[hash_number];
18236
18237   while (abbrev)
18238     {
18239       if (abbrev->number == abbrev_number)
18240         return abbrev;
18241       abbrev = abbrev->next;
18242     }
18243   return NULL;
18244 }
18245
18246 /* Read in an abbrev table.  */
18247
18248 static abbrev_table_up
18249 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18250                          struct dwarf2_section_info *section,
18251                          sect_offset sect_off)
18252 {
18253   struct objfile *objfile = dwarf2_per_objfile->objfile;
18254   bfd *abfd = get_section_bfd_owner (section);
18255   const gdb_byte *abbrev_ptr;
18256   struct abbrev_info *cur_abbrev;
18257   unsigned int abbrev_number, bytes_read, abbrev_name;
18258   unsigned int abbrev_form;
18259   struct attr_abbrev *cur_attrs;
18260   unsigned int allocated_attrs;
18261
18262   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18263
18264   dwarf2_read_section (objfile, section);
18265   abbrev_ptr = section->buffer + to_underlying (sect_off);
18266   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18267   abbrev_ptr += bytes_read;
18268
18269   allocated_attrs = ATTR_ALLOC_CHUNK;
18270   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18271
18272   /* Loop until we reach an abbrev number of 0.  */
18273   while (abbrev_number)
18274     {
18275       cur_abbrev = abbrev_table->alloc_abbrev ();
18276
18277       /* read in abbrev header */
18278       cur_abbrev->number = abbrev_number;
18279       cur_abbrev->tag
18280         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18281       abbrev_ptr += bytes_read;
18282       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18283       abbrev_ptr += 1;
18284
18285       /* now read in declarations */
18286       for (;;)
18287         {
18288           LONGEST implicit_const;
18289
18290           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18291           abbrev_ptr += bytes_read;
18292           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18293           abbrev_ptr += bytes_read;
18294           if (abbrev_form == DW_FORM_implicit_const)
18295             {
18296               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18297                                                    &bytes_read);
18298               abbrev_ptr += bytes_read;
18299             }
18300           else
18301             {
18302               /* Initialize it due to a false compiler warning.  */
18303               implicit_const = -1;
18304             }
18305
18306           if (abbrev_name == 0)
18307             break;
18308
18309           if (cur_abbrev->num_attrs == allocated_attrs)
18310             {
18311               allocated_attrs += ATTR_ALLOC_CHUNK;
18312               cur_attrs
18313                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18314             }
18315
18316           cur_attrs[cur_abbrev->num_attrs].name
18317             = (enum dwarf_attribute) abbrev_name;
18318           cur_attrs[cur_abbrev->num_attrs].form
18319             = (enum dwarf_form) abbrev_form;
18320           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18321           ++cur_abbrev->num_attrs;
18322         }
18323
18324       cur_abbrev->attrs =
18325         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18326                    cur_abbrev->num_attrs);
18327       memcpy (cur_abbrev->attrs, cur_attrs,
18328               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18329
18330       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18331
18332       /* Get next abbreviation.
18333          Under Irix6 the abbreviations for a compilation unit are not
18334          always properly terminated with an abbrev number of 0.
18335          Exit loop if we encounter an abbreviation which we have
18336          already read (which means we are about to read the abbreviations
18337          for the next compile unit) or if the end of the abbreviation
18338          table is reached.  */
18339       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18340         break;
18341       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18342       abbrev_ptr += bytes_read;
18343       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18344         break;
18345     }
18346
18347   xfree (cur_attrs);
18348   return abbrev_table;
18349 }
18350
18351 /* Returns nonzero if TAG represents a type that we might generate a partial
18352    symbol for.  */
18353
18354 static int
18355 is_type_tag_for_partial (int tag)
18356 {
18357   switch (tag)
18358     {
18359 #if 0
18360     /* Some types that would be reasonable to generate partial symbols for,
18361        that we don't at present.  */
18362     case DW_TAG_array_type:
18363     case DW_TAG_file_type:
18364     case DW_TAG_ptr_to_member_type:
18365     case DW_TAG_set_type:
18366     case DW_TAG_string_type:
18367     case DW_TAG_subroutine_type:
18368 #endif
18369     case DW_TAG_base_type:
18370     case DW_TAG_class_type:
18371     case DW_TAG_interface_type:
18372     case DW_TAG_enumeration_type:
18373     case DW_TAG_structure_type:
18374     case DW_TAG_subrange_type:
18375     case DW_TAG_typedef:
18376     case DW_TAG_union_type:
18377       return 1;
18378     default:
18379       return 0;
18380     }
18381 }
18382
18383 /* Load all DIEs that are interesting for partial symbols into memory.  */
18384
18385 static struct partial_die_info *
18386 load_partial_dies (const struct die_reader_specs *reader,
18387                    const gdb_byte *info_ptr, int building_psymtab)
18388 {
18389   struct dwarf2_cu *cu = reader->cu;
18390   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18391   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18392   unsigned int bytes_read;
18393   unsigned int load_all = 0;
18394   int nesting_level = 1;
18395
18396   parent_die = NULL;
18397   last_die = NULL;
18398
18399   gdb_assert (cu->per_cu != NULL);
18400   if (cu->per_cu->load_all_dies)
18401     load_all = 1;
18402
18403   cu->partial_dies
18404     = htab_create_alloc_ex (cu->header.length / 12,
18405                             partial_die_hash,
18406                             partial_die_eq,
18407                             NULL,
18408                             &cu->comp_unit_obstack,
18409                             hashtab_obstack_allocate,
18410                             dummy_obstack_deallocate);
18411
18412   while (1)
18413     {
18414       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18415
18416       /* A NULL abbrev means the end of a series of children.  */
18417       if (abbrev == NULL)
18418         {
18419           if (--nesting_level == 0)
18420             return first_die;
18421
18422           info_ptr += bytes_read;
18423           last_die = parent_die;
18424           parent_die = parent_die->die_parent;
18425           continue;
18426         }
18427
18428       /* Check for template arguments.  We never save these; if
18429          they're seen, we just mark the parent, and go on our way.  */
18430       if (parent_die != NULL
18431           && cu->language == language_cplus
18432           && (abbrev->tag == DW_TAG_template_type_param
18433               || abbrev->tag == DW_TAG_template_value_param))
18434         {
18435           parent_die->has_template_arguments = 1;
18436
18437           if (!load_all)
18438             {
18439               /* We don't need a partial DIE for the template argument.  */
18440               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18441               continue;
18442             }
18443         }
18444
18445       /* We only recurse into c++ subprograms looking for template arguments.
18446          Skip their other children.  */
18447       if (!load_all
18448           && cu->language == language_cplus
18449           && parent_die != NULL
18450           && parent_die->tag == DW_TAG_subprogram)
18451         {
18452           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18453           continue;
18454         }
18455
18456       /* Check whether this DIE is interesting enough to save.  Normally
18457          we would not be interested in members here, but there may be
18458          later variables referencing them via DW_AT_specification (for
18459          static members).  */
18460       if (!load_all
18461           && !is_type_tag_for_partial (abbrev->tag)
18462           && abbrev->tag != DW_TAG_constant
18463           && abbrev->tag != DW_TAG_enumerator
18464           && abbrev->tag != DW_TAG_subprogram
18465           && abbrev->tag != DW_TAG_inlined_subroutine
18466           && abbrev->tag != DW_TAG_lexical_block
18467           && abbrev->tag != DW_TAG_variable
18468           && abbrev->tag != DW_TAG_namespace
18469           && abbrev->tag != DW_TAG_module
18470           && abbrev->tag != DW_TAG_member
18471           && abbrev->tag != DW_TAG_imported_unit
18472           && abbrev->tag != DW_TAG_imported_declaration)
18473         {
18474           /* Otherwise we skip to the next sibling, if any.  */
18475           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18476           continue;
18477         }
18478
18479       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18480                                    abbrev);
18481
18482       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18483
18484       /* This two-pass algorithm for processing partial symbols has a
18485          high cost in cache pressure.  Thus, handle some simple cases
18486          here which cover the majority of C partial symbols.  DIEs
18487          which neither have specification tags in them, nor could have
18488          specification tags elsewhere pointing at them, can simply be
18489          processed and discarded.
18490
18491          This segment is also optional; scan_partial_symbols and
18492          add_partial_symbol will handle these DIEs if we chain
18493          them in normally.  When compilers which do not emit large
18494          quantities of duplicate debug information are more common,
18495          this code can probably be removed.  */
18496
18497       /* Any complete simple types at the top level (pretty much all
18498          of them, for a language without namespaces), can be processed
18499          directly.  */
18500       if (parent_die == NULL
18501           && pdi.has_specification == 0
18502           && pdi.is_declaration == 0
18503           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18504               || pdi.tag == DW_TAG_base_type
18505               || pdi.tag == DW_TAG_subrange_type))
18506         {
18507           if (building_psymtab && pdi.name != NULL)
18508             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18509                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18510                                  psymbol_placement::STATIC,
18511                                  0, cu->language, objfile);
18512           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18513           continue;
18514         }
18515
18516       /* The exception for DW_TAG_typedef with has_children above is
18517          a workaround of GCC PR debug/47510.  In the case of this complaint
18518          type_name_or_error will error on such types later.
18519
18520          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18521          it could not find the child DIEs referenced later, this is checked
18522          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18523
18524       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18525         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18526                      "- DIE at %s [in module %s]"),
18527                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18528
18529       /* If we're at the second level, and we're an enumerator, and
18530          our parent has no specification (meaning possibly lives in a
18531          namespace elsewhere), then we can add the partial symbol now
18532          instead of queueing it.  */
18533       if (pdi.tag == DW_TAG_enumerator
18534           && parent_die != NULL
18535           && parent_die->die_parent == NULL
18536           && parent_die->tag == DW_TAG_enumeration_type
18537           && parent_die->has_specification == 0)
18538         {
18539           if (pdi.name == NULL)
18540             complaint (_("malformed enumerator DIE ignored"));
18541           else if (building_psymtab)
18542             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18543                                  VAR_DOMAIN, LOC_CONST, -1,
18544                                  cu->language == language_cplus
18545                                  ? psymbol_placement::GLOBAL
18546                                  : psymbol_placement::STATIC,
18547                                  0, cu->language, objfile);
18548
18549           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18550           continue;
18551         }
18552
18553       struct partial_die_info *part_die
18554         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18555
18556       /* We'll save this DIE so link it in.  */
18557       part_die->die_parent = parent_die;
18558       part_die->die_sibling = NULL;
18559       part_die->die_child = NULL;
18560
18561       if (last_die && last_die == parent_die)
18562         last_die->die_child = part_die;
18563       else if (last_die)
18564         last_die->die_sibling = part_die;
18565
18566       last_die = part_die;
18567
18568       if (first_die == NULL)
18569         first_die = part_die;
18570
18571       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18572          find interesting need to be in the hash table, because we
18573          also have the parent/sibling/child chains; only those that we
18574          might refer to by offset later during partial symbol reading.
18575
18576          For now this means things that might have be the target of a
18577          DW_AT_specification, DW_AT_abstract_origin, or
18578          DW_AT_extension.  DW_AT_extension will refer only to
18579          namespaces; DW_AT_abstract_origin refers to functions (and
18580          many things under the function DIE, but we do not recurse
18581          into function DIEs during partial symbol reading) and
18582          possibly variables as well; DW_AT_specification refers to
18583          declarations.  Declarations ought to have the DW_AT_declaration
18584          flag.  It happens that GCC forgets to put it in sometimes, but
18585          only for functions, not for types.
18586
18587          Adding more things than necessary to the hash table is harmless
18588          except for the performance cost.  Adding too few will result in
18589          wasted time in find_partial_die, when we reread the compilation
18590          unit with load_all_dies set.  */
18591
18592       if (load_all
18593           || abbrev->tag == DW_TAG_constant
18594           || abbrev->tag == DW_TAG_subprogram
18595           || abbrev->tag == DW_TAG_variable
18596           || abbrev->tag == DW_TAG_namespace
18597           || part_die->is_declaration)
18598         {
18599           void **slot;
18600
18601           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18602                                            to_underlying (part_die->sect_off),
18603                                            INSERT);
18604           *slot = part_die;
18605         }
18606
18607       /* For some DIEs we want to follow their children (if any).  For C
18608          we have no reason to follow the children of structures; for other
18609          languages we have to, so that we can get at method physnames
18610          to infer fully qualified class names, for DW_AT_specification,
18611          and for C++ template arguments.  For C++, we also look one level
18612          inside functions to find template arguments (if the name of the
18613          function does not already contain the template arguments).
18614
18615          For Ada, we need to scan the children of subprograms and lexical
18616          blocks as well because Ada allows the definition of nested
18617          entities that could be interesting for the debugger, such as
18618          nested subprograms for instance.  */
18619       if (last_die->has_children
18620           && (load_all
18621               || last_die->tag == DW_TAG_namespace
18622               || last_die->tag == DW_TAG_module
18623               || last_die->tag == DW_TAG_enumeration_type
18624               || (cu->language == language_cplus
18625                   && last_die->tag == DW_TAG_subprogram
18626                   && (last_die->name == NULL
18627                       || strchr (last_die->name, '<') == NULL))
18628               || (cu->language != language_c
18629                   && (last_die->tag == DW_TAG_class_type
18630                       || last_die->tag == DW_TAG_interface_type
18631                       || last_die->tag == DW_TAG_structure_type
18632                       || last_die->tag == DW_TAG_union_type))
18633               || (cu->language == language_ada
18634                   && (last_die->tag == DW_TAG_subprogram
18635                       || last_die->tag == DW_TAG_lexical_block))))
18636         {
18637           nesting_level++;
18638           parent_die = last_die;
18639           continue;
18640         }
18641
18642       /* Otherwise we skip to the next sibling, if any.  */
18643       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18644
18645       /* Back to the top, do it again.  */
18646     }
18647 }
18648
18649 partial_die_info::partial_die_info (sect_offset sect_off_,
18650                                     struct abbrev_info *abbrev)
18651   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18652 {
18653 }
18654
18655 /* Read a minimal amount of information into the minimal die structure.
18656    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18657
18658 const gdb_byte *
18659 partial_die_info::read (const struct die_reader_specs *reader,
18660                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18661 {
18662   struct dwarf2_cu *cu = reader->cu;
18663   struct dwarf2_per_objfile *dwarf2_per_objfile
18664     = cu->per_cu->dwarf2_per_objfile;
18665   unsigned int i;
18666   int has_low_pc_attr = 0;
18667   int has_high_pc_attr = 0;
18668   int high_pc_relative = 0;
18669
18670   for (i = 0; i < abbrev.num_attrs; ++i)
18671     {
18672       struct attribute attr;
18673
18674       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18675
18676       /* Store the data if it is of an attribute we want to keep in a
18677          partial symbol table.  */
18678       switch (attr.name)
18679         {
18680         case DW_AT_name:
18681           switch (tag)
18682             {
18683             case DW_TAG_compile_unit:
18684             case DW_TAG_partial_unit:
18685             case DW_TAG_type_unit:
18686               /* Compilation units have a DW_AT_name that is a filename, not
18687                  a source language identifier.  */
18688             case DW_TAG_enumeration_type:
18689             case DW_TAG_enumerator:
18690               /* These tags always have simple identifiers already; no need
18691                  to canonicalize them.  */
18692               name = DW_STRING (&attr);
18693               break;
18694             default:
18695               {
18696                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18697
18698                 name
18699                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18700                                               &objfile->per_bfd->storage_obstack);
18701               }
18702               break;
18703             }
18704           break;
18705         case DW_AT_linkage_name:
18706         case DW_AT_MIPS_linkage_name:
18707           /* Note that both forms of linkage name might appear.  We
18708              assume they will be the same, and we only store the last
18709              one we see.  */
18710           if (cu->language == language_ada)
18711             name = DW_STRING (&attr);
18712           linkage_name = DW_STRING (&attr);
18713           break;
18714         case DW_AT_low_pc:
18715           has_low_pc_attr = 1;
18716           lowpc = attr_value_as_address (&attr);
18717           break;
18718         case DW_AT_high_pc:
18719           has_high_pc_attr = 1;
18720           highpc = attr_value_as_address (&attr);
18721           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18722                 high_pc_relative = 1;
18723           break;
18724         case DW_AT_location:
18725           /* Support the .debug_loc offsets.  */
18726           if (attr_form_is_block (&attr))
18727             {
18728                d.locdesc = DW_BLOCK (&attr);
18729             }
18730           else if (attr_form_is_section_offset (&attr))
18731             {
18732               dwarf2_complex_location_expr_complaint ();
18733             }
18734           else
18735             {
18736               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18737                                                      "partial symbol information");
18738             }
18739           break;
18740         case DW_AT_external:
18741           is_external = DW_UNSND (&attr);
18742           break;
18743         case DW_AT_declaration:
18744           is_declaration = DW_UNSND (&attr);
18745           break;
18746         case DW_AT_type:
18747           has_type = 1;
18748           break;
18749         case DW_AT_abstract_origin:
18750         case DW_AT_specification:
18751         case DW_AT_extension:
18752           has_specification = 1;
18753           spec_offset = dwarf2_get_ref_die_offset (&attr);
18754           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18755                                    || cu->per_cu->is_dwz);
18756           break;
18757         case DW_AT_sibling:
18758           /* Ignore absolute siblings, they might point outside of
18759              the current compile unit.  */
18760           if (attr.form == DW_FORM_ref_addr)
18761             complaint (_("ignoring absolute DW_AT_sibling"));
18762           else
18763             {
18764               const gdb_byte *buffer = reader->buffer;
18765               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18766               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18767
18768               if (sibling_ptr < info_ptr)
18769                 complaint (_("DW_AT_sibling points backwards"));
18770               else if (sibling_ptr > reader->buffer_end)
18771                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18772               else
18773                 sibling = sibling_ptr;
18774             }
18775           break;
18776         case DW_AT_byte_size:
18777           has_byte_size = 1;
18778           break;
18779         case DW_AT_const_value:
18780           has_const_value = 1;
18781           break;
18782         case DW_AT_calling_convention:
18783           /* DWARF doesn't provide a way to identify a program's source-level
18784              entry point.  DW_AT_calling_convention attributes are only meant
18785              to describe functions' calling conventions.
18786
18787              However, because it's a necessary piece of information in
18788              Fortran, and before DWARF 4 DW_CC_program was the only
18789              piece of debugging information whose definition refers to
18790              a 'main program' at all, several compilers marked Fortran
18791              main programs with DW_CC_program --- even when those
18792              functions use the standard calling conventions.
18793
18794              Although DWARF now specifies a way to provide this
18795              information, we support this practice for backward
18796              compatibility.  */
18797           if (DW_UNSND (&attr) == DW_CC_program
18798               && cu->language == language_fortran)
18799             main_subprogram = 1;
18800           break;
18801         case DW_AT_inline:
18802           if (DW_UNSND (&attr) == DW_INL_inlined
18803               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18804             may_be_inlined = 1;
18805           break;
18806
18807         case DW_AT_import:
18808           if (tag == DW_TAG_imported_unit)
18809             {
18810               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18811               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18812                                   || cu->per_cu->is_dwz);
18813             }
18814           break;
18815
18816         case DW_AT_main_subprogram:
18817           main_subprogram = DW_UNSND (&attr);
18818           break;
18819
18820         case DW_AT_ranges:
18821           {
18822             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18823                but that requires a full DIE, so instead we just
18824                reimplement it.  */
18825             int need_ranges_base = tag != DW_TAG_compile_unit;
18826             unsigned int ranges_offset = (DW_UNSND (&attr)
18827                                           + (need_ranges_base
18828                                              ? cu->ranges_base
18829                                              : 0));
18830
18831             /* Value of the DW_AT_ranges attribute is the offset in the
18832                .debug_ranges section.  */
18833             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18834                                     nullptr))
18835               has_pc_info = 1;
18836           }
18837           break;
18838
18839         default:
18840           break;
18841         }
18842     }
18843
18844   if (high_pc_relative)
18845     highpc += lowpc;
18846
18847   if (has_low_pc_attr && has_high_pc_attr)
18848     {
18849       /* When using the GNU linker, .gnu.linkonce. sections are used to
18850          eliminate duplicate copies of functions and vtables and such.
18851          The linker will arbitrarily choose one and discard the others.
18852          The AT_*_pc values for such functions refer to local labels in
18853          these sections.  If the section from that file was discarded, the
18854          labels are not in the output, so the relocs get a value of 0.
18855          If this is a discarded function, mark the pc bounds as invalid,
18856          so that GDB will ignore it.  */
18857       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18858         {
18859           struct objfile *objfile = dwarf2_per_objfile->objfile;
18860           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18861
18862           complaint (_("DW_AT_low_pc %s is zero "
18863                        "for DIE at %s [in module %s]"),
18864                      paddress (gdbarch, lowpc),
18865                      sect_offset_str (sect_off),
18866                      objfile_name (objfile));
18867         }
18868       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18869       else if (lowpc >= highpc)
18870         {
18871           struct objfile *objfile = dwarf2_per_objfile->objfile;
18872           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18873
18874           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18875                        "for DIE at %s [in module %s]"),
18876                      paddress (gdbarch, lowpc),
18877                      paddress (gdbarch, highpc),
18878                      sect_offset_str (sect_off),
18879                      objfile_name (objfile));
18880         }
18881       else
18882         has_pc_info = 1;
18883     }
18884
18885   return info_ptr;
18886 }
18887
18888 /* Find a cached partial DIE at OFFSET in CU.  */
18889
18890 struct partial_die_info *
18891 dwarf2_cu::find_partial_die (sect_offset sect_off)
18892 {
18893   struct partial_die_info *lookup_die = NULL;
18894   struct partial_die_info part_die (sect_off);
18895
18896   lookup_die = ((struct partial_die_info *)
18897                 htab_find_with_hash (partial_dies, &part_die,
18898                                      to_underlying (sect_off)));
18899
18900   return lookup_die;
18901 }
18902
18903 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18904    except in the case of .debug_types DIEs which do not reference
18905    outside their CU (they do however referencing other types via
18906    DW_FORM_ref_sig8).  */
18907
18908 static struct partial_die_info *
18909 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18910 {
18911   struct dwarf2_per_objfile *dwarf2_per_objfile
18912     = cu->per_cu->dwarf2_per_objfile;
18913   struct objfile *objfile = dwarf2_per_objfile->objfile;
18914   struct dwarf2_per_cu_data *per_cu = NULL;
18915   struct partial_die_info *pd = NULL;
18916
18917   if (offset_in_dwz == cu->per_cu->is_dwz
18918       && offset_in_cu_p (&cu->header, sect_off))
18919     {
18920       pd = cu->find_partial_die (sect_off);
18921       if (pd != NULL)
18922         return pd;
18923       /* We missed recording what we needed.
18924          Load all dies and try again.  */
18925       per_cu = cu->per_cu;
18926     }
18927   else
18928     {
18929       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18930       if (cu->per_cu->is_debug_types)
18931         {
18932           error (_("Dwarf Error: Type Unit at offset %s contains"
18933                    " external reference to offset %s [in module %s].\n"),
18934                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18935                  bfd_get_filename (objfile->obfd));
18936         }
18937       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18938                                                  dwarf2_per_objfile);
18939
18940       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18941         load_partial_comp_unit (per_cu);
18942
18943       per_cu->cu->last_used = 0;
18944       pd = per_cu->cu->find_partial_die (sect_off);
18945     }
18946
18947   /* If we didn't find it, and not all dies have been loaded,
18948      load them all and try again.  */
18949
18950   if (pd == NULL && per_cu->load_all_dies == 0)
18951     {
18952       per_cu->load_all_dies = 1;
18953
18954       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18955          THIS_CU->cu may already be in use.  So we can't just free it and
18956          replace its DIEs with the ones we read in.  Instead, we leave those
18957          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18958          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18959          set.  */
18960       load_partial_comp_unit (per_cu);
18961
18962       pd = per_cu->cu->find_partial_die (sect_off);
18963     }
18964
18965   if (pd == NULL)
18966     internal_error (__FILE__, __LINE__,
18967                     _("could not find partial DIE %s "
18968                       "in cache [from module %s]\n"),
18969                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18970   return pd;
18971 }
18972
18973 /* See if we can figure out if the class lives in a namespace.  We do
18974    this by looking for a member function; its demangled name will
18975    contain namespace info, if there is any.  */
18976
18977 static void
18978 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18979                                   struct dwarf2_cu *cu)
18980 {
18981   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18982      what template types look like, because the demangler
18983      frequently doesn't give the same name as the debug info.  We
18984      could fix this by only using the demangled name to get the
18985      prefix (but see comment in read_structure_type).  */
18986
18987   struct partial_die_info *real_pdi;
18988   struct partial_die_info *child_pdi;
18989
18990   /* If this DIE (this DIE's specification, if any) has a parent, then
18991      we should not do this.  We'll prepend the parent's fully qualified
18992      name when we create the partial symbol.  */
18993
18994   real_pdi = struct_pdi;
18995   while (real_pdi->has_specification)
18996     real_pdi = find_partial_die (real_pdi->spec_offset,
18997                                  real_pdi->spec_is_dwz, cu);
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                 = ((const char *)
19017                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
19018                                   actual_class_name,
19019                                   strlen (actual_class_name)));
19020               xfree (actual_class_name);
19021             }
19022           break;
19023         }
19024     }
19025 }
19026
19027 void
19028 partial_die_info::fixup (struct dwarf2_cu *cu)
19029 {
19030   /* Once we've fixed up a die, there's no point in doing so again.
19031      This also avoids a memory leak if we were to call
19032      guess_partial_die_structure_name multiple times.  */
19033   if (fixup_called)
19034     return;
19035
19036   /* If we found a reference attribute and the DIE has no name, try
19037      to find a name in the referred to DIE.  */
19038
19039   if (name == NULL && has_specification)
19040     {
19041       struct partial_die_info *spec_die;
19042
19043       spec_die = find_partial_die (spec_offset, spec_is_dwz, 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       && !VEC_empty (dwarf2_section_info_def,
19067                      cu->per_cu->dwarf2_per_objfile->types)
19068       && die_parent == NULL
19069       && has_children
19070       && (tag == DW_TAG_class_type
19071           || tag == DW_TAG_structure_type
19072           || tag == DW_TAG_union_type))
19073     guess_partial_die_structure_name (this, cu);
19074
19075   /* GCC might emit a nameless struct or union that has a linkage
19076      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19077   if (name == NULL
19078       && (tag == DW_TAG_class_type
19079           || tag == DW_TAG_interface_type
19080           || tag == DW_TAG_structure_type
19081           || tag == DW_TAG_union_type)
19082       && linkage_name != NULL)
19083     {
19084       char *demangled;
19085
19086       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
19087       if (demangled)
19088         {
19089           const char *base;
19090
19091           /* Strip any leading namespaces/classes, keep only the base name.
19092              DW_AT_name for named DIEs does not contain the prefixes.  */
19093           base = strrchr (demangled, ':');
19094           if (base && base > demangled && base[-1] == ':')
19095             base++;
19096           else
19097             base = demangled;
19098
19099           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19100           name
19101             = ((const char *)
19102                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19103                               base, strlen (base)));
19104           xfree (demangled);
19105         }
19106     }
19107
19108   fixup_called = 1;
19109 }
19110
19111 /* Read an attribute value described by an attribute form.  */
19112
19113 static const gdb_byte *
19114 read_attribute_value (const struct die_reader_specs *reader,
19115                       struct attribute *attr, unsigned form,
19116                       LONGEST implicit_const, const gdb_byte *info_ptr)
19117 {
19118   struct dwarf2_cu *cu = reader->cu;
19119   struct dwarf2_per_objfile *dwarf2_per_objfile
19120     = cu->per_cu->dwarf2_per_objfile;
19121   struct objfile *objfile = dwarf2_per_objfile->objfile;
19122   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19123   bfd *abfd = reader->abfd;
19124   struct comp_unit_head *cu_header = &cu->header;
19125   unsigned int bytes_read;
19126   struct dwarf_block *blk;
19127
19128   attr->form = (enum dwarf_form) form;
19129   switch (form)
19130     {
19131     case DW_FORM_ref_addr:
19132       if (cu->header.version == 2)
19133         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19134       else
19135         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19136                                        &cu->header, &bytes_read);
19137       info_ptr += bytes_read;
19138       break;
19139     case DW_FORM_GNU_ref_alt:
19140       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19141       info_ptr += bytes_read;
19142       break;
19143     case DW_FORM_addr:
19144       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19145       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19146       info_ptr += bytes_read;
19147       break;
19148     case DW_FORM_block2:
19149       blk = dwarf_alloc_block (cu);
19150       blk->size = read_2_bytes (abfd, info_ptr);
19151       info_ptr += 2;
19152       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19153       info_ptr += blk->size;
19154       DW_BLOCK (attr) = blk;
19155       break;
19156     case DW_FORM_block4:
19157       blk = dwarf_alloc_block (cu);
19158       blk->size = read_4_bytes (abfd, info_ptr);
19159       info_ptr += 4;
19160       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19161       info_ptr += blk->size;
19162       DW_BLOCK (attr) = blk;
19163       break;
19164     case DW_FORM_data2:
19165       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19166       info_ptr += 2;
19167       break;
19168     case DW_FORM_data4:
19169       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19170       info_ptr += 4;
19171       break;
19172     case DW_FORM_data8:
19173       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19174       info_ptr += 8;
19175       break;
19176     case DW_FORM_data16:
19177       blk = dwarf_alloc_block (cu);
19178       blk->size = 16;
19179       blk->data = read_n_bytes (abfd, info_ptr, 16);
19180       info_ptr += 16;
19181       DW_BLOCK (attr) = blk;
19182       break;
19183     case DW_FORM_sec_offset:
19184       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19185       info_ptr += bytes_read;
19186       break;
19187     case DW_FORM_string:
19188       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19189       DW_STRING_IS_CANONICAL (attr) = 0;
19190       info_ptr += bytes_read;
19191       break;
19192     case DW_FORM_strp:
19193       if (!cu->per_cu->is_dwz)
19194         {
19195           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19196                                                    abfd, info_ptr, cu_header,
19197                                                    &bytes_read);
19198           DW_STRING_IS_CANONICAL (attr) = 0;
19199           info_ptr += bytes_read;
19200           break;
19201         }
19202       /* FALLTHROUGH */
19203     case DW_FORM_line_strp:
19204       if (!cu->per_cu->is_dwz)
19205         {
19206           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19207                                                         abfd, info_ptr,
19208                                                         cu_header, &bytes_read);
19209           DW_STRING_IS_CANONICAL (attr) = 0;
19210           info_ptr += bytes_read;
19211           break;
19212         }
19213       /* FALLTHROUGH */
19214     case DW_FORM_GNU_strp_alt:
19215       {
19216         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19217         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19218                                           &bytes_read);
19219
19220         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19221                                                           dwz, str_offset);
19222         DW_STRING_IS_CANONICAL (attr) = 0;
19223         info_ptr += bytes_read;
19224       }
19225       break;
19226     case DW_FORM_exprloc:
19227     case DW_FORM_block:
19228       blk = dwarf_alloc_block (cu);
19229       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19230       info_ptr += bytes_read;
19231       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19232       info_ptr += blk->size;
19233       DW_BLOCK (attr) = blk;
19234       break;
19235     case DW_FORM_block1:
19236       blk = dwarf_alloc_block (cu);
19237       blk->size = read_1_byte (abfd, info_ptr);
19238       info_ptr += 1;
19239       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19240       info_ptr += blk->size;
19241       DW_BLOCK (attr) = blk;
19242       break;
19243     case DW_FORM_data1:
19244       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19245       info_ptr += 1;
19246       break;
19247     case DW_FORM_flag:
19248       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19249       info_ptr += 1;
19250       break;
19251     case DW_FORM_flag_present:
19252       DW_UNSND (attr) = 1;
19253       break;
19254     case DW_FORM_sdata:
19255       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19256       info_ptr += bytes_read;
19257       break;
19258     case DW_FORM_udata:
19259       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19260       info_ptr += bytes_read;
19261       break;
19262     case DW_FORM_ref1:
19263       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19264                          + read_1_byte (abfd, info_ptr));
19265       info_ptr += 1;
19266       break;
19267     case DW_FORM_ref2:
19268       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19269                          + read_2_bytes (abfd, info_ptr));
19270       info_ptr += 2;
19271       break;
19272     case DW_FORM_ref4:
19273       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19274                          + read_4_bytes (abfd, info_ptr));
19275       info_ptr += 4;
19276       break;
19277     case DW_FORM_ref8:
19278       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19279                          + read_8_bytes (abfd, info_ptr));
19280       info_ptr += 8;
19281       break;
19282     case DW_FORM_ref_sig8:
19283       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19284       info_ptr += 8;
19285       break;
19286     case DW_FORM_ref_udata:
19287       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19288                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19289       info_ptr += bytes_read;
19290       break;
19291     case DW_FORM_indirect:
19292       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19293       info_ptr += bytes_read;
19294       if (form == DW_FORM_implicit_const)
19295         {
19296           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19297           info_ptr += bytes_read;
19298         }
19299       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19300                                        info_ptr);
19301       break;
19302     case DW_FORM_implicit_const:
19303       DW_SND (attr) = implicit_const;
19304       break;
19305     case DW_FORM_addrx:
19306     case DW_FORM_GNU_addr_index:
19307       if (reader->dwo_file == NULL)
19308         {
19309           /* For now flag a hard error.
19310              Later we can turn this into a complaint.  */
19311           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19312                  dwarf_form_name (form),
19313                  bfd_get_filename (abfd));
19314         }
19315       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19316       info_ptr += bytes_read;
19317       break;
19318     case DW_FORM_strx:
19319     case DW_FORM_strx1:
19320     case DW_FORM_strx2:
19321     case DW_FORM_strx3:
19322     case DW_FORM_strx4:
19323     case DW_FORM_GNU_str_index:
19324       if (reader->dwo_file == NULL)
19325         {
19326           /* For now flag a hard error.
19327              Later we can turn this into a complaint if warranted.  */
19328           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19329                  dwarf_form_name (form),
19330                  bfd_get_filename (abfd));
19331         }
19332       {
19333         ULONGEST str_index;
19334         if (form == DW_FORM_strx1)
19335           {
19336             str_index = read_1_byte (abfd, info_ptr);
19337             info_ptr += 1;
19338           }
19339         else if (form == DW_FORM_strx2)
19340           {
19341             str_index = read_2_bytes (abfd, info_ptr);
19342             info_ptr += 2;
19343           }
19344         else if (form == DW_FORM_strx3)
19345           {
19346             str_index = read_3_bytes (abfd, info_ptr);
19347             info_ptr += 3;
19348           }
19349         else if (form == DW_FORM_strx4)
19350           {
19351             str_index = read_4_bytes (abfd, info_ptr);
19352             info_ptr += 4;
19353           }
19354         else
19355           {
19356             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19357             info_ptr += bytes_read;
19358           }
19359         DW_STRING (attr) = read_str_index (reader, str_index);
19360         DW_STRING_IS_CANONICAL (attr) = 0;
19361       }
19362       break;
19363     default:
19364       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19365              dwarf_form_name (form),
19366              bfd_get_filename (abfd));
19367     }
19368
19369   /* Super hack.  */
19370   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19371     attr->form = DW_FORM_GNU_ref_alt;
19372
19373   /* We have seen instances where the compiler tried to emit a byte
19374      size attribute of -1 which ended up being encoded as an unsigned
19375      0xffffffff.  Although 0xffffffff is technically a valid size value,
19376      an object of this size seems pretty unlikely so we can relatively
19377      safely treat these cases as if the size attribute was invalid and
19378      treat them as zero by default.  */
19379   if (attr->name == DW_AT_byte_size
19380       && form == DW_FORM_data4
19381       && DW_UNSND (attr) >= 0xffffffff)
19382     {
19383       complaint
19384         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19385          hex_string (DW_UNSND (attr)));
19386       DW_UNSND (attr) = 0;
19387     }
19388
19389   return info_ptr;
19390 }
19391
19392 /* Read an attribute described by an abbreviated attribute.  */
19393
19394 static const gdb_byte *
19395 read_attribute (const struct die_reader_specs *reader,
19396                 struct attribute *attr, struct attr_abbrev *abbrev,
19397                 const gdb_byte *info_ptr)
19398 {
19399   attr->name = abbrev->name;
19400   return read_attribute_value (reader, attr, abbrev->form,
19401                                abbrev->implicit_const, info_ptr);
19402 }
19403
19404 /* Read dwarf information from a buffer.  */
19405
19406 static unsigned int
19407 read_1_byte (bfd *abfd, const gdb_byte *buf)
19408 {
19409   return bfd_get_8 (abfd, buf);
19410 }
19411
19412 static int
19413 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19414 {
19415   return bfd_get_signed_8 (abfd, buf);
19416 }
19417
19418 static unsigned int
19419 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19420 {
19421   return bfd_get_16 (abfd, buf);
19422 }
19423
19424 static int
19425 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19426 {
19427   return bfd_get_signed_16 (abfd, buf);
19428 }
19429
19430 static unsigned int
19431 read_3_bytes (bfd *abfd, const gdb_byte *buf)
19432 {
19433   unsigned int result = 0;
19434   for (int i = 0; i < 3; ++i)
19435     {
19436       unsigned char byte = bfd_get_8 (abfd, buf);
19437       buf++;
19438       result |= ((unsigned int) byte << (i * 8));
19439     }
19440   return result;
19441 }
19442
19443 static unsigned int
19444 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19445 {
19446   return bfd_get_32 (abfd, buf);
19447 }
19448
19449 static int
19450 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19451 {
19452   return bfd_get_signed_32 (abfd, buf);
19453 }
19454
19455 static ULONGEST
19456 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19457 {
19458   return bfd_get_64 (abfd, buf);
19459 }
19460
19461 static CORE_ADDR
19462 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19463               unsigned int *bytes_read)
19464 {
19465   struct comp_unit_head *cu_header = &cu->header;
19466   CORE_ADDR retval = 0;
19467
19468   if (cu_header->signed_addr_p)
19469     {
19470       switch (cu_header->addr_size)
19471         {
19472         case 2:
19473           retval = bfd_get_signed_16 (abfd, buf);
19474           break;
19475         case 4:
19476           retval = bfd_get_signed_32 (abfd, buf);
19477           break;
19478         case 8:
19479           retval = bfd_get_signed_64 (abfd, buf);
19480           break;
19481         default:
19482           internal_error (__FILE__, __LINE__,
19483                           _("read_address: bad switch, signed [in module %s]"),
19484                           bfd_get_filename (abfd));
19485         }
19486     }
19487   else
19488     {
19489       switch (cu_header->addr_size)
19490         {
19491         case 2:
19492           retval = bfd_get_16 (abfd, buf);
19493           break;
19494         case 4:
19495           retval = bfd_get_32 (abfd, buf);
19496           break;
19497         case 8:
19498           retval = bfd_get_64 (abfd, buf);
19499           break;
19500         default:
19501           internal_error (__FILE__, __LINE__,
19502                           _("read_address: bad switch, "
19503                             "unsigned [in module %s]"),
19504                           bfd_get_filename (abfd));
19505         }
19506     }
19507
19508   *bytes_read = cu_header->addr_size;
19509   return retval;
19510 }
19511
19512 /* Read the initial length from a section.  The (draft) DWARF 3
19513    specification allows the initial length to take up either 4 bytes
19514    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19515    bytes describe the length and all offsets will be 8 bytes in length
19516    instead of 4.
19517
19518    An older, non-standard 64-bit format is also handled by this
19519    function.  The older format in question stores the initial length
19520    as an 8-byte quantity without an escape value.  Lengths greater
19521    than 2^32 aren't very common which means that the initial 4 bytes
19522    is almost always zero.  Since a length value of zero doesn't make
19523    sense for the 32-bit format, this initial zero can be considered to
19524    be an escape value which indicates the presence of the older 64-bit
19525    format.  As written, the code can't detect (old format) lengths
19526    greater than 4GB.  If it becomes necessary to handle lengths
19527    somewhat larger than 4GB, we could allow other small values (such
19528    as the non-sensical values of 1, 2, and 3) to also be used as
19529    escape values indicating the presence of the old format.
19530
19531    The value returned via bytes_read should be used to increment the
19532    relevant pointer after calling read_initial_length().
19533
19534    [ Note:  read_initial_length() and read_offset() are based on the
19535      document entitled "DWARF Debugging Information Format", revision
19536      3, draft 8, dated November 19, 2001.  This document was obtained
19537      from:
19538
19539         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19540
19541      This document is only a draft and is subject to change.  (So beware.)
19542
19543      Details regarding the older, non-standard 64-bit format were
19544      determined empirically by examining 64-bit ELF files produced by
19545      the SGI toolchain on an IRIX 6.5 machine.
19546
19547      - Kevin, July 16, 2002
19548    ] */
19549
19550 static LONGEST
19551 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19552 {
19553   LONGEST length = bfd_get_32 (abfd, buf);
19554
19555   if (length == 0xffffffff)
19556     {
19557       length = bfd_get_64 (abfd, buf + 4);
19558       *bytes_read = 12;
19559     }
19560   else if (length == 0)
19561     {
19562       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19563       length = bfd_get_64 (abfd, buf);
19564       *bytes_read = 8;
19565     }
19566   else
19567     {
19568       *bytes_read = 4;
19569     }
19570
19571   return length;
19572 }
19573
19574 /* Cover function for read_initial_length.
19575    Returns the length of the object at BUF, and stores the size of the
19576    initial length in *BYTES_READ and stores the size that offsets will be in
19577    *OFFSET_SIZE.
19578    If the initial length size is not equivalent to that specified in
19579    CU_HEADER then issue a complaint.
19580    This is useful when reading non-comp-unit headers.  */
19581
19582 static LONGEST
19583 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19584                                         const struct comp_unit_head *cu_header,
19585                                         unsigned int *bytes_read,
19586                                         unsigned int *offset_size)
19587 {
19588   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19589
19590   gdb_assert (cu_header->initial_length_size == 4
19591               || cu_header->initial_length_size == 8
19592               || cu_header->initial_length_size == 12);
19593
19594   if (cu_header->initial_length_size != *bytes_read)
19595     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19596
19597   *offset_size = (*bytes_read == 4) ? 4 : 8;
19598   return length;
19599 }
19600
19601 /* Read an offset from the data stream.  The size of the offset is
19602    given by cu_header->offset_size.  */
19603
19604 static LONGEST
19605 read_offset (bfd *abfd, const gdb_byte *buf,
19606              const struct comp_unit_head *cu_header,
19607              unsigned int *bytes_read)
19608 {
19609   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19610
19611   *bytes_read = cu_header->offset_size;
19612   return offset;
19613 }
19614
19615 /* Read an offset from the data stream.  */
19616
19617 static LONGEST
19618 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19619 {
19620   LONGEST retval = 0;
19621
19622   switch (offset_size)
19623     {
19624     case 4:
19625       retval = bfd_get_32 (abfd, buf);
19626       break;
19627     case 8:
19628       retval = bfd_get_64 (abfd, buf);
19629       break;
19630     default:
19631       internal_error (__FILE__, __LINE__,
19632                       _("read_offset_1: bad switch [in module %s]"),
19633                       bfd_get_filename (abfd));
19634     }
19635
19636   return retval;
19637 }
19638
19639 static const gdb_byte *
19640 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19641 {
19642   /* If the size of a host char is 8 bits, we can return a pointer
19643      to the buffer, otherwise we have to copy the data to a buffer
19644      allocated on the temporary obstack.  */
19645   gdb_assert (HOST_CHAR_BIT == 8);
19646   return buf;
19647 }
19648
19649 static const char *
19650 read_direct_string (bfd *abfd, const gdb_byte *buf,
19651                     unsigned int *bytes_read_ptr)
19652 {
19653   /* If the size of a host char is 8 bits, we can return a pointer
19654      to the string, otherwise we have to copy the string to a buffer
19655      allocated on the temporary obstack.  */
19656   gdb_assert (HOST_CHAR_BIT == 8);
19657   if (*buf == '\0')
19658     {
19659       *bytes_read_ptr = 1;
19660       return NULL;
19661     }
19662   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19663   return (const char *) buf;
19664 }
19665
19666 /* Return pointer to string at section SECT offset STR_OFFSET with error
19667    reporting strings FORM_NAME and SECT_NAME.  */
19668
19669 static const char *
19670 read_indirect_string_at_offset_from (struct objfile *objfile,
19671                                      bfd *abfd, LONGEST str_offset,
19672                                      struct dwarf2_section_info *sect,
19673                                      const char *form_name,
19674                                      const char *sect_name)
19675 {
19676   dwarf2_read_section (objfile, sect);
19677   if (sect->buffer == NULL)
19678     error (_("%s used without %s section [in module %s]"),
19679            form_name, sect_name, bfd_get_filename (abfd));
19680   if (str_offset >= sect->size)
19681     error (_("%s pointing outside of %s section [in module %s]"),
19682            form_name, sect_name, bfd_get_filename (abfd));
19683   gdb_assert (HOST_CHAR_BIT == 8);
19684   if (sect->buffer[str_offset] == '\0')
19685     return NULL;
19686   return (const char *) (sect->buffer + str_offset);
19687 }
19688
19689 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19690
19691 static const char *
19692 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19693                                 bfd *abfd, LONGEST str_offset)
19694 {
19695   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19696                                               abfd, str_offset,
19697                                               &dwarf2_per_objfile->str,
19698                                               "DW_FORM_strp", ".debug_str");
19699 }
19700
19701 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19702
19703 static const char *
19704 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19705                                      bfd *abfd, LONGEST str_offset)
19706 {
19707   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19708                                               abfd, str_offset,
19709                                               &dwarf2_per_objfile->line_str,
19710                                               "DW_FORM_line_strp",
19711                                               ".debug_line_str");
19712 }
19713
19714 /* Read a string at offset STR_OFFSET in the .debug_str section from
19715    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19716    the string consists of a single NUL byte, return NULL; otherwise
19717    return a pointer to the string.  */
19718
19719 static const char *
19720 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19721                                LONGEST str_offset)
19722 {
19723   dwarf2_read_section (objfile, &dwz->str);
19724
19725   if (dwz->str.buffer == NULL)
19726     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19727              "section [in module %s]"),
19728            bfd_get_filename (dwz->dwz_bfd));
19729   if (str_offset >= dwz->str.size)
19730     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19731              ".debug_str section [in module %s]"),
19732            bfd_get_filename (dwz->dwz_bfd));
19733   gdb_assert (HOST_CHAR_BIT == 8);
19734   if (dwz->str.buffer[str_offset] == '\0')
19735     return NULL;
19736   return (const char *) (dwz->str.buffer + str_offset);
19737 }
19738
19739 /* Return pointer to string at .debug_str offset as read from BUF.
19740    BUF is assumed to be in a compilation unit described by CU_HEADER.
19741    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19742
19743 static const char *
19744 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19745                       const gdb_byte *buf,
19746                       const struct comp_unit_head *cu_header,
19747                       unsigned int *bytes_read_ptr)
19748 {
19749   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19750
19751   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19752 }
19753
19754 /* Return pointer to string at .debug_line_str offset as read from BUF.
19755    BUF is assumed to be in a compilation unit described by CU_HEADER.
19756    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19757
19758 static const char *
19759 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19760                            bfd *abfd, const gdb_byte *buf,
19761                            const struct comp_unit_head *cu_header,
19762                            unsigned int *bytes_read_ptr)
19763 {
19764   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19765
19766   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19767                                               str_offset);
19768 }
19769
19770 ULONGEST
19771 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19772                           unsigned int *bytes_read_ptr)
19773 {
19774   ULONGEST result;
19775   unsigned int num_read;
19776   int shift;
19777   unsigned char byte;
19778
19779   result = 0;
19780   shift = 0;
19781   num_read = 0;
19782   while (1)
19783     {
19784       byte = bfd_get_8 (abfd, buf);
19785       buf++;
19786       num_read++;
19787       result |= ((ULONGEST) (byte & 127) << shift);
19788       if ((byte & 128) == 0)
19789         {
19790           break;
19791         }
19792       shift += 7;
19793     }
19794   *bytes_read_ptr = num_read;
19795   return result;
19796 }
19797
19798 static LONGEST
19799 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19800                     unsigned int *bytes_read_ptr)
19801 {
19802   ULONGEST result;
19803   int shift, num_read;
19804   unsigned char byte;
19805
19806   result = 0;
19807   shift = 0;
19808   num_read = 0;
19809   while (1)
19810     {
19811       byte = bfd_get_8 (abfd, buf);
19812       buf++;
19813       num_read++;
19814       result |= ((ULONGEST) (byte & 127) << shift);
19815       shift += 7;
19816       if ((byte & 128) == 0)
19817         {
19818           break;
19819         }
19820     }
19821   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19822     result |= -(((ULONGEST) 1) << shift);
19823   *bytes_read_ptr = num_read;
19824   return result;
19825 }
19826
19827 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19828    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19829    ADDR_SIZE is the size of addresses from the CU header.  */
19830
19831 static CORE_ADDR
19832 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19833                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19834 {
19835   struct objfile *objfile = dwarf2_per_objfile->objfile;
19836   bfd *abfd = objfile->obfd;
19837   const gdb_byte *info_ptr;
19838
19839   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19840   if (dwarf2_per_objfile->addr.buffer == NULL)
19841     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19842            objfile_name (objfile));
19843   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19844     error (_("DW_FORM_addr_index pointing outside of "
19845              ".debug_addr section [in module %s]"),
19846            objfile_name (objfile));
19847   info_ptr = (dwarf2_per_objfile->addr.buffer
19848               + addr_base + addr_index * addr_size);
19849   if (addr_size == 4)
19850     return bfd_get_32 (abfd, info_ptr);
19851   else
19852     return bfd_get_64 (abfd, info_ptr);
19853 }
19854
19855 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19856
19857 static CORE_ADDR
19858 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19859 {
19860   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19861                             cu->addr_base, cu->header.addr_size);
19862 }
19863
19864 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19865
19866 static CORE_ADDR
19867 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19868                              unsigned int *bytes_read)
19869 {
19870   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19871   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19872
19873   return read_addr_index (cu, addr_index);
19874 }
19875
19876 /* Data structure to pass results from dwarf2_read_addr_index_reader
19877    back to dwarf2_read_addr_index.  */
19878
19879 struct dwarf2_read_addr_index_data
19880 {
19881   ULONGEST addr_base;
19882   int addr_size;
19883 };
19884
19885 /* die_reader_func for dwarf2_read_addr_index.  */
19886
19887 static void
19888 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19889                                const gdb_byte *info_ptr,
19890                                struct die_info *comp_unit_die,
19891                                int has_children,
19892                                void *data)
19893 {
19894   struct dwarf2_cu *cu = reader->cu;
19895   struct dwarf2_read_addr_index_data *aidata =
19896     (struct dwarf2_read_addr_index_data *) data;
19897
19898   aidata->addr_base = cu->addr_base;
19899   aidata->addr_size = cu->header.addr_size;
19900 }
19901
19902 /* Given an index in .debug_addr, fetch the value.
19903    NOTE: This can be called during dwarf expression evaluation,
19904    long after the debug information has been read, and thus per_cu->cu
19905    may no longer exist.  */
19906
19907 CORE_ADDR
19908 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19909                         unsigned int addr_index)
19910 {
19911   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19912   struct dwarf2_cu *cu = per_cu->cu;
19913   ULONGEST addr_base;
19914   int addr_size;
19915
19916   /* We need addr_base and addr_size.
19917      If we don't have PER_CU->cu, we have to get it.
19918      Nasty, but the alternative is storing the needed info in PER_CU,
19919      which at this point doesn't seem justified: it's not clear how frequently
19920      it would get used and it would increase the size of every PER_CU.
19921      Entry points like dwarf2_per_cu_addr_size do a similar thing
19922      so we're not in uncharted territory here.
19923      Alas we need to be a bit more complicated as addr_base is contained
19924      in the DIE.
19925
19926      We don't need to read the entire CU(/TU).
19927      We just need the header and top level die.
19928
19929      IWBN to use the aging mechanism to let us lazily later discard the CU.
19930      For now we skip this optimization.  */
19931
19932   if (cu != NULL)
19933     {
19934       addr_base = cu->addr_base;
19935       addr_size = cu->header.addr_size;
19936     }
19937   else
19938     {
19939       struct dwarf2_read_addr_index_data aidata;
19940
19941       /* Note: We can't use init_cutu_and_read_dies_simple here,
19942          we need addr_base.  */
19943       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19944                                dwarf2_read_addr_index_reader, &aidata);
19945       addr_base = aidata.addr_base;
19946       addr_size = aidata.addr_size;
19947     }
19948
19949   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19950                             addr_size);
19951 }
19952
19953 /* Given a DW_FORM_GNU_str_index or DW_FORM_strx, fetch the string.
19954    This is only used by the Fission support.  */
19955
19956 static const char *
19957 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19958 {
19959   struct dwarf2_cu *cu = reader->cu;
19960   struct dwarf2_per_objfile *dwarf2_per_objfile
19961     = cu->per_cu->dwarf2_per_objfile;
19962   struct objfile *objfile = dwarf2_per_objfile->objfile;
19963   const char *objf_name = objfile_name (objfile);
19964   bfd *abfd = objfile->obfd;
19965   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19966   struct dwarf2_section_info *str_offsets_section =
19967     &reader->dwo_file->sections.str_offsets;
19968   const gdb_byte *info_ptr;
19969   ULONGEST str_offset;
19970   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
19971
19972   dwarf2_read_section (objfile, str_section);
19973   dwarf2_read_section (objfile, str_offsets_section);
19974   if (str_section->buffer == NULL)
19975     error (_("%s used without .debug_str.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_offsets_section->buffer == NULL)
19979     error (_("%s used without .debug_str_offsets.dwo section"
19980              " in CU at offset %s [in module %s]"),
19981            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19982   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19983     error (_("%s pointing outside of .debug_str_offsets.dwo"
19984              " section in CU at offset %s [in module %s]"),
19985            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19986   info_ptr = (str_offsets_section->buffer
19987               + str_index * cu->header.offset_size);
19988   if (cu->header.offset_size == 4)
19989     str_offset = bfd_get_32 (abfd, info_ptr);
19990   else
19991     str_offset = bfd_get_64 (abfd, info_ptr);
19992   if (str_offset >= str_section->size)
19993     error (_("Offset from %s pointing outside of"
19994              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19995            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19996   return (const char *) (str_section->buffer + str_offset);
19997 }
19998
19999 /* Return the length of an LEB128 number in BUF.  */
20000
20001 static int
20002 leb128_size (const gdb_byte *buf)
20003 {
20004   const gdb_byte *begin = buf;
20005   gdb_byte byte;
20006
20007   while (1)
20008     {
20009       byte = *buf++;
20010       if ((byte & 128) == 0)
20011         return buf - begin;
20012     }
20013 }
20014
20015 static void
20016 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
20017 {
20018   switch (lang)
20019     {
20020     case DW_LANG_C89:
20021     case DW_LANG_C99:
20022     case DW_LANG_C11:
20023     case DW_LANG_C:
20024     case DW_LANG_UPC:
20025       cu->language = language_c;
20026       break;
20027     case DW_LANG_Java:
20028     case DW_LANG_C_plus_plus:
20029     case DW_LANG_C_plus_plus_11:
20030     case DW_LANG_C_plus_plus_14:
20031       cu->language = language_cplus;
20032       break;
20033     case DW_LANG_D:
20034       cu->language = language_d;
20035       break;
20036     case DW_LANG_Fortran77:
20037     case DW_LANG_Fortran90:
20038     case DW_LANG_Fortran95:
20039     case DW_LANG_Fortran03:
20040     case DW_LANG_Fortran08:
20041       cu->language = language_fortran;
20042       break;
20043     case DW_LANG_Go:
20044       cu->language = language_go;
20045       break;
20046     case DW_LANG_Mips_Assembler:
20047       cu->language = language_asm;
20048       break;
20049     case DW_LANG_Ada83:
20050     case DW_LANG_Ada95:
20051       cu->language = language_ada;
20052       break;
20053     case DW_LANG_Modula2:
20054       cu->language = language_m2;
20055       break;
20056     case DW_LANG_Pascal83:
20057       cu->language = language_pascal;
20058       break;
20059     case DW_LANG_ObjC:
20060       cu->language = language_objc;
20061       break;
20062     case DW_LANG_Rust:
20063     case DW_LANG_Rust_old:
20064       cu->language = language_rust;
20065       break;
20066     case DW_LANG_Cobol74:
20067     case DW_LANG_Cobol85:
20068     default:
20069       cu->language = language_minimal;
20070       break;
20071     }
20072   cu->language_defn = language_def (cu->language);
20073 }
20074
20075 /* Return the named attribute or NULL if not there.  */
20076
20077 static struct attribute *
20078 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20079 {
20080   for (;;)
20081     {
20082       unsigned int i;
20083       struct attribute *spec = NULL;
20084
20085       for (i = 0; i < die->num_attrs; ++i)
20086         {
20087           if (die->attrs[i].name == name)
20088             return &die->attrs[i];
20089           if (die->attrs[i].name == DW_AT_specification
20090               || die->attrs[i].name == DW_AT_abstract_origin)
20091             spec = &die->attrs[i];
20092         }
20093
20094       if (!spec)
20095         break;
20096
20097       die = follow_die_ref (die, spec, &cu);
20098     }
20099
20100   return NULL;
20101 }
20102
20103 /* Return the named attribute or NULL if not there,
20104    but do not follow DW_AT_specification, etc.
20105    This is for use in contexts where we're reading .debug_types dies.
20106    Following DW_AT_specification, DW_AT_abstract_origin will take us
20107    back up the chain, and we want to go down.  */
20108
20109 static struct attribute *
20110 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20111 {
20112   unsigned int i;
20113
20114   for (i = 0; i < die->num_attrs; ++i)
20115     if (die->attrs[i].name == name)
20116       return &die->attrs[i];
20117
20118   return NULL;
20119 }
20120
20121 /* Return the string associated with a string-typed attribute, or NULL if it
20122    is either not found or is of an incorrect type.  */
20123
20124 static const char *
20125 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20126 {
20127   struct attribute *attr;
20128   const char *str = NULL;
20129
20130   attr = dwarf2_attr (die, name, cu);
20131
20132   if (attr != NULL)
20133     {
20134       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20135           || attr->form == DW_FORM_string
20136           || attr->form == DW_FORM_strx
20137           || attr->form == DW_FORM_GNU_str_index
20138           || attr->form == DW_FORM_GNU_strp_alt)
20139         str = DW_STRING (attr);
20140       else
20141         complaint (_("string type expected for attribute %s for "
20142                      "DIE at %s in module %s"),
20143                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20144                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20145     }
20146
20147   return str;
20148 }
20149
20150 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20151    and holds a non-zero value.  This function should only be used for
20152    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20153
20154 static int
20155 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20156 {
20157   struct attribute *attr = dwarf2_attr (die, name, cu);
20158
20159   return (attr && DW_UNSND (attr));
20160 }
20161
20162 static int
20163 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20164 {
20165   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20166      which value is non-zero.  However, we have to be careful with
20167      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20168      (via dwarf2_flag_true_p) follows this attribute.  So we may
20169      end up accidently finding a declaration attribute that belongs
20170      to a different DIE referenced by the specification attribute,
20171      even though the given DIE does not have a declaration attribute.  */
20172   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20173           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20174 }
20175
20176 /* Return the die giving the specification for DIE, if there is
20177    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20178    containing the return value on output.  If there is no
20179    specification, but there is an abstract origin, that is
20180    returned.  */
20181
20182 static struct die_info *
20183 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20184 {
20185   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20186                                              *spec_cu);
20187
20188   if (spec_attr == NULL)
20189     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20190
20191   if (spec_attr == NULL)
20192     return NULL;
20193   else
20194     return follow_die_ref (die, spec_attr, spec_cu);
20195 }
20196
20197 /* Stub for free_line_header to match void * callback types.  */
20198
20199 static void
20200 free_line_header_voidp (void *arg)
20201 {
20202   struct line_header *lh = (struct line_header *) arg;
20203
20204   delete lh;
20205 }
20206
20207 void
20208 line_header::add_include_dir (const char *include_dir)
20209 {
20210   if (dwarf_line_debug >= 2)
20211     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20212                         include_dirs.size () + 1, include_dir);
20213
20214   include_dirs.push_back (include_dir);
20215 }
20216
20217 void
20218 line_header::add_file_name (const char *name,
20219                             dir_index d_index,
20220                             unsigned int mod_time,
20221                             unsigned int length)
20222 {
20223   if (dwarf_line_debug >= 2)
20224     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20225                         (unsigned) file_names.size () + 1, name);
20226
20227   file_names.emplace_back (name, d_index, mod_time, length);
20228 }
20229
20230 /* A convenience function to find the proper .debug_line section for a CU.  */
20231
20232 static struct dwarf2_section_info *
20233 get_debug_line_section (struct dwarf2_cu *cu)
20234 {
20235   struct dwarf2_section_info *section;
20236   struct dwarf2_per_objfile *dwarf2_per_objfile
20237     = cu->per_cu->dwarf2_per_objfile;
20238
20239   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20240      DWO file.  */
20241   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20242     section = &cu->dwo_unit->dwo_file->sections.line;
20243   else if (cu->per_cu->is_dwz)
20244     {
20245       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20246
20247       section = &dwz->line;
20248     }
20249   else
20250     section = &dwarf2_per_objfile->line;
20251
20252   return section;
20253 }
20254
20255 /* Read directory or file name entry format, starting with byte of
20256    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20257    entries count and the entries themselves in the described entry
20258    format.  */
20259
20260 static void
20261 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20262                         bfd *abfd, const gdb_byte **bufp,
20263                         struct line_header *lh,
20264                         const struct comp_unit_head *cu_header,
20265                         void (*callback) (struct line_header *lh,
20266                                           const char *name,
20267                                           dir_index d_index,
20268                                           unsigned int mod_time,
20269                                           unsigned int length))
20270 {
20271   gdb_byte format_count, formati;
20272   ULONGEST data_count, datai;
20273   const gdb_byte *buf = *bufp;
20274   const gdb_byte *format_header_data;
20275   unsigned int bytes_read;
20276
20277   format_count = read_1_byte (abfd, buf);
20278   buf += 1;
20279   format_header_data = buf;
20280   for (formati = 0; formati < format_count; formati++)
20281     {
20282       read_unsigned_leb128 (abfd, buf, &bytes_read);
20283       buf += bytes_read;
20284       read_unsigned_leb128 (abfd, buf, &bytes_read);
20285       buf += bytes_read;
20286     }
20287
20288   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20289   buf += bytes_read;
20290   for (datai = 0; datai < data_count; datai++)
20291     {
20292       const gdb_byte *format = format_header_data;
20293       struct file_entry fe;
20294
20295       for (formati = 0; formati < format_count; formati++)
20296         {
20297           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20298           format += bytes_read;
20299
20300           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20301           format += bytes_read;
20302
20303           gdb::optional<const char *> string;
20304           gdb::optional<unsigned int> uint;
20305
20306           switch (form)
20307             {
20308             case DW_FORM_string:
20309               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20310               buf += bytes_read;
20311               break;
20312
20313             case DW_FORM_line_strp:
20314               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20315                                                          abfd, buf,
20316                                                          cu_header,
20317                                                          &bytes_read));
20318               buf += bytes_read;
20319               break;
20320
20321             case DW_FORM_data1:
20322               uint.emplace (read_1_byte (abfd, buf));
20323               buf += 1;
20324               break;
20325
20326             case DW_FORM_data2:
20327               uint.emplace (read_2_bytes (abfd, buf));
20328               buf += 2;
20329               break;
20330
20331             case DW_FORM_data4:
20332               uint.emplace (read_4_bytes (abfd, buf));
20333               buf += 4;
20334               break;
20335
20336             case DW_FORM_data8:
20337               uint.emplace (read_8_bytes (abfd, buf));
20338               buf += 8;
20339               break;
20340
20341             case DW_FORM_udata:
20342               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20343               buf += bytes_read;
20344               break;
20345
20346             case DW_FORM_block:
20347               /* It is valid only for DW_LNCT_timestamp which is ignored by
20348                  current GDB.  */
20349               break;
20350             }
20351
20352           switch (content_type)
20353             {
20354             case DW_LNCT_path:
20355               if (string.has_value ())
20356                 fe.name = *string;
20357               break;
20358             case DW_LNCT_directory_index:
20359               if (uint.has_value ())
20360                 fe.d_index = (dir_index) *uint;
20361               break;
20362             case DW_LNCT_timestamp:
20363               if (uint.has_value ())
20364                 fe.mod_time = *uint;
20365               break;
20366             case DW_LNCT_size:
20367               if (uint.has_value ())
20368                 fe.length = *uint;
20369               break;
20370             case DW_LNCT_MD5:
20371               break;
20372             default:
20373               complaint (_("Unknown format content type %s"),
20374                          pulongest (content_type));
20375             }
20376         }
20377
20378       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20379     }
20380
20381   *bufp = buf;
20382 }
20383
20384 /* Read the statement program header starting at OFFSET in
20385    .debug_line, or .debug_line.dwo.  Return a pointer
20386    to a struct line_header, allocated using xmalloc.
20387    Returns NULL if there is a problem reading the header, e.g., if it
20388    has a version we don't understand.
20389
20390    NOTE: the strings in the include directory and file name tables of
20391    the returned object point into the dwarf line section buffer,
20392    and must not be freed.  */
20393
20394 static line_header_up
20395 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20396 {
20397   const gdb_byte *line_ptr;
20398   unsigned int bytes_read, offset_size;
20399   int i;
20400   const char *cur_dir, *cur_file;
20401   struct dwarf2_section_info *section;
20402   bfd *abfd;
20403   struct dwarf2_per_objfile *dwarf2_per_objfile
20404     = cu->per_cu->dwarf2_per_objfile;
20405
20406   section = get_debug_line_section (cu);
20407   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20408   if (section->buffer == NULL)
20409     {
20410       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20411         complaint (_("missing .debug_line.dwo section"));
20412       else
20413         complaint (_("missing .debug_line section"));
20414       return 0;
20415     }
20416
20417   /* We can't do this until we know the section is non-empty.
20418      Only then do we know we have such a section.  */
20419   abfd = get_section_bfd_owner (section);
20420
20421   /* Make sure that at least there's room for the total_length field.
20422      That could be 12 bytes long, but we're just going to fudge that.  */
20423   if (to_underlying (sect_off) + 4 >= section->size)
20424     {
20425       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20426       return 0;
20427     }
20428
20429   line_header_up lh (new line_header ());
20430
20431   lh->sect_off = sect_off;
20432   lh->offset_in_dwz = cu->per_cu->is_dwz;
20433
20434   line_ptr = section->buffer + to_underlying (sect_off);
20435
20436   /* Read in the header.  */
20437   lh->total_length =
20438     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20439                                             &bytes_read, &offset_size);
20440   line_ptr += bytes_read;
20441   if (line_ptr + lh->total_length > (section->buffer + section->size))
20442     {
20443       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20444       return 0;
20445     }
20446   lh->statement_program_end = line_ptr + lh->total_length;
20447   lh->version = read_2_bytes (abfd, line_ptr);
20448   line_ptr += 2;
20449   if (lh->version > 5)
20450     {
20451       /* This is a version we don't understand.  The format could have
20452          changed in ways we don't handle properly so just punt.  */
20453       complaint (_("unsupported version in .debug_line section"));
20454       return NULL;
20455     }
20456   if (lh->version >= 5)
20457     {
20458       gdb_byte segment_selector_size;
20459
20460       /* Skip address size.  */
20461       read_1_byte (abfd, line_ptr);
20462       line_ptr += 1;
20463
20464       segment_selector_size = read_1_byte (abfd, line_ptr);
20465       line_ptr += 1;
20466       if (segment_selector_size != 0)
20467         {
20468           complaint (_("unsupported segment selector size %u "
20469                        "in .debug_line section"),
20470                      segment_selector_size);
20471           return NULL;
20472         }
20473     }
20474   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20475   line_ptr += offset_size;
20476   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20477   line_ptr += 1;
20478   if (lh->version >= 4)
20479     {
20480       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20481       line_ptr += 1;
20482     }
20483   else
20484     lh->maximum_ops_per_instruction = 1;
20485
20486   if (lh->maximum_ops_per_instruction == 0)
20487     {
20488       lh->maximum_ops_per_instruction = 1;
20489       complaint (_("invalid maximum_ops_per_instruction "
20490                    "in `.debug_line' section"));
20491     }
20492
20493   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20494   line_ptr += 1;
20495   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20496   line_ptr += 1;
20497   lh->line_range = read_1_byte (abfd, line_ptr);
20498   line_ptr += 1;
20499   lh->opcode_base = read_1_byte (abfd, line_ptr);
20500   line_ptr += 1;
20501   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20502
20503   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20504   for (i = 1; i < lh->opcode_base; ++i)
20505     {
20506       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20507       line_ptr += 1;
20508     }
20509
20510   if (lh->version >= 5)
20511     {
20512       /* Read directory table.  */
20513       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20514                               &cu->header,
20515                               [] (struct line_header *header, const char *name,
20516                                   dir_index d_index, unsigned int mod_time,
20517                                   unsigned int length)
20518         {
20519           header->add_include_dir (name);
20520         });
20521
20522       /* Read file name table.  */
20523       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20524                               &cu->header,
20525                               [] (struct line_header *header, const char *name,
20526                                   dir_index d_index, unsigned int mod_time,
20527                                   unsigned int length)
20528         {
20529           header->add_file_name (name, d_index, mod_time, length);
20530         });
20531     }
20532   else
20533     {
20534       /* Read directory table.  */
20535       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20536         {
20537           line_ptr += bytes_read;
20538           lh->add_include_dir (cur_dir);
20539         }
20540       line_ptr += bytes_read;
20541
20542       /* Read file name table.  */
20543       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20544         {
20545           unsigned int mod_time, length;
20546           dir_index d_index;
20547
20548           line_ptr += bytes_read;
20549           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20550           line_ptr += bytes_read;
20551           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20552           line_ptr += bytes_read;
20553           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20554           line_ptr += bytes_read;
20555
20556           lh->add_file_name (cur_file, d_index, mod_time, length);
20557         }
20558       line_ptr += bytes_read;
20559     }
20560   lh->statement_program_start = line_ptr;
20561
20562   if (line_ptr > (section->buffer + section->size))
20563     complaint (_("line number info header doesn't "
20564                  "fit in `.debug_line' section"));
20565
20566   return lh;
20567 }
20568
20569 /* Subroutine of dwarf_decode_lines to simplify it.
20570    Return the file name of the psymtab for included file FILE_INDEX
20571    in line header LH of PST.
20572    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20573    If space for the result is malloc'd, *NAME_HOLDER will be set.
20574    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20575
20576 static const char *
20577 psymtab_include_file_name (const struct line_header *lh, int file_index,
20578                            const struct partial_symtab *pst,
20579                            const char *comp_dir,
20580                            gdb::unique_xmalloc_ptr<char> *name_holder)
20581 {
20582   const file_entry &fe = lh->file_names[file_index];
20583   const char *include_name = fe.name;
20584   const char *include_name_to_compare = include_name;
20585   const char *pst_filename;
20586   int file_is_pst;
20587
20588   const char *dir_name = fe.include_dir (lh);
20589
20590   gdb::unique_xmalloc_ptr<char> hold_compare;
20591   if (!IS_ABSOLUTE_PATH (include_name)
20592       && (dir_name != NULL || comp_dir != NULL))
20593     {
20594       /* Avoid creating a duplicate psymtab for PST.
20595          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20596          Before we do the comparison, however, we need to account
20597          for DIR_NAME and COMP_DIR.
20598          First prepend dir_name (if non-NULL).  If we still don't
20599          have an absolute path prepend comp_dir (if non-NULL).
20600          However, the directory we record in the include-file's
20601          psymtab does not contain COMP_DIR (to match the
20602          corresponding symtab(s)).
20603
20604          Example:
20605
20606          bash$ cd /tmp
20607          bash$ gcc -g ./hello.c
20608          include_name = "hello.c"
20609          dir_name = "."
20610          DW_AT_comp_dir = comp_dir = "/tmp"
20611          DW_AT_name = "./hello.c"
20612
20613       */
20614
20615       if (dir_name != NULL)
20616         {
20617           name_holder->reset (concat (dir_name, SLASH_STRING,
20618                                       include_name, (char *) NULL));
20619           include_name = name_holder->get ();
20620           include_name_to_compare = include_name;
20621         }
20622       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20623         {
20624           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20625                                       include_name, (char *) NULL));
20626           include_name_to_compare = hold_compare.get ();
20627         }
20628     }
20629
20630   pst_filename = pst->filename;
20631   gdb::unique_xmalloc_ptr<char> copied_name;
20632   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20633     {
20634       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20635                                  pst_filename, (char *) NULL));
20636       pst_filename = copied_name.get ();
20637     }
20638
20639   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20640
20641   if (file_is_pst)
20642     return NULL;
20643   return include_name;
20644 }
20645
20646 /* State machine to track the state of the line number program.  */
20647
20648 class lnp_state_machine
20649 {
20650 public:
20651   /* Initialize a machine state for the start of a line number
20652      program.  */
20653   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20654                      bool record_lines_p);
20655
20656   file_entry *current_file ()
20657   {
20658     /* lh->file_names is 0-based, but the file name numbers in the
20659        statement program are 1-based.  */
20660     return m_line_header->file_name_at (m_file);
20661   }
20662
20663   /* Record the line in the state machine.  END_SEQUENCE is true if
20664      we're processing the end of a sequence.  */
20665   void record_line (bool end_sequence);
20666
20667   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20668      nop-out rest of the lines in this sequence.  */
20669   void check_line_address (struct dwarf2_cu *cu,
20670                            const gdb_byte *line_ptr,
20671                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20672
20673   void handle_set_discriminator (unsigned int discriminator)
20674   {
20675     m_discriminator = discriminator;
20676     m_line_has_non_zero_discriminator |= discriminator != 0;
20677   }
20678
20679   /* Handle DW_LNE_set_address.  */
20680   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20681   {
20682     m_op_index = 0;
20683     address += baseaddr;
20684     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20685   }
20686
20687   /* Handle DW_LNS_advance_pc.  */
20688   void handle_advance_pc (CORE_ADDR adjust);
20689
20690   /* Handle a special opcode.  */
20691   void handle_special_opcode (unsigned char op_code);
20692
20693   /* Handle DW_LNS_advance_line.  */
20694   void handle_advance_line (int line_delta)
20695   {
20696     advance_line (line_delta);
20697   }
20698
20699   /* Handle DW_LNS_set_file.  */
20700   void handle_set_file (file_name_index file);
20701
20702   /* Handle DW_LNS_negate_stmt.  */
20703   void handle_negate_stmt ()
20704   {
20705     m_is_stmt = !m_is_stmt;
20706   }
20707
20708   /* Handle DW_LNS_const_add_pc.  */
20709   void handle_const_add_pc ();
20710
20711   /* Handle DW_LNS_fixed_advance_pc.  */
20712   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20713   {
20714     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20715     m_op_index = 0;
20716   }
20717
20718   /* Handle DW_LNS_copy.  */
20719   void handle_copy ()
20720   {
20721     record_line (false);
20722     m_discriminator = 0;
20723   }
20724
20725   /* Handle DW_LNE_end_sequence.  */
20726   void handle_end_sequence ()
20727   {
20728     m_currently_recording_lines = true;
20729   }
20730
20731 private:
20732   /* Advance the line by LINE_DELTA.  */
20733   void advance_line (int line_delta)
20734   {
20735     m_line += line_delta;
20736
20737     if (line_delta != 0)
20738       m_line_has_non_zero_discriminator = m_discriminator != 0;
20739   }
20740
20741   struct dwarf2_cu *m_cu;
20742
20743   gdbarch *m_gdbarch;
20744
20745   /* True if we're recording lines.
20746      Otherwise we're building partial symtabs and are just interested in
20747      finding include files mentioned by the line number program.  */
20748   bool m_record_lines_p;
20749
20750   /* The line number header.  */
20751   line_header *m_line_header;
20752
20753   /* These are part of the standard DWARF line number state machine,
20754      and initialized according to the DWARF spec.  */
20755
20756   unsigned char m_op_index = 0;
20757   /* The line table index (1-based) of the current file.  */
20758   file_name_index m_file = (file_name_index) 1;
20759   unsigned int m_line = 1;
20760
20761   /* These are initialized in the constructor.  */
20762
20763   CORE_ADDR m_address;
20764   bool m_is_stmt;
20765   unsigned int m_discriminator;
20766
20767   /* Additional bits of state we need to track.  */
20768
20769   /* The last file that we called dwarf2_start_subfile for.
20770      This is only used for TLLs.  */
20771   unsigned int m_last_file = 0;
20772   /* The last file a line number was recorded for.  */
20773   struct subfile *m_last_subfile = NULL;
20774
20775   /* When true, record the lines we decode.  */
20776   bool m_currently_recording_lines = false;
20777
20778   /* The last line number that was recorded, used to coalesce
20779      consecutive entries for the same line.  This can happen, for
20780      example, when discriminators are present.  PR 17276.  */
20781   unsigned int m_last_line = 0;
20782   bool m_line_has_non_zero_discriminator = false;
20783 };
20784
20785 void
20786 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20787 {
20788   CORE_ADDR addr_adj = (((m_op_index + adjust)
20789                          / m_line_header->maximum_ops_per_instruction)
20790                         * m_line_header->minimum_instruction_length);
20791   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20792   m_op_index = ((m_op_index + adjust)
20793                 % m_line_header->maximum_ops_per_instruction);
20794 }
20795
20796 void
20797 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20798 {
20799   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20800   CORE_ADDR addr_adj = (((m_op_index
20801                           + (adj_opcode / m_line_header->line_range))
20802                          / m_line_header->maximum_ops_per_instruction)
20803                         * m_line_header->minimum_instruction_length);
20804   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20805   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20806                 % m_line_header->maximum_ops_per_instruction);
20807
20808   int line_delta = (m_line_header->line_base
20809                     + (adj_opcode % m_line_header->line_range));
20810   advance_line (line_delta);
20811   record_line (false);
20812   m_discriminator = 0;
20813 }
20814
20815 void
20816 lnp_state_machine::handle_set_file (file_name_index file)
20817 {
20818   m_file = file;
20819
20820   const file_entry *fe = current_file ();
20821   if (fe == NULL)
20822     dwarf2_debug_line_missing_file_complaint ();
20823   else if (m_record_lines_p)
20824     {
20825       const char *dir = fe->include_dir (m_line_header);
20826
20827       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20828       m_line_has_non_zero_discriminator = m_discriminator != 0;
20829       dwarf2_start_subfile (m_cu, fe->name, dir);
20830     }
20831 }
20832
20833 void
20834 lnp_state_machine::handle_const_add_pc ()
20835 {
20836   CORE_ADDR adjust
20837     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20838
20839   CORE_ADDR addr_adj
20840     = (((m_op_index + adjust)
20841         / m_line_header->maximum_ops_per_instruction)
20842        * m_line_header->minimum_instruction_length);
20843
20844   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20845   m_op_index = ((m_op_index + adjust)
20846                 % m_line_header->maximum_ops_per_instruction);
20847 }
20848
20849 /* Return non-zero if we should add LINE to the line number table.
20850    LINE is the line to add, LAST_LINE is the last line that was added,
20851    LAST_SUBFILE is the subfile for LAST_LINE.
20852    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20853    had a non-zero discriminator.
20854
20855    We have to be careful in the presence of discriminators.
20856    E.g., for this line:
20857
20858      for (i = 0; i < 100000; i++);
20859
20860    clang can emit four line number entries for that one line,
20861    each with a different discriminator.
20862    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20863
20864    However, we want gdb to coalesce all four entries into one.
20865    Otherwise the user could stepi into the middle of the line and
20866    gdb would get confused about whether the pc really was in the
20867    middle of the line.
20868
20869    Things are further complicated by the fact that two consecutive
20870    line number entries for the same line is a heuristic used by gcc
20871    to denote the end of the prologue.  So we can't just discard duplicate
20872    entries, we have to be selective about it.  The heuristic we use is
20873    that we only collapse consecutive entries for the same line if at least
20874    one of those entries has a non-zero discriminator.  PR 17276.
20875
20876    Note: Addresses in the line number state machine can never go backwards
20877    within one sequence, thus this coalescing is ok.  */
20878
20879 static int
20880 dwarf_record_line_p (struct dwarf2_cu *cu,
20881                      unsigned int line, unsigned int last_line,
20882                      int line_has_non_zero_discriminator,
20883                      struct subfile *last_subfile)
20884 {
20885   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20886     return 1;
20887   if (line != last_line)
20888     return 1;
20889   /* Same line for the same file that we've seen already.
20890      As a last check, for pr 17276, only record the line if the line
20891      has never had a non-zero discriminator.  */
20892   if (!line_has_non_zero_discriminator)
20893     return 1;
20894   return 0;
20895 }
20896
20897 /* Use the CU's builder to record line number LINE beginning at
20898    address ADDRESS in the line table of subfile SUBFILE.  */
20899
20900 static void
20901 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20902                      unsigned int line, CORE_ADDR address,
20903                      struct dwarf2_cu *cu)
20904 {
20905   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20906
20907   if (dwarf_line_debug)
20908     {
20909       fprintf_unfiltered (gdb_stdlog,
20910                           "Recording line %u, file %s, address %s\n",
20911                           line, lbasename (subfile->name),
20912                           paddress (gdbarch, address));
20913     }
20914
20915   if (cu != nullptr)
20916     cu->get_builder ()->record_line (subfile, line, addr);
20917 }
20918
20919 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20920    Mark the end of a set of line number records.
20921    The arguments are the same as for dwarf_record_line_1.
20922    If SUBFILE is NULL the request is ignored.  */
20923
20924 static void
20925 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20926                    CORE_ADDR address, struct dwarf2_cu *cu)
20927 {
20928   if (subfile == NULL)
20929     return;
20930
20931   if (dwarf_line_debug)
20932     {
20933       fprintf_unfiltered (gdb_stdlog,
20934                           "Finishing current line, file %s, address %s\n",
20935                           lbasename (subfile->name),
20936                           paddress (gdbarch, address));
20937     }
20938
20939   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20940 }
20941
20942 void
20943 lnp_state_machine::record_line (bool end_sequence)
20944 {
20945   if (dwarf_line_debug)
20946     {
20947       fprintf_unfiltered (gdb_stdlog,
20948                           "Processing actual line %u: file %u,"
20949                           " address %s, is_stmt %u, discrim %u\n",
20950                           m_line, to_underlying (m_file),
20951                           paddress (m_gdbarch, m_address),
20952                           m_is_stmt, m_discriminator);
20953     }
20954
20955   file_entry *fe = current_file ();
20956
20957   if (fe == NULL)
20958     dwarf2_debug_line_missing_file_complaint ();
20959   /* For now we ignore lines not starting on an instruction boundary.
20960      But not when processing end_sequence for compatibility with the
20961      previous version of the code.  */
20962   else if (m_op_index == 0 || end_sequence)
20963     {
20964       fe->included_p = 1;
20965       if (m_record_lines_p && (producer_is_codewarrior (m_cu) || m_is_stmt))
20966         {
20967           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
20968               || end_sequence)
20969             {
20970               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20971                                  m_currently_recording_lines ? m_cu : nullptr);
20972             }
20973
20974           if (!end_sequence)
20975             {
20976               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20977                                        m_line_has_non_zero_discriminator,
20978                                        m_last_subfile))
20979                 {
20980                   buildsym_compunit *builder = m_cu->get_builder ();
20981                   dwarf_record_line_1 (m_gdbarch,
20982                                        builder->get_current_subfile (),
20983                                        m_line, m_address,
20984                                        m_currently_recording_lines ? m_cu : nullptr);
20985                 }
20986               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20987               m_last_line = m_line;
20988             }
20989         }
20990     }
20991 }
20992
20993 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20994                                       line_header *lh, bool record_lines_p)
20995 {
20996   m_cu = cu;
20997   m_gdbarch = arch;
20998   m_record_lines_p = record_lines_p;
20999   m_line_header = lh;
21000
21001   m_currently_recording_lines = true;
21002
21003   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21004      was a line entry for it so that the backend has a chance to adjust it
21005      and also record it in case it needs it.  This is currently used by MIPS
21006      code, cf. `mips_adjust_dwarf2_line'.  */
21007   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21008   m_is_stmt = lh->default_is_stmt;
21009   m_discriminator = 0;
21010 }
21011
21012 void
21013 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21014                                        const gdb_byte *line_ptr,
21015                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
21016 {
21017   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
21018      the pc range of the CU.  However, we restrict the test to only ADDRESS
21019      values of zero to preserve GDB's previous behaviour which is to handle
21020      the specific case of a function being GC'd by the linker.  */
21021
21022   if (address == 0 && address < unrelocated_lowpc)
21023     {
21024       /* This line table is for a function which has been
21025          GCd by the linker.  Ignore it.  PR gdb/12528 */
21026
21027       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21028       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21029
21030       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21031                  line_offset, objfile_name (objfile));
21032       m_currently_recording_lines = false;
21033       /* Note: m_currently_recording_lines is left as false until we see
21034          DW_LNE_end_sequence.  */
21035     }
21036 }
21037
21038 /* Subroutine of dwarf_decode_lines to simplify it.
21039    Process the line number information in LH.
21040    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21041    program in order to set included_p for every referenced header.  */
21042
21043 static void
21044 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21045                       const int decode_for_pst_p, CORE_ADDR lowpc)
21046 {
21047   const gdb_byte *line_ptr, *extended_end;
21048   const gdb_byte *line_end;
21049   unsigned int bytes_read, extended_len;
21050   unsigned char op_code, extended_op;
21051   CORE_ADDR baseaddr;
21052   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21053   bfd *abfd = objfile->obfd;
21054   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21055   /* True if we're recording line info (as opposed to building partial
21056      symtabs and just interested in finding include files mentioned by
21057      the line number program).  */
21058   bool record_lines_p = !decode_for_pst_p;
21059
21060   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21061
21062   line_ptr = lh->statement_program_start;
21063   line_end = lh->statement_program_end;
21064
21065   /* Read the statement sequences until there's nothing left.  */
21066   while (line_ptr < line_end)
21067     {
21068       /* The DWARF line number program state machine.  Reset the state
21069          machine at the start of each sequence.  */
21070       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21071       bool end_sequence = false;
21072
21073       if (record_lines_p)
21074         {
21075           /* Start a subfile for the current file of the state
21076              machine.  */
21077           const file_entry *fe = state_machine.current_file ();
21078
21079           if (fe != NULL)
21080             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21081         }
21082
21083       /* Decode the table.  */
21084       while (line_ptr < line_end && !end_sequence)
21085         {
21086           op_code = read_1_byte (abfd, line_ptr);
21087           line_ptr += 1;
21088
21089           if (op_code >= lh->opcode_base)
21090             {
21091               /* Special opcode.  */
21092               state_machine.handle_special_opcode (op_code);
21093             }
21094           else switch (op_code)
21095             {
21096             case DW_LNS_extended_op:
21097               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21098                                                    &bytes_read);
21099               line_ptr += bytes_read;
21100               extended_end = line_ptr + extended_len;
21101               extended_op = read_1_byte (abfd, line_ptr);
21102               line_ptr += 1;
21103               switch (extended_op)
21104                 {
21105                 case DW_LNE_end_sequence:
21106                   state_machine.handle_end_sequence ();
21107                   end_sequence = true;
21108                   break;
21109                 case DW_LNE_set_address:
21110                   {
21111                     CORE_ADDR address
21112                       = read_address (abfd, line_ptr, cu, &bytes_read);
21113                     line_ptr += bytes_read;
21114
21115                     state_machine.check_line_address (cu, line_ptr,
21116                                                       lowpc - baseaddr, address);
21117                     state_machine.handle_set_address (baseaddr, address);
21118                   }
21119                   break;
21120                 case DW_LNE_define_file:
21121                   {
21122                     const char *cur_file;
21123                     unsigned int mod_time, length;
21124                     dir_index dindex;
21125
21126                     cur_file = read_direct_string (abfd, line_ptr,
21127                                                    &bytes_read);
21128                     line_ptr += bytes_read;
21129                     dindex = (dir_index)
21130                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21131                     line_ptr += bytes_read;
21132                     mod_time =
21133                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21134                     line_ptr += bytes_read;
21135                     length =
21136                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21137                     line_ptr += bytes_read;
21138                     lh->add_file_name (cur_file, dindex, mod_time, length);
21139                   }
21140                   break;
21141                 case DW_LNE_set_discriminator:
21142                   {
21143                     /* The discriminator is not interesting to the
21144                        debugger; just ignore it.  We still need to
21145                        check its value though:
21146                        if there are consecutive entries for the same
21147                        (non-prologue) line we want to coalesce them.
21148                        PR 17276.  */
21149                     unsigned int discr
21150                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21151                     line_ptr += bytes_read;
21152
21153                     state_machine.handle_set_discriminator (discr);
21154                   }
21155                   break;
21156                 default:
21157                   complaint (_("mangled .debug_line section"));
21158                   return;
21159                 }
21160               /* Make sure that we parsed the extended op correctly.  If e.g.
21161                  we expected a different address size than the producer used,
21162                  we may have read the wrong number of bytes.  */
21163               if (line_ptr != extended_end)
21164                 {
21165                   complaint (_("mangled .debug_line section"));
21166                   return;
21167                 }
21168               break;
21169             case DW_LNS_copy:
21170               state_machine.handle_copy ();
21171               break;
21172             case DW_LNS_advance_pc:
21173               {
21174                 CORE_ADDR adjust
21175                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21176                 line_ptr += bytes_read;
21177
21178                 state_machine.handle_advance_pc (adjust);
21179               }
21180               break;
21181             case DW_LNS_advance_line:
21182               {
21183                 int line_delta
21184                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21185                 line_ptr += bytes_read;
21186
21187                 state_machine.handle_advance_line (line_delta);
21188               }
21189               break;
21190             case DW_LNS_set_file:
21191               {
21192                 file_name_index file
21193                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21194                                                             &bytes_read);
21195                 line_ptr += bytes_read;
21196
21197                 state_machine.handle_set_file (file);
21198               }
21199               break;
21200             case DW_LNS_set_column:
21201               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21202               line_ptr += bytes_read;
21203               break;
21204             case DW_LNS_negate_stmt:
21205               state_machine.handle_negate_stmt ();
21206               break;
21207             case DW_LNS_set_basic_block:
21208               break;
21209             /* Add to the address register of the state machine the
21210                address increment value corresponding to special opcode
21211                255.  I.e., this value is scaled by the minimum
21212                instruction length since special opcode 255 would have
21213                scaled the increment.  */
21214             case DW_LNS_const_add_pc:
21215               state_machine.handle_const_add_pc ();
21216               break;
21217             case DW_LNS_fixed_advance_pc:
21218               {
21219                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21220                 line_ptr += 2;
21221
21222                 state_machine.handle_fixed_advance_pc (addr_adj);
21223               }
21224               break;
21225             default:
21226               {
21227                 /* Unknown standard opcode, ignore it.  */
21228                 int i;
21229
21230                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21231                   {
21232                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21233                     line_ptr += bytes_read;
21234                   }
21235               }
21236             }
21237         }
21238
21239       if (!end_sequence)
21240         dwarf2_debug_line_missing_end_sequence_complaint ();
21241
21242       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21243          in which case we still finish recording the last line).  */
21244       state_machine.record_line (true);
21245     }
21246 }
21247
21248 /* Decode the Line Number Program (LNP) for the given line_header
21249    structure and CU.  The actual information extracted and the type
21250    of structures created from the LNP depends on the value of PST.
21251
21252    1. If PST is NULL, then this procedure uses the data from the program
21253       to create all necessary symbol tables, and their linetables.
21254
21255    2. If PST is not NULL, this procedure reads the program to determine
21256       the list of files included by the unit represented by PST, and
21257       builds all the associated partial symbol tables.
21258
21259    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21260    It is used for relative paths in the line table.
21261    NOTE: When processing partial symtabs (pst != NULL),
21262    comp_dir == pst->dirname.
21263
21264    NOTE: It is important that psymtabs have the same file name (via strcmp)
21265    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21266    symtab we don't use it in the name of the psymtabs we create.
21267    E.g. expand_line_sal requires this when finding psymtabs to expand.
21268    A good testcase for this is mb-inline.exp.
21269
21270    LOWPC is the lowest address in CU (or 0 if not known).
21271
21272    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21273    for its PC<->lines mapping information.  Otherwise only the filename
21274    table is read in.  */
21275
21276 static void
21277 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21278                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21279                     CORE_ADDR lowpc, int decode_mapping)
21280 {
21281   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21282   const int decode_for_pst_p = (pst != NULL);
21283
21284   if (decode_mapping)
21285     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21286
21287   if (decode_for_pst_p)
21288     {
21289       int file_index;
21290
21291       /* Now that we're done scanning the Line Header Program, we can
21292          create the psymtab of each included file.  */
21293       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21294         if (lh->file_names[file_index].included_p == 1)
21295           {
21296             gdb::unique_xmalloc_ptr<char> name_holder;
21297             const char *include_name =
21298               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21299                                          &name_holder);
21300             if (include_name != NULL)
21301               dwarf2_create_include_psymtab (include_name, pst, objfile);
21302           }
21303     }
21304   else
21305     {
21306       /* Make sure a symtab is created for every file, even files
21307          which contain only variables (i.e. no code with associated
21308          line numbers).  */
21309       buildsym_compunit *builder = cu->get_builder ();
21310       struct compunit_symtab *cust = builder->get_compunit_symtab ();
21311       int i;
21312
21313       for (i = 0; i < lh->file_names.size (); i++)
21314         {
21315           file_entry &fe = lh->file_names[i];
21316
21317           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21318
21319           if (builder->get_current_subfile ()->symtab == NULL)
21320             {
21321               builder->get_current_subfile ()->symtab
21322                 = allocate_symtab (cust,
21323                                    builder->get_current_subfile ()->name);
21324             }
21325           fe.symtab = builder->get_current_subfile ()->symtab;
21326         }
21327     }
21328 }
21329
21330 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21331    DIRNAME the name of the source directory which contains FILENAME
21332    or NULL if not known.
21333    This routine tries to keep line numbers from identical absolute and
21334    relative file names in a common subfile.
21335
21336    Using the `list' example from the GDB testsuite, which resides in
21337    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21338    of /srcdir/list0.c yields the following debugging information for list0.c:
21339
21340    DW_AT_name:          /srcdir/list0.c
21341    DW_AT_comp_dir:      /compdir
21342    files.files[0].name: list0.h
21343    files.files[0].dir:  /srcdir
21344    files.files[1].name: list0.c
21345    files.files[1].dir:  /srcdir
21346
21347    The line number information for list0.c has to end up in a single
21348    subfile, so that `break /srcdir/list0.c:1' works as expected.
21349    start_subfile will ensure that this happens provided that we pass the
21350    concatenation of files.files[1].dir and files.files[1].name as the
21351    subfile's name.  */
21352
21353 static void
21354 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21355                       const char *dirname)
21356 {
21357   char *copy = NULL;
21358
21359   /* In order not to lose the line information directory,
21360      we concatenate it to the filename when it makes sense.
21361      Note that the Dwarf3 standard says (speaking of filenames in line
21362      information): ``The directory index is ignored for file names
21363      that represent full path names''.  Thus ignoring dirname in the
21364      `else' branch below isn't an issue.  */
21365
21366   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21367     {
21368       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21369       filename = copy;
21370     }
21371
21372   cu->get_builder ()->start_subfile (filename);
21373
21374   if (copy != NULL)
21375     xfree (copy);
21376 }
21377
21378 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21379    buildsym_compunit constructor.  */
21380
21381 struct compunit_symtab *
21382 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
21383                          CORE_ADDR low_pc)
21384 {
21385   gdb_assert (m_builder == nullptr);
21386
21387   m_builder.reset (new struct buildsym_compunit
21388                    (per_cu->dwarf2_per_objfile->objfile,
21389                     name, comp_dir, language, low_pc));
21390
21391   list_in_scope = get_builder ()->get_file_symbols ();
21392
21393   get_builder ()->record_debugformat ("DWARF 2");
21394   get_builder ()->record_producer (producer);
21395
21396   processing_has_namespace_info = false;
21397
21398   return get_builder ()->get_compunit_symtab ();
21399 }
21400
21401 static void
21402 var_decode_location (struct attribute *attr, struct symbol *sym,
21403                      struct dwarf2_cu *cu)
21404 {
21405   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21406   struct comp_unit_head *cu_header = &cu->header;
21407
21408   /* NOTE drow/2003-01-30: There used to be a comment and some special
21409      code here to turn a symbol with DW_AT_external and a
21410      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21411      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21412      with some versions of binutils) where shared libraries could have
21413      relocations against symbols in their debug information - the
21414      minimal symbol would have the right address, but the debug info
21415      would not.  It's no longer necessary, because we will explicitly
21416      apply relocations when we read in the debug information now.  */
21417
21418   /* A DW_AT_location attribute with no contents indicates that a
21419      variable has been optimized away.  */
21420   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21421     {
21422       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21423       return;
21424     }
21425
21426   /* Handle one degenerate form of location expression specially, to
21427      preserve GDB's previous behavior when section offsets are
21428      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21429      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21430
21431   if (attr_form_is_block (attr)
21432       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21433            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21434           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21435                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
21436               && (DW_BLOCK (attr)->size
21437                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21438     {
21439       unsigned int dummy;
21440
21441       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21442         SYMBOL_VALUE_ADDRESS (sym) =
21443           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21444       else
21445         SYMBOL_VALUE_ADDRESS (sym) =
21446           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21447       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21448       fixup_symbol_section (sym, objfile);
21449       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21450                                               SYMBOL_SECTION (sym));
21451       return;
21452     }
21453
21454   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21455      expression evaluator, and use LOC_COMPUTED only when necessary
21456      (i.e. when the value of a register or memory location is
21457      referenced, or a thread-local block, etc.).  Then again, it might
21458      not be worthwhile.  I'm assuming that it isn't unless performance
21459      or memory numbers show me otherwise.  */
21460
21461   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21462
21463   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21464     cu->has_loclist = true;
21465 }
21466
21467 /* Given a pointer to a DWARF information entry, figure out if we need
21468    to make a symbol table entry for it, and if so, create a new entry
21469    and return a pointer to it.
21470    If TYPE is NULL, determine symbol type from the die, otherwise
21471    used the passed type.
21472    If SPACE is not NULL, use it to hold the new symbol.  If it is
21473    NULL, allocate a new symbol on the objfile's obstack.  */
21474
21475 static struct symbol *
21476 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21477             struct symbol *space)
21478 {
21479   struct dwarf2_per_objfile *dwarf2_per_objfile
21480     = cu->per_cu->dwarf2_per_objfile;
21481   struct objfile *objfile = dwarf2_per_objfile->objfile;
21482   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21483   struct symbol *sym = NULL;
21484   const char *name;
21485   struct attribute *attr = NULL;
21486   struct attribute *attr2 = NULL;
21487   CORE_ADDR baseaddr;
21488   struct pending **list_to_add = NULL;
21489
21490   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21491
21492   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21493
21494   name = dwarf2_name (die, cu);
21495   if (name)
21496     {
21497       const char *linkagename;
21498       int suppress_add = 0;
21499
21500       if (space)
21501         sym = space;
21502       else
21503         sym = allocate_symbol (objfile);
21504       OBJSTAT (objfile, n_syms++);
21505
21506       /* Cache this symbol's name and the name's demangled form (if any).  */
21507       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21508       linkagename = dwarf2_physname (name, die, cu);
21509       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21510
21511       /* Fortran does not have mangling standard and the mangling does differ
21512          between gfortran, iFort etc.  */
21513       if (cu->language == language_fortran
21514           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21515         symbol_set_demangled_name (&(sym->ginfo),
21516                                    dwarf2_full_name (name, die, cu),
21517                                    NULL);
21518
21519       /* Default assumptions.
21520          Use the passed type or decode it from the die.  */
21521       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21522       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21523       if (type != NULL)
21524         SYMBOL_TYPE (sym) = type;
21525       else
21526         SYMBOL_TYPE (sym) = die_type (die, cu);
21527       attr = dwarf2_attr (die,
21528                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21529                           cu);
21530       if (attr)
21531         {
21532           SYMBOL_LINE (sym) = DW_UNSND (attr);
21533         }
21534
21535       attr = dwarf2_attr (die,
21536                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21537                           cu);
21538       if (attr)
21539         {
21540           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21541           struct file_entry *fe;
21542
21543           if (cu->line_header != NULL)
21544             fe = cu->line_header->file_name_at (file_index);
21545           else
21546             fe = NULL;
21547
21548           if (fe == NULL)
21549             complaint (_("file index out of range"));
21550           else
21551             symbol_set_symtab (sym, fe->symtab);
21552         }
21553
21554       switch (die->tag)
21555         {
21556         case DW_TAG_label:
21557           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21558           if (attr)
21559             {
21560               CORE_ADDR addr;
21561
21562               addr = attr_value_as_address (attr);
21563               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21564               SYMBOL_VALUE_ADDRESS (sym) = addr;
21565             }
21566           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21567           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21568           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21569           add_symbol_to_list (sym, cu->list_in_scope);
21570           break;
21571         case DW_TAG_subprogram:
21572           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21573              finish_block.  */
21574           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21575           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21576           if ((attr2 && (DW_UNSND (attr2) != 0))
21577               || cu->language == language_ada)
21578             {
21579               /* Subprograms marked external are stored as a global symbol.
21580                  Ada subprograms, whether marked external or not, are always
21581                  stored as a global symbol, because we want to be able to
21582                  access them globally.  For instance, we want to be able
21583                  to break on a nested subprogram without having to
21584                  specify the context.  */
21585               list_to_add = cu->get_builder ()->get_global_symbols ();
21586             }
21587           else
21588             {
21589               list_to_add = cu->list_in_scope;
21590             }
21591           break;
21592         case DW_TAG_inlined_subroutine:
21593           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21594              finish_block.  */
21595           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21596           SYMBOL_INLINED (sym) = 1;
21597           list_to_add = cu->list_in_scope;
21598           break;
21599         case DW_TAG_template_value_param:
21600           suppress_add = 1;
21601           /* Fall through.  */
21602         case DW_TAG_constant:
21603         case DW_TAG_variable:
21604         case DW_TAG_member:
21605           /* Compilation with minimal debug info may result in
21606              variables with missing type entries.  Change the
21607              misleading `void' type to something sensible.  */
21608           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21609             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21610
21611           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21612           /* In the case of DW_TAG_member, we should only be called for
21613              static const members.  */
21614           if (die->tag == DW_TAG_member)
21615             {
21616               /* dwarf2_add_field uses die_is_declaration,
21617                  so we do the same.  */
21618               gdb_assert (die_is_declaration (die, cu));
21619               gdb_assert (attr);
21620             }
21621           if (attr)
21622             {
21623               dwarf2_const_value (attr, sym, cu);
21624               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21625               if (!suppress_add)
21626                 {
21627                   if (attr2 && (DW_UNSND (attr2) != 0))
21628                     list_to_add = cu->get_builder ()->get_global_symbols ();
21629                   else
21630                     list_to_add = cu->list_in_scope;
21631                 }
21632               break;
21633             }
21634           attr = dwarf2_attr (die, DW_AT_location, cu);
21635           if (attr)
21636             {
21637               var_decode_location (attr, sym, cu);
21638               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21639
21640               /* Fortran explicitly imports any global symbols to the local
21641                  scope by DW_TAG_common_block.  */
21642               if (cu->language == language_fortran && die->parent
21643                   && die->parent->tag == DW_TAG_common_block)
21644                 attr2 = NULL;
21645
21646               if (SYMBOL_CLASS (sym) == LOC_STATIC
21647                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21648                   && !dwarf2_per_objfile->has_section_at_zero)
21649                 {
21650                   /* When a static variable is eliminated by the linker,
21651                      the corresponding debug information is not stripped
21652                      out, but the variable address is set to null;
21653                      do not add such variables into symbol table.  */
21654                 }
21655               else if (attr2 && (DW_UNSND (attr2) != 0))
21656                 {
21657                   /* Workaround gfortran PR debug/40040 - it uses
21658                      DW_AT_location for variables in -fPIC libraries which may
21659                      get overriden by other libraries/executable and get
21660                      a different address.  Resolve it by the minimal symbol
21661                      which may come from inferior's executable using copy
21662                      relocation.  Make this workaround only for gfortran as for
21663                      other compilers GDB cannot guess the minimal symbol
21664                      Fortran mangling kind.  */
21665                   if (cu->language == language_fortran && die->parent
21666                       && die->parent->tag == DW_TAG_module
21667                       && cu->producer
21668                       && startswith (cu->producer, "GNU Fortran"))
21669                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21670
21671                   /* A variable with DW_AT_external is never static,
21672                      but it may be block-scoped.  */
21673                   list_to_add
21674                     = ((cu->list_in_scope
21675                         == cu->get_builder ()->get_file_symbols ())
21676                        ? cu->get_builder ()->get_global_symbols ()
21677                        : cu->list_in_scope);
21678                 }
21679               else
21680                 list_to_add = cu->list_in_scope;
21681             }
21682           else
21683             {
21684               /* We do not know the address of this symbol.
21685                  If it is an external symbol and we have type information
21686                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21687                  The address of the variable will then be determined from
21688                  the minimal symbol table whenever the variable is
21689                  referenced.  */
21690               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21691
21692               /* Fortran explicitly imports any global symbols to the local
21693                  scope by DW_TAG_common_block.  */
21694               if (cu->language == language_fortran && die->parent
21695                   && die->parent->tag == DW_TAG_common_block)
21696                 {
21697                   /* SYMBOL_CLASS doesn't matter here because
21698                      read_common_block is going to reset it.  */
21699                   if (!suppress_add)
21700                     list_to_add = cu->list_in_scope;
21701                 }
21702               else if (attr2 && (DW_UNSND (attr2) != 0)
21703                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21704                 {
21705                   /* A variable with DW_AT_external is never static, but it
21706                      may be block-scoped.  */
21707                   list_to_add
21708                     = ((cu->list_in_scope
21709                         == cu->get_builder ()->get_file_symbols ())
21710                        ? cu->get_builder ()->get_global_symbols ()
21711                        : cu->list_in_scope);
21712
21713                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21714                 }
21715               else if (!die_is_declaration (die, cu))
21716                 {
21717                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21718                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21719                   if (!suppress_add)
21720                     list_to_add = cu->list_in_scope;
21721                 }
21722             }
21723           break;
21724         case DW_TAG_formal_parameter:
21725           {
21726             /* If we are inside a function, mark this as an argument.  If
21727                not, we might be looking at an argument to an inlined function
21728                when we do not have enough information to show inlined frames;
21729                pretend it's a local variable in that case so that the user can
21730                still see it.  */
21731             struct context_stack *curr
21732               = cu->get_builder ()->get_current_context_stack ();
21733             if (curr != nullptr && curr->name != nullptr)
21734               SYMBOL_IS_ARGUMENT (sym) = 1;
21735             attr = dwarf2_attr (die, DW_AT_location, cu);
21736             if (attr)
21737               {
21738                 var_decode_location (attr, sym, cu);
21739               }
21740             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21741             if (attr)
21742               {
21743                 dwarf2_const_value (attr, sym, cu);
21744               }
21745
21746             list_to_add = cu->list_in_scope;
21747           }
21748           break;
21749         case DW_TAG_unspecified_parameters:
21750           /* From varargs functions; gdb doesn't seem to have any
21751              interest in this information, so just ignore it for now.
21752              (FIXME?) */
21753           break;
21754         case DW_TAG_template_type_param:
21755           suppress_add = 1;
21756           /* Fall through.  */
21757         case DW_TAG_class_type:
21758         case DW_TAG_interface_type:
21759         case DW_TAG_structure_type:
21760         case DW_TAG_union_type:
21761         case DW_TAG_set_type:
21762         case DW_TAG_enumeration_type:
21763           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21764           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21765
21766           {
21767             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21768                really ever be static objects: otherwise, if you try
21769                to, say, break of a class's method and you're in a file
21770                which doesn't mention that class, it won't work unless
21771                the check for all static symbols in lookup_symbol_aux
21772                saves you.  See the OtherFileClass tests in
21773                gdb.c++/namespace.exp.  */
21774
21775             if (!suppress_add)
21776               {
21777                 buildsym_compunit *builder = cu->get_builder ();
21778                 list_to_add
21779                   = (cu->list_in_scope == builder->get_file_symbols ()
21780                      && cu->language == language_cplus
21781                      ? builder->get_global_symbols ()
21782                      : cu->list_in_scope);
21783
21784                 /* The semantics of C++ state that "struct foo {
21785                    ... }" also defines a typedef for "foo".  */
21786                 if (cu->language == language_cplus
21787                     || cu->language == language_ada
21788                     || cu->language == language_d
21789                     || cu->language == language_rust)
21790                   {
21791                     /* The symbol's name is already allocated along
21792                        with this objfile, so we don't need to
21793                        duplicate it for the type.  */
21794                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21795                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21796                   }
21797               }
21798           }
21799           break;
21800         case DW_TAG_typedef:
21801           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21802           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21803           list_to_add = cu->list_in_scope;
21804           break;
21805         case DW_TAG_base_type:
21806         case DW_TAG_subrange_type:
21807           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21808           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21809           list_to_add = cu->list_in_scope;
21810           break;
21811         case DW_TAG_enumerator:
21812           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21813           if (attr)
21814             {
21815               dwarf2_const_value (attr, sym, cu);
21816             }
21817           {
21818             /* NOTE: carlton/2003-11-10: See comment above in the
21819                DW_TAG_class_type, etc. block.  */
21820
21821             list_to_add
21822               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21823                  && cu->language == language_cplus
21824                  ? cu->get_builder ()->get_global_symbols ()
21825                  : cu->list_in_scope);
21826           }
21827           break;
21828         case DW_TAG_imported_declaration:
21829         case DW_TAG_namespace:
21830           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21831           list_to_add = cu->get_builder ()->get_global_symbols ();
21832           break;
21833         case DW_TAG_module:
21834           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21835           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21836           list_to_add = cu->get_builder ()->get_global_symbols ();
21837           break;
21838         case DW_TAG_common_block:
21839           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21840           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21841           add_symbol_to_list (sym, cu->list_in_scope);
21842           break;
21843         default:
21844           /* Not a tag we recognize.  Hopefully we aren't processing
21845              trash data, but since we must specifically ignore things
21846              we don't recognize, there is nothing else we should do at
21847              this point.  */
21848           complaint (_("unsupported tag: '%s'"),
21849                      dwarf_tag_name (die->tag));
21850           break;
21851         }
21852
21853       if (suppress_add)
21854         {
21855           sym->hash_next = objfile->template_symbols;
21856           objfile->template_symbols = sym;
21857           list_to_add = NULL;
21858         }
21859
21860       if (list_to_add != NULL)
21861         add_symbol_to_list (sym, list_to_add);
21862
21863       /* For the benefit of old versions of GCC, check for anonymous
21864          namespaces based on the demangled name.  */
21865       if (!cu->processing_has_namespace_info
21866           && cu->language == language_cplus)
21867         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21868     }
21869   return (sym);
21870 }
21871
21872 /* Given an attr with a DW_FORM_dataN value in host byte order,
21873    zero-extend it as appropriate for the symbol's type.  The DWARF
21874    standard (v4) is not entirely clear about the meaning of using
21875    DW_FORM_dataN for a constant with a signed type, where the type is
21876    wider than the data.  The conclusion of a discussion on the DWARF
21877    list was that this is unspecified.  We choose to always zero-extend
21878    because that is the interpretation long in use by GCC.  */
21879
21880 static gdb_byte *
21881 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21882                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21883 {
21884   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21885   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21886                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21887   LONGEST l = DW_UNSND (attr);
21888
21889   if (bits < sizeof (*value) * 8)
21890     {
21891       l &= ((LONGEST) 1 << bits) - 1;
21892       *value = l;
21893     }
21894   else if (bits == sizeof (*value) * 8)
21895     *value = l;
21896   else
21897     {
21898       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21899       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21900       return bytes;
21901     }
21902
21903   return NULL;
21904 }
21905
21906 /* Read a constant value from an attribute.  Either set *VALUE, or if
21907    the value does not fit in *VALUE, set *BYTES - either already
21908    allocated on the objfile obstack, or newly allocated on OBSTACK,
21909    or, set *BATON, if we translated the constant to a location
21910    expression.  */
21911
21912 static void
21913 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21914                          const char *name, struct obstack *obstack,
21915                          struct dwarf2_cu *cu,
21916                          LONGEST *value, const gdb_byte **bytes,
21917                          struct dwarf2_locexpr_baton **baton)
21918 {
21919   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21920   struct comp_unit_head *cu_header = &cu->header;
21921   struct dwarf_block *blk;
21922   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21923                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21924
21925   *value = 0;
21926   *bytes = NULL;
21927   *baton = NULL;
21928
21929   switch (attr->form)
21930     {
21931     case DW_FORM_addr:
21932     case DW_FORM_addrx:
21933     case DW_FORM_GNU_addr_index:
21934       {
21935         gdb_byte *data;
21936
21937         if (TYPE_LENGTH (type) != cu_header->addr_size)
21938           dwarf2_const_value_length_mismatch_complaint (name,
21939                                                         cu_header->addr_size,
21940                                                         TYPE_LENGTH (type));
21941         /* Symbols of this form are reasonably rare, so we just
21942            piggyback on the existing location code rather than writing
21943            a new implementation of symbol_computed_ops.  */
21944         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21945         (*baton)->per_cu = cu->per_cu;
21946         gdb_assert ((*baton)->per_cu);
21947
21948         (*baton)->size = 2 + cu_header->addr_size;
21949         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21950         (*baton)->data = data;
21951
21952         data[0] = DW_OP_addr;
21953         store_unsigned_integer (&data[1], cu_header->addr_size,
21954                                 byte_order, DW_ADDR (attr));
21955         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21956       }
21957       break;
21958     case DW_FORM_string:
21959     case DW_FORM_strp:
21960     case DW_FORM_strx:
21961     case DW_FORM_GNU_str_index:
21962     case DW_FORM_GNU_strp_alt:
21963       /* DW_STRING is already allocated on the objfile obstack, point
21964          directly to it.  */
21965       *bytes = (const gdb_byte *) DW_STRING (attr);
21966       break;
21967     case DW_FORM_block1:
21968     case DW_FORM_block2:
21969     case DW_FORM_block4:
21970     case DW_FORM_block:
21971     case DW_FORM_exprloc:
21972     case DW_FORM_data16:
21973       blk = DW_BLOCK (attr);
21974       if (TYPE_LENGTH (type) != blk->size)
21975         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21976                                                       TYPE_LENGTH (type));
21977       *bytes = blk->data;
21978       break;
21979
21980       /* The DW_AT_const_value attributes are supposed to carry the
21981          symbol's value "represented as it would be on the target
21982          architecture."  By the time we get here, it's already been
21983          converted to host endianness, so we just need to sign- or
21984          zero-extend it as appropriate.  */
21985     case DW_FORM_data1:
21986       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21987       break;
21988     case DW_FORM_data2:
21989       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21990       break;
21991     case DW_FORM_data4:
21992       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21993       break;
21994     case DW_FORM_data8:
21995       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21996       break;
21997
21998     case DW_FORM_sdata:
21999     case DW_FORM_implicit_const:
22000       *value = DW_SND (attr);
22001       break;
22002
22003     case DW_FORM_udata:
22004       *value = DW_UNSND (attr);
22005       break;
22006
22007     default:
22008       complaint (_("unsupported const value attribute form: '%s'"),
22009                  dwarf_form_name (attr->form));
22010       *value = 0;
22011       break;
22012     }
22013 }
22014
22015
22016 /* Copy constant value from an attribute to a symbol.  */
22017
22018 static void
22019 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22020                     struct dwarf2_cu *cu)
22021 {
22022   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22023   LONGEST value;
22024   const gdb_byte *bytes;
22025   struct dwarf2_locexpr_baton *baton;
22026
22027   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22028                            SYMBOL_PRINT_NAME (sym),
22029                            &objfile->objfile_obstack, cu,
22030                            &value, &bytes, &baton);
22031
22032   if (baton != NULL)
22033     {
22034       SYMBOL_LOCATION_BATON (sym) = baton;
22035       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22036     }
22037   else if (bytes != NULL)
22038      {
22039       SYMBOL_VALUE_BYTES (sym) = bytes;
22040       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22041     }
22042   else
22043     {
22044       SYMBOL_VALUE (sym) = value;
22045       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22046     }
22047 }
22048
22049 /* Return the type of the die in question using its DW_AT_type attribute.  */
22050
22051 static struct type *
22052 die_type (struct die_info *die, struct dwarf2_cu *cu)
22053 {
22054   struct attribute *type_attr;
22055
22056   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22057   if (!type_attr)
22058     {
22059       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22060       /* A missing DW_AT_type represents a void type.  */
22061       return objfile_type (objfile)->builtin_void;
22062     }
22063
22064   return lookup_die_type (die, type_attr, cu);
22065 }
22066
22067 /* True iff CU's producer generates GNAT Ada auxiliary information
22068    that allows to find parallel types through that information instead
22069    of having to do expensive parallel lookups by type name.  */
22070
22071 static int
22072 need_gnat_info (struct dwarf2_cu *cu)
22073 {
22074   /* Assume that the Ada compiler was GNAT, which always produces
22075      the auxiliary information.  */
22076   return (cu->language == language_ada);
22077 }
22078
22079 /* Return the auxiliary type of the die in question using its
22080    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22081    attribute is not present.  */
22082
22083 static struct type *
22084 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22085 {
22086   struct attribute *type_attr;
22087
22088   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22089   if (!type_attr)
22090     return NULL;
22091
22092   return lookup_die_type (die, type_attr, cu);
22093 }
22094
22095 /* If DIE has a descriptive_type attribute, then set the TYPE's
22096    descriptive type accordingly.  */
22097
22098 static void
22099 set_descriptive_type (struct type *type, struct die_info *die,
22100                       struct dwarf2_cu *cu)
22101 {
22102   struct type *descriptive_type = die_descriptive_type (die, cu);
22103
22104   if (descriptive_type)
22105     {
22106       ALLOCATE_GNAT_AUX_TYPE (type);
22107       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22108     }
22109 }
22110
22111 /* Return the containing type of the die in question using its
22112    DW_AT_containing_type attribute.  */
22113
22114 static struct type *
22115 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22116 {
22117   struct attribute *type_attr;
22118   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22119
22120   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22121   if (!type_attr)
22122     error (_("Dwarf Error: Problem turning containing type into gdb type "
22123              "[in module %s]"), objfile_name (objfile));
22124
22125   return lookup_die_type (die, type_attr, cu);
22126 }
22127
22128 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22129
22130 static struct type *
22131 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22132 {
22133   struct dwarf2_per_objfile *dwarf2_per_objfile
22134     = cu->per_cu->dwarf2_per_objfile;
22135   struct objfile *objfile = dwarf2_per_objfile->objfile;
22136   char *saved;
22137
22138   std::string message
22139     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22140                      objfile_name (objfile),
22141                      sect_offset_str (cu->header.sect_off),
22142                      sect_offset_str (die->sect_off));
22143   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22144                                   message.c_str (), message.length ());
22145
22146   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22147 }
22148
22149 /* Look up the type of DIE in CU using its type attribute ATTR.
22150    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22151    DW_AT_containing_type.
22152    If there is no type substitute an error marker.  */
22153
22154 static struct type *
22155 lookup_die_type (struct die_info *die, const struct attribute *attr,
22156                  struct dwarf2_cu *cu)
22157 {
22158   struct dwarf2_per_objfile *dwarf2_per_objfile
22159     = cu->per_cu->dwarf2_per_objfile;
22160   struct objfile *objfile = dwarf2_per_objfile->objfile;
22161   struct type *this_type;
22162
22163   gdb_assert (attr->name == DW_AT_type
22164               || attr->name == DW_AT_GNAT_descriptive_type
22165               || attr->name == DW_AT_containing_type);
22166
22167   /* First see if we have it cached.  */
22168
22169   if (attr->form == DW_FORM_GNU_ref_alt)
22170     {
22171       struct dwarf2_per_cu_data *per_cu;
22172       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22173
22174       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22175                                                  dwarf2_per_objfile);
22176       this_type = get_die_type_at_offset (sect_off, per_cu);
22177     }
22178   else if (attr_form_is_ref (attr))
22179     {
22180       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22181
22182       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22183     }
22184   else if (attr->form == DW_FORM_ref_sig8)
22185     {
22186       ULONGEST signature = DW_SIGNATURE (attr);
22187
22188       return get_signatured_type (die, signature, cu);
22189     }
22190   else
22191     {
22192       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22193                    " at %s [in module %s]"),
22194                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22195                  objfile_name (objfile));
22196       return build_error_marker_type (cu, die);
22197     }
22198
22199   /* If not cached we need to read it in.  */
22200
22201   if (this_type == NULL)
22202     {
22203       struct die_info *type_die = NULL;
22204       struct dwarf2_cu *type_cu = cu;
22205
22206       if (attr_form_is_ref (attr))
22207         type_die = follow_die_ref (die, attr, &type_cu);
22208       if (type_die == NULL)
22209         return build_error_marker_type (cu, die);
22210       /* If we find the type now, it's probably because the type came
22211          from an inter-CU reference and the type's CU got expanded before
22212          ours.  */
22213       this_type = read_type_die (type_die, type_cu);
22214     }
22215
22216   /* If we still don't have a type use an error marker.  */
22217
22218   if (this_type == NULL)
22219     return build_error_marker_type (cu, die);
22220
22221   return this_type;
22222 }
22223
22224 /* Return the type in DIE, CU.
22225    Returns NULL for invalid types.
22226
22227    This first does a lookup in die_type_hash,
22228    and only reads the die in if necessary.
22229
22230    NOTE: This can be called when reading in partial or full symbols.  */
22231
22232 static struct type *
22233 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22234 {
22235   struct type *this_type;
22236
22237   this_type = get_die_type (die, cu);
22238   if (this_type)
22239     return this_type;
22240
22241   return read_type_die_1 (die, cu);
22242 }
22243
22244 /* Read the type in DIE, CU.
22245    Returns NULL for invalid types.  */
22246
22247 static struct type *
22248 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22249 {
22250   struct type *this_type = NULL;
22251
22252   switch (die->tag)
22253     {
22254     case DW_TAG_class_type:
22255     case DW_TAG_interface_type:
22256     case DW_TAG_structure_type:
22257     case DW_TAG_union_type:
22258       this_type = read_structure_type (die, cu);
22259       break;
22260     case DW_TAG_enumeration_type:
22261       this_type = read_enumeration_type (die, cu);
22262       break;
22263     case DW_TAG_subprogram:
22264     case DW_TAG_subroutine_type:
22265     case DW_TAG_inlined_subroutine:
22266       this_type = read_subroutine_type (die, cu);
22267       break;
22268     case DW_TAG_array_type:
22269       this_type = read_array_type (die, cu);
22270       break;
22271     case DW_TAG_set_type:
22272       this_type = read_set_type (die, cu);
22273       break;
22274     case DW_TAG_pointer_type:
22275       this_type = read_tag_pointer_type (die, cu);
22276       break;
22277     case DW_TAG_ptr_to_member_type:
22278       this_type = read_tag_ptr_to_member_type (die, cu);
22279       break;
22280     case DW_TAG_reference_type:
22281       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22282       break;
22283     case DW_TAG_rvalue_reference_type:
22284       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22285       break;
22286     case DW_TAG_const_type:
22287       this_type = read_tag_const_type (die, cu);
22288       break;
22289     case DW_TAG_volatile_type:
22290       this_type = read_tag_volatile_type (die, cu);
22291       break;
22292     case DW_TAG_restrict_type:
22293       this_type = read_tag_restrict_type (die, cu);
22294       break;
22295     case DW_TAG_string_type:
22296       this_type = read_tag_string_type (die, cu);
22297       break;
22298     case DW_TAG_typedef:
22299       this_type = read_typedef (die, cu);
22300       break;
22301     case DW_TAG_subrange_type:
22302       this_type = read_subrange_type (die, cu);
22303       break;
22304     case DW_TAG_base_type:
22305       this_type = read_base_type (die, cu);
22306       break;
22307     case DW_TAG_unspecified_type:
22308       this_type = read_unspecified_type (die, cu);
22309       break;
22310     case DW_TAG_namespace:
22311       this_type = read_namespace_type (die, cu);
22312       break;
22313     case DW_TAG_module:
22314       this_type = read_module_type (die, cu);
22315       break;
22316     case DW_TAG_atomic_type:
22317       this_type = read_tag_atomic_type (die, cu);
22318       break;
22319     default:
22320       complaint (_("unexpected tag in read_type_die: '%s'"),
22321                  dwarf_tag_name (die->tag));
22322       break;
22323     }
22324
22325   return this_type;
22326 }
22327
22328 /* See if we can figure out if the class lives in a namespace.  We do
22329    this by looking for a member function; its demangled name will
22330    contain namespace info, if there is any.
22331    Return the computed name or NULL.
22332    Space for the result is allocated on the objfile's obstack.
22333    This is the full-die version of guess_partial_die_structure_name.
22334    In this case we know DIE has no useful parent.  */
22335
22336 static char *
22337 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22338 {
22339   struct die_info *spec_die;
22340   struct dwarf2_cu *spec_cu;
22341   struct die_info *child;
22342   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22343
22344   spec_cu = cu;
22345   spec_die = die_specification (die, &spec_cu);
22346   if (spec_die != NULL)
22347     {
22348       die = spec_die;
22349       cu = spec_cu;
22350     }
22351
22352   for (child = die->child;
22353        child != NULL;
22354        child = child->sibling)
22355     {
22356       if (child->tag == DW_TAG_subprogram)
22357         {
22358           const char *linkage_name = dw2_linkage_name (child, cu);
22359
22360           if (linkage_name != NULL)
22361             {
22362               char *actual_name
22363                 = language_class_name_from_physname (cu->language_defn,
22364                                                      linkage_name);
22365               char *name = NULL;
22366
22367               if (actual_name != NULL)
22368                 {
22369                   const char *die_name = dwarf2_name (die, cu);
22370
22371                   if (die_name != NULL
22372                       && strcmp (die_name, actual_name) != 0)
22373                     {
22374                       /* Strip off the class name from the full name.
22375                          We want the prefix.  */
22376                       int die_name_len = strlen (die_name);
22377                       int actual_name_len = strlen (actual_name);
22378
22379                       /* Test for '::' as a sanity check.  */
22380                       if (actual_name_len > die_name_len + 2
22381                           && actual_name[actual_name_len
22382                                          - die_name_len - 1] == ':')
22383                         name = (char *) obstack_copy0 (
22384                           &objfile->per_bfd->storage_obstack,
22385                           actual_name, actual_name_len - die_name_len - 2);
22386                     }
22387                 }
22388               xfree (actual_name);
22389               return name;
22390             }
22391         }
22392     }
22393
22394   return NULL;
22395 }
22396
22397 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22398    prefix part in such case.  See
22399    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22400
22401 static const char *
22402 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22403 {
22404   struct attribute *attr;
22405   const char *base;
22406
22407   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22408       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22409     return NULL;
22410
22411   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22412     return NULL;
22413
22414   attr = dw2_linkage_name_attr (die, cu);
22415   if (attr == NULL || DW_STRING (attr) == NULL)
22416     return NULL;
22417
22418   /* dwarf2_name had to be already called.  */
22419   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22420
22421   /* Strip the base name, keep any leading namespaces/classes.  */
22422   base = strrchr (DW_STRING (attr), ':');
22423   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22424     return "";
22425
22426   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22427   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22428                                  DW_STRING (attr),
22429                                  &base[-1] - DW_STRING (attr));
22430 }
22431
22432 /* Return the name of the namespace/class that DIE is defined within,
22433    or "" if we can't tell.  The caller should not xfree the result.
22434
22435    For example, if we're within the method foo() in the following
22436    code:
22437
22438    namespace N {
22439      class C {
22440        void foo () {
22441        }
22442      };
22443    }
22444
22445    then determine_prefix on foo's die will return "N::C".  */
22446
22447 static const char *
22448 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22449 {
22450   struct dwarf2_per_objfile *dwarf2_per_objfile
22451     = cu->per_cu->dwarf2_per_objfile;
22452   struct die_info *parent, *spec_die;
22453   struct dwarf2_cu *spec_cu;
22454   struct type *parent_type;
22455   const char *retval;
22456
22457   if (cu->language != language_cplus
22458       && cu->language != language_fortran && cu->language != language_d
22459       && cu->language != language_rust)
22460     return "";
22461
22462   retval = anonymous_struct_prefix (die, cu);
22463   if (retval)
22464     return retval;
22465
22466   /* We have to be careful in the presence of DW_AT_specification.
22467      For example, with GCC 3.4, given the code
22468
22469      namespace N {
22470        void foo() {
22471          // Definition of N::foo.
22472        }
22473      }
22474
22475      then we'll have a tree of DIEs like this:
22476
22477      1: DW_TAG_compile_unit
22478        2: DW_TAG_namespace        // N
22479          3: DW_TAG_subprogram     // declaration of N::foo
22480        4: DW_TAG_subprogram       // definition of N::foo
22481             DW_AT_specification   // refers to die #3
22482
22483      Thus, when processing die #4, we have to pretend that we're in
22484      the context of its DW_AT_specification, namely the contex of die
22485      #3.  */
22486   spec_cu = cu;
22487   spec_die = die_specification (die, &spec_cu);
22488   if (spec_die == NULL)
22489     parent = die->parent;
22490   else
22491     {
22492       parent = spec_die->parent;
22493       cu = spec_cu;
22494     }
22495
22496   if (parent == NULL)
22497     return "";
22498   else if (parent->building_fullname)
22499     {
22500       const char *name;
22501       const char *parent_name;
22502
22503       /* It has been seen on RealView 2.2 built binaries,
22504          DW_TAG_template_type_param types actually _defined_ as
22505          children of the parent class:
22506
22507          enum E {};
22508          template class <class Enum> Class{};
22509          Class<enum E> class_e;
22510
22511          1: DW_TAG_class_type (Class)
22512            2: DW_TAG_enumeration_type (E)
22513              3: DW_TAG_enumerator (enum1:0)
22514              3: DW_TAG_enumerator (enum2:1)
22515              ...
22516            2: DW_TAG_template_type_param
22517               DW_AT_type  DW_FORM_ref_udata (E)
22518
22519          Besides being broken debug info, it can put GDB into an
22520          infinite loop.  Consider:
22521
22522          When we're building the full name for Class<E>, we'll start
22523          at Class, and go look over its template type parameters,
22524          finding E.  We'll then try to build the full name of E, and
22525          reach here.  We're now trying to build the full name of E,
22526          and look over the parent DIE for containing scope.  In the
22527          broken case, if we followed the parent DIE of E, we'd again
22528          find Class, and once again go look at its template type
22529          arguments, etc., etc.  Simply don't consider such parent die
22530          as source-level parent of this die (it can't be, the language
22531          doesn't allow it), and break the loop here.  */
22532       name = dwarf2_name (die, cu);
22533       parent_name = dwarf2_name (parent, cu);
22534       complaint (_("template param type '%s' defined within parent '%s'"),
22535                  name ? name : "<unknown>",
22536                  parent_name ? parent_name : "<unknown>");
22537       return "";
22538     }
22539   else
22540     switch (parent->tag)
22541       {
22542       case DW_TAG_namespace:
22543         parent_type = read_type_die (parent, cu);
22544         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22545            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22546            Work around this problem here.  */
22547         if (cu->language == language_cplus
22548             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22549           return "";
22550         /* We give a name to even anonymous namespaces.  */
22551         return TYPE_NAME (parent_type);
22552       case DW_TAG_class_type:
22553       case DW_TAG_interface_type:
22554       case DW_TAG_structure_type:
22555       case DW_TAG_union_type:
22556       case DW_TAG_module:
22557         parent_type = read_type_die (parent, cu);
22558         if (TYPE_NAME (parent_type) != NULL)
22559           return TYPE_NAME (parent_type);
22560         else
22561           /* An anonymous structure is only allowed non-static data
22562              members; no typedefs, no member functions, et cetera.
22563              So it does not need a prefix.  */
22564           return "";
22565       case DW_TAG_compile_unit:
22566       case DW_TAG_partial_unit:
22567         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22568         if (cu->language == language_cplus
22569             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22570             && die->child != NULL
22571             && (die->tag == DW_TAG_class_type
22572                 || die->tag == DW_TAG_structure_type
22573                 || die->tag == DW_TAG_union_type))
22574           {
22575             char *name = guess_full_die_structure_name (die, cu);
22576             if (name != NULL)
22577               return name;
22578           }
22579         return "";
22580       case DW_TAG_enumeration_type:
22581         parent_type = read_type_die (parent, cu);
22582         if (TYPE_DECLARED_CLASS (parent_type))
22583           {
22584             if (TYPE_NAME (parent_type) != NULL)
22585               return TYPE_NAME (parent_type);
22586             return "";
22587           }
22588         /* Fall through.  */
22589       default:
22590         return determine_prefix (parent, cu);
22591       }
22592 }
22593
22594 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22595    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22596    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22597    an obconcat, otherwise allocate storage for the result.  The CU argument is
22598    used to determine the language and hence, the appropriate separator.  */
22599
22600 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22601
22602 static char *
22603 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22604                  int physname, struct dwarf2_cu *cu)
22605 {
22606   const char *lead = "";
22607   const char *sep;
22608
22609   if (suffix == NULL || suffix[0] == '\0'
22610       || prefix == NULL || prefix[0] == '\0')
22611     sep = "";
22612   else if (cu->language == language_d)
22613     {
22614       /* For D, the 'main' function could be defined in any module, but it
22615          should never be prefixed.  */
22616       if (strcmp (suffix, "D main") == 0)
22617         {
22618           prefix = "";
22619           sep = "";
22620         }
22621       else
22622         sep = ".";
22623     }
22624   else if (cu->language == language_fortran && physname)
22625     {
22626       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22627          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22628
22629       lead = "__";
22630       sep = "_MOD_";
22631     }
22632   else
22633     sep = "::";
22634
22635   if (prefix == NULL)
22636     prefix = "";
22637   if (suffix == NULL)
22638     suffix = "";
22639
22640   if (obs == NULL)
22641     {
22642       char *retval
22643         = ((char *)
22644            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22645
22646       strcpy (retval, lead);
22647       strcat (retval, prefix);
22648       strcat (retval, sep);
22649       strcat (retval, suffix);
22650       return retval;
22651     }
22652   else
22653     {
22654       /* We have an obstack.  */
22655       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22656     }
22657 }
22658
22659 /* Return sibling of die, NULL if no sibling.  */
22660
22661 static struct die_info *
22662 sibling_die (struct die_info *die)
22663 {
22664   return die->sibling;
22665 }
22666
22667 /* Get name of a die, return NULL if not found.  */
22668
22669 static const char *
22670 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22671                           struct obstack *obstack)
22672 {
22673   if (name && cu->language == language_cplus)
22674     {
22675       std::string canon_name = cp_canonicalize_string (name);
22676
22677       if (!canon_name.empty ())
22678         {
22679           if (canon_name != name)
22680             name = (const char *) obstack_copy0 (obstack,
22681                                                  canon_name.c_str (),
22682                                                  canon_name.length ());
22683         }
22684     }
22685
22686   return name;
22687 }
22688
22689 /* Get name of a die, return NULL if not found.
22690    Anonymous namespaces are converted to their magic string.  */
22691
22692 static const char *
22693 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22694 {
22695   struct attribute *attr;
22696   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22697
22698   attr = dwarf2_attr (die, DW_AT_name, cu);
22699   if ((!attr || !DW_STRING (attr))
22700       && die->tag != DW_TAG_namespace
22701       && die->tag != DW_TAG_class_type
22702       && die->tag != DW_TAG_interface_type
22703       && die->tag != DW_TAG_structure_type
22704       && die->tag != DW_TAG_union_type)
22705     return NULL;
22706
22707   switch (die->tag)
22708     {
22709     case DW_TAG_compile_unit:
22710     case DW_TAG_partial_unit:
22711       /* Compilation units have a DW_AT_name that is a filename, not
22712          a source language identifier.  */
22713     case DW_TAG_enumeration_type:
22714     case DW_TAG_enumerator:
22715       /* These tags always have simple identifiers already; no need
22716          to canonicalize them.  */
22717       return DW_STRING (attr);
22718
22719     case DW_TAG_namespace:
22720       if (attr != NULL && DW_STRING (attr) != NULL)
22721         return DW_STRING (attr);
22722       return CP_ANONYMOUS_NAMESPACE_STR;
22723
22724     case DW_TAG_class_type:
22725     case DW_TAG_interface_type:
22726     case DW_TAG_structure_type:
22727     case DW_TAG_union_type:
22728       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22729          structures or unions.  These were of the form "._%d" in GCC 4.1,
22730          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22731          and GCC 4.4.  We work around this problem by ignoring these.  */
22732       if (attr && DW_STRING (attr)
22733           && (startswith (DW_STRING (attr), "._")
22734               || startswith (DW_STRING (attr), "<anonymous")))
22735         return NULL;
22736
22737       /* GCC might emit a nameless typedef that has a linkage name.  See
22738          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22739       if (!attr || DW_STRING (attr) == NULL)
22740         {
22741           char *demangled = NULL;
22742
22743           attr = dw2_linkage_name_attr (die, cu);
22744           if (attr == NULL || DW_STRING (attr) == NULL)
22745             return NULL;
22746
22747           /* Avoid demangling DW_STRING (attr) the second time on a second
22748              call for the same DIE.  */
22749           if (!DW_STRING_IS_CANONICAL (attr))
22750             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22751
22752           if (demangled)
22753             {
22754               const char *base;
22755
22756               /* FIXME: we already did this for the partial symbol... */
22757               DW_STRING (attr)
22758                 = ((const char *)
22759                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22760                                   demangled, strlen (demangled)));
22761               DW_STRING_IS_CANONICAL (attr) = 1;
22762               xfree (demangled);
22763
22764               /* Strip any leading namespaces/classes, keep only the base name.
22765                  DW_AT_name for named DIEs does not contain the prefixes.  */
22766               base = strrchr (DW_STRING (attr), ':');
22767               if (base && base > DW_STRING (attr) && base[-1] == ':')
22768                 return &base[1];
22769               else
22770                 return DW_STRING (attr);
22771             }
22772         }
22773       break;
22774
22775     default:
22776       break;
22777     }
22778
22779   if (!DW_STRING_IS_CANONICAL (attr))
22780     {
22781       DW_STRING (attr)
22782         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22783                                     &objfile->per_bfd->storage_obstack);
22784       DW_STRING_IS_CANONICAL (attr) = 1;
22785     }
22786   return DW_STRING (attr);
22787 }
22788
22789 /* Return the die that this die in an extension of, or NULL if there
22790    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22791    containing the return value on output.  */
22792
22793 static struct die_info *
22794 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22795 {
22796   struct attribute *attr;
22797
22798   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22799   if (attr == NULL)
22800     return NULL;
22801
22802   return follow_die_ref (die, attr, ext_cu);
22803 }
22804
22805 /* Convert a DIE tag into its string name.  */
22806
22807 static const char *
22808 dwarf_tag_name (unsigned tag)
22809 {
22810   const char *name = get_DW_TAG_name (tag);
22811
22812   if (name == NULL)
22813     return "DW_TAG_<unknown>";
22814
22815   return name;
22816 }
22817
22818 /* Convert a DWARF attribute code into its string name.  */
22819
22820 static const char *
22821 dwarf_attr_name (unsigned attr)
22822 {
22823   const char *name;
22824
22825 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22826   if (attr == DW_AT_MIPS_fde)
22827     return "DW_AT_MIPS_fde";
22828 #else
22829   if (attr == DW_AT_HP_block_index)
22830     return "DW_AT_HP_block_index";
22831 #endif
22832
22833   name = get_DW_AT_name (attr);
22834
22835   if (name == NULL)
22836     return "DW_AT_<unknown>";
22837
22838   return name;
22839 }
22840
22841 /* Convert a DWARF value form code into its string name.  */
22842
22843 static const char *
22844 dwarf_form_name (unsigned form)
22845 {
22846   const char *name = get_DW_FORM_name (form);
22847
22848   if (name == NULL)
22849     return "DW_FORM_<unknown>";
22850
22851   return name;
22852 }
22853
22854 static const char *
22855 dwarf_bool_name (unsigned mybool)
22856 {
22857   if (mybool)
22858     return "TRUE";
22859   else
22860     return "FALSE";
22861 }
22862
22863 /* Convert a DWARF type code into its string name.  */
22864
22865 static const char *
22866 dwarf_type_encoding_name (unsigned enc)
22867 {
22868   const char *name = get_DW_ATE_name (enc);
22869
22870   if (name == NULL)
22871     return "DW_ATE_<unknown>";
22872
22873   return name;
22874 }
22875
22876 static void
22877 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22878 {
22879   unsigned int i;
22880
22881   print_spaces (indent, f);
22882   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22883                       dwarf_tag_name (die->tag), die->abbrev,
22884                       sect_offset_str (die->sect_off));
22885
22886   if (die->parent != NULL)
22887     {
22888       print_spaces (indent, f);
22889       fprintf_unfiltered (f, "  parent at offset: %s\n",
22890                           sect_offset_str (die->parent->sect_off));
22891     }
22892
22893   print_spaces (indent, f);
22894   fprintf_unfiltered (f, "  has children: %s\n",
22895            dwarf_bool_name (die->child != NULL));
22896
22897   print_spaces (indent, f);
22898   fprintf_unfiltered (f, "  attributes:\n");
22899
22900   for (i = 0; i < die->num_attrs; ++i)
22901     {
22902       print_spaces (indent, f);
22903       fprintf_unfiltered (f, "    %s (%s) ",
22904                dwarf_attr_name (die->attrs[i].name),
22905                dwarf_form_name (die->attrs[i].form));
22906
22907       switch (die->attrs[i].form)
22908         {
22909         case DW_FORM_addr:
22910         case DW_FORM_addrx:
22911         case DW_FORM_GNU_addr_index:
22912           fprintf_unfiltered (f, "address: ");
22913           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22914           break;
22915         case DW_FORM_block2:
22916         case DW_FORM_block4:
22917         case DW_FORM_block:
22918         case DW_FORM_block1:
22919           fprintf_unfiltered (f, "block: size %s",
22920                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22921           break;
22922         case DW_FORM_exprloc:
22923           fprintf_unfiltered (f, "expression: size %s",
22924                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22925           break;
22926         case DW_FORM_data16:
22927           fprintf_unfiltered (f, "constant of 16 bytes");
22928           break;
22929         case DW_FORM_ref_addr:
22930           fprintf_unfiltered (f, "ref address: ");
22931           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22932           break;
22933         case DW_FORM_GNU_ref_alt:
22934           fprintf_unfiltered (f, "alt ref address: ");
22935           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22936           break;
22937         case DW_FORM_ref1:
22938         case DW_FORM_ref2:
22939         case DW_FORM_ref4:
22940         case DW_FORM_ref8:
22941         case DW_FORM_ref_udata:
22942           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22943                               (long) (DW_UNSND (&die->attrs[i])));
22944           break;
22945         case DW_FORM_data1:
22946         case DW_FORM_data2:
22947         case DW_FORM_data4:
22948         case DW_FORM_data8:
22949         case DW_FORM_udata:
22950         case DW_FORM_sdata:
22951           fprintf_unfiltered (f, "constant: %s",
22952                               pulongest (DW_UNSND (&die->attrs[i])));
22953           break;
22954         case DW_FORM_sec_offset:
22955           fprintf_unfiltered (f, "section offset: %s",
22956                               pulongest (DW_UNSND (&die->attrs[i])));
22957           break;
22958         case DW_FORM_ref_sig8:
22959           fprintf_unfiltered (f, "signature: %s",
22960                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22961           break;
22962         case DW_FORM_string:
22963         case DW_FORM_strp:
22964         case DW_FORM_line_strp:
22965         case DW_FORM_strx:
22966         case DW_FORM_GNU_str_index:
22967         case DW_FORM_GNU_strp_alt:
22968           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22969                    DW_STRING (&die->attrs[i])
22970                    ? DW_STRING (&die->attrs[i]) : "",
22971                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22972           break;
22973         case DW_FORM_flag:
22974           if (DW_UNSND (&die->attrs[i]))
22975             fprintf_unfiltered (f, "flag: TRUE");
22976           else
22977             fprintf_unfiltered (f, "flag: FALSE");
22978           break;
22979         case DW_FORM_flag_present:
22980           fprintf_unfiltered (f, "flag: TRUE");
22981           break;
22982         case DW_FORM_indirect:
22983           /* The reader will have reduced the indirect form to
22984              the "base form" so this form should not occur.  */
22985           fprintf_unfiltered (f, 
22986                               "unexpected attribute form: DW_FORM_indirect");
22987           break;
22988         case DW_FORM_implicit_const:
22989           fprintf_unfiltered (f, "constant: %s",
22990                               plongest (DW_SND (&die->attrs[i])));
22991           break;
22992         default:
22993           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22994                    die->attrs[i].form);
22995           break;
22996         }
22997       fprintf_unfiltered (f, "\n");
22998     }
22999 }
23000
23001 static void
23002 dump_die_for_error (struct die_info *die)
23003 {
23004   dump_die_shallow (gdb_stderr, 0, die);
23005 }
23006
23007 static void
23008 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23009 {
23010   int indent = level * 4;
23011
23012   gdb_assert (die != NULL);
23013
23014   if (level >= max_level)
23015     return;
23016
23017   dump_die_shallow (f, indent, die);
23018
23019   if (die->child != NULL)
23020     {
23021       print_spaces (indent, f);
23022       fprintf_unfiltered (f, "  Children:");
23023       if (level + 1 < max_level)
23024         {
23025           fprintf_unfiltered (f, "\n");
23026           dump_die_1 (f, level + 1, max_level, die->child);
23027         }
23028       else
23029         {
23030           fprintf_unfiltered (f,
23031                               " [not printed, max nesting level reached]\n");
23032         }
23033     }
23034
23035   if (die->sibling != NULL && level > 0)
23036     {
23037       dump_die_1 (f, level, max_level, die->sibling);
23038     }
23039 }
23040
23041 /* This is called from the pdie macro in gdbinit.in.
23042    It's not static so gcc will keep a copy callable from gdb.  */
23043
23044 void
23045 dump_die (struct die_info *die, int max_level)
23046 {
23047   dump_die_1 (gdb_stdlog, 0, max_level, die);
23048 }
23049
23050 static void
23051 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23052 {
23053   void **slot;
23054
23055   slot = htab_find_slot_with_hash (cu->die_hash, die,
23056                                    to_underlying (die->sect_off),
23057                                    INSERT);
23058
23059   *slot = die;
23060 }
23061
23062 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
23063    required kind.  */
23064
23065 static sect_offset
23066 dwarf2_get_ref_die_offset (const struct attribute *attr)
23067 {
23068   if (attr_form_is_ref (attr))
23069     return (sect_offset) DW_UNSND (attr);
23070
23071   complaint (_("unsupported die ref attribute form: '%s'"),
23072              dwarf_form_name (attr->form));
23073   return {};
23074 }
23075
23076 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
23077  * the value held by the attribute is not constant.  */
23078
23079 static LONGEST
23080 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
23081 {
23082   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
23083     return DW_SND (attr);
23084   else if (attr->form == DW_FORM_udata
23085            || attr->form == DW_FORM_data1
23086            || attr->form == DW_FORM_data2
23087            || attr->form == DW_FORM_data4
23088            || attr->form == DW_FORM_data8)
23089     return DW_UNSND (attr);
23090   else
23091     {
23092       /* For DW_FORM_data16 see attr_form_is_constant.  */
23093       complaint (_("Attribute value is not a constant (%s)"),
23094                  dwarf_form_name (attr->form));
23095       return default_value;
23096     }
23097 }
23098
23099 /* Follow reference or signature attribute ATTR of SRC_DIE.
23100    On entry *REF_CU is the CU of SRC_DIE.
23101    On exit *REF_CU is the CU of the result.  */
23102
23103 static struct die_info *
23104 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23105                        struct dwarf2_cu **ref_cu)
23106 {
23107   struct die_info *die;
23108
23109   if (attr_form_is_ref (attr))
23110     die = follow_die_ref (src_die, attr, ref_cu);
23111   else if (attr->form == DW_FORM_ref_sig8)
23112     die = follow_die_sig (src_die, attr, ref_cu);
23113   else
23114     {
23115       dump_die_for_error (src_die);
23116       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23117              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23118     }
23119
23120   return die;
23121 }
23122
23123 /* Follow reference OFFSET.
23124    On entry *REF_CU is the CU of the source die referencing OFFSET.
23125    On exit *REF_CU is the CU of the result.
23126    Returns NULL if OFFSET is invalid.  */
23127
23128 static struct die_info *
23129 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23130                    struct dwarf2_cu **ref_cu)
23131 {
23132   struct die_info temp_die;
23133   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23134   struct dwarf2_per_objfile *dwarf2_per_objfile
23135     = cu->per_cu->dwarf2_per_objfile;
23136
23137   gdb_assert (cu->per_cu != NULL);
23138
23139   target_cu = cu;
23140
23141   if (cu->per_cu->is_debug_types)
23142     {
23143       /* .debug_types CUs cannot reference anything outside their CU.
23144          If they need to, they have to reference a signatured type via
23145          DW_FORM_ref_sig8.  */
23146       if (!offset_in_cu_p (&cu->header, sect_off))
23147         return NULL;
23148     }
23149   else if (offset_in_dwz != cu->per_cu->is_dwz
23150            || !offset_in_cu_p (&cu->header, sect_off))
23151     {
23152       struct dwarf2_per_cu_data *per_cu;
23153
23154       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23155                                                  dwarf2_per_objfile);
23156
23157       /* If necessary, add it to the queue and load its DIEs.  */
23158       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23159         load_full_comp_unit (per_cu, false, cu->language);
23160
23161       target_cu = per_cu->cu;
23162     }
23163   else if (cu->dies == NULL)
23164     {
23165       /* We're loading full DIEs during partial symbol reading.  */
23166       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23167       load_full_comp_unit (cu->per_cu, false, language_minimal);
23168     }
23169
23170   *ref_cu = target_cu;
23171   temp_die.sect_off = sect_off;
23172
23173   if (target_cu != cu)
23174     target_cu->ancestor = cu;
23175
23176   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23177                                                   &temp_die,
23178                                                   to_underlying (sect_off));
23179 }
23180
23181 /* Follow reference attribute ATTR of SRC_DIE.
23182    On entry *REF_CU is the CU of SRC_DIE.
23183    On exit *REF_CU is the CU of the result.  */
23184
23185 static struct die_info *
23186 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23187                 struct dwarf2_cu **ref_cu)
23188 {
23189   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23190   struct dwarf2_cu *cu = *ref_cu;
23191   struct die_info *die;
23192
23193   die = follow_die_offset (sect_off,
23194                            (attr->form == DW_FORM_GNU_ref_alt
23195                             || cu->per_cu->is_dwz),
23196                            ref_cu);
23197   if (!die)
23198     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23199            "at %s [in module %s]"),
23200            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23201            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23202
23203   return die;
23204 }
23205
23206 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23207    Returned value is intended for DW_OP_call*.  Returned
23208    dwarf2_locexpr_baton->data has lifetime of
23209    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23210
23211 struct dwarf2_locexpr_baton
23212 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23213                                struct dwarf2_per_cu_data *per_cu,
23214                                CORE_ADDR (*get_frame_pc) (void *baton),
23215                                void *baton, bool resolve_abstract_p)
23216 {
23217   struct dwarf2_cu *cu;
23218   struct die_info *die;
23219   struct attribute *attr;
23220   struct dwarf2_locexpr_baton retval;
23221   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
23222   struct objfile *objfile = dwarf2_per_objfile->objfile;
23223
23224   if (per_cu->cu == NULL)
23225     load_cu (per_cu, false);
23226   cu = per_cu->cu;
23227   if (cu == NULL)
23228     {
23229       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23230          Instead just throw an error, not much else we can do.  */
23231       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23232              sect_offset_str (sect_off), objfile_name (objfile));
23233     }
23234
23235   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23236   if (!die)
23237     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23238            sect_offset_str (sect_off), objfile_name (objfile));
23239
23240   attr = dwarf2_attr (die, DW_AT_location, cu);
23241   if (!attr && resolve_abstract_p
23242       && (dwarf2_per_objfile->abstract_to_concrete.find (die)
23243           != dwarf2_per_objfile->abstract_to_concrete.end ()))
23244     {
23245       CORE_ADDR pc = (*get_frame_pc) (baton);
23246
23247       for (const auto &cand : dwarf2_per_objfile->abstract_to_concrete[die])
23248         {
23249           if (!cand->parent
23250               || cand->parent->tag != DW_TAG_subprogram)
23251             continue;
23252
23253           CORE_ADDR pc_low, pc_high;
23254           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23255           if (pc_low == ((CORE_ADDR) -1)
23256               || !(pc_low <= pc && pc < pc_high))
23257             continue;
23258
23259           die = cand;
23260           attr = dwarf2_attr (die, DW_AT_location, cu);
23261           break;
23262         }
23263     }
23264
23265   if (!attr)
23266     {
23267       /* DWARF: "If there is no such attribute, then there is no effect.".
23268          DATA is ignored if SIZE is 0.  */
23269
23270       retval.data = NULL;
23271       retval.size = 0;
23272     }
23273   else if (attr_form_is_section_offset (attr))
23274     {
23275       struct dwarf2_loclist_baton loclist_baton;
23276       CORE_ADDR pc = (*get_frame_pc) (baton);
23277       size_t size;
23278
23279       fill_in_loclist_baton (cu, &loclist_baton, attr);
23280
23281       retval.data = dwarf2_find_location_expression (&loclist_baton,
23282                                                      &size, pc);
23283       retval.size = size;
23284     }
23285   else
23286     {
23287       if (!attr_form_is_block (attr))
23288         error (_("Dwarf Error: DIE at %s referenced in module %s "
23289                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23290                sect_offset_str (sect_off), objfile_name (objfile));
23291
23292       retval.data = DW_BLOCK (attr)->data;
23293       retval.size = DW_BLOCK (attr)->size;
23294     }
23295   retval.per_cu = cu->per_cu;
23296
23297   age_cached_comp_units (dwarf2_per_objfile);
23298
23299   return retval;
23300 }
23301
23302 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23303    offset.  */
23304
23305 struct dwarf2_locexpr_baton
23306 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23307                              struct dwarf2_per_cu_data *per_cu,
23308                              CORE_ADDR (*get_frame_pc) (void *baton),
23309                              void *baton)
23310 {
23311   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23312
23313   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23314 }
23315
23316 /* Write a constant of a given type as target-ordered bytes into
23317    OBSTACK.  */
23318
23319 static const gdb_byte *
23320 write_constant_as_bytes (struct obstack *obstack,
23321                          enum bfd_endian byte_order,
23322                          struct type *type,
23323                          ULONGEST value,
23324                          LONGEST *len)
23325 {
23326   gdb_byte *result;
23327
23328   *len = TYPE_LENGTH (type);
23329   result = (gdb_byte *) obstack_alloc (obstack, *len);
23330   store_unsigned_integer (result, *len, byte_order, value);
23331
23332   return result;
23333 }
23334
23335 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23336    pointer to the constant bytes and set LEN to the length of the
23337    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23338    does not have a DW_AT_const_value, return NULL.  */
23339
23340 const gdb_byte *
23341 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23342                              struct dwarf2_per_cu_data *per_cu,
23343                              struct obstack *obstack,
23344                              LONGEST *len)
23345 {
23346   struct dwarf2_cu *cu;
23347   struct die_info *die;
23348   struct attribute *attr;
23349   const gdb_byte *result = NULL;
23350   struct type *type;
23351   LONGEST value;
23352   enum bfd_endian byte_order;
23353   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23354
23355   if (per_cu->cu == NULL)
23356     load_cu (per_cu, false);
23357   cu = per_cu->cu;
23358   if (cu == NULL)
23359     {
23360       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23361          Instead just throw an error, not much else we can do.  */
23362       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23363              sect_offset_str (sect_off), objfile_name (objfile));
23364     }
23365
23366   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23367   if (!die)
23368     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23369            sect_offset_str (sect_off), objfile_name (objfile));
23370
23371   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23372   if (attr == NULL)
23373     return NULL;
23374
23375   byte_order = (bfd_big_endian (objfile->obfd)
23376                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23377
23378   switch (attr->form)
23379     {
23380     case DW_FORM_addr:
23381     case DW_FORM_addrx:
23382     case DW_FORM_GNU_addr_index:
23383       {
23384         gdb_byte *tem;
23385
23386         *len = cu->header.addr_size;
23387         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23388         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23389         result = tem;
23390       }
23391       break;
23392     case DW_FORM_string:
23393     case DW_FORM_strp:
23394     case DW_FORM_strx:
23395     case DW_FORM_GNU_str_index:
23396     case DW_FORM_GNU_strp_alt:
23397       /* DW_STRING is already allocated on the objfile obstack, point
23398          directly to it.  */
23399       result = (const gdb_byte *) DW_STRING (attr);
23400       *len = strlen (DW_STRING (attr));
23401       break;
23402     case DW_FORM_block1:
23403     case DW_FORM_block2:
23404     case DW_FORM_block4:
23405     case DW_FORM_block:
23406     case DW_FORM_exprloc:
23407     case DW_FORM_data16:
23408       result = DW_BLOCK (attr)->data;
23409       *len = DW_BLOCK (attr)->size;
23410       break;
23411
23412       /* The DW_AT_const_value attributes are supposed to carry the
23413          symbol's value "represented as it would be on the target
23414          architecture."  By the time we get here, it's already been
23415          converted to host endianness, so we just need to sign- or
23416          zero-extend it as appropriate.  */
23417     case DW_FORM_data1:
23418       type = die_type (die, cu);
23419       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23420       if (result == NULL)
23421         result = write_constant_as_bytes (obstack, byte_order,
23422                                           type, value, len);
23423       break;
23424     case DW_FORM_data2:
23425       type = die_type (die, cu);
23426       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23427       if (result == NULL)
23428         result = write_constant_as_bytes (obstack, byte_order,
23429                                           type, value, len);
23430       break;
23431     case DW_FORM_data4:
23432       type = die_type (die, cu);
23433       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23434       if (result == NULL)
23435         result = write_constant_as_bytes (obstack, byte_order,
23436                                           type, value, len);
23437       break;
23438     case DW_FORM_data8:
23439       type = die_type (die, cu);
23440       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23441       if (result == NULL)
23442         result = write_constant_as_bytes (obstack, byte_order,
23443                                           type, value, len);
23444       break;
23445
23446     case DW_FORM_sdata:
23447     case DW_FORM_implicit_const:
23448       type = die_type (die, cu);
23449       result = write_constant_as_bytes (obstack, byte_order,
23450                                         type, DW_SND (attr), len);
23451       break;
23452
23453     case DW_FORM_udata:
23454       type = die_type (die, cu);
23455       result = write_constant_as_bytes (obstack, byte_order,
23456                                         type, DW_UNSND (attr), len);
23457       break;
23458
23459     default:
23460       complaint (_("unsupported const value attribute form: '%s'"),
23461                  dwarf_form_name (attr->form));
23462       break;
23463     }
23464
23465   return result;
23466 }
23467
23468 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23469    valid type for this die is found.  */
23470
23471 struct type *
23472 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23473                                 struct dwarf2_per_cu_data *per_cu)
23474 {
23475   struct dwarf2_cu *cu;
23476   struct die_info *die;
23477
23478   if (per_cu->cu == NULL)
23479     load_cu (per_cu, false);
23480   cu = per_cu->cu;
23481   if (!cu)
23482     return NULL;
23483
23484   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23485   if (!die)
23486     return NULL;
23487
23488   return die_type (die, cu);
23489 }
23490
23491 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23492    PER_CU.  */
23493
23494 struct type *
23495 dwarf2_get_die_type (cu_offset die_offset,
23496                      struct dwarf2_per_cu_data *per_cu)
23497 {
23498   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23499   return get_die_type_at_offset (die_offset_sect, per_cu);
23500 }
23501
23502 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23503    On entry *REF_CU is the CU of SRC_DIE.
23504    On exit *REF_CU is the CU of the result.
23505    Returns NULL if the referenced DIE isn't found.  */
23506
23507 static struct die_info *
23508 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23509                   struct dwarf2_cu **ref_cu)
23510 {
23511   struct die_info temp_die;
23512   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
23513   struct die_info *die;
23514
23515   /* While it might be nice to assert sig_type->type == NULL here,
23516      we can get here for DW_AT_imported_declaration where we need
23517      the DIE not the type.  */
23518
23519   /* If necessary, add it to the queue and load its DIEs.  */
23520
23521   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23522     read_signatured_type (sig_type);
23523
23524   sig_cu = sig_type->per_cu.cu;
23525   gdb_assert (sig_cu != NULL);
23526   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23527   temp_die.sect_off = sig_type->type_offset_in_section;
23528   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23529                                                  to_underlying (temp_die.sect_off));
23530   if (die)
23531     {
23532       struct dwarf2_per_objfile *dwarf2_per_objfile
23533         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23534
23535       /* For .gdb_index version 7 keep track of included TUs.
23536          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23537       if (dwarf2_per_objfile->index_table != NULL
23538           && dwarf2_per_objfile->index_table->version <= 7)
23539         {
23540           VEC_safe_push (dwarf2_per_cu_ptr,
23541                          (*ref_cu)->per_cu->imported_symtabs,
23542                          sig_cu->per_cu);
23543         }
23544
23545       *ref_cu = sig_cu;
23546       if (sig_cu != cu)
23547         sig_cu->ancestor = cu;
23548
23549       return die;
23550     }
23551
23552   return NULL;
23553 }
23554
23555 /* Follow signatured type referenced by ATTR in 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    The result is the DIE of the type.
23559    If the referenced type cannot be found an error is thrown.  */
23560
23561 static struct die_info *
23562 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23563                 struct dwarf2_cu **ref_cu)
23564 {
23565   ULONGEST signature = DW_SIGNATURE (attr);
23566   struct signatured_type *sig_type;
23567   struct die_info *die;
23568
23569   gdb_assert (attr->form == DW_FORM_ref_sig8);
23570
23571   sig_type = lookup_signatured_type (*ref_cu, signature);
23572   /* sig_type will be NULL if the signatured type is missing from
23573      the debug info.  */
23574   if (sig_type == NULL)
23575     {
23576       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23577                " from DIE at %s [in module %s]"),
23578              hex_string (signature), sect_offset_str (src_die->sect_off),
23579              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23580     }
23581
23582   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23583   if (die == NULL)
23584     {
23585       dump_die_for_error (src_die);
23586       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23587                " from DIE at %s [in module %s]"),
23588              hex_string (signature), sect_offset_str (src_die->sect_off),
23589              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23590     }
23591
23592   return die;
23593 }
23594
23595 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23596    reading in and processing the type unit if necessary.  */
23597
23598 static struct type *
23599 get_signatured_type (struct die_info *die, ULONGEST signature,
23600                      struct dwarf2_cu *cu)
23601 {
23602   struct dwarf2_per_objfile *dwarf2_per_objfile
23603     = cu->per_cu->dwarf2_per_objfile;
23604   struct signatured_type *sig_type;
23605   struct dwarf2_cu *type_cu;
23606   struct die_info *type_die;
23607   struct type *type;
23608
23609   sig_type = lookup_signatured_type (cu, signature);
23610   /* sig_type will be NULL if the signatured type is missing from
23611      the debug info.  */
23612   if (sig_type == NULL)
23613     {
23614       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23615                    " from DIE at %s [in module %s]"),
23616                  hex_string (signature), sect_offset_str (die->sect_off),
23617                  objfile_name (dwarf2_per_objfile->objfile));
23618       return build_error_marker_type (cu, die);
23619     }
23620
23621   /* If we already know the type we're done.  */
23622   if (sig_type->type != NULL)
23623     return sig_type->type;
23624
23625   type_cu = cu;
23626   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23627   if (type_die != NULL)
23628     {
23629       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23630          is created.  This is important, for example, because for c++ classes
23631          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23632       type = read_type_die (type_die, type_cu);
23633       if (type == NULL)
23634         {
23635           complaint (_("Dwarf Error: Cannot build signatured type %s"
23636                        " referenced from DIE at %s [in module %s]"),
23637                      hex_string (signature), sect_offset_str (die->sect_off),
23638                      objfile_name (dwarf2_per_objfile->objfile));
23639           type = build_error_marker_type (cu, die);
23640         }
23641     }
23642   else
23643     {
23644       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23645                    " from DIE at %s [in module %s]"),
23646                  hex_string (signature), sect_offset_str (die->sect_off),
23647                  objfile_name (dwarf2_per_objfile->objfile));
23648       type = build_error_marker_type (cu, die);
23649     }
23650   sig_type->type = type;
23651
23652   return type;
23653 }
23654
23655 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23656    reading in and processing the type unit if necessary.  */
23657
23658 static struct type *
23659 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23660                           struct dwarf2_cu *cu) /* ARI: editCase function */
23661 {
23662   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23663   if (attr_form_is_ref (attr))
23664     {
23665       struct dwarf2_cu *type_cu = cu;
23666       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23667
23668       return read_type_die (type_die, type_cu);
23669     }
23670   else if (attr->form == DW_FORM_ref_sig8)
23671     {
23672       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23673     }
23674   else
23675     {
23676       struct dwarf2_per_objfile *dwarf2_per_objfile
23677         = cu->per_cu->dwarf2_per_objfile;
23678
23679       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23680                    " at %s [in module %s]"),
23681                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23682                  objfile_name (dwarf2_per_objfile->objfile));
23683       return build_error_marker_type (cu, die);
23684     }
23685 }
23686
23687 /* Load the DIEs associated with type unit PER_CU into memory.  */
23688
23689 static void
23690 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23691 {
23692   struct signatured_type *sig_type;
23693
23694   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23695   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23696
23697   /* We have the per_cu, but we need the signatured_type.
23698      Fortunately this is an easy translation.  */
23699   gdb_assert (per_cu->is_debug_types);
23700   sig_type = (struct signatured_type *) per_cu;
23701
23702   gdb_assert (per_cu->cu == NULL);
23703
23704   read_signatured_type (sig_type);
23705
23706   gdb_assert (per_cu->cu != NULL);
23707 }
23708
23709 /* die_reader_func for read_signatured_type.
23710    This is identical to load_full_comp_unit_reader,
23711    but is kept separate for now.  */
23712
23713 static void
23714 read_signatured_type_reader (const struct die_reader_specs *reader,
23715                              const gdb_byte *info_ptr,
23716                              struct die_info *comp_unit_die,
23717                              int has_children,
23718                              void *data)
23719 {
23720   struct dwarf2_cu *cu = reader->cu;
23721
23722   gdb_assert (cu->die_hash == NULL);
23723   cu->die_hash =
23724     htab_create_alloc_ex (cu->header.length / 12,
23725                           die_hash,
23726                           die_eq,
23727                           NULL,
23728                           &cu->comp_unit_obstack,
23729                           hashtab_obstack_allocate,
23730                           dummy_obstack_deallocate);
23731
23732   if (has_children)
23733     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23734                                                   &info_ptr, comp_unit_die);
23735   cu->dies = comp_unit_die;
23736   /* comp_unit_die is not stored in die_hash, no need.  */
23737
23738   /* We try not to read any attributes in this function, because not
23739      all CUs needed for references have been loaded yet, and symbol
23740      table processing isn't initialized.  But we have to set the CU language,
23741      or we won't be able to build types correctly.
23742      Similarly, if we do not read the producer, we can not apply
23743      producer-specific interpretation.  */
23744   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23745 }
23746
23747 /* Read in a signatured type and build its CU and DIEs.
23748    If the type is a stub for the real type in a DWO file,
23749    read in the real type from the DWO file as well.  */
23750
23751 static void
23752 read_signatured_type (struct signatured_type *sig_type)
23753 {
23754   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23755
23756   gdb_assert (per_cu->is_debug_types);
23757   gdb_assert (per_cu->cu == NULL);
23758
23759   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23760                            read_signatured_type_reader, NULL);
23761   sig_type->per_cu.tu_read = 1;
23762 }
23763
23764 /* Decode simple location descriptions.
23765    Given a pointer to a dwarf block that defines a location, compute
23766    the location and return the value.
23767
23768    NOTE drow/2003-11-18: This function is called in two situations
23769    now: for the address of static or global variables (partial symbols
23770    only) and for offsets into structures which are expected to be
23771    (more or less) constant.  The partial symbol case should go away,
23772    and only the constant case should remain.  That will let this
23773    function complain more accurately.  A few special modes are allowed
23774    without complaint for global variables (for instance, global
23775    register values and thread-local values).
23776
23777    A location description containing no operations indicates that the
23778    object is optimized out.  The return value is 0 for that case.
23779    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23780    callers will only want a very basic result and this can become a
23781    complaint.
23782
23783    Note that stack[0] is unused except as a default error return.  */
23784
23785 static CORE_ADDR
23786 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23787 {
23788   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23789   size_t i;
23790   size_t size = blk->size;
23791   const gdb_byte *data = blk->data;
23792   CORE_ADDR stack[64];
23793   int stacki;
23794   unsigned int bytes_read, unsnd;
23795   gdb_byte op;
23796
23797   i = 0;
23798   stacki = 0;
23799   stack[stacki] = 0;
23800   stack[++stacki] = 0;
23801
23802   while (i < size)
23803     {
23804       op = data[i++];
23805       switch (op)
23806         {
23807         case DW_OP_lit0:
23808         case DW_OP_lit1:
23809         case DW_OP_lit2:
23810         case DW_OP_lit3:
23811         case DW_OP_lit4:
23812         case DW_OP_lit5:
23813         case DW_OP_lit6:
23814         case DW_OP_lit7:
23815         case DW_OP_lit8:
23816         case DW_OP_lit9:
23817         case DW_OP_lit10:
23818         case DW_OP_lit11:
23819         case DW_OP_lit12:
23820         case DW_OP_lit13:
23821         case DW_OP_lit14:
23822         case DW_OP_lit15:
23823         case DW_OP_lit16:
23824         case DW_OP_lit17:
23825         case DW_OP_lit18:
23826         case DW_OP_lit19:
23827         case DW_OP_lit20:
23828         case DW_OP_lit21:
23829         case DW_OP_lit22:
23830         case DW_OP_lit23:
23831         case DW_OP_lit24:
23832         case DW_OP_lit25:
23833         case DW_OP_lit26:
23834         case DW_OP_lit27:
23835         case DW_OP_lit28:
23836         case DW_OP_lit29:
23837         case DW_OP_lit30:
23838         case DW_OP_lit31:
23839           stack[++stacki] = op - DW_OP_lit0;
23840           break;
23841
23842         case DW_OP_reg0:
23843         case DW_OP_reg1:
23844         case DW_OP_reg2:
23845         case DW_OP_reg3:
23846         case DW_OP_reg4:
23847         case DW_OP_reg5:
23848         case DW_OP_reg6:
23849         case DW_OP_reg7:
23850         case DW_OP_reg8:
23851         case DW_OP_reg9:
23852         case DW_OP_reg10:
23853         case DW_OP_reg11:
23854         case DW_OP_reg12:
23855         case DW_OP_reg13:
23856         case DW_OP_reg14:
23857         case DW_OP_reg15:
23858         case DW_OP_reg16:
23859         case DW_OP_reg17:
23860         case DW_OP_reg18:
23861         case DW_OP_reg19:
23862         case DW_OP_reg20:
23863         case DW_OP_reg21:
23864         case DW_OP_reg22:
23865         case DW_OP_reg23:
23866         case DW_OP_reg24:
23867         case DW_OP_reg25:
23868         case DW_OP_reg26:
23869         case DW_OP_reg27:
23870         case DW_OP_reg28:
23871         case DW_OP_reg29:
23872         case DW_OP_reg30:
23873         case DW_OP_reg31:
23874           stack[++stacki] = op - DW_OP_reg0;
23875           if (i < size)
23876             dwarf2_complex_location_expr_complaint ();
23877           break;
23878
23879         case DW_OP_regx:
23880           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23881           i += bytes_read;
23882           stack[++stacki] = unsnd;
23883           if (i < size)
23884             dwarf2_complex_location_expr_complaint ();
23885           break;
23886
23887         case DW_OP_addr:
23888           stack[++stacki] = read_address (objfile->obfd, &data[i],
23889                                           cu, &bytes_read);
23890           i += bytes_read;
23891           break;
23892
23893         case DW_OP_const1u:
23894           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23895           i += 1;
23896           break;
23897
23898         case DW_OP_const1s:
23899           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23900           i += 1;
23901           break;
23902
23903         case DW_OP_const2u:
23904           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23905           i += 2;
23906           break;
23907
23908         case DW_OP_const2s:
23909           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23910           i += 2;
23911           break;
23912
23913         case DW_OP_const4u:
23914           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23915           i += 4;
23916           break;
23917
23918         case DW_OP_const4s:
23919           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23920           i += 4;
23921           break;
23922
23923         case DW_OP_const8u:
23924           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23925           i += 8;
23926           break;
23927
23928         case DW_OP_constu:
23929           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23930                                                   &bytes_read);
23931           i += bytes_read;
23932           break;
23933
23934         case DW_OP_consts:
23935           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23936           i += bytes_read;
23937           break;
23938
23939         case DW_OP_dup:
23940           stack[stacki + 1] = stack[stacki];
23941           stacki++;
23942           break;
23943
23944         case DW_OP_plus:
23945           stack[stacki - 1] += stack[stacki];
23946           stacki--;
23947           break;
23948
23949         case DW_OP_plus_uconst:
23950           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23951                                                  &bytes_read);
23952           i += bytes_read;
23953           break;
23954
23955         case DW_OP_minus:
23956           stack[stacki - 1] -= stack[stacki];
23957           stacki--;
23958           break;
23959
23960         case DW_OP_deref:
23961           /* If we're not the last op, then we definitely can't encode
23962              this using GDB's address_class enum.  This is valid for partial
23963              global symbols, although the variable's address will be bogus
23964              in the psymtab.  */
23965           if (i < size)
23966             dwarf2_complex_location_expr_complaint ();
23967           break;
23968
23969         case DW_OP_GNU_push_tls_address:
23970         case DW_OP_form_tls_address:
23971           /* The top of the stack has the offset from the beginning
23972              of the thread control block at which the variable is located.  */
23973           /* Nothing should follow this operator, so the top of stack would
23974              be returned.  */
23975           /* This is valid for partial global symbols, but the variable's
23976              address will be bogus in the psymtab.  Make it always at least
23977              non-zero to not look as a variable garbage collected by linker
23978              which have DW_OP_addr 0.  */
23979           if (i < size)
23980             dwarf2_complex_location_expr_complaint ();
23981           stack[stacki]++;
23982           break;
23983
23984         case DW_OP_GNU_uninit:
23985           break;
23986
23987         case DW_OP_addrx:
23988         case DW_OP_GNU_addr_index:
23989         case DW_OP_GNU_const_index:
23990           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23991                                                          &bytes_read);
23992           i += bytes_read;
23993           break;
23994
23995         default:
23996           {
23997             const char *name = get_DW_OP_name (op);
23998
23999             if (name)
24000               complaint (_("unsupported stack op: '%s'"),
24001                          name);
24002             else
24003               complaint (_("unsupported stack op: '%02x'"),
24004                          op);
24005           }
24006
24007           return (stack[stacki]);
24008         }
24009
24010       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24011          outside of the allocated space.  Also enforce minimum>0.  */
24012       if (stacki >= ARRAY_SIZE (stack) - 1)
24013         {
24014           complaint (_("location description stack overflow"));
24015           return 0;
24016         }
24017
24018       if (stacki <= 0)
24019         {
24020           complaint (_("location description stack underflow"));
24021           return 0;
24022         }
24023     }
24024   return (stack[stacki]);
24025 }
24026
24027 /* memory allocation interface */
24028
24029 static struct dwarf_block *
24030 dwarf_alloc_block (struct dwarf2_cu *cu)
24031 {
24032   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24033 }
24034
24035 static struct die_info *
24036 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24037 {
24038   struct die_info *die;
24039   size_t size = sizeof (struct die_info);
24040
24041   if (num_attrs > 1)
24042     size += (num_attrs - 1) * sizeof (struct attribute);
24043
24044   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24045   memset (die, 0, sizeof (struct die_info));
24046   return (die);
24047 }
24048
24049 \f
24050 /* Macro support.  */
24051
24052 /* Return file name relative to the compilation directory of file number I in
24053    *LH's file name table.  The result is allocated using xmalloc; the caller is
24054    responsible for freeing it.  */
24055
24056 static char *
24057 file_file_name (int file, struct line_header *lh)
24058 {
24059   /* Is the file number a valid index into the line header's file name
24060      table?  Remember that file numbers start with one, not zero.  */
24061   if (1 <= file && file <= lh->file_names.size ())
24062     {
24063       const file_entry &fe = lh->file_names[file - 1];
24064
24065       if (!IS_ABSOLUTE_PATH (fe.name))
24066         {
24067           const char *dir = fe.include_dir (lh);
24068           if (dir != NULL)
24069             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
24070         }
24071       return xstrdup (fe.name);
24072     }
24073   else
24074     {
24075       /* The compiler produced a bogus file number.  We can at least
24076          record the macro definitions made in the file, even if we
24077          won't be able to find the file by name.  */
24078       char fake_name[80];
24079
24080       xsnprintf (fake_name, sizeof (fake_name),
24081                  "<bad macro file number %d>", file);
24082
24083       complaint (_("bad file number in macro information (%d)"),
24084                  file);
24085
24086       return xstrdup (fake_name);
24087     }
24088 }
24089
24090 /* Return the full name of file number I in *LH's file name table.
24091    Use COMP_DIR as the name of the current directory of the
24092    compilation.  The result is allocated using xmalloc; the caller is
24093    responsible for freeing it.  */
24094 static char *
24095 file_full_name (int file, struct line_header *lh, const char *comp_dir)
24096 {
24097   /* Is the file number a valid index into the line header's file name
24098      table?  Remember that file numbers start with one, not zero.  */
24099   if (1 <= file && file <= lh->file_names.size ())
24100     {
24101       char *relative = file_file_name (file, lh);
24102
24103       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
24104         return relative;
24105       return reconcat (relative, comp_dir, SLASH_STRING,
24106                        relative, (char *) NULL);
24107     }
24108   else
24109     return file_file_name (file, lh);
24110 }
24111
24112
24113 static struct macro_source_file *
24114 macro_start_file (struct dwarf2_cu *cu,
24115                   int file, int line,
24116                   struct macro_source_file *current_file,
24117                   struct line_header *lh)
24118 {
24119   /* File name relative to the compilation directory of this source file.  */
24120   char *file_name = file_file_name (file, lh);
24121
24122   if (! current_file)
24123     {
24124       /* Note: We don't create a macro table for this compilation unit
24125          at all until we actually get a filename.  */
24126       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
24127
24128       /* If we have no current file, then this must be the start_file
24129          directive for the compilation unit's main source file.  */
24130       current_file = macro_set_main (macro_table, file_name);
24131       macro_define_special (macro_table);
24132     }
24133   else
24134     current_file = macro_include (current_file, line, file_name);
24135
24136   xfree (file_name);
24137
24138   return current_file;
24139 }
24140
24141 static const char *
24142 consume_improper_spaces (const char *p, const char *body)
24143 {
24144   if (*p == ' ')
24145     {
24146       complaint (_("macro definition contains spaces "
24147                    "in formal argument list:\n`%s'"),
24148                  body);
24149
24150       while (*p == ' ')
24151         p++;
24152     }
24153
24154   return p;
24155 }
24156
24157
24158 static void
24159 parse_macro_definition (struct macro_source_file *file, int line,
24160                         const char *body)
24161 {
24162   const char *p;
24163
24164   /* The body string takes one of two forms.  For object-like macro
24165      definitions, it should be:
24166
24167         <macro name> " " <definition>
24168
24169      For function-like macro definitions, it should be:
24170
24171         <macro name> "() " <definition>
24172      or
24173         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24174
24175      Spaces may appear only where explicitly indicated, and in the
24176      <definition>.
24177
24178      The Dwarf 2 spec says that an object-like macro's name is always
24179      followed by a space, but versions of GCC around March 2002 omit
24180      the space when the macro's definition is the empty string.
24181
24182      The Dwarf 2 spec says that there should be no spaces between the
24183      formal arguments in a function-like macro's formal argument list,
24184      but versions of GCC around March 2002 include spaces after the
24185      commas.  */
24186
24187
24188   /* Find the extent of the macro name.  The macro name is terminated
24189      by either a space or null character (for an object-like macro) or
24190      an opening paren (for a function-like macro).  */
24191   for (p = body; *p; p++)
24192     if (*p == ' ' || *p == '(')
24193       break;
24194
24195   if (*p == ' ' || *p == '\0')
24196     {
24197       /* It's an object-like macro.  */
24198       int name_len = p - body;
24199       char *name = savestring (body, name_len);
24200       const char *replacement;
24201
24202       if (*p == ' ')
24203         replacement = body + name_len + 1;
24204       else
24205         {
24206           dwarf2_macro_malformed_definition_complaint (body);
24207           replacement = body + name_len;
24208         }
24209
24210       macro_define_object (file, line, name, replacement);
24211
24212       xfree (name);
24213     }
24214   else if (*p == '(')
24215     {
24216       /* It's a function-like macro.  */
24217       char *name = savestring (body, p - body);
24218       int argc = 0;
24219       int argv_size = 1;
24220       char **argv = XNEWVEC (char *, argv_size);
24221
24222       p++;
24223
24224       p = consume_improper_spaces (p, body);
24225
24226       /* Parse the formal argument list.  */
24227       while (*p && *p != ')')
24228         {
24229           /* Find the extent of the current argument name.  */
24230           const char *arg_start = p;
24231
24232           while (*p && *p != ',' && *p != ')' && *p != ' ')
24233             p++;
24234
24235           if (! *p || p == arg_start)
24236             dwarf2_macro_malformed_definition_complaint (body);
24237           else
24238             {
24239               /* Make sure argv has room for the new argument.  */
24240               if (argc >= argv_size)
24241                 {
24242                   argv_size *= 2;
24243                   argv = XRESIZEVEC (char *, argv, argv_size);
24244                 }
24245
24246               argv[argc++] = savestring (arg_start, p - arg_start);
24247             }
24248
24249           p = consume_improper_spaces (p, body);
24250
24251           /* Consume the comma, if present.  */
24252           if (*p == ',')
24253             {
24254               p++;
24255
24256               p = consume_improper_spaces (p, body);
24257             }
24258         }
24259
24260       if (*p == ')')
24261         {
24262           p++;
24263
24264           if (*p == ' ')
24265             /* Perfectly formed definition, no complaints.  */
24266             macro_define_function (file, line, name,
24267                                    argc, (const char **) argv,
24268                                    p + 1);
24269           else if (*p == '\0')
24270             {
24271               /* Complain, but do define it.  */
24272               dwarf2_macro_malformed_definition_complaint (body);
24273               macro_define_function (file, line, name,
24274                                      argc, (const char **) argv,
24275                                      p);
24276             }
24277           else
24278             /* Just complain.  */
24279             dwarf2_macro_malformed_definition_complaint (body);
24280         }
24281       else
24282         /* Just complain.  */
24283         dwarf2_macro_malformed_definition_complaint (body);
24284
24285       xfree (name);
24286       {
24287         int i;
24288
24289         for (i = 0; i < argc; i++)
24290           xfree (argv[i]);
24291       }
24292       xfree (argv);
24293     }
24294   else
24295     dwarf2_macro_malformed_definition_complaint (body);
24296 }
24297
24298 /* Skip some bytes from BYTES according to the form given in FORM.
24299    Returns the new pointer.  */
24300
24301 static const gdb_byte *
24302 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24303                  enum dwarf_form form,
24304                  unsigned int offset_size,
24305                  struct dwarf2_section_info *section)
24306 {
24307   unsigned int bytes_read;
24308
24309   switch (form)
24310     {
24311     case DW_FORM_data1:
24312     case DW_FORM_flag:
24313       ++bytes;
24314       break;
24315
24316     case DW_FORM_data2:
24317       bytes += 2;
24318       break;
24319
24320     case DW_FORM_data4:
24321       bytes += 4;
24322       break;
24323
24324     case DW_FORM_data8:
24325       bytes += 8;
24326       break;
24327
24328     case DW_FORM_data16:
24329       bytes += 16;
24330       break;
24331
24332     case DW_FORM_string:
24333       read_direct_string (abfd, bytes, &bytes_read);
24334       bytes += bytes_read;
24335       break;
24336
24337     case DW_FORM_sec_offset:
24338     case DW_FORM_strp:
24339     case DW_FORM_GNU_strp_alt:
24340       bytes += offset_size;
24341       break;
24342
24343     case DW_FORM_block:
24344       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24345       bytes += bytes_read;
24346       break;
24347
24348     case DW_FORM_block1:
24349       bytes += 1 + read_1_byte (abfd, bytes);
24350       break;
24351     case DW_FORM_block2:
24352       bytes += 2 + read_2_bytes (abfd, bytes);
24353       break;
24354     case DW_FORM_block4:
24355       bytes += 4 + read_4_bytes (abfd, bytes);
24356       break;
24357
24358     case DW_FORM_addrx:
24359     case DW_FORM_sdata:
24360     case DW_FORM_strx:
24361     case DW_FORM_udata:
24362     case DW_FORM_GNU_addr_index:
24363     case DW_FORM_GNU_str_index:
24364       bytes = gdb_skip_leb128 (bytes, buffer_end);
24365       if (bytes == NULL)
24366         {
24367           dwarf2_section_buffer_overflow_complaint (section);
24368           return NULL;
24369         }
24370       break;
24371
24372     case DW_FORM_implicit_const:
24373       break;
24374
24375     default:
24376       {
24377         complaint (_("invalid form 0x%x in `%s'"),
24378                    form, get_section_name (section));
24379         return NULL;
24380       }
24381     }
24382
24383   return bytes;
24384 }
24385
24386 /* A helper for dwarf_decode_macros that handles skipping an unknown
24387    opcode.  Returns an updated pointer to the macro data buffer; or,
24388    on error, issues a complaint and returns NULL.  */
24389
24390 static const gdb_byte *
24391 skip_unknown_opcode (unsigned int opcode,
24392                      const gdb_byte **opcode_definitions,
24393                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24394                      bfd *abfd,
24395                      unsigned int offset_size,
24396                      struct dwarf2_section_info *section)
24397 {
24398   unsigned int bytes_read, i;
24399   unsigned long arg;
24400   const gdb_byte *defn;
24401
24402   if (opcode_definitions[opcode] == NULL)
24403     {
24404       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24405                  opcode);
24406       return NULL;
24407     }
24408
24409   defn = opcode_definitions[opcode];
24410   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24411   defn += bytes_read;
24412
24413   for (i = 0; i < arg; ++i)
24414     {
24415       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24416                                  (enum dwarf_form) defn[i], offset_size,
24417                                  section);
24418       if (mac_ptr == NULL)
24419         {
24420           /* skip_form_bytes already issued the complaint.  */
24421           return NULL;
24422         }
24423     }
24424
24425   return mac_ptr;
24426 }
24427
24428 /* A helper function which parses the header of a macro section.
24429    If the macro section is the extended (for now called "GNU") type,
24430    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24431    the header, or issues a complaint and returns NULL on error.  */
24432
24433 static const gdb_byte *
24434 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24435                           bfd *abfd,
24436                           const gdb_byte *mac_ptr,
24437                           unsigned int *offset_size,
24438                           int section_is_gnu)
24439 {
24440   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24441
24442   if (section_is_gnu)
24443     {
24444       unsigned int version, flags;
24445
24446       version = read_2_bytes (abfd, mac_ptr);
24447       if (version != 4 && version != 5)
24448         {
24449           complaint (_("unrecognized version `%d' in .debug_macro section"),
24450                      version);
24451           return NULL;
24452         }
24453       mac_ptr += 2;
24454
24455       flags = read_1_byte (abfd, mac_ptr);
24456       ++mac_ptr;
24457       *offset_size = (flags & 1) ? 8 : 4;
24458
24459       if ((flags & 2) != 0)
24460         /* We don't need the line table offset.  */
24461         mac_ptr += *offset_size;
24462
24463       /* Vendor opcode descriptions.  */
24464       if ((flags & 4) != 0)
24465         {
24466           unsigned int i, count;
24467
24468           count = read_1_byte (abfd, mac_ptr);
24469           ++mac_ptr;
24470           for (i = 0; i < count; ++i)
24471             {
24472               unsigned int opcode, bytes_read;
24473               unsigned long arg;
24474
24475               opcode = read_1_byte (abfd, mac_ptr);
24476               ++mac_ptr;
24477               opcode_definitions[opcode] = mac_ptr;
24478               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24479               mac_ptr += bytes_read;
24480               mac_ptr += arg;
24481             }
24482         }
24483     }
24484
24485   return mac_ptr;
24486 }
24487
24488 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24489    including DW_MACRO_import.  */
24490
24491 static void
24492 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24493                           bfd *abfd,
24494                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24495                           struct macro_source_file *current_file,
24496                           struct line_header *lh,
24497                           struct dwarf2_section_info *section,
24498                           int section_is_gnu, int section_is_dwz,
24499                           unsigned int offset_size,
24500                           htab_t include_hash)
24501 {
24502   struct dwarf2_per_objfile *dwarf2_per_objfile
24503     = cu->per_cu->dwarf2_per_objfile;
24504   struct objfile *objfile = dwarf2_per_objfile->objfile;
24505   enum dwarf_macro_record_type macinfo_type;
24506   int at_commandline;
24507   const gdb_byte *opcode_definitions[256];
24508
24509   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24510                                       &offset_size, section_is_gnu);
24511   if (mac_ptr == NULL)
24512     {
24513       /* We already issued a complaint.  */
24514       return;
24515     }
24516
24517   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24518      GDB is still reading the definitions from command line.  First
24519      DW_MACINFO_start_file will need to be ignored as it was already executed
24520      to create CURRENT_FILE for the main source holding also the command line
24521      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24522      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24523
24524   at_commandline = 1;
24525
24526   do
24527     {
24528       /* Do we at least have room for a macinfo type byte?  */
24529       if (mac_ptr >= mac_end)
24530         {
24531           dwarf2_section_buffer_overflow_complaint (section);
24532           break;
24533         }
24534
24535       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24536       mac_ptr++;
24537
24538       /* Note that we rely on the fact that the corresponding GNU and
24539          DWARF constants are the same.  */
24540       DIAGNOSTIC_PUSH
24541       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24542       switch (macinfo_type)
24543         {
24544           /* A zero macinfo type indicates the end of the macro
24545              information.  */
24546         case 0:
24547           break;
24548
24549         case DW_MACRO_define:
24550         case DW_MACRO_undef:
24551         case DW_MACRO_define_strp:
24552         case DW_MACRO_undef_strp:
24553         case DW_MACRO_define_sup:
24554         case DW_MACRO_undef_sup:
24555           {
24556             unsigned int bytes_read;
24557             int line;
24558             const char *body;
24559             int is_define;
24560
24561             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24562             mac_ptr += bytes_read;
24563
24564             if (macinfo_type == DW_MACRO_define
24565                 || macinfo_type == DW_MACRO_undef)
24566               {
24567                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24568                 mac_ptr += bytes_read;
24569               }
24570             else
24571               {
24572                 LONGEST str_offset;
24573
24574                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24575                 mac_ptr += offset_size;
24576
24577                 if (macinfo_type == DW_MACRO_define_sup
24578                     || macinfo_type == DW_MACRO_undef_sup
24579                     || section_is_dwz)
24580                   {
24581                     struct dwz_file *dwz
24582                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24583
24584                     body = read_indirect_string_from_dwz (objfile,
24585                                                           dwz, str_offset);
24586                   }
24587                 else
24588                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24589                                                          abfd, str_offset);
24590               }
24591
24592             is_define = (macinfo_type == DW_MACRO_define
24593                          || macinfo_type == DW_MACRO_define_strp
24594                          || macinfo_type == DW_MACRO_define_sup);
24595             if (! current_file)
24596               {
24597                 /* DWARF violation as no main source is present.  */
24598                 complaint (_("debug info with no main source gives macro %s "
24599                              "on line %d: %s"),
24600                            is_define ? _("definition") : _("undefinition"),
24601                            line, body);
24602                 break;
24603               }
24604             if ((line == 0 && !at_commandline)
24605                 || (line != 0 && at_commandline))
24606               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24607                          at_commandline ? _("command-line") : _("in-file"),
24608                          is_define ? _("definition") : _("undefinition"),
24609                          line == 0 ? _("zero") : _("non-zero"), line, body);
24610
24611             if (is_define)
24612               {
24613                 if (body != NULL)
24614                   parse_macro_definition (current_file, line, body);
24615                 else
24616                   {
24617                     /* Fedora's rpm-build's "debugedit" binary
24618                        corrupted .debug_macro sections.
24619
24620                        For more info, see
24621                        https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
24622                     complaint (_("debug info gives %s invalid macro definition "
24623                                  "without body (corrupted?) at line %d"
24624                                  "on file %s"),
24625                                at_commandline ? _("command-line")
24626                                : _("in-file"),
24627                                line, current_file->filename);
24628                   }
24629               }
24630             else
24631               {
24632                 gdb_assert (macinfo_type == DW_MACRO_undef
24633                             || macinfo_type == DW_MACRO_undef_strp
24634                             || macinfo_type == DW_MACRO_undef_sup);
24635                 macro_undef (current_file, line, body);
24636               }
24637           }
24638           break;
24639
24640         case DW_MACRO_start_file:
24641           {
24642             unsigned int bytes_read;
24643             int line, file;
24644
24645             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24646             mac_ptr += bytes_read;
24647             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24648             mac_ptr += bytes_read;
24649
24650             if ((line == 0 && !at_commandline)
24651                 || (line != 0 && at_commandline))
24652               complaint (_("debug info gives source %d included "
24653                            "from %s at %s line %d"),
24654                          file, at_commandline ? _("command-line") : _("file"),
24655                          line == 0 ? _("zero") : _("non-zero"), line);
24656
24657             if (at_commandline)
24658               {
24659                 /* This DW_MACRO_start_file was executed in the
24660                    pass one.  */
24661                 at_commandline = 0;
24662               }
24663             else
24664               current_file = macro_start_file (cu, file, line, current_file,
24665                                                lh);
24666           }
24667           break;
24668
24669         case DW_MACRO_end_file:
24670           if (! current_file)
24671             complaint (_("macro debug info has an unmatched "
24672                          "`close_file' directive"));
24673           else
24674             {
24675               current_file = current_file->included_by;
24676               if (! current_file)
24677                 {
24678                   enum dwarf_macro_record_type next_type;
24679
24680                   /* GCC circa March 2002 doesn't produce the zero
24681                      type byte marking the end of the compilation
24682                      unit.  Complain if it's not there, but exit no
24683                      matter what.  */
24684
24685                   /* Do we at least have room for a macinfo type byte?  */
24686                   if (mac_ptr >= mac_end)
24687                     {
24688                       dwarf2_section_buffer_overflow_complaint (section);
24689                       return;
24690                     }
24691
24692                   /* We don't increment mac_ptr here, so this is just
24693                      a look-ahead.  */
24694                   next_type
24695                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24696                                                                   mac_ptr);
24697                   if (next_type != 0)
24698                     complaint (_("no terminating 0-type entry for "
24699                                  "macros in `.debug_macinfo' section"));
24700
24701                   return;
24702                 }
24703             }
24704           break;
24705
24706         case DW_MACRO_import:
24707         case DW_MACRO_import_sup:
24708           {
24709             LONGEST offset;
24710             void **slot;
24711             bfd *include_bfd = abfd;
24712             struct dwarf2_section_info *include_section = section;
24713             const gdb_byte *include_mac_end = mac_end;
24714             int is_dwz = section_is_dwz;
24715             const gdb_byte *new_mac_ptr;
24716
24717             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24718             mac_ptr += offset_size;
24719
24720             if (macinfo_type == DW_MACRO_import_sup)
24721               {
24722                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24723
24724                 dwarf2_read_section (objfile, &dwz->macro);
24725
24726                 include_section = &dwz->macro;
24727                 include_bfd = get_section_bfd_owner (include_section);
24728                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24729                 is_dwz = 1;
24730               }
24731
24732             new_mac_ptr = include_section->buffer + offset;
24733             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24734
24735             if (*slot != NULL)
24736               {
24737                 /* This has actually happened; see
24738                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24739                 complaint (_("recursive DW_MACRO_import in "
24740                              ".debug_macro section"));
24741               }
24742             else
24743               {
24744                 *slot = (void *) new_mac_ptr;
24745
24746                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24747                                           include_mac_end, current_file, lh,
24748                                           section, section_is_gnu, is_dwz,
24749                                           offset_size, include_hash);
24750
24751                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24752               }
24753           }
24754           break;
24755
24756         case DW_MACINFO_vendor_ext:
24757           if (!section_is_gnu)
24758             {
24759               unsigned int bytes_read;
24760
24761               /* This reads the constant, but since we don't recognize
24762                  any vendor extensions, we ignore it.  */
24763               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24764               mac_ptr += bytes_read;
24765               read_direct_string (abfd, mac_ptr, &bytes_read);
24766               mac_ptr += bytes_read;
24767
24768               /* We don't recognize any vendor extensions.  */
24769               break;
24770             }
24771           /* FALLTHROUGH */
24772
24773         default:
24774           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24775                                          mac_ptr, mac_end, abfd, offset_size,
24776                                          section);
24777           if (mac_ptr == NULL)
24778             return;
24779           break;
24780         }
24781       DIAGNOSTIC_POP
24782     } while (macinfo_type != 0);
24783 }
24784
24785 static void
24786 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24787                      int section_is_gnu)
24788 {
24789   struct dwarf2_per_objfile *dwarf2_per_objfile
24790     = cu->per_cu->dwarf2_per_objfile;
24791   struct objfile *objfile = dwarf2_per_objfile->objfile;
24792   struct line_header *lh = cu->line_header;
24793   bfd *abfd;
24794   const gdb_byte *mac_ptr, *mac_end;
24795   struct macro_source_file *current_file = 0;
24796   enum dwarf_macro_record_type macinfo_type;
24797   unsigned int offset_size = cu->header.offset_size;
24798   const gdb_byte *opcode_definitions[256];
24799   void **slot;
24800   struct dwarf2_section_info *section;
24801   const char *section_name;
24802
24803   if (cu->dwo_unit != NULL)
24804     {
24805       if (section_is_gnu)
24806         {
24807           section = &cu->dwo_unit->dwo_file->sections.macro;
24808           section_name = ".debug_macro.dwo";
24809         }
24810       else
24811         {
24812           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24813           section_name = ".debug_macinfo.dwo";
24814         }
24815     }
24816   else
24817     {
24818       if (section_is_gnu)
24819         {
24820           section = &dwarf2_per_objfile->macro;
24821           section_name = ".debug_macro";
24822         }
24823       else
24824         {
24825           section = &dwarf2_per_objfile->macinfo;
24826           section_name = ".debug_macinfo";
24827         }
24828     }
24829
24830   dwarf2_read_section (objfile, section);
24831   if (section->buffer == NULL)
24832     {
24833       complaint (_("missing %s section"), section_name);
24834       return;
24835     }
24836   abfd = get_section_bfd_owner (section);
24837
24838   /* First pass: Find the name of the base filename.
24839      This filename is needed in order to process all macros whose definition
24840      (or undefinition) comes from the command line.  These macros are defined
24841      before the first DW_MACINFO_start_file entry, and yet still need to be
24842      associated to the base file.
24843
24844      To determine the base file name, we scan the macro definitions until we
24845      reach the first DW_MACINFO_start_file entry.  We then initialize
24846      CURRENT_FILE accordingly so that any macro definition found before the
24847      first DW_MACINFO_start_file can still be associated to the base file.  */
24848
24849   mac_ptr = section->buffer + offset;
24850   mac_end = section->buffer + section->size;
24851
24852   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24853                                       &offset_size, section_is_gnu);
24854   if (mac_ptr == NULL)
24855     {
24856       /* We already issued a complaint.  */
24857       return;
24858     }
24859
24860   do
24861     {
24862       /* Do we at least have room for a macinfo type byte?  */
24863       if (mac_ptr >= mac_end)
24864         {
24865           /* Complaint is printed during the second pass as GDB will probably
24866              stop the first pass earlier upon finding
24867              DW_MACINFO_start_file.  */
24868           break;
24869         }
24870
24871       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24872       mac_ptr++;
24873
24874       /* Note that we rely on the fact that the corresponding GNU and
24875          DWARF constants are the same.  */
24876       DIAGNOSTIC_PUSH
24877       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24878       switch (macinfo_type)
24879         {
24880           /* A zero macinfo type indicates the end of the macro
24881              information.  */
24882         case 0:
24883           break;
24884
24885         case DW_MACRO_define:
24886         case DW_MACRO_undef:
24887           /* Only skip the data by MAC_PTR.  */
24888           {
24889             unsigned int bytes_read;
24890
24891             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24892             mac_ptr += bytes_read;
24893             read_direct_string (abfd, mac_ptr, &bytes_read);
24894             mac_ptr += bytes_read;
24895           }
24896           break;
24897
24898         case DW_MACRO_start_file:
24899           {
24900             unsigned int bytes_read;
24901             int line, file;
24902
24903             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24904             mac_ptr += bytes_read;
24905             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24906             mac_ptr += bytes_read;
24907
24908             current_file = macro_start_file (cu, file, line, current_file, lh);
24909           }
24910           break;
24911
24912         case DW_MACRO_end_file:
24913           /* No data to skip by MAC_PTR.  */
24914           break;
24915
24916         case DW_MACRO_define_strp:
24917         case DW_MACRO_undef_strp:
24918         case DW_MACRO_define_sup:
24919         case DW_MACRO_undef_sup:
24920           {
24921             unsigned int bytes_read;
24922
24923             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24924             mac_ptr += bytes_read;
24925             mac_ptr += offset_size;
24926           }
24927           break;
24928
24929         case DW_MACRO_import:
24930         case DW_MACRO_import_sup:
24931           /* Note that, according to the spec, a transparent include
24932              chain cannot call DW_MACRO_start_file.  So, we can just
24933              skip this opcode.  */
24934           mac_ptr += offset_size;
24935           break;
24936
24937         case DW_MACINFO_vendor_ext:
24938           /* Only skip the data by MAC_PTR.  */
24939           if (!section_is_gnu)
24940             {
24941               unsigned int bytes_read;
24942
24943               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24944               mac_ptr += bytes_read;
24945               read_direct_string (abfd, mac_ptr, &bytes_read);
24946               mac_ptr += bytes_read;
24947             }
24948           /* FALLTHROUGH */
24949
24950         default:
24951           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24952                                          mac_ptr, mac_end, abfd, offset_size,
24953                                          section);
24954           if (mac_ptr == NULL)
24955             return;
24956           break;
24957         }
24958       DIAGNOSTIC_POP
24959     } while (macinfo_type != 0 && current_file == NULL);
24960
24961   /* Second pass: Process all entries.
24962
24963      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24964      command-line macro definitions/undefinitions.  This flag is unset when we
24965      reach the first DW_MACINFO_start_file entry.  */
24966
24967   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24968                                            htab_eq_pointer,
24969                                            NULL, xcalloc, xfree));
24970   mac_ptr = section->buffer + offset;
24971   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24972   *slot = (void *) mac_ptr;
24973   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24974                             current_file, lh, section,
24975                             section_is_gnu, 0, offset_size,
24976                             include_hash.get ());
24977 }
24978
24979 /* Check if the attribute's form is a DW_FORM_block*
24980    if so return true else false.  */
24981
24982 static int
24983 attr_form_is_block (const struct attribute *attr)
24984 {
24985   return (attr == NULL ? 0 :
24986       attr->form == DW_FORM_block1
24987       || attr->form == DW_FORM_block2
24988       || attr->form == DW_FORM_block4
24989       || attr->form == DW_FORM_block
24990       || attr->form == DW_FORM_exprloc);
24991 }
24992
24993 /* Return non-zero if ATTR's value is a section offset --- classes
24994    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24995    You may use DW_UNSND (attr) to retrieve such offsets.
24996
24997    Section 7.5.4, "Attribute Encodings", explains that no attribute
24998    may have a value that belongs to more than one of these classes; it
24999    would be ambiguous if we did, because we use the same forms for all
25000    of them.  */
25001
25002 static int
25003 attr_form_is_section_offset (const struct attribute *attr)
25004 {
25005   return (attr->form == DW_FORM_data4
25006           || attr->form == DW_FORM_data8
25007           || attr->form == DW_FORM_sec_offset);
25008 }
25009
25010 /* Return non-zero if ATTR's value falls in the 'constant' class, or
25011    zero otherwise.  When this function returns true, you can apply
25012    dwarf2_get_attr_constant_value to it.
25013
25014    However, note that for some attributes you must check
25015    attr_form_is_section_offset before using this test.  DW_FORM_data4
25016    and DW_FORM_data8 are members of both the constant class, and of
25017    the classes that contain offsets into other debug sections
25018    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
25019    that, if an attribute's can be either a constant or one of the
25020    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
25021    taken as section offsets, not constants.
25022
25023    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
25024    cannot handle that.  */
25025
25026 static int
25027 attr_form_is_constant (const struct attribute *attr)
25028 {
25029   switch (attr->form)
25030     {
25031     case DW_FORM_sdata:
25032     case DW_FORM_udata:
25033     case DW_FORM_data1:
25034     case DW_FORM_data2:
25035     case DW_FORM_data4:
25036     case DW_FORM_data8:
25037     case DW_FORM_implicit_const:
25038       return 1;
25039     default:
25040       return 0;
25041     }
25042 }
25043
25044
25045 /* DW_ADDR is always stored already as sect_offset; despite for the forms
25046    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
25047
25048 static int
25049 attr_form_is_ref (const struct attribute *attr)
25050 {
25051   switch (attr->form)
25052     {
25053     case DW_FORM_ref_addr:
25054     case DW_FORM_ref1:
25055     case DW_FORM_ref2:
25056     case DW_FORM_ref4:
25057     case DW_FORM_ref8:
25058     case DW_FORM_ref_udata:
25059     case DW_FORM_GNU_ref_alt:
25060       return 1;
25061     default:
25062       return 0;
25063     }
25064 }
25065
25066 /* Return the .debug_loc section to use for CU.
25067    For DWO files use .debug_loc.dwo.  */
25068
25069 static struct dwarf2_section_info *
25070 cu_debug_loc_section (struct dwarf2_cu *cu)
25071 {
25072   struct dwarf2_per_objfile *dwarf2_per_objfile
25073     = cu->per_cu->dwarf2_per_objfile;
25074
25075   if (cu->dwo_unit)
25076     {
25077       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
25078       
25079       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
25080     }
25081   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
25082                                   : &dwarf2_per_objfile->loc);
25083 }
25084
25085 /* A helper function that fills in a dwarf2_loclist_baton.  */
25086
25087 static void
25088 fill_in_loclist_baton (struct dwarf2_cu *cu,
25089                        struct dwarf2_loclist_baton *baton,
25090                        const struct attribute *attr)
25091 {
25092   struct dwarf2_per_objfile *dwarf2_per_objfile
25093     = cu->per_cu->dwarf2_per_objfile;
25094   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25095
25096   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
25097
25098   baton->per_cu = cu->per_cu;
25099   gdb_assert (baton->per_cu);
25100   /* We don't know how long the location list is, but make sure we
25101      don't run off the edge of the section.  */
25102   baton->size = section->size - DW_UNSND (attr);
25103   baton->data = section->buffer + DW_UNSND (attr);
25104   baton->base_address = cu->base_address;
25105   baton->from_dwo = cu->dwo_unit != NULL;
25106 }
25107
25108 static void
25109 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
25110                              struct dwarf2_cu *cu, int is_block)
25111 {
25112   struct dwarf2_per_objfile *dwarf2_per_objfile
25113     = cu->per_cu->dwarf2_per_objfile;
25114   struct objfile *objfile = dwarf2_per_objfile->objfile;
25115   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25116
25117   if (attr_form_is_section_offset (attr)
25118       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
25119          the section.  If so, fall through to the complaint in the
25120          other branch.  */
25121       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
25122     {
25123       struct dwarf2_loclist_baton *baton;
25124
25125       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
25126
25127       fill_in_loclist_baton (cu, baton, attr);
25128
25129       if (cu->base_known == 0)
25130         complaint (_("Location list used without "
25131                      "specifying the CU base address."));
25132
25133       SYMBOL_ACLASS_INDEX (sym) = (is_block
25134                                    ? dwarf2_loclist_block_index
25135                                    : dwarf2_loclist_index);
25136       SYMBOL_LOCATION_BATON (sym) = baton;
25137     }
25138   else
25139     {
25140       struct dwarf2_locexpr_baton *baton;
25141
25142       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25143       baton->per_cu = cu->per_cu;
25144       gdb_assert (baton->per_cu);
25145
25146       if (attr_form_is_block (attr))
25147         {
25148           /* Note that we're just copying the block's data pointer
25149              here, not the actual data.  We're still pointing into the
25150              info_buffer for SYM's objfile; right now we never release
25151              that buffer, but when we do clean up properly this may
25152              need to change.  */
25153           baton->size = DW_BLOCK (attr)->size;
25154           baton->data = DW_BLOCK (attr)->data;
25155         }
25156       else
25157         {
25158           dwarf2_invalid_attrib_class_complaint ("location description",
25159                                                  SYMBOL_NATURAL_NAME (sym));
25160           baton->size = 0;
25161         }
25162
25163       SYMBOL_ACLASS_INDEX (sym) = (is_block
25164                                    ? dwarf2_locexpr_block_index
25165                                    : dwarf2_locexpr_index);
25166       SYMBOL_LOCATION_BATON (sym) = baton;
25167     }
25168 }
25169
25170 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25171    came from a separate debuginfo file, then the master objfile is
25172    returned.  */
25173
25174 struct objfile *
25175 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25176 {
25177   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25178
25179   /* Return the master objfile, so that we can report and look up the
25180      correct file containing this variable.  */
25181   if (objfile->separate_debug_objfile_backlink)
25182     objfile = objfile->separate_debug_objfile_backlink;
25183
25184   return objfile;
25185 }
25186
25187 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25188    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25189    CU_HEADERP first.  */
25190
25191 static const struct comp_unit_head *
25192 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25193                        struct dwarf2_per_cu_data *per_cu)
25194 {
25195   const gdb_byte *info_ptr;
25196
25197   if (per_cu->cu)
25198     return &per_cu->cu->header;
25199
25200   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25201
25202   memset (cu_headerp, 0, sizeof (*cu_headerp));
25203   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25204                        rcuh_kind::COMPILE);
25205
25206   return cu_headerp;
25207 }
25208
25209 /* Return the address size given in the compilation unit header for CU.  */
25210
25211 int
25212 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25213 {
25214   struct comp_unit_head cu_header_local;
25215   const struct comp_unit_head *cu_headerp;
25216
25217   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25218
25219   return cu_headerp->addr_size;
25220 }
25221
25222 /* Return the offset size given in the compilation unit header for CU.  */
25223
25224 int
25225 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25226 {
25227   struct comp_unit_head cu_header_local;
25228   const struct comp_unit_head *cu_headerp;
25229
25230   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25231
25232   return cu_headerp->offset_size;
25233 }
25234
25235 /* See its dwarf2loc.h declaration.  */
25236
25237 int
25238 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25239 {
25240   struct comp_unit_head cu_header_local;
25241   const struct comp_unit_head *cu_headerp;
25242
25243   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25244
25245   if (cu_headerp->version == 2)
25246     return cu_headerp->addr_size;
25247   else
25248     return cu_headerp->offset_size;
25249 }
25250
25251 /* Return the text offset of the CU.  The returned offset comes from
25252    this CU's objfile.  If this objfile came from a separate debuginfo
25253    file, then the offset may be different from the corresponding
25254    offset in the parent objfile.  */
25255
25256 CORE_ADDR
25257 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25258 {
25259   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25260
25261   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25262 }
25263
25264 /* Return DWARF version number of PER_CU.  */
25265
25266 short
25267 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25268 {
25269   return per_cu->dwarf_version;
25270 }
25271
25272 /* Locate the .debug_info compilation unit from CU's objfile which contains
25273    the DIE at OFFSET.  Raises an error on failure.  */
25274
25275 static struct dwarf2_per_cu_data *
25276 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25277                                   unsigned int offset_in_dwz,
25278                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25279 {
25280   struct dwarf2_per_cu_data *this_cu;
25281   int low, high;
25282
25283   low = 0;
25284   high = dwarf2_per_objfile->all_comp_units.size () - 1;
25285   while (high > low)
25286     {
25287       struct dwarf2_per_cu_data *mid_cu;
25288       int mid = low + (high - low) / 2;
25289
25290       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25291       if (mid_cu->is_dwz > offset_in_dwz
25292           || (mid_cu->is_dwz == offset_in_dwz
25293               && mid_cu->sect_off + mid_cu->length >= sect_off))
25294         high = mid;
25295       else
25296         low = mid + 1;
25297     }
25298   gdb_assert (low == high);
25299   this_cu = dwarf2_per_objfile->all_comp_units[low];
25300   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
25301     {
25302       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25303         error (_("Dwarf Error: could not find partial DIE containing "
25304                "offset %s [in module %s]"),
25305                sect_offset_str (sect_off),
25306                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25307
25308       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25309                   <= sect_off);
25310       return dwarf2_per_objfile->all_comp_units[low-1];
25311     }
25312   else
25313     {
25314       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25315           && sect_off >= this_cu->sect_off + this_cu->length)
25316         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25317       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25318       return this_cu;
25319     }
25320 }
25321
25322 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25323
25324 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25325   : per_cu (per_cu_),
25326     mark (false),
25327     has_loclist (false),
25328     checked_producer (false),
25329     producer_is_gxx_lt_4_6 (false),
25330     producer_is_gcc_lt_4_3 (false),
25331     producer_is_icc (false),
25332     producer_is_icc_lt_14 (false),
25333     producer_is_codewarrior (false),
25334     processing_has_namespace_info (false)
25335 {
25336   per_cu->cu = this;
25337 }
25338
25339 /* Destroy a dwarf2_cu.  */
25340
25341 dwarf2_cu::~dwarf2_cu ()
25342 {
25343   per_cu->cu = NULL;
25344 }
25345
25346 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25347
25348 static void
25349 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25350                        enum language pretend_language)
25351 {
25352   struct attribute *attr;
25353
25354   /* Set the language we're debugging.  */
25355   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25356   if (attr)
25357     set_cu_language (DW_UNSND (attr), cu);
25358   else
25359     {
25360       cu->language = pretend_language;
25361       cu->language_defn = language_def (cu->language);
25362     }
25363
25364   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25365 }
25366
25367 /* Increase the age counter on each cached compilation unit, and free
25368    any that are too old.  */
25369
25370 static void
25371 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25372 {
25373   struct dwarf2_per_cu_data *per_cu, **last_chain;
25374
25375   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25376   per_cu = dwarf2_per_objfile->read_in_chain;
25377   while (per_cu != NULL)
25378     {
25379       per_cu->cu->last_used ++;
25380       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25381         dwarf2_mark (per_cu->cu);
25382       per_cu = per_cu->cu->read_in_chain;
25383     }
25384
25385   per_cu = dwarf2_per_objfile->read_in_chain;
25386   last_chain = &dwarf2_per_objfile->read_in_chain;
25387   while (per_cu != NULL)
25388     {
25389       struct dwarf2_per_cu_data *next_cu;
25390
25391       next_cu = per_cu->cu->read_in_chain;
25392
25393       if (!per_cu->cu->mark)
25394         {
25395           delete per_cu->cu;
25396           *last_chain = next_cu;
25397         }
25398       else
25399         last_chain = &per_cu->cu->read_in_chain;
25400
25401       per_cu = next_cu;
25402     }
25403 }
25404
25405 /* Remove a single compilation unit from the cache.  */
25406
25407 static void
25408 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25409 {
25410   struct dwarf2_per_cu_data *per_cu, **last_chain;
25411   struct dwarf2_per_objfile *dwarf2_per_objfile
25412     = target_per_cu->dwarf2_per_objfile;
25413
25414   per_cu = dwarf2_per_objfile->read_in_chain;
25415   last_chain = &dwarf2_per_objfile->read_in_chain;
25416   while (per_cu != NULL)
25417     {
25418       struct dwarf2_per_cu_data *next_cu;
25419
25420       next_cu = per_cu->cu->read_in_chain;
25421
25422       if (per_cu == target_per_cu)
25423         {
25424           delete per_cu->cu;
25425           per_cu->cu = NULL;
25426           *last_chain = next_cu;
25427           break;
25428         }
25429       else
25430         last_chain = &per_cu->cu->read_in_chain;
25431
25432       per_cu = next_cu;
25433     }
25434 }
25435
25436 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25437    We store these in a hash table separate from the DIEs, and preserve them
25438    when the DIEs are flushed out of cache.
25439
25440    The CU "per_cu" pointer is needed because offset alone is not enough to
25441    uniquely identify the type.  A file may have multiple .debug_types sections,
25442    or the type may come from a DWO file.  Furthermore, while it's more logical
25443    to use per_cu->section+offset, with Fission the section with the data is in
25444    the DWO file but we don't know that section at the point we need it.
25445    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25446    because we can enter the lookup routine, get_die_type_at_offset, from
25447    outside this file, and thus won't necessarily have PER_CU->cu.
25448    Fortunately, PER_CU is stable for the life of the objfile.  */
25449
25450 struct dwarf2_per_cu_offset_and_type
25451 {
25452   const struct dwarf2_per_cu_data *per_cu;
25453   sect_offset sect_off;
25454   struct type *type;
25455 };
25456
25457 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25458
25459 static hashval_t
25460 per_cu_offset_and_type_hash (const void *item)
25461 {
25462   const struct dwarf2_per_cu_offset_and_type *ofs
25463     = (const struct dwarf2_per_cu_offset_and_type *) item;
25464
25465   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25466 }
25467
25468 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25469
25470 static int
25471 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25472 {
25473   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25474     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25475   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25476     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25477
25478   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25479           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25480 }
25481
25482 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25483    table if necessary.  For convenience, return TYPE.
25484
25485    The DIEs reading must have careful ordering to:
25486     * Not cause infite loops trying to read in DIEs as a prerequisite for
25487       reading current DIE.
25488     * Not trying to dereference contents of still incompletely read in types
25489       while reading in other DIEs.
25490     * Enable referencing still incompletely read in types just by a pointer to
25491       the type without accessing its fields.
25492
25493    Therefore caller should follow these rules:
25494      * Try to fetch any prerequisite types we may need to build this DIE type
25495        before building the type and calling set_die_type.
25496      * After building type call set_die_type for current DIE as soon as
25497        possible before fetching more types to complete the current type.
25498      * Make the type as complete as possible before fetching more types.  */
25499
25500 static struct type *
25501 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25502 {
25503   struct dwarf2_per_objfile *dwarf2_per_objfile
25504     = cu->per_cu->dwarf2_per_objfile;
25505   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25506   struct objfile *objfile = dwarf2_per_objfile->objfile;
25507   struct attribute *attr;
25508   struct dynamic_prop prop;
25509
25510   /* For Ada types, make sure that the gnat-specific data is always
25511      initialized (if not already set).  There are a few types where
25512      we should not be doing so, because the type-specific area is
25513      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25514      where the type-specific area is used to store the floatformat).
25515      But this is not a problem, because the gnat-specific information
25516      is actually not needed for these types.  */
25517   if (need_gnat_info (cu)
25518       && TYPE_CODE (type) != TYPE_CODE_FUNC
25519       && TYPE_CODE (type) != TYPE_CODE_FLT
25520       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25521       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25522       && TYPE_CODE (type) != TYPE_CODE_METHOD
25523       && !HAVE_GNAT_AUX_INFO (type))
25524     INIT_GNAT_SPECIFIC (type);
25525
25526   /* Read DW_AT_allocated and set in type.  */
25527   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25528   if (attr_form_is_block (attr))
25529     {
25530       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25531         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25532     }
25533   else if (attr != NULL)
25534     {
25535       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25536                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25537                  sect_offset_str (die->sect_off));
25538     }
25539
25540   /* Read DW_AT_associated and set in type.  */
25541   attr = dwarf2_attr (die, DW_AT_associated, cu);
25542   if (attr_form_is_block (attr))
25543     {
25544       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25545         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25546     }
25547   else if (attr != NULL)
25548     {
25549       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25550                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25551                  sect_offset_str (die->sect_off));
25552     }
25553
25554   /* Read DW_AT_data_location and set in type.  */
25555   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25556   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25557     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25558
25559   if (dwarf2_per_objfile->die_type_hash == NULL)
25560     {
25561       dwarf2_per_objfile->die_type_hash =
25562         htab_create_alloc_ex (127,
25563                               per_cu_offset_and_type_hash,
25564                               per_cu_offset_and_type_eq,
25565                               NULL,
25566                               &objfile->objfile_obstack,
25567                               hashtab_obstack_allocate,
25568                               dummy_obstack_deallocate);
25569     }
25570
25571   ofs.per_cu = cu->per_cu;
25572   ofs.sect_off = die->sect_off;
25573   ofs.type = type;
25574   slot = (struct dwarf2_per_cu_offset_and_type **)
25575     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25576   if (*slot)
25577     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25578                sect_offset_str (die->sect_off));
25579   *slot = XOBNEW (&objfile->objfile_obstack,
25580                   struct dwarf2_per_cu_offset_and_type);
25581   **slot = ofs;
25582   return type;
25583 }
25584
25585 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25586    or return NULL if the die does not have a saved type.  */
25587
25588 static struct type *
25589 get_die_type_at_offset (sect_offset sect_off,
25590                         struct dwarf2_per_cu_data *per_cu)
25591 {
25592   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25593   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25594
25595   if (dwarf2_per_objfile->die_type_hash == NULL)
25596     return NULL;
25597
25598   ofs.per_cu = per_cu;
25599   ofs.sect_off = sect_off;
25600   slot = ((struct dwarf2_per_cu_offset_and_type *)
25601           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25602   if (slot)
25603     return slot->type;
25604   else
25605     return NULL;
25606 }
25607
25608 /* Look up the type for DIE in CU in die_type_hash,
25609    or return NULL if DIE does not have a saved type.  */
25610
25611 static struct type *
25612 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25613 {
25614   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25615 }
25616
25617 /* Add a dependence relationship from CU to REF_PER_CU.  */
25618
25619 static void
25620 dwarf2_add_dependence (struct dwarf2_cu *cu,
25621                        struct dwarf2_per_cu_data *ref_per_cu)
25622 {
25623   void **slot;
25624
25625   if (cu->dependencies == NULL)
25626     cu->dependencies
25627       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25628                               NULL, &cu->comp_unit_obstack,
25629                               hashtab_obstack_allocate,
25630                               dummy_obstack_deallocate);
25631
25632   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25633   if (*slot == NULL)
25634     *slot = ref_per_cu;
25635 }
25636
25637 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25638    Set the mark field in every compilation unit in the
25639    cache that we must keep because we are keeping CU.  */
25640
25641 static int
25642 dwarf2_mark_helper (void **slot, void *data)
25643 {
25644   struct dwarf2_per_cu_data *per_cu;
25645
25646   per_cu = (struct dwarf2_per_cu_data *) *slot;
25647
25648   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25649      reading of the chain.  As such dependencies remain valid it is not much
25650      useful to track and undo them during QUIT cleanups.  */
25651   if (per_cu->cu == NULL)
25652     return 1;
25653
25654   if (per_cu->cu->mark)
25655     return 1;
25656   per_cu->cu->mark = true;
25657
25658   if (per_cu->cu->dependencies != NULL)
25659     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25660
25661   return 1;
25662 }
25663
25664 /* Set the mark field in CU and in every other compilation unit in the
25665    cache that we must keep because we are keeping CU.  */
25666
25667 static void
25668 dwarf2_mark (struct dwarf2_cu *cu)
25669 {
25670   if (cu->mark)
25671     return;
25672   cu->mark = true;
25673   if (cu->dependencies != NULL)
25674     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25675 }
25676
25677 static void
25678 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25679 {
25680   while (per_cu)
25681     {
25682       per_cu->cu->mark = false;
25683       per_cu = per_cu->cu->read_in_chain;
25684     }
25685 }
25686
25687 /* Trivial hash function for partial_die_info: the hash value of a DIE
25688    is its offset in .debug_info for this objfile.  */
25689
25690 static hashval_t
25691 partial_die_hash (const void *item)
25692 {
25693   const struct partial_die_info *part_die
25694     = (const struct partial_die_info *) item;
25695
25696   return to_underlying (part_die->sect_off);
25697 }
25698
25699 /* Trivial comparison function for partial_die_info structures: two DIEs
25700    are equal if they have the same offset.  */
25701
25702 static int
25703 partial_die_eq (const void *item_lhs, const void *item_rhs)
25704 {
25705   const struct partial_die_info *part_die_lhs
25706     = (const struct partial_die_info *) item_lhs;
25707   const struct partial_die_info *part_die_rhs
25708     = (const struct partial_die_info *) item_rhs;
25709
25710   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25711 }
25712
25713 struct cmd_list_element *set_dwarf_cmdlist;
25714 struct cmd_list_element *show_dwarf_cmdlist;
25715
25716 static void
25717 set_dwarf_cmd (const char *args, int from_tty)
25718 {
25719   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25720              gdb_stdout);
25721 }
25722
25723 static void
25724 show_dwarf_cmd (const char *args, int from_tty)
25725 {
25726   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25727 }
25728
25729 int dwarf_always_disassemble;
25730
25731 static void
25732 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25733                                struct cmd_list_element *c, const char *value)
25734 {
25735   fprintf_filtered (file,
25736                     _("Whether to always disassemble "
25737                       "DWARF expressions is %s.\n"),
25738                     value);
25739 }
25740
25741 static void
25742 show_check_physname (struct ui_file *file, int from_tty,
25743                      struct cmd_list_element *c, const char *value)
25744 {
25745   fprintf_filtered (file,
25746                     _("Whether to check \"physname\" is %s.\n"),
25747                     value);
25748 }
25749
25750 void
25751 _initialize_dwarf2_read (void)
25752 {
25753   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25754 Set DWARF specific variables.\n\
25755 Configure DWARF variables such as the cache size"),
25756                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25757                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25758
25759   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25760 Show DWARF specific variables\n\
25761 Show DWARF variables such as the cache size"),
25762                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25763                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25764
25765   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25766                             &dwarf_max_cache_age, _("\
25767 Set the upper bound on the age of cached DWARF compilation units."), _("\
25768 Show the upper bound on the age of cached DWARF compilation units."), _("\
25769 A higher limit means that cached compilation units will be stored\n\
25770 in memory longer, and more total memory will be used.  Zero disables\n\
25771 caching, which can slow down startup."),
25772                             NULL,
25773                             show_dwarf_max_cache_age,
25774                             &set_dwarf_cmdlist,
25775                             &show_dwarf_cmdlist);
25776
25777   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25778                            &dwarf_always_disassemble, _("\
25779 Set whether `info address' always disassembles DWARF expressions."), _("\
25780 Show whether `info address' always disassembles DWARF expressions."), _("\
25781 When enabled, DWARF expressions are always printed in an assembly-like\n\
25782 syntax.  When disabled, expressions will be printed in a more\n\
25783 conversational style, when possible."),
25784                            NULL,
25785                            show_dwarf_always_disassemble,
25786                            &set_dwarf_cmdlist,
25787                            &show_dwarf_cmdlist);
25788
25789   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25790 Set debugging of the DWARF reader."), _("\
25791 Show debugging of the DWARF reader."), _("\
25792 When enabled (non-zero), debugging messages are printed during DWARF\n\
25793 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25794 information.  A value greater than 1 provides more verbose information."),
25795                             NULL,
25796                             NULL,
25797                             &setdebuglist, &showdebuglist);
25798
25799   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25800 Set debugging of the DWARF DIE reader."), _("\
25801 Show debugging of the DWARF DIE reader."), _("\
25802 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25803 The value is the maximum depth to print."),
25804                              NULL,
25805                              NULL,
25806                              &setdebuglist, &showdebuglist);
25807
25808   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25809 Set debugging of the dwarf line reader."), _("\
25810 Show debugging of the dwarf line reader."), _("\
25811 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25812 A value of 1 (one) provides basic information.\n\
25813 A value greater than 1 provides more verbose information."),
25814                              NULL,
25815                              NULL,
25816                              &setdebuglist, &showdebuglist);
25817
25818   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25819 Set cross-checking of \"physname\" code against demangler."), _("\
25820 Show cross-checking of \"physname\" code against demangler."), _("\
25821 When enabled, GDB's internal \"physname\" code is checked against\n\
25822 the demangler."),
25823                            NULL, show_check_physname,
25824                            &setdebuglist, &showdebuglist);
25825
25826   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25827                            no_class, &use_deprecated_index_sections, _("\
25828 Set whether to use deprecated gdb_index sections."), _("\
25829 Show whether to use deprecated gdb_index sections."), _("\
25830 When enabled, deprecated .gdb_index sections are used anyway.\n\
25831 Normally they are ignored either because of a missing feature or\n\
25832 performance issue.\n\
25833 Warning: This option must be enabled before gdb reads the file."),
25834                            NULL,
25835                            NULL,
25836                            &setlist, &showlist);
25837
25838   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25839                                                         &dwarf2_locexpr_funcs);
25840   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25841                                                         &dwarf2_loclist_funcs);
25842
25843   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25844                                         &dwarf2_block_frame_base_locexpr_funcs);
25845   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25846                                         &dwarf2_block_frame_base_loclist_funcs);
25847
25848 #if GDB_SELF_TEST
25849   selftests::register_test ("dw2_expand_symtabs_matching",
25850                             selftests::dw2_expand_symtabs_matching::run_test);
25851 #endif
25852 }