dwarf2read: Make dwo_file::dbfd a gdb_bfd_ref_ptr
[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 == 0;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return dwarf2_objfile_data_key.get (objfile);
285 }
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_loclists", ".zdebug_loclists" },
299   { ".debug_macinfo", ".zdebug_macinfo" },
300   { ".debug_macro", ".zdebug_macro" },
301   { ".debug_str", ".zdebug_str" },
302   { ".debug_line_str", ".zdebug_line_str" },
303   { ".debug_ranges", ".zdebug_ranges" },
304   { ".debug_rnglists", ".zdebug_rnglists" },
305   { ".debug_types", ".zdebug_types" },
306   { ".debug_addr", ".zdebug_addr" },
307   { ".debug_frame", ".zdebug_frame" },
308   { ".eh_frame", NULL },
309   { ".gdb_index", ".zgdb_index" },
310   { ".debug_names", ".zdebug_names" },
311   { ".debug_aranges", ".zdebug_aranges" },
312   23
313 };
314
315 /* List of DWO/DWP sections.  */
316
317 static const struct dwop_section_names
318 {
319   struct dwarf2_section_names abbrev_dwo;
320   struct dwarf2_section_names info_dwo;
321   struct dwarf2_section_names line_dwo;
322   struct dwarf2_section_names loc_dwo;
323   struct dwarf2_section_names loclists_dwo;
324   struct dwarf2_section_names macinfo_dwo;
325   struct dwarf2_section_names macro_dwo;
326   struct dwarf2_section_names str_dwo;
327   struct dwarf2_section_names str_offsets_dwo;
328   struct dwarf2_section_names types_dwo;
329   struct dwarf2_section_names cu_index;
330   struct dwarf2_section_names tu_index;
331 }
332 dwop_section_names =
333 {
334   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
335   { ".debug_info.dwo", ".zdebug_info.dwo" },
336   { ".debug_line.dwo", ".zdebug_line.dwo" },
337   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
338   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
339   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
340   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
341   { ".debug_str.dwo", ".zdebug_str.dwo" },
342   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
343   { ".debug_types.dwo", ".zdebug_types.dwo" },
344   { ".debug_cu_index", ".zdebug_cu_index" },
345   { ".debug_tu_index", ".zdebug_tu_index" },
346 };
347
348 /* local data types */
349
350 /* The data in a compilation unit header, after target2host
351    translation, looks like this.  */
352 struct comp_unit_head
353 {
354   unsigned int length;
355   short version;
356   unsigned char addr_size;
357   unsigned char signed_addr_p;
358   sect_offset abbrev_sect_off;
359
360   /* Size of file offsets; either 4 or 8.  */
361   unsigned int offset_size;
362
363   /* Size of the length field; either 4 or 12.  */
364   unsigned int initial_length_size;
365
366   enum dwarf_unit_type unit_type;
367
368   /* Offset to the first byte of this compilation unit header in the
369      .debug_info section, for resolving relative reference dies.  */
370   sect_offset sect_off;
371
372   /* Offset to first die in this cu from the start of the cu.
373      This will be the first byte following the compilation unit header.  */
374   cu_offset first_die_cu_offset;
375
376   /* 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   dwo_file () = default;
707   DISABLE_COPY_AND_ASSIGN (dwo_file);
708
709   ~dwo_file ()
710   {
711     VEC_free (dwarf2_section_info_def, sections.types);
712   }
713
714   /* The DW_AT_GNU_dwo_name attribute.
715      For virtual DWO files the name is constructed from the section offsets
716      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
717      from related CU+TUs.  */
718   const char *dwo_name = nullptr;
719
720   /* The DW_AT_comp_dir attribute.  */
721   const char *comp_dir = nullptr;
722
723   /* The bfd, when the file is open.  Otherwise this is NULL.
724      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
725   gdb_bfd_ref_ptr dbfd;
726
727   /* The sections that make up this DWO file.
728      Remember that for virtual DWO files in DWP V2, these are virtual
729      sections (for lack of a better name).  */
730   struct dwo_sections sections {};
731
732   /* The CUs in the file.
733      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
734      an extension to handle LLVM's Link Time Optimization output (where
735      multiple source files may be compiled into a single object/dwo pair). */
736   htab_t cus {};
737
738   /* Table of TUs in the file.
739      Each element is a struct dwo_unit.  */
740   htab_t tus {};
741 };
742
743 /* These sections are what may appear in a DWP file.  */
744
745 struct dwp_sections
746 {
747   /* These are used by both DWP version 1 and 2.  */
748   struct dwarf2_section_info str;
749   struct dwarf2_section_info cu_index;
750   struct dwarf2_section_info tu_index;
751
752   /* These are only used by DWP version 2 files.
753      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
754      sections are referenced by section number, and are not recorded here.
755      In DWP version 2 there is at most one copy of all these sections, each
756      section being (effectively) comprised of the concatenation of all of the
757      individual sections that exist in the version 1 format.
758      To keep the code simple we treat each of these concatenated pieces as a
759      section itself (a virtual section?).  */
760   struct dwarf2_section_info abbrev;
761   struct dwarf2_section_info info;
762   struct dwarf2_section_info line;
763   struct dwarf2_section_info loc;
764   struct dwarf2_section_info macinfo;
765   struct dwarf2_section_info macro;
766   struct dwarf2_section_info str_offsets;
767   struct dwarf2_section_info types;
768 };
769
770 /* These sections are what may appear in a virtual DWO file in DWP version 1.
771    A virtual DWO file is a DWO file as it appears in a DWP file.  */
772
773 struct virtual_v1_dwo_sections
774 {
775   struct dwarf2_section_info abbrev;
776   struct dwarf2_section_info line;
777   struct dwarf2_section_info loc;
778   struct dwarf2_section_info macinfo;
779   struct dwarf2_section_info macro;
780   struct dwarf2_section_info str_offsets;
781   /* Each DWP hash table entry records one CU or one TU.
782      That is recorded here, and copied to dwo_unit.section.  */
783   struct dwarf2_section_info info_or_types;
784 };
785
786 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
787    In version 2, the sections of the DWO files are concatenated together
788    and stored in one section of that name.  Thus each ELF section contains
789    several "virtual" sections.  */
790
791 struct virtual_v2_dwo_sections
792 {
793   bfd_size_type abbrev_offset;
794   bfd_size_type abbrev_size;
795
796   bfd_size_type line_offset;
797   bfd_size_type line_size;
798
799   bfd_size_type loc_offset;
800   bfd_size_type loc_size;
801
802   bfd_size_type macinfo_offset;
803   bfd_size_type macinfo_size;
804
805   bfd_size_type macro_offset;
806   bfd_size_type macro_size;
807
808   bfd_size_type str_offsets_offset;
809   bfd_size_type str_offsets_size;
810
811   /* Each DWP hash table entry records one CU or one TU.
812      That is recorded here, and copied to dwo_unit.section.  */
813   bfd_size_type info_or_types_offset;
814   bfd_size_type info_or_types_size;
815 };
816
817 /* Contents of DWP hash tables.  */
818
819 struct dwp_hash_table
820 {
821   uint32_t version, nr_columns;
822   uint32_t nr_units, nr_slots;
823   const gdb_byte *hash_table, *unit_table;
824   union
825   {
826     struct
827     {
828       const gdb_byte *indices;
829     } v1;
830     struct
831     {
832       /* This is indexed by column number and gives the id of the section
833          in that column.  */
834 #define MAX_NR_V2_DWO_SECTIONS \
835   (1 /* .debug_info or .debug_types */ \
836    + 1 /* .debug_abbrev */ \
837    + 1 /* .debug_line */ \
838    + 1 /* .debug_loc */ \
839    + 1 /* .debug_str_offsets */ \
840    + 1 /* .debug_macro or .debug_macinfo */)
841       int section_ids[MAX_NR_V2_DWO_SECTIONS];
842       const gdb_byte *offsets;
843       const gdb_byte *sizes;
844     } v2;
845   } section_pool;
846 };
847
848 /* Data for one DWP file.  */
849
850 struct dwp_file
851 {
852   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
853     : name (name_),
854       dbfd (std::move (abfd))
855   {
856   }
857
858   /* Name of the file.  */
859   const char *name;
860
861   /* File format version.  */
862   int version = 0;
863
864   /* The bfd.  */
865   gdb_bfd_ref_ptr dbfd;
866
867   /* Section info for this file.  */
868   struct dwp_sections sections {};
869
870   /* Table of CUs in the file.  */
871   const struct dwp_hash_table *cus = nullptr;
872
873   /* Table of TUs in the file.  */
874   const struct dwp_hash_table *tus = nullptr;
875
876   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
877   htab_t loaded_cus {};
878   htab_t loaded_tus {};
879
880   /* Table to map ELF section numbers to their sections.
881      This is only needed for the DWP V1 file format.  */
882   unsigned int num_sections = 0;
883   asection **elf_sections = nullptr;
884 };
885
886 /* Struct used to pass misc. parameters to read_die_and_children, et
887    al.  which are used for both .debug_info and .debug_types dies.
888    All parameters here are unchanging for the life of the call.  This
889    struct exists to abstract away the constant parameters of die reading.  */
890
891 struct die_reader_specs
892 {
893   /* The bfd of die_section.  */
894   bfd* abfd;
895
896   /* The CU of the DIE we are parsing.  */
897   struct dwarf2_cu *cu;
898
899   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
900   struct dwo_file *dwo_file;
901
902   /* The section the die comes from.
903      This is either .debug_info or .debug_types, or the .dwo variants.  */
904   struct dwarf2_section_info *die_section;
905
906   /* die_section->buffer.  */
907   const gdb_byte *buffer;
908
909   /* The end of the buffer.  */
910   const gdb_byte *buffer_end;
911
912   /* The value of the DW_AT_comp_dir attribute.  */
913   const char *comp_dir;
914
915   /* The abbreviation table to use when reading the DIEs.  */
916   struct abbrev_table *abbrev_table;
917 };
918
919 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
920 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
921                                       const gdb_byte *info_ptr,
922                                       struct die_info *comp_unit_die,
923                                       int has_children,
924                                       void *data);
925
926 /* A 1-based directory index.  This is a strong typedef to prevent
927    accidentally using a directory index as a 0-based index into an
928    array/vector.  */
929 enum class dir_index : unsigned int {};
930
931 /* Likewise, a 1-based file name index.  */
932 enum class file_name_index : unsigned int {};
933
934 struct file_entry
935 {
936   file_entry () = default;
937
938   file_entry (const char *name_, dir_index d_index_,
939               unsigned int mod_time_, unsigned int length_)
940     : name (name_),
941       d_index (d_index_),
942       mod_time (mod_time_),
943       length (length_)
944   {}
945
946   /* Return the include directory at D_INDEX stored in LH.  Returns
947      NULL if D_INDEX is out of bounds.  */
948   const char *include_dir (const line_header *lh) const;
949
950   /* The file name.  Note this is an observing pointer.  The memory is
951      owned by debug_line_buffer.  */
952   const char *name {};
953
954   /* The directory index (1-based).  */
955   dir_index d_index {};
956
957   unsigned int mod_time {};
958
959   unsigned int length {};
960
961   /* True if referenced by the Line Number Program.  */
962   bool included_p {};
963
964   /* The associated symbol table, if any.  */
965   struct symtab *symtab {};
966 };
967
968 /* The line number information for a compilation unit (found in the
969    .debug_line section) begins with a "statement program header",
970    which contains the following information.  */
971 struct line_header
972 {
973   line_header ()
974     : offset_in_dwz {}
975   {}
976
977   /* Add an entry to the include directory table.  */
978   void add_include_dir (const char *include_dir);
979
980   /* Add an entry to the file name table.  */
981   void add_file_name (const char *name, dir_index d_index,
982                       unsigned int mod_time, unsigned int length);
983
984   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
985      is out of bounds.  */
986   const char *include_dir_at (dir_index index) const
987   {
988     /* Convert directory index number (1-based) to vector index
989        (0-based).  */
990     size_t vec_index = to_underlying (index) - 1;
991
992     if (vec_index >= include_dirs.size ())
993       return NULL;
994     return include_dirs[vec_index];
995   }
996
997   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
998      is out of bounds.  */
999   file_entry *file_name_at (file_name_index index)
1000   {
1001     /* Convert file name index number (1-based) to vector index
1002        (0-based).  */
1003     size_t vec_index = to_underlying (index) - 1;
1004
1005     if (vec_index >= file_names.size ())
1006       return NULL;
1007     return &file_names[vec_index];
1008   }
1009
1010   /* Offset of line number information in .debug_line section.  */
1011   sect_offset sect_off {};
1012
1013   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1014   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1015
1016   unsigned int total_length {};
1017   unsigned short version {};
1018   unsigned int header_length {};
1019   unsigned char minimum_instruction_length {};
1020   unsigned char maximum_ops_per_instruction {};
1021   unsigned char default_is_stmt {};
1022   int line_base {};
1023   unsigned char line_range {};
1024   unsigned char opcode_base {};
1025
1026   /* standard_opcode_lengths[i] is the number of operands for the
1027      standard opcode whose value is i.  This means that
1028      standard_opcode_lengths[0] is unused, and the last meaningful
1029      element is standard_opcode_lengths[opcode_base - 1].  */
1030   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1031
1032   /* The include_directories table.  Note these are observing
1033      pointers.  The memory is owned by debug_line_buffer.  */
1034   std::vector<const char *> include_dirs;
1035
1036   /* The file_names table.  */
1037   std::vector<file_entry> file_names;
1038
1039   /* The start and end of the statement program following this
1040      header.  These point into dwarf2_per_objfile->line_buffer.  */
1041   const gdb_byte *statement_program_start {}, *statement_program_end {};
1042 };
1043
1044 typedef std::unique_ptr<line_header> line_header_up;
1045
1046 const char *
1047 file_entry::include_dir (const line_header *lh) const
1048 {
1049   return lh->include_dir_at (d_index);
1050 }
1051
1052 /* When we construct a partial symbol table entry we only
1053    need this much information.  */
1054 struct partial_die_info : public allocate_on_obstack
1055   {
1056     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1057
1058     /* Disable assign but still keep copy ctor, which is needed
1059        load_partial_dies.   */
1060     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1061
1062     /* Adjust the partial die before generating a symbol for it.  This
1063        function may set the is_external flag or change the DIE's
1064        name.  */
1065     void fixup (struct dwarf2_cu *cu);
1066
1067     /* Read a minimal amount of information into the minimal die
1068        structure.  */
1069     const gdb_byte *read (const struct die_reader_specs *reader,
1070                           const struct abbrev_info &abbrev,
1071                           const gdb_byte *info_ptr);
1072
1073     /* Offset of this DIE.  */
1074     const sect_offset sect_off;
1075
1076     /* DWARF-2 tag for this DIE.  */
1077     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1078
1079     /* Assorted flags describing the data found in this DIE.  */
1080     const unsigned int has_children : 1;
1081
1082     unsigned int is_external : 1;
1083     unsigned int is_declaration : 1;
1084     unsigned int has_type : 1;
1085     unsigned int has_specification : 1;
1086     unsigned int has_pc_info : 1;
1087     unsigned int may_be_inlined : 1;
1088
1089     /* This DIE has been marked DW_AT_main_subprogram.  */
1090     unsigned int main_subprogram : 1;
1091
1092     /* Flag set if the SCOPE field of this structure has been
1093        computed.  */
1094     unsigned int scope_set : 1;
1095
1096     /* Flag set if the DIE has a byte_size attribute.  */
1097     unsigned int has_byte_size : 1;
1098
1099     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1100     unsigned int has_const_value : 1;
1101
1102     /* Flag set if any of the DIE's children are template arguments.  */
1103     unsigned int has_template_arguments : 1;
1104
1105     /* Flag set if fixup has been called on this die.  */
1106     unsigned int fixup_called : 1;
1107
1108     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1109     unsigned int is_dwz : 1;
1110
1111     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1112     unsigned int spec_is_dwz : 1;
1113
1114     /* The name of this DIE.  Normally the value of DW_AT_name, but
1115        sometimes a default name for unnamed DIEs.  */
1116     const char *name = nullptr;
1117
1118     /* The linkage name, if present.  */
1119     const char *linkage_name = nullptr;
1120
1121     /* The scope to prepend to our children.  This is generally
1122        allocated on the comp_unit_obstack, so will disappear
1123        when this compilation unit leaves the cache.  */
1124     const char *scope = nullptr;
1125
1126     /* Some data associated with the partial DIE.  The tag determines
1127        which field is live.  */
1128     union
1129     {
1130       /* The location description associated with this DIE, if any.  */
1131       struct dwarf_block *locdesc;
1132       /* The offset of an import, for DW_TAG_imported_unit.  */
1133       sect_offset sect_off;
1134     } d {};
1135
1136     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1137     CORE_ADDR lowpc = 0;
1138     CORE_ADDR highpc = 0;
1139
1140     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1141        DW_AT_sibling, if any.  */
1142     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1143        could return DW_AT_sibling values to its caller load_partial_dies.  */
1144     const gdb_byte *sibling = nullptr;
1145
1146     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1147        DW_AT_specification (or DW_AT_abstract_origin or
1148        DW_AT_extension).  */
1149     sect_offset spec_offset {};
1150
1151     /* Pointers to this DIE's parent, first child, and next sibling,
1152        if any.  */
1153     struct partial_die_info *die_parent = nullptr;
1154     struct partial_die_info *die_child = nullptr;
1155     struct partial_die_info *die_sibling = nullptr;
1156
1157     friend struct partial_die_info *
1158     dwarf2_cu::find_partial_die (sect_offset sect_off);
1159
1160   private:
1161     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1162     partial_die_info (sect_offset sect_off)
1163       : partial_die_info (sect_off, DW_TAG_padding, 0)
1164     {
1165     }
1166
1167     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1168                       int has_children_)
1169       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1170     {
1171       is_external = 0;
1172       is_declaration = 0;
1173       has_type = 0;
1174       has_specification = 0;
1175       has_pc_info = 0;
1176       may_be_inlined = 0;
1177       main_subprogram = 0;
1178       scope_set = 0;
1179       has_byte_size = 0;
1180       has_const_value = 0;
1181       has_template_arguments = 0;
1182       fixup_called = 0;
1183       is_dwz = 0;
1184       spec_is_dwz = 0;
1185     }
1186   };
1187
1188 /* This data structure holds the information of an abbrev.  */
1189 struct abbrev_info
1190   {
1191     unsigned int number;        /* number identifying abbrev */
1192     enum dwarf_tag tag;         /* dwarf tag */
1193     unsigned short has_children;                /* boolean */
1194     unsigned short num_attrs;   /* number of attributes */
1195     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1196     struct abbrev_info *next;   /* next in chain */
1197   };
1198
1199 struct attr_abbrev
1200   {
1201     ENUM_BITFIELD(dwarf_attribute) name : 16;
1202     ENUM_BITFIELD(dwarf_form) form : 16;
1203
1204     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1205     LONGEST implicit_const;
1206   };
1207
1208 /* Size of abbrev_table.abbrev_hash_table.  */
1209 #define ABBREV_HASH_SIZE 121
1210
1211 /* Top level data structure to contain an abbreviation table.  */
1212
1213 struct abbrev_table
1214 {
1215   explicit abbrev_table (sect_offset off)
1216     : sect_off (off)
1217   {
1218     m_abbrevs =
1219       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1220     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1221   }
1222
1223   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1224
1225   /* Allocate space for a struct abbrev_info object in
1226      ABBREV_TABLE.  */
1227   struct abbrev_info *alloc_abbrev ();
1228
1229   /* Add an abbreviation to the table.  */
1230   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1231
1232   /* Look up an abbrev in the table.
1233      Returns NULL if the abbrev is not found.  */
1234
1235   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1236
1237
1238   /* Where the abbrev table came from.
1239      This is used as a sanity check when the table is used.  */
1240   const sect_offset sect_off;
1241
1242   /* Storage for the abbrev table.  */
1243   auto_obstack abbrev_obstack;
1244
1245 private:
1246
1247   /* Hash table of abbrevs.
1248      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1249      It could be statically allocated, but the previous code didn't so we
1250      don't either.  */
1251   struct abbrev_info **m_abbrevs;
1252 };
1253
1254 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1255
1256 /* Attributes have a name and a value.  */
1257 struct attribute
1258   {
1259     ENUM_BITFIELD(dwarf_attribute) name : 16;
1260     ENUM_BITFIELD(dwarf_form) form : 15;
1261
1262     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1263        field should be in u.str (existing only for DW_STRING) but it is kept
1264        here for better struct attribute alignment.  */
1265     unsigned int string_is_canonical : 1;
1266
1267     union
1268       {
1269         const char *str;
1270         struct dwarf_block *blk;
1271         ULONGEST unsnd;
1272         LONGEST snd;
1273         CORE_ADDR addr;
1274         ULONGEST signature;
1275       }
1276     u;
1277   };
1278
1279 /* This data structure holds a complete die structure.  */
1280 struct die_info
1281   {
1282     /* DWARF-2 tag for this DIE.  */
1283     ENUM_BITFIELD(dwarf_tag) tag : 16;
1284
1285     /* Number of attributes */
1286     unsigned char num_attrs;
1287
1288     /* True if we're presently building the full type name for the
1289        type derived from this DIE.  */
1290     unsigned char building_fullname : 1;
1291
1292     /* True if this die is in process.  PR 16581.  */
1293     unsigned char in_process : 1;
1294
1295     /* Abbrev number */
1296     unsigned int abbrev;
1297
1298     /* Offset in .debug_info or .debug_types section.  */
1299     sect_offset sect_off;
1300
1301     /* The dies in a compilation unit form an n-ary tree.  PARENT
1302        points to this die's parent; CHILD points to the first child of
1303        this node; and all the children of a given node are chained
1304        together via their SIBLING fields.  */
1305     struct die_info *child;     /* Its first child, if any.  */
1306     struct die_info *sibling;   /* Its next sibling, if any.  */
1307     struct die_info *parent;    /* Its parent, if any.  */
1308
1309     /* An array of attributes, with NUM_ATTRS elements.  There may be
1310        zero, but it's not common and zero-sized arrays are not
1311        sufficiently portable C.  */
1312     struct attribute attrs[1];
1313   };
1314
1315 /* Get at parts of an attribute structure.  */
1316
1317 #define DW_STRING(attr)    ((attr)->u.str)
1318 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1319 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1320 #define DW_BLOCK(attr)     ((attr)->u.blk)
1321 #define DW_SND(attr)       ((attr)->u.snd)
1322 #define DW_ADDR(attr)      ((attr)->u.addr)
1323 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1324
1325 /* Blocks are a bunch of untyped bytes.  */
1326 struct dwarf_block
1327   {
1328     size_t size;
1329
1330     /* Valid only if SIZE is not zero.  */
1331     const gdb_byte *data;
1332   };
1333
1334 #ifndef ATTR_ALLOC_CHUNK
1335 #define ATTR_ALLOC_CHUNK 4
1336 #endif
1337
1338 /* Allocate fields for structs, unions and enums in this size.  */
1339 #ifndef DW_FIELD_ALLOC_CHUNK
1340 #define DW_FIELD_ALLOC_CHUNK 4
1341 #endif
1342
1343 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1344    but this would require a corresponding change in unpack_field_as_long
1345    and friends.  */
1346 static int bits_per_byte = 8;
1347
1348 /* When reading a variant or variant part, we track a bit more
1349    information about the field, and store it in an object of this
1350    type.  */
1351
1352 struct variant_field
1353 {
1354   /* If we see a DW_TAG_variant, then this will be the discriminant
1355      value.  */
1356   ULONGEST discriminant_value;
1357   /* If we see a DW_TAG_variant, then this will be set if this is the
1358      default branch.  */
1359   bool default_branch;
1360   /* While reading a DW_TAG_variant_part, this will be set if this
1361      field is the discriminant.  */
1362   bool is_discriminant;
1363 };
1364
1365 struct nextfield
1366 {
1367   int accessibility = 0;
1368   int virtuality = 0;
1369   /* Extra information to describe a variant or variant part.  */
1370   struct variant_field variant {};
1371   struct field field {};
1372 };
1373
1374 struct fnfieldlist
1375 {
1376   const char *name = nullptr;
1377   std::vector<struct fn_field> fnfields;
1378 };
1379
1380 /* The routines that read and process dies for a C struct or C++ class
1381    pass lists of data member fields and lists of member function fields
1382    in an instance of a field_info structure, as defined below.  */
1383 struct field_info
1384   {
1385     /* List of data member and baseclasses fields.  */
1386     std::vector<struct nextfield> fields;
1387     std::vector<struct nextfield> baseclasses;
1388
1389     /* Number of fields (including baseclasses).  */
1390     int nfields = 0;
1391
1392     /* Set if the accesibility of one of the fields is not public.  */
1393     int non_public_fields = 0;
1394
1395     /* Member function fieldlist array, contains name of possibly overloaded
1396        member function, number of overloaded member functions and a pointer
1397        to the head of the member function field chain.  */
1398     std::vector<struct fnfieldlist> fnfieldlists;
1399
1400     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1401        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1402     std::vector<struct decl_field> typedef_field_list;
1403
1404     /* Nested types defined by this class and the number of elements in this
1405        list.  */
1406     std::vector<struct decl_field> nested_types_list;
1407   };
1408
1409 /* One item on the queue of compilation units to read in full symbols
1410    for.  */
1411 struct dwarf2_queue_item
1412 {
1413   struct dwarf2_per_cu_data *per_cu;
1414   enum language pretend_language;
1415   struct dwarf2_queue_item *next;
1416 };
1417
1418 /* The current queue.  */
1419 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1420
1421 /* Loaded secondary compilation units are kept in memory until they
1422    have not been referenced for the processing of this many
1423    compilation units.  Set this to zero to disable caching.  Cache
1424    sizes of up to at least twenty will improve startup time for
1425    typical inter-CU-reference binaries, at an obvious memory cost.  */
1426 static int dwarf_max_cache_age = 5;
1427 static void
1428 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1429                           struct cmd_list_element *c, const char *value)
1430 {
1431   fprintf_filtered (file, _("The upper bound on the age of cached "
1432                             "DWARF compilation units is %s.\n"),
1433                     value);
1434 }
1435 \f
1436 /* local function prototypes */
1437
1438 static const char *get_section_name (const struct dwarf2_section_info *);
1439
1440 static const char *get_section_file_name (const struct dwarf2_section_info *);
1441
1442 static void dwarf2_find_base_address (struct die_info *die,
1443                                       struct dwarf2_cu *cu);
1444
1445 static struct partial_symtab *create_partial_symtab
1446   (struct dwarf2_per_cu_data *per_cu, const char *name);
1447
1448 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1449                                         const gdb_byte *info_ptr,
1450                                         struct die_info *type_unit_die,
1451                                         int has_children, void *data);
1452
1453 static void dwarf2_build_psymtabs_hard
1454   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1455
1456 static void scan_partial_symbols (struct partial_die_info *,
1457                                   CORE_ADDR *, CORE_ADDR *,
1458                                   int, struct dwarf2_cu *);
1459
1460 static void add_partial_symbol (struct partial_die_info *,
1461                                 struct dwarf2_cu *);
1462
1463 static void add_partial_namespace (struct partial_die_info *pdi,
1464                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1465                                    int set_addrmap, struct dwarf2_cu *cu);
1466
1467 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1468                                 CORE_ADDR *highpc, int set_addrmap,
1469                                 struct dwarf2_cu *cu);
1470
1471 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1472                                      struct dwarf2_cu *cu);
1473
1474 static void add_partial_subprogram (struct partial_die_info *pdi,
1475                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1476                                     int need_pc, struct dwarf2_cu *cu);
1477
1478 static void dwarf2_read_symtab (struct partial_symtab *,
1479                                 struct objfile *);
1480
1481 static void psymtab_to_symtab_1 (struct partial_symtab *);
1482
1483 static abbrev_table_up abbrev_table_read_table
1484   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1485    sect_offset);
1486
1487 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1488
1489 static struct partial_die_info *load_partial_dies
1490   (const struct die_reader_specs *, const gdb_byte *, int);
1491
1492 /* A pair of partial_die_info and compilation unit.  */
1493 struct cu_partial_die_info
1494 {
1495   /* The compilation unit of the partial_die_info.  */
1496   struct dwarf2_cu *cu;
1497   /* A partial_die_info.  */
1498   struct partial_die_info *pdi;
1499
1500   cu_partial_die_info (struct dwarf2_cu *cu, struct partial_die_info *pdi)
1501     : cu (cu),
1502       pdi (pdi)
1503   { /* Nothhing.  */ }
1504
1505 private:
1506   cu_partial_die_info () = delete;
1507 };
1508
1509 static const struct cu_partial_die_info find_partial_die (sect_offset, int,
1510                                                           struct dwarf2_cu *);
1511
1512 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1513                                        struct attribute *, struct attr_abbrev *,
1514                                        const gdb_byte *);
1515
1516 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1517
1518 static int read_1_signed_byte (bfd *, const gdb_byte *);
1519
1520 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1521
1522 /* Read the next three bytes (little-endian order) as an unsigned integer.  */
1523 static unsigned int read_3_bytes (bfd *, const gdb_byte *);
1524
1525 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1526
1527 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1528
1529 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1530                                unsigned int *);
1531
1532 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1533
1534 static LONGEST read_checked_initial_length_and_offset
1535   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1536    unsigned int *, unsigned int *);
1537
1538 static LONGEST read_offset (bfd *, const gdb_byte *,
1539                             const struct comp_unit_head *,
1540                             unsigned int *);
1541
1542 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1543
1544 static sect_offset read_abbrev_offset
1545   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1546    struct dwarf2_section_info *, sect_offset);
1547
1548 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1549
1550 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1551
1552 static const char *read_indirect_string
1553   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1554    const struct comp_unit_head *, unsigned int *);
1555
1556 static const char *read_indirect_line_string
1557   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1558    const struct comp_unit_head *, unsigned int *);
1559
1560 static const char *read_indirect_string_at_offset
1561   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1562    LONGEST str_offset);
1563
1564 static const char *read_indirect_string_from_dwz
1565   (struct objfile *objfile, struct dwz_file *, LONGEST);
1566
1567 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1568
1569 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1570                                               const gdb_byte *,
1571                                               unsigned int *);
1572
1573 static const char *read_str_index (const struct die_reader_specs *reader,
1574                                    ULONGEST str_index);
1575
1576 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1577
1578 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1579                                       struct dwarf2_cu *);
1580
1581 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1582                                                 unsigned int);
1583
1584 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1585                                        struct dwarf2_cu *cu);
1586
1587 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1588                                struct dwarf2_cu *cu);
1589
1590 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1591
1592 static struct die_info *die_specification (struct die_info *die,
1593                                            struct dwarf2_cu **);
1594
1595 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1596                                                 struct dwarf2_cu *cu);
1597
1598 static void dwarf_decode_lines (struct line_header *, const char *,
1599                                 struct dwarf2_cu *, struct partial_symtab *,
1600                                 CORE_ADDR, int decode_mapping);
1601
1602 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1603                                   const char *);
1604
1605 static struct symbol *new_symbol (struct die_info *, struct type *,
1606                                   struct dwarf2_cu *, struct symbol * = NULL);
1607
1608 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1609                                 struct dwarf2_cu *);
1610
1611 static void dwarf2_const_value_attr (const struct attribute *attr,
1612                                      struct type *type,
1613                                      const char *name,
1614                                      struct obstack *obstack,
1615                                      struct dwarf2_cu *cu, LONGEST *value,
1616                                      const gdb_byte **bytes,
1617                                      struct dwarf2_locexpr_baton **baton);
1618
1619 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1620
1621 static int need_gnat_info (struct dwarf2_cu *);
1622
1623 static struct type *die_descriptive_type (struct die_info *,
1624                                           struct dwarf2_cu *);
1625
1626 static void set_descriptive_type (struct type *, struct die_info *,
1627                                   struct dwarf2_cu *);
1628
1629 static struct type *die_containing_type (struct die_info *,
1630                                          struct dwarf2_cu *);
1631
1632 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1633                                      struct dwarf2_cu *);
1634
1635 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1636
1637 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1638
1639 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1640
1641 static char *typename_concat (struct obstack *obs, const char *prefix,
1642                               const char *suffix, int physname,
1643                               struct dwarf2_cu *cu);
1644
1645 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1646
1647 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1648
1649 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1650
1651 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1652
1653 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1654
1655 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1656
1657 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1658                                struct dwarf2_cu *, struct partial_symtab *);
1659
1660 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1661    values.  Keep the items ordered with increasing constraints compliance.  */
1662 enum pc_bounds_kind
1663 {
1664   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1665   PC_BOUNDS_NOT_PRESENT,
1666
1667   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1668      were present but they do not form a valid range of PC addresses.  */
1669   PC_BOUNDS_INVALID,
1670
1671   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1672   PC_BOUNDS_RANGES,
1673
1674   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1675   PC_BOUNDS_HIGH_LOW,
1676 };
1677
1678 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1679                                                  CORE_ADDR *, CORE_ADDR *,
1680                                                  struct dwarf2_cu *,
1681                                                  struct partial_symtab *);
1682
1683 static void get_scope_pc_bounds (struct die_info *,
1684                                  CORE_ADDR *, CORE_ADDR *,
1685                                  struct dwarf2_cu *);
1686
1687 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1688                                         CORE_ADDR, struct dwarf2_cu *);
1689
1690 static void dwarf2_add_field (struct field_info *, struct die_info *,
1691                               struct dwarf2_cu *);
1692
1693 static void dwarf2_attach_fields_to_type (struct field_info *,
1694                                           struct type *, struct dwarf2_cu *);
1695
1696 static void dwarf2_add_member_fn (struct field_info *,
1697                                   struct die_info *, struct type *,
1698                                   struct dwarf2_cu *);
1699
1700 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1701                                              struct type *,
1702                                              struct dwarf2_cu *);
1703
1704 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1705
1706 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1707
1708 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1709
1710 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1711
1712 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1713
1714 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1715
1716 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1717
1718 static struct type *read_module_type (struct die_info *die,
1719                                       struct dwarf2_cu *cu);
1720
1721 static const char *namespace_name (struct die_info *die,
1722                                    int *is_anonymous, struct dwarf2_cu *);
1723
1724 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1725
1726 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1727
1728 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1729                                                        struct dwarf2_cu *);
1730
1731 static struct die_info *read_die_and_siblings_1
1732   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1733    struct die_info *);
1734
1735 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1736                                                const gdb_byte *info_ptr,
1737                                                const gdb_byte **new_info_ptr,
1738                                                struct die_info *parent);
1739
1740 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1741                                         struct die_info **, const gdb_byte *,
1742                                         int *, int);
1743
1744 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1745                                       struct die_info **, const gdb_byte *,
1746                                       int *);
1747
1748 static void process_die (struct die_info *, struct dwarf2_cu *);
1749
1750 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1751                                              struct obstack *);
1752
1753 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1754
1755 static const char *dwarf2_full_name (const char *name,
1756                                      struct die_info *die,
1757                                      struct dwarf2_cu *cu);
1758
1759 static const char *dwarf2_physname (const char *name, struct die_info *die,
1760                                     struct dwarf2_cu *cu);
1761
1762 static struct die_info *dwarf2_extension (struct die_info *die,
1763                                           struct dwarf2_cu **);
1764
1765 static const char *dwarf_tag_name (unsigned int);
1766
1767 static const char *dwarf_attr_name (unsigned int);
1768
1769 static const char *dwarf_form_name (unsigned int);
1770
1771 static const char *dwarf_bool_name (unsigned int);
1772
1773 static const char *dwarf_type_encoding_name (unsigned int);
1774
1775 static struct die_info *sibling_die (struct die_info *);
1776
1777 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1778
1779 static void dump_die_for_error (struct die_info *);
1780
1781 static void dump_die_1 (struct ui_file *, int level, int max_level,
1782                         struct die_info *);
1783
1784 /*static*/ void dump_die (struct die_info *, int max_level);
1785
1786 static void store_in_ref_table (struct die_info *,
1787                                 struct dwarf2_cu *);
1788
1789 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1790
1791 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1792
1793 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1794                                                const struct attribute *,
1795                                                struct dwarf2_cu **);
1796
1797 static struct die_info *follow_die_ref (struct die_info *,
1798                                         const struct attribute *,
1799                                         struct dwarf2_cu **);
1800
1801 static struct die_info *follow_die_sig (struct die_info *,
1802                                         const struct attribute *,
1803                                         struct dwarf2_cu **);
1804
1805 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1806                                          struct dwarf2_cu *);
1807
1808 static struct type *get_DW_AT_signature_type (struct die_info *,
1809                                               const struct attribute *,
1810                                               struct dwarf2_cu *);
1811
1812 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1813
1814 static void read_signatured_type (struct signatured_type *);
1815
1816 static int attr_to_dynamic_prop (const struct attribute *attr,
1817                                  struct die_info *die, struct dwarf2_cu *cu,
1818                                  struct dynamic_prop *prop);
1819
1820 /* memory allocation interface */
1821
1822 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1823
1824 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1825
1826 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1827
1828 static int attr_form_is_block (const struct attribute *);
1829
1830 static int attr_form_is_section_offset (const struct attribute *);
1831
1832 static int attr_form_is_constant (const struct attribute *);
1833
1834 static int attr_form_is_ref (const struct attribute *);
1835
1836 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1837                                    struct dwarf2_loclist_baton *baton,
1838                                    const struct attribute *attr);
1839
1840 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1841                                          struct symbol *sym,
1842                                          struct dwarf2_cu *cu,
1843                                          int is_block);
1844
1845 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1846                                      const gdb_byte *info_ptr,
1847                                      struct abbrev_info *abbrev);
1848
1849 static hashval_t partial_die_hash (const void *item);
1850
1851 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1852
1853 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1854   (sect_offset sect_off, unsigned int offset_in_dwz,
1855    struct dwarf2_per_objfile *dwarf2_per_objfile);
1856
1857 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1858                                    struct die_info *comp_unit_die,
1859                                    enum language pretend_language);
1860
1861 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1862
1863 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1864
1865 static struct type *set_die_type (struct die_info *, struct type *,
1866                                   struct dwarf2_cu *);
1867
1868 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1869
1870 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1871
1872 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1873                                  enum language);
1874
1875 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1876                                     enum language);
1877
1878 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1879                                     enum language);
1880
1881 static void dwarf2_add_dependence (struct dwarf2_cu *,
1882                                    struct dwarf2_per_cu_data *);
1883
1884 static void dwarf2_mark (struct dwarf2_cu *);
1885
1886 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1887
1888 static struct type *get_die_type_at_offset (sect_offset,
1889                                             struct dwarf2_per_cu_data *);
1890
1891 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1892
1893 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1894                              enum language pretend_language);
1895
1896 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1897
1898 /* Class, the destructor of which frees all allocated queue entries.  This
1899    will only have work to do if an error was thrown while processing the
1900    dwarf.  If no error was thrown then the queue entries should have all
1901    been processed, and freed, as we went along.  */
1902
1903 class dwarf2_queue_guard
1904 {
1905 public:
1906   dwarf2_queue_guard () = default;
1907
1908   /* Free any entries remaining on the queue.  There should only be
1909      entries left if we hit an error while processing the dwarf.  */
1910   ~dwarf2_queue_guard ()
1911   {
1912     struct dwarf2_queue_item *item, *last;
1913
1914     item = dwarf2_queue;
1915     while (item)
1916       {
1917         /* Anything still marked queued is likely to be in an
1918            inconsistent state, so discard it.  */
1919         if (item->per_cu->queued)
1920           {
1921             if (item->per_cu->cu != NULL)
1922               free_one_cached_comp_unit (item->per_cu);
1923             item->per_cu->queued = 0;
1924           }
1925
1926         last = item;
1927         item = item->next;
1928         xfree (last);
1929       }
1930
1931     dwarf2_queue = dwarf2_queue_tail = NULL;
1932   }
1933 };
1934
1935 /* The return type of find_file_and_directory.  Note, the enclosed
1936    string pointers are only valid while this object is valid.  */
1937
1938 struct file_and_directory
1939 {
1940   /* The filename.  This is never NULL.  */
1941   const char *name;
1942
1943   /* The compilation directory.  NULL if not known.  If we needed to
1944      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1945      points directly to the DW_AT_comp_dir string attribute owned by
1946      the obstack that owns the DIE.  */
1947   const char *comp_dir;
1948
1949   /* If we needed to build a new string for comp_dir, this is what
1950      owns the storage.  */
1951   std::string comp_dir_storage;
1952 };
1953
1954 static file_and_directory find_file_and_directory (struct die_info *die,
1955                                                    struct dwarf2_cu *cu);
1956
1957 static char *file_full_name (int file, struct line_header *lh,
1958                              const char *comp_dir);
1959
1960 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1961 enum class rcuh_kind { COMPILE, TYPE };
1962
1963 static const gdb_byte *read_and_check_comp_unit_head
1964   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1965    struct comp_unit_head *header,
1966    struct dwarf2_section_info *section,
1967    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1968    rcuh_kind section_kind);
1969
1970 static void init_cutu_and_read_dies
1971   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1972    int use_existing_cu, int keep, bool skip_partial,
1973    die_reader_func_ftype *die_reader_func, void *data);
1974
1975 static void init_cutu_and_read_dies_simple
1976   (struct dwarf2_per_cu_data *this_cu,
1977    die_reader_func_ftype *die_reader_func, void *data);
1978
1979 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1980
1981 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1982
1983 static struct dwo_unit *lookup_dwo_unit_in_dwp
1984   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1985    struct dwp_file *dwp_file, const char *comp_dir,
1986    ULONGEST signature, int is_debug_types);
1987
1988 static struct dwp_file *get_dwp_file
1989   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1990
1991 static struct dwo_unit *lookup_dwo_comp_unit
1992   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1993
1994 static struct dwo_unit *lookup_dwo_type_unit
1995   (struct signatured_type *, const char *, const char *);
1996
1997 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1998
1999 /* A unique pointer to a dwo_file.  */
2000
2001 typedef std::unique_ptr<struct dwo_file> dwo_file_up;
2002
2003 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2004
2005 static void check_producer (struct dwarf2_cu *cu);
2006
2007 static void free_line_header_voidp (void *arg);
2008 \f
2009 /* Various complaints about symbol reading that don't abort the process.  */
2010
2011 static void
2012 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2013 {
2014   complaint (_("statement list doesn't fit in .debug_line section"));
2015 }
2016
2017 static void
2018 dwarf2_debug_line_missing_file_complaint (void)
2019 {
2020   complaint (_(".debug_line section has line data without a file"));
2021 }
2022
2023 static void
2024 dwarf2_debug_line_missing_end_sequence_complaint (void)
2025 {
2026   complaint (_(".debug_line section has line "
2027                "program sequence without an end"));
2028 }
2029
2030 static void
2031 dwarf2_complex_location_expr_complaint (void)
2032 {
2033   complaint (_("location expression too complex"));
2034 }
2035
2036 static void
2037 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2038                                               int arg3)
2039 {
2040   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2041              arg1, arg2, arg3);
2042 }
2043
2044 static void
2045 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2046 {
2047   complaint (_("debug info runs off end of %s section"
2048                " [in module %s]"),
2049              get_section_name (section),
2050              get_section_file_name (section));
2051 }
2052
2053 static void
2054 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2055 {
2056   complaint (_("macro debug info contains a "
2057                "malformed macro definition:\n`%s'"),
2058              arg1);
2059 }
2060
2061 static void
2062 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2063 {
2064   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2065              arg1, arg2);
2066 }
2067
2068 /* Hash function for line_header_hash.  */
2069
2070 static hashval_t
2071 line_header_hash (const struct line_header *ofs)
2072 {
2073   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2074 }
2075
2076 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2077
2078 static hashval_t
2079 line_header_hash_voidp (const void *item)
2080 {
2081   const struct line_header *ofs = (const struct line_header *) item;
2082
2083   return line_header_hash (ofs);
2084 }
2085
2086 /* Equality function for line_header_hash.  */
2087
2088 static int
2089 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2090 {
2091   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2092   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2093
2094   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2095           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2096 }
2097
2098 \f
2099
2100 /* Read the given attribute value as an address, taking the attribute's
2101    form into account.  */
2102
2103 static CORE_ADDR
2104 attr_value_as_address (struct attribute *attr)
2105 {
2106   CORE_ADDR addr;
2107
2108   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_addrx
2109       && attr->form != DW_FORM_GNU_addr_index)
2110     {
2111       /* Aside from a few clearly defined exceptions, attributes that
2112          contain an address must always be in DW_FORM_addr form.
2113          Unfortunately, some compilers happen to be violating this
2114          requirement by encoding addresses using other forms, such
2115          as DW_FORM_data4 for example.  For those broken compilers,
2116          we try to do our best, without any guarantee of success,
2117          to interpret the address correctly.  It would also be nice
2118          to generate a complaint, but that would require us to maintain
2119          a list of legitimate cases where a non-address form is allowed,
2120          as well as update callers to pass in at least the CU's DWARF
2121          version.  This is more overhead than what we're willing to
2122          expand for a pretty rare case.  */
2123       addr = DW_UNSND (attr);
2124     }
2125   else
2126     addr = DW_ADDR (attr);
2127
2128   return addr;
2129 }
2130
2131 /* See declaration.  */
2132
2133 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2134                                         const dwarf2_debug_sections *names)
2135   : objfile (objfile_)
2136 {
2137   if (names == NULL)
2138     names = &dwarf2_elf_names;
2139
2140   bfd *obfd = objfile->obfd;
2141
2142   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2143     locate_sections (obfd, sec, *names);
2144 }
2145
2146 dwarf2_per_objfile::~dwarf2_per_objfile ()
2147 {
2148   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2149   free_cached_comp_units ();
2150
2151   if (quick_file_names_table)
2152     htab_delete (quick_file_names_table);
2153
2154   if (line_header_hash)
2155     htab_delete (line_header_hash);
2156
2157   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2158     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2159
2160   for (signatured_type *sig_type : all_type_units)
2161     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2162
2163   VEC_free (dwarf2_section_info_def, types);
2164
2165   /* Everything else should be on the objfile obstack.  */
2166 }
2167
2168 /* See declaration.  */
2169
2170 void
2171 dwarf2_per_objfile::free_cached_comp_units ()
2172 {
2173   dwarf2_per_cu_data *per_cu = read_in_chain;
2174   dwarf2_per_cu_data **last_chain = &read_in_chain;
2175   while (per_cu != NULL)
2176     {
2177       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2178
2179       delete per_cu->cu;
2180       *last_chain = next_cu;
2181       per_cu = next_cu;
2182     }
2183 }
2184
2185 /* A helper class that calls free_cached_comp_units on
2186    destruction.  */
2187
2188 class free_cached_comp_units
2189 {
2190 public:
2191
2192   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2193     : m_per_objfile (per_objfile)
2194   {
2195   }
2196
2197   ~free_cached_comp_units ()
2198   {
2199     m_per_objfile->free_cached_comp_units ();
2200   }
2201
2202   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2203
2204 private:
2205
2206   dwarf2_per_objfile *m_per_objfile;
2207 };
2208
2209 /* Try to locate the sections we need for DWARF 2 debugging
2210    information and return true if we have enough to do something.
2211    NAMES points to the dwarf2 section names, or is NULL if the standard
2212    ELF names are used.  */
2213
2214 int
2215 dwarf2_has_info (struct objfile *objfile,
2216                  const struct dwarf2_debug_sections *names)
2217 {
2218   if (objfile->flags & OBJF_READNEVER)
2219     return 0;
2220
2221   struct dwarf2_per_objfile *dwarf2_per_objfile
2222     = get_dwarf2_per_objfile (objfile);
2223
2224   if (dwarf2_per_objfile == NULL)
2225     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
2226                                                           names);
2227
2228   return (!dwarf2_per_objfile->info.is_virtual
2229           && dwarf2_per_objfile->info.s.section != NULL
2230           && !dwarf2_per_objfile->abbrev.is_virtual
2231           && dwarf2_per_objfile->abbrev.s.section != NULL);
2232 }
2233
2234 /* Return the containing section of virtual section SECTION.  */
2235
2236 static struct dwarf2_section_info *
2237 get_containing_section (const struct dwarf2_section_info *section)
2238 {
2239   gdb_assert (section->is_virtual);
2240   return section->s.containing_section;
2241 }
2242
2243 /* Return the bfd owner of SECTION.  */
2244
2245 static struct bfd *
2246 get_section_bfd_owner (const struct dwarf2_section_info *section)
2247 {
2248   if (section->is_virtual)
2249     {
2250       section = get_containing_section (section);
2251       gdb_assert (!section->is_virtual);
2252     }
2253   return section->s.section->owner;
2254 }
2255
2256 /* Return the bfd section of SECTION.
2257    Returns NULL if the section is not present.  */
2258
2259 static asection *
2260 get_section_bfd_section (const struct dwarf2_section_info *section)
2261 {
2262   if (section->is_virtual)
2263     {
2264       section = get_containing_section (section);
2265       gdb_assert (!section->is_virtual);
2266     }
2267   return section->s.section;
2268 }
2269
2270 /* Return the name of SECTION.  */
2271
2272 static const char *
2273 get_section_name (const struct dwarf2_section_info *section)
2274 {
2275   asection *sectp = get_section_bfd_section (section);
2276
2277   gdb_assert (sectp != NULL);
2278   return bfd_section_name (get_section_bfd_owner (section), sectp);
2279 }
2280
2281 /* Return the name of the file SECTION is in.  */
2282
2283 static const char *
2284 get_section_file_name (const struct dwarf2_section_info *section)
2285 {
2286   bfd *abfd = get_section_bfd_owner (section);
2287
2288   return bfd_get_filename (abfd);
2289 }
2290
2291 /* Return the id of SECTION.
2292    Returns 0 if SECTION doesn't exist.  */
2293
2294 static int
2295 get_section_id (const struct dwarf2_section_info *section)
2296 {
2297   asection *sectp = get_section_bfd_section (section);
2298
2299   if (sectp == NULL)
2300     return 0;
2301   return sectp->id;
2302 }
2303
2304 /* Return the flags of SECTION.
2305    SECTION (or containing section if this is a virtual section) must exist.  */
2306
2307 static int
2308 get_section_flags (const struct dwarf2_section_info *section)
2309 {
2310   asection *sectp = get_section_bfd_section (section);
2311
2312   gdb_assert (sectp != NULL);
2313   return bfd_get_section_flags (sectp->owner, sectp);
2314 }
2315
2316 /* When loading sections, we look either for uncompressed section or for
2317    compressed section names.  */
2318
2319 static int
2320 section_is_p (const char *section_name,
2321               const struct dwarf2_section_names *names)
2322 {
2323   if (names->normal != NULL
2324       && strcmp (section_name, names->normal) == 0)
2325     return 1;
2326   if (names->compressed != NULL
2327       && strcmp (section_name, names->compressed) == 0)
2328     return 1;
2329   return 0;
2330 }
2331
2332 /* See declaration.  */
2333
2334 void
2335 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2336                                      const dwarf2_debug_sections &names)
2337 {
2338   flagword aflag = bfd_get_section_flags (abfd, sectp);
2339
2340   if ((aflag & SEC_HAS_CONTENTS) == 0)
2341     {
2342     }
2343   else if (section_is_p (sectp->name, &names.info))
2344     {
2345       this->info.s.section = sectp;
2346       this->info.size = bfd_get_section_size (sectp);
2347     }
2348   else if (section_is_p (sectp->name, &names.abbrev))
2349     {
2350       this->abbrev.s.section = sectp;
2351       this->abbrev.size = bfd_get_section_size (sectp);
2352     }
2353   else if (section_is_p (sectp->name, &names.line))
2354     {
2355       this->line.s.section = sectp;
2356       this->line.size = bfd_get_section_size (sectp);
2357     }
2358   else if (section_is_p (sectp->name, &names.loc))
2359     {
2360       this->loc.s.section = sectp;
2361       this->loc.size = bfd_get_section_size (sectp);
2362     }
2363   else if (section_is_p (sectp->name, &names.loclists))
2364     {
2365       this->loclists.s.section = sectp;
2366       this->loclists.size = bfd_get_section_size (sectp);
2367     }
2368   else if (section_is_p (sectp->name, &names.macinfo))
2369     {
2370       this->macinfo.s.section = sectp;
2371       this->macinfo.size = bfd_get_section_size (sectp);
2372     }
2373   else if (section_is_p (sectp->name, &names.macro))
2374     {
2375       this->macro.s.section = sectp;
2376       this->macro.size = bfd_get_section_size (sectp);
2377     }
2378   else if (section_is_p (sectp->name, &names.str))
2379     {
2380       this->str.s.section = sectp;
2381       this->str.size = bfd_get_section_size (sectp);
2382     }
2383   else if (section_is_p (sectp->name, &names.line_str))
2384     {
2385       this->line_str.s.section = sectp;
2386       this->line_str.size = bfd_get_section_size (sectp);
2387     }
2388   else if (section_is_p (sectp->name, &names.addr))
2389     {
2390       this->addr.s.section = sectp;
2391       this->addr.size = bfd_get_section_size (sectp);
2392     }
2393   else if (section_is_p (sectp->name, &names.frame))
2394     {
2395       this->frame.s.section = sectp;
2396       this->frame.size = bfd_get_section_size (sectp);
2397     }
2398   else if (section_is_p (sectp->name, &names.eh_frame))
2399     {
2400       this->eh_frame.s.section = sectp;
2401       this->eh_frame.size = bfd_get_section_size (sectp);
2402     }
2403   else if (section_is_p (sectp->name, &names.ranges))
2404     {
2405       this->ranges.s.section = sectp;
2406       this->ranges.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.rnglists))
2409     {
2410       this->rnglists.s.section = sectp;
2411       this->rnglists.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.types))
2414     {
2415       struct dwarf2_section_info type_section;
2416
2417       memset (&type_section, 0, sizeof (type_section));
2418       type_section.s.section = sectp;
2419       type_section.size = bfd_get_section_size (sectp);
2420
2421       VEC_safe_push (dwarf2_section_info_def, this->types,
2422                      &type_section);
2423     }
2424   else if (section_is_p (sectp->name, &names.gdb_index))
2425     {
2426       this->gdb_index.s.section = sectp;
2427       this->gdb_index.size = bfd_get_section_size (sectp);
2428     }
2429   else if (section_is_p (sectp->name, &names.debug_names))
2430     {
2431       this->debug_names.s.section = sectp;
2432       this->debug_names.size = bfd_get_section_size (sectp);
2433     }
2434   else if (section_is_p (sectp->name, &names.debug_aranges))
2435     {
2436       this->debug_aranges.s.section = sectp;
2437       this->debug_aranges.size = bfd_get_section_size (sectp);
2438     }
2439
2440   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2441       && bfd_section_vma (abfd, sectp) == 0)
2442     this->has_section_at_zero = true;
2443 }
2444
2445 /* A helper function that decides whether a section is empty,
2446    or not present.  */
2447
2448 static int
2449 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2450 {
2451   if (section->is_virtual)
2452     return section->size == 0;
2453   return section->s.section == NULL || section->size == 0;
2454 }
2455
2456 /* See dwarf2read.h.  */
2457
2458 void
2459 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2460 {
2461   asection *sectp;
2462   bfd *abfd;
2463   gdb_byte *buf, *retbuf;
2464
2465   if (info->readin)
2466     return;
2467   info->buffer = NULL;
2468   info->readin = true;
2469
2470   if (dwarf2_section_empty_p (info))
2471     return;
2472
2473   sectp = get_section_bfd_section (info);
2474
2475   /* If this is a virtual section we need to read in the real one first.  */
2476   if (info->is_virtual)
2477     {
2478       struct dwarf2_section_info *containing_section =
2479         get_containing_section (info);
2480
2481       gdb_assert (sectp != NULL);
2482       if ((sectp->flags & SEC_RELOC) != 0)
2483         {
2484           error (_("Dwarf Error: DWP format V2 with relocations is not"
2485                    " supported in section %s [in module %s]"),
2486                  get_section_name (info), get_section_file_name (info));
2487         }
2488       dwarf2_read_section (objfile, containing_section);
2489       /* Other code should have already caught virtual sections that don't
2490          fit.  */
2491       gdb_assert (info->virtual_offset + info->size
2492                   <= containing_section->size);
2493       /* If the real section is empty or there was a problem reading the
2494          section we shouldn't get here.  */
2495       gdb_assert (containing_section->buffer != NULL);
2496       info->buffer = containing_section->buffer + info->virtual_offset;
2497       return;
2498     }
2499
2500   /* If the section has relocations, we must read it ourselves.
2501      Otherwise we attach it to the BFD.  */
2502   if ((sectp->flags & SEC_RELOC) == 0)
2503     {
2504       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2505       return;
2506     }
2507
2508   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2509   info->buffer = buf;
2510
2511   /* When debugging .o files, we may need to apply relocations; see
2512      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2513      We never compress sections in .o files, so we only need to
2514      try this when the section is not compressed.  */
2515   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2516   if (retbuf != NULL)
2517     {
2518       info->buffer = retbuf;
2519       return;
2520     }
2521
2522   abfd = get_section_bfd_owner (info);
2523   gdb_assert (abfd != NULL);
2524
2525   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2526       || bfd_bread (buf, info->size, abfd) != info->size)
2527     {
2528       error (_("Dwarf Error: Can't read DWARF data"
2529                " in section %s [in module %s]"),
2530              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2531     }
2532 }
2533
2534 /* A helper function that returns the size of a section in a safe way.
2535    If you are positive that the section has been read before using the
2536    size, then it is safe to refer to the dwarf2_section_info object's
2537    "size" field directly.  In other cases, you must call this
2538    function, because for compressed sections the size field is not set
2539    correctly until the section has been read.  */
2540
2541 static bfd_size_type
2542 dwarf2_section_size (struct objfile *objfile,
2543                      struct dwarf2_section_info *info)
2544 {
2545   if (!info->readin)
2546     dwarf2_read_section (objfile, info);
2547   return info->size;
2548 }
2549
2550 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2551    SECTION_NAME.  */
2552
2553 void
2554 dwarf2_get_section_info (struct objfile *objfile,
2555                          enum dwarf2_section_enum sect,
2556                          asection **sectp, const gdb_byte **bufp,
2557                          bfd_size_type *sizep)
2558 {
2559   struct dwarf2_per_objfile *data = dwarf2_objfile_data_key.get (objfile);
2560   struct dwarf2_section_info *info;
2561
2562   /* We may see an objfile without any DWARF, in which case we just
2563      return nothing.  */
2564   if (data == NULL)
2565     {
2566       *sectp = NULL;
2567       *bufp = NULL;
2568       *sizep = 0;
2569       return;
2570     }
2571   switch (sect)
2572     {
2573     case DWARF2_DEBUG_FRAME:
2574       info = &data->frame;
2575       break;
2576     case DWARF2_EH_FRAME:
2577       info = &data->eh_frame;
2578       break;
2579     default:
2580       gdb_assert_not_reached ("unexpected section");
2581     }
2582
2583   dwarf2_read_section (objfile, info);
2584
2585   *sectp = get_section_bfd_section (info);
2586   *bufp = info->buffer;
2587   *sizep = info->size;
2588 }
2589
2590 /* A helper function to find the sections for a .dwz file.  */
2591
2592 static void
2593 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2594 {
2595   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2596
2597   /* Note that we only support the standard ELF names, because .dwz
2598      is ELF-only (at the time of writing).  */
2599   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2600     {
2601       dwz_file->abbrev.s.section = sectp;
2602       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2603     }
2604   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2605     {
2606       dwz_file->info.s.section = sectp;
2607       dwz_file->info.size = bfd_get_section_size (sectp);
2608     }
2609   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2610     {
2611       dwz_file->str.s.section = sectp;
2612       dwz_file->str.size = bfd_get_section_size (sectp);
2613     }
2614   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2615     {
2616       dwz_file->line.s.section = sectp;
2617       dwz_file->line.size = bfd_get_section_size (sectp);
2618     }
2619   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2620     {
2621       dwz_file->macro.s.section = sectp;
2622       dwz_file->macro.size = bfd_get_section_size (sectp);
2623     }
2624   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2625     {
2626       dwz_file->gdb_index.s.section = sectp;
2627       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2628     }
2629   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2630     {
2631       dwz_file->debug_names.s.section = sectp;
2632       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2633     }
2634 }
2635
2636 /* See dwarf2read.h.  */
2637
2638 struct dwz_file *
2639 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2640 {
2641   const char *filename;
2642   bfd_size_type buildid_len_arg;
2643   size_t buildid_len;
2644   bfd_byte *buildid;
2645
2646   if (dwarf2_per_objfile->dwz_file != NULL)
2647     return dwarf2_per_objfile->dwz_file.get ();
2648
2649   bfd_set_error (bfd_error_no_error);
2650   gdb::unique_xmalloc_ptr<char> data
2651     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2652                                   &buildid_len_arg, &buildid));
2653   if (data == NULL)
2654     {
2655       if (bfd_get_error () == bfd_error_no_error)
2656         return NULL;
2657       error (_("could not read '.gnu_debugaltlink' section: %s"),
2658              bfd_errmsg (bfd_get_error ()));
2659     }
2660
2661   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2662
2663   buildid_len = (size_t) buildid_len_arg;
2664
2665   filename = data.get ();
2666
2667   std::string abs_storage;
2668   if (!IS_ABSOLUTE_PATH (filename))
2669     {
2670       gdb::unique_xmalloc_ptr<char> abs
2671         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2672
2673       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2674       filename = abs_storage.c_str ();
2675     }
2676
2677   /* First try the file name given in the section.  If that doesn't
2678      work, try to use the build-id instead.  */
2679   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2680   if (dwz_bfd != NULL)
2681     {
2682       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2683         dwz_bfd.reset (nullptr);
2684     }
2685
2686   if (dwz_bfd == NULL)
2687     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2688
2689   if (dwz_bfd == NULL)
2690     error (_("could not find '.gnu_debugaltlink' file for %s"),
2691            objfile_name (dwarf2_per_objfile->objfile));
2692
2693   std::unique_ptr<struct dwz_file> result
2694     (new struct dwz_file (std::move (dwz_bfd)));
2695
2696   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2697                          result.get ());
2698
2699   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2700                             result->dwz_bfd.get ());
2701   dwarf2_per_objfile->dwz_file = std::move (result);
2702   return dwarf2_per_objfile->dwz_file.get ();
2703 }
2704 \f
2705 /* DWARF quick_symbols_functions support.  */
2706
2707 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2708    unique line tables, so we maintain a separate table of all .debug_line
2709    derived entries to support the sharing.
2710    All the quick functions need is the list of file names.  We discard the
2711    line_header when we're done and don't need to record it here.  */
2712 struct quick_file_names
2713 {
2714   /* The data used to construct the hash key.  */
2715   struct stmt_list_hash hash;
2716
2717   /* The number of entries in file_names, real_names.  */
2718   unsigned int num_file_names;
2719
2720   /* The file names from the line table, after being run through
2721      file_full_name.  */
2722   const char **file_names;
2723
2724   /* The file names from the line table after being run through
2725      gdb_realpath.  These are computed lazily.  */
2726   const char **real_names;
2727 };
2728
2729 /* When using the index (and thus not using psymtabs), each CU has an
2730    object of this type.  This is used to hold information needed by
2731    the various "quick" methods.  */
2732 struct dwarf2_per_cu_quick_data
2733 {
2734   /* The file table.  This can be NULL if there was no file table
2735      or it's currently not read in.
2736      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2737   struct quick_file_names *file_names;
2738
2739   /* The corresponding symbol table.  This is NULL if symbols for this
2740      CU have not yet been read.  */
2741   struct compunit_symtab *compunit_symtab;
2742
2743   /* A temporary mark bit used when iterating over all CUs in
2744      expand_symtabs_matching.  */
2745   unsigned int mark : 1;
2746
2747   /* True if we've tried to read the file table and found there isn't one.
2748      There will be no point in trying to read it again next time.  */
2749   unsigned int no_file_data : 1;
2750 };
2751
2752 /* Utility hash function for a stmt_list_hash.  */
2753
2754 static hashval_t
2755 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2756 {
2757   hashval_t v = 0;
2758
2759   if (stmt_list_hash->dwo_unit != NULL)
2760     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2761   v += to_underlying (stmt_list_hash->line_sect_off);
2762   return v;
2763 }
2764
2765 /* Utility equality function for a stmt_list_hash.  */
2766
2767 static int
2768 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2769                     const struct stmt_list_hash *rhs)
2770 {
2771   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2772     return 0;
2773   if (lhs->dwo_unit != NULL
2774       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2775     return 0;
2776
2777   return lhs->line_sect_off == rhs->line_sect_off;
2778 }
2779
2780 /* Hash function for a quick_file_names.  */
2781
2782 static hashval_t
2783 hash_file_name_entry (const void *e)
2784 {
2785   const struct quick_file_names *file_data
2786     = (const struct quick_file_names *) e;
2787
2788   return hash_stmt_list_entry (&file_data->hash);
2789 }
2790
2791 /* Equality function for a quick_file_names.  */
2792
2793 static int
2794 eq_file_name_entry (const void *a, const void *b)
2795 {
2796   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2797   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2798
2799   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2800 }
2801
2802 /* Delete function for a quick_file_names.  */
2803
2804 static void
2805 delete_file_name_entry (void *e)
2806 {
2807   struct quick_file_names *file_data = (struct quick_file_names *) e;
2808   int i;
2809
2810   for (i = 0; i < file_data->num_file_names; ++i)
2811     {
2812       xfree ((void*) file_data->file_names[i]);
2813       if (file_data->real_names)
2814         xfree ((void*) file_data->real_names[i]);
2815     }
2816
2817   /* The space for the struct itself lives on objfile_obstack,
2818      so we don't free it here.  */
2819 }
2820
2821 /* Create a quick_file_names hash table.  */
2822
2823 static htab_t
2824 create_quick_file_names_table (unsigned int nr_initial_entries)
2825 {
2826   return htab_create_alloc (nr_initial_entries,
2827                             hash_file_name_entry, eq_file_name_entry,
2828                             delete_file_name_entry, xcalloc, xfree);
2829 }
2830
2831 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2832    have to be created afterwards.  You should call age_cached_comp_units after
2833    processing PER_CU->CU.  dw2_setup must have been already called.  */
2834
2835 static void
2836 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2837 {
2838   if (per_cu->is_debug_types)
2839     load_full_type_unit (per_cu);
2840   else
2841     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2842
2843   if (per_cu->cu == NULL)
2844     return;  /* Dummy CU.  */
2845
2846   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2847 }
2848
2849 /* Read in the symbols for PER_CU.  */
2850
2851 static void
2852 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2853 {
2854   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2855
2856   /* Skip type_unit_groups, reading the type units they contain
2857      is handled elsewhere.  */
2858   if (IS_TYPE_UNIT_GROUP (per_cu))
2859     return;
2860
2861   /* The destructor of dwarf2_queue_guard frees any entries left on
2862      the queue.  After this point we're guaranteed to leave this function
2863      with the dwarf queue empty.  */
2864   dwarf2_queue_guard q_guard;
2865
2866   if (dwarf2_per_objfile->using_index
2867       ? per_cu->v.quick->compunit_symtab == NULL
2868       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2869     {
2870       queue_comp_unit (per_cu, language_minimal);
2871       load_cu (per_cu, skip_partial);
2872
2873       /* If we just loaded a CU from a DWO, and we're working with an index
2874          that may badly handle TUs, load all the TUs in that DWO as well.
2875          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2876       if (!per_cu->is_debug_types
2877           && per_cu->cu != NULL
2878           && per_cu->cu->dwo_unit != NULL
2879           && dwarf2_per_objfile->index_table != NULL
2880           && dwarf2_per_objfile->index_table->version <= 7
2881           /* DWP files aren't supported yet.  */
2882           && get_dwp_file (dwarf2_per_objfile) == NULL)
2883         queue_and_load_all_dwo_tus (per_cu);
2884     }
2885
2886   process_queue (dwarf2_per_objfile);
2887
2888   /* Age the cache, releasing compilation units that have not
2889      been used recently.  */
2890   age_cached_comp_units (dwarf2_per_objfile);
2891 }
2892
2893 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2894    the objfile from which this CU came.  Returns the resulting symbol
2895    table.  */
2896
2897 static struct compunit_symtab *
2898 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2899 {
2900   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2901
2902   gdb_assert (dwarf2_per_objfile->using_index);
2903   if (!per_cu->v.quick->compunit_symtab)
2904     {
2905       free_cached_comp_units freer (dwarf2_per_objfile);
2906       scoped_restore decrementer = increment_reading_symtab ();
2907       dw2_do_instantiate_symtab (per_cu, skip_partial);
2908       process_cu_includes (dwarf2_per_objfile);
2909     }
2910
2911   return per_cu->v.quick->compunit_symtab;
2912 }
2913
2914 /* See declaration.  */
2915
2916 dwarf2_per_cu_data *
2917 dwarf2_per_objfile::get_cutu (int index)
2918 {
2919   if (index >= this->all_comp_units.size ())
2920     {
2921       index -= this->all_comp_units.size ();
2922       gdb_assert (index < this->all_type_units.size ());
2923       return &this->all_type_units[index]->per_cu;
2924     }
2925
2926   return this->all_comp_units[index];
2927 }
2928
2929 /* See declaration.  */
2930
2931 dwarf2_per_cu_data *
2932 dwarf2_per_objfile::get_cu (int index)
2933 {
2934   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2935
2936   return this->all_comp_units[index];
2937 }
2938
2939 /* See declaration.  */
2940
2941 signatured_type *
2942 dwarf2_per_objfile::get_tu (int index)
2943 {
2944   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2945
2946   return this->all_type_units[index];
2947 }
2948
2949 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2950    objfile_obstack, and constructed with the specified field
2951    values.  */
2952
2953 static dwarf2_per_cu_data *
2954 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2955                           struct dwarf2_section_info *section,
2956                           int is_dwz,
2957                           sect_offset sect_off, ULONGEST length)
2958 {
2959   struct objfile *objfile = dwarf2_per_objfile->objfile;
2960   dwarf2_per_cu_data *the_cu
2961     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2962                      struct dwarf2_per_cu_data);
2963   the_cu->sect_off = sect_off;
2964   the_cu->length = length;
2965   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2966   the_cu->section = section;
2967   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2968                                    struct dwarf2_per_cu_quick_data);
2969   the_cu->is_dwz = is_dwz;
2970   return the_cu;
2971 }
2972
2973 /* A helper for create_cus_from_index that handles a given list of
2974    CUs.  */
2975
2976 static void
2977 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2978                             const gdb_byte *cu_list, offset_type n_elements,
2979                             struct dwarf2_section_info *section,
2980                             int is_dwz)
2981 {
2982   for (offset_type i = 0; i < n_elements; i += 2)
2983     {
2984       gdb_static_assert (sizeof (ULONGEST) >= 8);
2985
2986       sect_offset sect_off
2987         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2988       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2989       cu_list += 2 * 8;
2990
2991       dwarf2_per_cu_data *per_cu
2992         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2993                                      sect_off, length);
2994       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2995     }
2996 }
2997
2998 /* Read the CU list from the mapped index, and use it to create all
2999    the CU objects for this objfile.  */
3000
3001 static void
3002 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3003                        const gdb_byte *cu_list, offset_type cu_list_elements,
3004                        const gdb_byte *dwz_list, offset_type dwz_elements)
3005 {
3006   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3007   dwarf2_per_objfile->all_comp_units.reserve
3008     ((cu_list_elements + dwz_elements) / 2);
3009
3010   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3011                               &dwarf2_per_objfile->info, 0);
3012
3013   if (dwz_elements == 0)
3014     return;
3015
3016   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3017   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3018                               &dwz->info, 1);
3019 }
3020
3021 /* Create the signatured type hash table from the index.  */
3022
3023 static void
3024 create_signatured_type_table_from_index
3025   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3026    struct dwarf2_section_info *section,
3027    const gdb_byte *bytes,
3028    offset_type elements)
3029 {
3030   struct objfile *objfile = dwarf2_per_objfile->objfile;
3031
3032   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3033   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3034
3035   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3036
3037   for (offset_type i = 0; i < elements; i += 3)
3038     {
3039       struct signatured_type *sig_type;
3040       ULONGEST signature;
3041       void **slot;
3042       cu_offset type_offset_in_tu;
3043
3044       gdb_static_assert (sizeof (ULONGEST) >= 8);
3045       sect_offset sect_off
3046         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3047       type_offset_in_tu
3048         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3049                                                 BFD_ENDIAN_LITTLE);
3050       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3051       bytes += 3 * 8;
3052
3053       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3054                                  struct signatured_type);
3055       sig_type->signature = signature;
3056       sig_type->type_offset_in_tu = type_offset_in_tu;
3057       sig_type->per_cu.is_debug_types = 1;
3058       sig_type->per_cu.section = section;
3059       sig_type->per_cu.sect_off = sect_off;
3060       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3061       sig_type->per_cu.v.quick
3062         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3063                           struct dwarf2_per_cu_quick_data);
3064
3065       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3066       *slot = sig_type;
3067
3068       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3069     }
3070
3071   dwarf2_per_objfile->signatured_types = sig_types_hash;
3072 }
3073
3074 /* Create the signatured type hash table from .debug_names.  */
3075
3076 static void
3077 create_signatured_type_table_from_debug_names
3078   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3079    const mapped_debug_names &map,
3080    struct dwarf2_section_info *section,
3081    struct dwarf2_section_info *abbrev_section)
3082 {
3083   struct objfile *objfile = dwarf2_per_objfile->objfile;
3084
3085   dwarf2_read_section (objfile, section);
3086   dwarf2_read_section (objfile, abbrev_section);
3087
3088   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3089   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3090
3091   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3092
3093   for (uint32_t i = 0; i < map.tu_count; ++i)
3094     {
3095       struct signatured_type *sig_type;
3096       void **slot;
3097
3098       sect_offset sect_off
3099         = (sect_offset) (extract_unsigned_integer
3100                          (map.tu_table_reordered + i * map.offset_size,
3101                           map.offset_size,
3102                           map.dwarf5_byte_order));
3103
3104       comp_unit_head cu_header;
3105       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3106                                      abbrev_section,
3107                                      section->buffer + to_underlying (sect_off),
3108                                      rcuh_kind::TYPE);
3109
3110       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3111                                  struct signatured_type);
3112       sig_type->signature = cu_header.signature;
3113       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3114       sig_type->per_cu.is_debug_types = 1;
3115       sig_type->per_cu.section = section;
3116       sig_type->per_cu.sect_off = sect_off;
3117       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3118       sig_type->per_cu.v.quick
3119         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3120                           struct dwarf2_per_cu_quick_data);
3121
3122       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3123       *slot = sig_type;
3124
3125       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3126     }
3127
3128   dwarf2_per_objfile->signatured_types = sig_types_hash;
3129 }
3130
3131 /* Read the address map data from the mapped index, and use it to
3132    populate the objfile's psymtabs_addrmap.  */
3133
3134 static void
3135 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3136                            struct mapped_index *index)
3137 {
3138   struct objfile *objfile = dwarf2_per_objfile->objfile;
3139   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3140   const gdb_byte *iter, *end;
3141   struct addrmap *mutable_map;
3142   CORE_ADDR baseaddr;
3143
3144   auto_obstack temp_obstack;
3145
3146   mutable_map = addrmap_create_mutable (&temp_obstack);
3147
3148   iter = index->address_table.data ();
3149   end = iter + index->address_table.size ();
3150
3151   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3152
3153   while (iter < end)
3154     {
3155       ULONGEST hi, lo, cu_index;
3156       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3157       iter += 8;
3158       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3159       iter += 8;
3160       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3161       iter += 4;
3162
3163       if (lo > hi)
3164         {
3165           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3166                      hex_string (lo), hex_string (hi));
3167           continue;
3168         }
3169
3170       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3171         {
3172           complaint (_(".gdb_index address table has invalid CU number %u"),
3173                      (unsigned) cu_index);
3174           continue;
3175         }
3176
3177       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
3178       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
3179       addrmap_set_empty (mutable_map, lo, hi - 1,
3180                          dwarf2_per_objfile->get_cu (cu_index));
3181     }
3182
3183   objfile->partial_symtabs->psymtabs_addrmap
3184     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3185 }
3186
3187 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3188    populate the objfile's psymtabs_addrmap.  */
3189
3190 static void
3191 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3192                              struct dwarf2_section_info *section)
3193 {
3194   struct objfile *objfile = dwarf2_per_objfile->objfile;
3195   bfd *abfd = objfile->obfd;
3196   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3197   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3198                                        SECT_OFF_TEXT (objfile));
3199
3200   auto_obstack temp_obstack;
3201   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3202
3203   std::unordered_map<sect_offset,
3204                      dwarf2_per_cu_data *,
3205                      gdb::hash_enum<sect_offset>>
3206     debug_info_offset_to_per_cu;
3207   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3208     {
3209       const auto insertpair
3210         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3211       if (!insertpair.second)
3212         {
3213           warning (_("Section .debug_aranges in %s has duplicate "
3214                      "debug_info_offset %s, ignoring .debug_aranges."),
3215                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3216           return;
3217         }
3218     }
3219
3220   dwarf2_read_section (objfile, section);
3221
3222   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3223
3224   const gdb_byte *addr = section->buffer;
3225
3226   while (addr < section->buffer + section->size)
3227     {
3228       const gdb_byte *const entry_addr = addr;
3229       unsigned int bytes_read;
3230
3231       const LONGEST entry_length = read_initial_length (abfd, addr,
3232                                                         &bytes_read);
3233       addr += bytes_read;
3234
3235       const gdb_byte *const entry_end = addr + entry_length;
3236       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3237       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3238       if (addr + entry_length > section->buffer + section->size)
3239         {
3240           warning (_("Section .debug_aranges in %s entry at offset %zu "
3241                      "length %s exceeds section length %s, "
3242                      "ignoring .debug_aranges."),
3243                    objfile_name (objfile), entry_addr - section->buffer,
3244                    plongest (bytes_read + entry_length),
3245                    pulongest (section->size));
3246           return;
3247         }
3248
3249       /* The version number.  */
3250       const uint16_t version = read_2_bytes (abfd, addr);
3251       addr += 2;
3252       if (version != 2)
3253         {
3254           warning (_("Section .debug_aranges in %s entry at offset %zu "
3255                      "has unsupported version %d, ignoring .debug_aranges."),
3256                    objfile_name (objfile), entry_addr - section->buffer,
3257                    version);
3258           return;
3259         }
3260
3261       const uint64_t debug_info_offset
3262         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3263       addr += offset_size;
3264       const auto per_cu_it
3265         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3266       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3267         {
3268           warning (_("Section .debug_aranges in %s entry at offset %zu "
3269                      "debug_info_offset %s does not exists, "
3270                      "ignoring .debug_aranges."),
3271                    objfile_name (objfile), entry_addr - section->buffer,
3272                    pulongest (debug_info_offset));
3273           return;
3274         }
3275       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3276
3277       const uint8_t address_size = *addr++;
3278       if (address_size < 1 || address_size > 8)
3279         {
3280           warning (_("Section .debug_aranges in %s entry at offset %zu "
3281                      "address_size %u is invalid, ignoring .debug_aranges."),
3282                    objfile_name (objfile), entry_addr - section->buffer,
3283                    address_size);
3284           return;
3285         }
3286
3287       const uint8_t segment_selector_size = *addr++;
3288       if (segment_selector_size != 0)
3289         {
3290           warning (_("Section .debug_aranges in %s entry at offset %zu "
3291                      "segment_selector_size %u is not supported, "
3292                      "ignoring .debug_aranges."),
3293                    objfile_name (objfile), entry_addr - section->buffer,
3294                    segment_selector_size);
3295           return;
3296         }
3297
3298       /* Must pad to an alignment boundary that is twice the address
3299          size.  It is undocumented by the DWARF standard but GCC does
3300          use it.  */
3301       for (size_t padding = ((-(addr - section->buffer))
3302                              & (2 * address_size - 1));
3303            padding > 0; padding--)
3304         if (*addr++ != 0)
3305           {
3306             warning (_("Section .debug_aranges in %s entry at offset %zu "
3307                        "padding is not zero, ignoring .debug_aranges."),
3308                      objfile_name (objfile), entry_addr - section->buffer);
3309             return;
3310           }
3311
3312       for (;;)
3313         {
3314           if (addr + 2 * address_size > entry_end)
3315             {
3316               warning (_("Section .debug_aranges in %s entry at offset %zu "
3317                          "address list is not properly terminated, "
3318                          "ignoring .debug_aranges."),
3319                        objfile_name (objfile), entry_addr - section->buffer);
3320               return;
3321             }
3322           ULONGEST start = extract_unsigned_integer (addr, address_size,
3323                                                      dwarf5_byte_order);
3324           addr += address_size;
3325           ULONGEST length = extract_unsigned_integer (addr, address_size,
3326                                                       dwarf5_byte_order);
3327           addr += address_size;
3328           if (start == 0 && length == 0)
3329             break;
3330           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3331             {
3332               /* Symbol was eliminated due to a COMDAT group.  */
3333               continue;
3334             }
3335           ULONGEST end = start + length;
3336           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3337                    - baseaddr);
3338           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3339                  - baseaddr);
3340           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3341         }
3342     }
3343
3344   objfile->partial_symtabs->psymtabs_addrmap
3345     = addrmap_create_fixed (mutable_map, objfile->partial_symtabs->obstack ());
3346 }
3347
3348 /* Find a slot in the mapped index INDEX for the object named NAME.
3349    If NAME is found, set *VEC_OUT to point to the CU vector in the
3350    constant pool and return true.  If NAME cannot be found, return
3351    false.  */
3352
3353 static bool
3354 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3355                           offset_type **vec_out)
3356 {
3357   offset_type hash;
3358   offset_type slot, step;
3359   int (*cmp) (const char *, const char *);
3360
3361   gdb::unique_xmalloc_ptr<char> without_params;
3362   if (current_language->la_language == language_cplus
3363       || current_language->la_language == language_fortran
3364       || current_language->la_language == language_d)
3365     {
3366       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3367          not contain any.  */
3368
3369       if (strchr (name, '(') != NULL)
3370         {
3371           without_params = cp_remove_params (name);
3372
3373           if (without_params != NULL)
3374             name = without_params.get ();
3375         }
3376     }
3377
3378   /* Index version 4 did not support case insensitive searches.  But the
3379      indices for case insensitive languages are built in lowercase, therefore
3380      simulate our NAME being searched is also lowercased.  */
3381   hash = mapped_index_string_hash ((index->version == 4
3382                                     && case_sensitivity == case_sensitive_off
3383                                     ? 5 : index->version),
3384                                    name);
3385
3386   slot = hash & (index->symbol_table.size () - 1);
3387   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3388   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3389
3390   for (;;)
3391     {
3392       const char *str;
3393
3394       const auto &bucket = index->symbol_table[slot];
3395       if (bucket.name == 0 && bucket.vec == 0)
3396         return false;
3397
3398       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3399       if (!cmp (name, str))
3400         {
3401           *vec_out = (offset_type *) (index->constant_pool
3402                                       + MAYBE_SWAP (bucket.vec));
3403           return true;
3404         }
3405
3406       slot = (slot + step) & (index->symbol_table.size () - 1);
3407     }
3408 }
3409
3410 /* A helper function that reads the .gdb_index from BUFFER and fills
3411    in MAP.  FILENAME is the name of the file containing the data;
3412    it is used for error reporting.  DEPRECATED_OK is true if it is
3413    ok to use deprecated sections.
3414
3415    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3416    out parameters that are filled in with information about the CU and
3417    TU lists in the section.
3418
3419    Returns true if all went well, false otherwise.  */
3420
3421 static bool
3422 read_gdb_index_from_buffer (struct objfile *objfile,
3423                             const char *filename,
3424                             bool deprecated_ok,
3425                             gdb::array_view<const gdb_byte> buffer,
3426                             struct mapped_index *map,
3427                             const gdb_byte **cu_list,
3428                             offset_type *cu_list_elements,
3429                             const gdb_byte **types_list,
3430                             offset_type *types_list_elements)
3431 {
3432   const gdb_byte *addr = &buffer[0];
3433
3434   /* Version check.  */
3435   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3436   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3437      causes the index to behave very poorly for certain requests.  Version 3
3438      contained incomplete addrmap.  So, it seems better to just ignore such
3439      indices.  */
3440   if (version < 4)
3441     {
3442       static int warning_printed = 0;
3443       if (!warning_printed)
3444         {
3445           warning (_("Skipping obsolete .gdb_index section in %s."),
3446                    filename);
3447           warning_printed = 1;
3448         }
3449       return 0;
3450     }
3451   /* Index version 4 uses a different hash function than index version
3452      5 and later.
3453
3454      Versions earlier than 6 did not emit psymbols for inlined
3455      functions.  Using these files will cause GDB not to be able to
3456      set breakpoints on inlined functions by name, so we ignore these
3457      indices unless the user has done
3458      "set use-deprecated-index-sections on".  */
3459   if (version < 6 && !deprecated_ok)
3460     {
3461       static int warning_printed = 0;
3462       if (!warning_printed)
3463         {
3464           warning (_("\
3465 Skipping deprecated .gdb_index section in %s.\n\
3466 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3467 to use the section anyway."),
3468                    filename);
3469           warning_printed = 1;
3470         }
3471       return 0;
3472     }
3473   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3474      of the TU (for symbols coming from TUs),
3475      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3476      Plus gold-generated indices can have duplicate entries for global symbols,
3477      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3478      These are just performance bugs, and we can't distinguish gdb-generated
3479      indices from gold-generated ones, so issue no warning here.  */
3480
3481   /* Indexes with higher version than the one supported by GDB may be no
3482      longer backward compatible.  */
3483   if (version > 8)
3484     return 0;
3485
3486   map->version = version;
3487
3488   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3489
3490   int i = 0;
3491   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3492   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3493                        / 8);
3494   ++i;
3495
3496   *types_list = addr + MAYBE_SWAP (metadata[i]);
3497   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3498                            - MAYBE_SWAP (metadata[i]))
3499                           / 8);
3500   ++i;
3501
3502   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3503   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3504   map->address_table
3505     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3506   ++i;
3507
3508   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3509   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3510   map->symbol_table
3511     = gdb::array_view<mapped_index::symbol_table_slot>
3512        ((mapped_index::symbol_table_slot *) symbol_table,
3513         (mapped_index::symbol_table_slot *) symbol_table_end);
3514
3515   ++i;
3516   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3517
3518   return 1;
3519 }
3520
3521 /* Callback types for dwarf2_read_gdb_index.  */
3522
3523 typedef gdb::function_view
3524     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3525     get_gdb_index_contents_ftype;
3526 typedef gdb::function_view
3527     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3528     get_gdb_index_contents_dwz_ftype;
3529
3530 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3531    elements of all the CUs and return 1.  Otherwise, return 0.  */
3532
3533 static int
3534 dwarf2_read_gdb_index
3535   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3536    get_gdb_index_contents_ftype get_gdb_index_contents,
3537    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3538 {
3539   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3540   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3541   struct dwz_file *dwz;
3542   struct objfile *objfile = dwarf2_per_objfile->objfile;
3543
3544   gdb::array_view<const gdb_byte> main_index_contents
3545     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3546
3547   if (main_index_contents.empty ())
3548     return 0;
3549
3550   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3551   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3552                                    use_deprecated_index_sections,
3553                                    main_index_contents, map.get (), &cu_list,
3554                                    &cu_list_elements, &types_list,
3555                                    &types_list_elements))
3556     return 0;
3557
3558   /* Don't use the index if it's empty.  */
3559   if (map->symbol_table.empty ())
3560     return 0;
3561
3562   /* If there is a .dwz file, read it so we can get its CU list as
3563      well.  */
3564   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3565   if (dwz != NULL)
3566     {
3567       struct mapped_index dwz_map;
3568       const gdb_byte *dwz_types_ignore;
3569       offset_type dwz_types_elements_ignore;
3570
3571       gdb::array_view<const gdb_byte> dwz_index_content
3572         = get_gdb_index_contents_dwz (objfile, dwz);
3573
3574       if (dwz_index_content.empty ())
3575         return 0;
3576
3577       if (!read_gdb_index_from_buffer (objfile,
3578                                        bfd_get_filename (dwz->dwz_bfd), 1,
3579                                        dwz_index_content, &dwz_map,
3580                                        &dwz_list, &dwz_list_elements,
3581                                        &dwz_types_ignore,
3582                                        &dwz_types_elements_ignore))
3583         {
3584           warning (_("could not read '.gdb_index' section from %s; skipping"),
3585                    bfd_get_filename (dwz->dwz_bfd));
3586           return 0;
3587         }
3588     }
3589
3590   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3591                          dwz_list, dwz_list_elements);
3592
3593   if (types_list_elements)
3594     {
3595       struct dwarf2_section_info *section;
3596
3597       /* We can only handle a single .debug_types when we have an
3598          index.  */
3599       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3600         return 0;
3601
3602       section = VEC_index (dwarf2_section_info_def,
3603                            dwarf2_per_objfile->types, 0);
3604
3605       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3606                                                types_list, types_list_elements);
3607     }
3608
3609   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3610
3611   dwarf2_per_objfile->index_table = std::move (map);
3612   dwarf2_per_objfile->using_index = 1;
3613   dwarf2_per_objfile->quick_file_names_table =
3614     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3615
3616   return 1;
3617 }
3618
3619 /* die_reader_func for dw2_get_file_names.  */
3620
3621 static void
3622 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3623                            const gdb_byte *info_ptr,
3624                            struct die_info *comp_unit_die,
3625                            int has_children,
3626                            void *data)
3627 {
3628   struct dwarf2_cu *cu = reader->cu;
3629   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3630   struct dwarf2_per_objfile *dwarf2_per_objfile
3631     = cu->per_cu->dwarf2_per_objfile;
3632   struct objfile *objfile = dwarf2_per_objfile->objfile;
3633   struct dwarf2_per_cu_data *lh_cu;
3634   struct attribute *attr;
3635   int i;
3636   void **slot;
3637   struct quick_file_names *qfn;
3638
3639   gdb_assert (! this_cu->is_debug_types);
3640
3641   /* Our callers never want to match partial units -- instead they
3642      will match the enclosing full CU.  */
3643   if (comp_unit_die->tag == DW_TAG_partial_unit)
3644     {
3645       this_cu->v.quick->no_file_data = 1;
3646       return;
3647     }
3648
3649   lh_cu = this_cu;
3650   slot = NULL;
3651
3652   line_header_up lh;
3653   sect_offset line_offset {};
3654
3655   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3656   if (attr)
3657     {
3658       struct quick_file_names find_entry;
3659
3660       line_offset = (sect_offset) DW_UNSND (attr);
3661
3662       /* We may have already read in this line header (TU line header sharing).
3663          If we have we're done.  */
3664       find_entry.hash.dwo_unit = cu->dwo_unit;
3665       find_entry.hash.line_sect_off = line_offset;
3666       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3667                              &find_entry, INSERT);
3668       if (*slot != NULL)
3669         {
3670           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3671           return;
3672         }
3673
3674       lh = dwarf_decode_line_header (line_offset, cu);
3675     }
3676   if (lh == NULL)
3677     {
3678       lh_cu->v.quick->no_file_data = 1;
3679       return;
3680     }
3681
3682   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3683   qfn->hash.dwo_unit = cu->dwo_unit;
3684   qfn->hash.line_sect_off = line_offset;
3685   gdb_assert (slot != NULL);
3686   *slot = qfn;
3687
3688   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3689
3690   qfn->num_file_names = lh->file_names.size ();
3691   qfn->file_names =
3692     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3693   for (i = 0; i < lh->file_names.size (); ++i)
3694     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3695   qfn->real_names = NULL;
3696
3697   lh_cu->v.quick->file_names = qfn;
3698 }
3699
3700 /* A helper for the "quick" functions which attempts to read the line
3701    table for THIS_CU.  */
3702
3703 static struct quick_file_names *
3704 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3705 {
3706   /* This should never be called for TUs.  */
3707   gdb_assert (! this_cu->is_debug_types);
3708   /* Nor type unit groups.  */
3709   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3710
3711   if (this_cu->v.quick->file_names != NULL)
3712     return this_cu->v.quick->file_names;
3713   /* If we know there is no line data, no point in looking again.  */
3714   if (this_cu->v.quick->no_file_data)
3715     return NULL;
3716
3717   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3718
3719   if (this_cu->v.quick->no_file_data)
3720     return NULL;
3721   return this_cu->v.quick->file_names;
3722 }
3723
3724 /* A helper for the "quick" functions which computes and caches the
3725    real path for a given file name from the line table.  */
3726
3727 static const char *
3728 dw2_get_real_path (struct objfile *objfile,
3729                    struct quick_file_names *qfn, int index)
3730 {
3731   if (qfn->real_names == NULL)
3732     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3733                                       qfn->num_file_names, const char *);
3734
3735   if (qfn->real_names[index] == NULL)
3736     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3737
3738   return qfn->real_names[index];
3739 }
3740
3741 static struct symtab *
3742 dw2_find_last_source_symtab (struct objfile *objfile)
3743 {
3744   struct dwarf2_per_objfile *dwarf2_per_objfile
3745     = get_dwarf2_per_objfile (objfile);
3746   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3747   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3748
3749   if (cust == NULL)
3750     return NULL;
3751
3752   return compunit_primary_filetab (cust);
3753 }
3754
3755 /* Traversal function for dw2_forget_cached_source_info.  */
3756
3757 static int
3758 dw2_free_cached_file_names (void **slot, void *info)
3759 {
3760   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3761
3762   if (file_data->real_names)
3763     {
3764       int i;
3765
3766       for (i = 0; i < file_data->num_file_names; ++i)
3767         {
3768           xfree ((void*) file_data->real_names[i]);
3769           file_data->real_names[i] = NULL;
3770         }
3771     }
3772
3773   return 1;
3774 }
3775
3776 static void
3777 dw2_forget_cached_source_info (struct objfile *objfile)
3778 {
3779   struct dwarf2_per_objfile *dwarf2_per_objfile
3780     = get_dwarf2_per_objfile (objfile);
3781
3782   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3783                           dw2_free_cached_file_names, NULL);
3784 }
3785
3786 /* Helper function for dw2_map_symtabs_matching_filename that expands
3787    the symtabs and calls the iterator.  */
3788
3789 static int
3790 dw2_map_expand_apply (struct objfile *objfile,
3791                       struct dwarf2_per_cu_data *per_cu,
3792                       const char *name, const char *real_path,
3793                       gdb::function_view<bool (symtab *)> callback)
3794 {
3795   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3796
3797   /* Don't visit already-expanded CUs.  */
3798   if (per_cu->v.quick->compunit_symtab)
3799     return 0;
3800
3801   /* This may expand more than one symtab, and we want to iterate over
3802      all of them.  */
3803   dw2_instantiate_symtab (per_cu, false);
3804
3805   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3806                                     last_made, callback);
3807 }
3808
3809 /* Implementation of the map_symtabs_matching_filename method.  */
3810
3811 static bool
3812 dw2_map_symtabs_matching_filename
3813   (struct objfile *objfile, const char *name, const char *real_path,
3814    gdb::function_view<bool (symtab *)> callback)
3815 {
3816   const char *name_basename = lbasename (name);
3817   struct dwarf2_per_objfile *dwarf2_per_objfile
3818     = get_dwarf2_per_objfile (objfile);
3819
3820   /* The rule is CUs specify all the files, including those used by
3821      any TU, so there's no need to scan TUs here.  */
3822
3823   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3824     {
3825       /* We only need to look at symtabs not already expanded.  */
3826       if (per_cu->v.quick->compunit_symtab)
3827         continue;
3828
3829       quick_file_names *file_data = dw2_get_file_names (per_cu);
3830       if (file_data == NULL)
3831         continue;
3832
3833       for (int j = 0; j < file_data->num_file_names; ++j)
3834         {
3835           const char *this_name = file_data->file_names[j];
3836           const char *this_real_name;
3837
3838           if (compare_filenames_for_search (this_name, name))
3839             {
3840               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3841                                         callback))
3842                 return true;
3843               continue;
3844             }
3845
3846           /* Before we invoke realpath, which can get expensive when many
3847              files are involved, do a quick comparison of the basenames.  */
3848           if (! basenames_may_differ
3849               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3850             continue;
3851
3852           this_real_name = dw2_get_real_path (objfile, file_data, j);
3853           if (compare_filenames_for_search (this_real_name, name))
3854             {
3855               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3856                                         callback))
3857                 return true;
3858               continue;
3859             }
3860
3861           if (real_path != NULL)
3862             {
3863               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3864               gdb_assert (IS_ABSOLUTE_PATH (name));
3865               if (this_real_name != NULL
3866                   && FILENAME_CMP (real_path, this_real_name) == 0)
3867                 {
3868                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3869                                             callback))
3870                     return true;
3871                   continue;
3872                 }
3873             }
3874         }
3875     }
3876
3877   return false;
3878 }
3879
3880 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3881
3882 struct dw2_symtab_iterator
3883 {
3884   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3885   struct dwarf2_per_objfile *dwarf2_per_objfile;
3886   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3887   int want_specific_block;
3888   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3889      Unused if !WANT_SPECIFIC_BLOCK.  */
3890   int block_index;
3891   /* The kind of symbol we're looking for.  */
3892   domain_enum domain;
3893   /* The list of CUs from the index entry of the symbol,
3894      or NULL if not found.  */
3895   offset_type *vec;
3896   /* The next element in VEC to look at.  */
3897   int next;
3898   /* The number of elements in VEC, or zero if there is no match.  */
3899   int length;
3900   /* Have we seen a global version of the symbol?
3901      If so we can ignore all further global instances.
3902      This is to work around gold/15646, inefficient gold-generated
3903      indices.  */
3904   int global_seen;
3905 };
3906
3907 /* Initialize the index symtab iterator ITER.
3908    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3909    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3910
3911 static void
3912 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3913                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3914                       int want_specific_block,
3915                       int block_index,
3916                       domain_enum domain,
3917                       const char *name)
3918 {
3919   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3920   iter->want_specific_block = want_specific_block;
3921   iter->block_index = block_index;
3922   iter->domain = domain;
3923   iter->next = 0;
3924   iter->global_seen = 0;
3925
3926   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3927
3928   /* index is NULL if OBJF_READNOW.  */
3929   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3930     iter->length = MAYBE_SWAP (*iter->vec);
3931   else
3932     {
3933       iter->vec = NULL;
3934       iter->length = 0;
3935     }
3936 }
3937
3938 /* Return the next matching CU or NULL if there are no more.  */
3939
3940 static struct dwarf2_per_cu_data *
3941 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3942 {
3943   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3944
3945   for ( ; iter->next < iter->length; ++iter->next)
3946     {
3947       offset_type cu_index_and_attrs =
3948         MAYBE_SWAP (iter->vec[iter->next + 1]);
3949       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3950       int want_static = iter->block_index != GLOBAL_BLOCK;
3951       /* This value is only valid for index versions >= 7.  */
3952       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3953       gdb_index_symbol_kind symbol_kind =
3954         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3955       /* Only check the symbol attributes if they're present.
3956          Indices prior to version 7 don't record them,
3957          and indices >= 7 may elide them for certain symbols
3958          (gold does this).  */
3959       int attrs_valid =
3960         (dwarf2_per_objfile->index_table->version >= 7
3961          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3962
3963       /* Don't crash on bad data.  */
3964       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3965                        + dwarf2_per_objfile->all_type_units.size ()))
3966         {
3967           complaint (_(".gdb_index entry has bad CU index"
3968                        " [in module %s]"),
3969                      objfile_name (dwarf2_per_objfile->objfile));
3970           continue;
3971         }
3972
3973       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3974
3975       /* Skip if already read in.  */
3976       if (per_cu->v.quick->compunit_symtab)
3977         continue;
3978
3979       /* Check static vs global.  */
3980       if (attrs_valid)
3981         {
3982           if (iter->want_specific_block
3983               && want_static != is_static)
3984             continue;
3985           /* Work around gold/15646.  */
3986           if (!is_static && iter->global_seen)
3987             continue;
3988           if (!is_static)
3989             iter->global_seen = 1;
3990         }
3991
3992       /* Only check the symbol's kind if it has one.  */
3993       if (attrs_valid)
3994         {
3995           switch (iter->domain)
3996             {
3997             case VAR_DOMAIN:
3998               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3999                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4000                   /* Some types are also in VAR_DOMAIN.  */
4001                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4002                 continue;
4003               break;
4004             case STRUCT_DOMAIN:
4005               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4006                 continue;
4007               break;
4008             case LABEL_DOMAIN:
4009               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4010                 continue;
4011               break;
4012             default:
4013               break;
4014             }
4015         }
4016
4017       ++iter->next;
4018       return per_cu;
4019     }
4020
4021   return NULL;
4022 }
4023
4024 static struct compunit_symtab *
4025 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4026                    const char *name, domain_enum domain)
4027 {
4028   struct compunit_symtab *stab_best = NULL;
4029   struct dwarf2_per_objfile *dwarf2_per_objfile
4030     = get_dwarf2_per_objfile (objfile);
4031
4032   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4033
4034   struct dw2_symtab_iterator iter;
4035   struct dwarf2_per_cu_data *per_cu;
4036
4037   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4038
4039   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4040     {
4041       struct symbol *sym, *with_opaque = NULL;
4042       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4043       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4044       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4045
4046       sym = block_find_symbol (block, name, domain,
4047                                block_find_non_opaque_type_preferred,
4048                                &with_opaque);
4049
4050       /* Some caution must be observed with overloaded functions
4051          and methods, since the index will not contain any overload
4052          information (but NAME might contain it).  */
4053
4054       if (sym != NULL
4055           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4056         return stab;
4057       if (with_opaque != NULL
4058           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4059         stab_best = stab;
4060
4061       /* Keep looking through other CUs.  */
4062     }
4063
4064   return stab_best;
4065 }
4066
4067 static void
4068 dw2_print_stats (struct objfile *objfile)
4069 {
4070   struct dwarf2_per_objfile *dwarf2_per_objfile
4071     = get_dwarf2_per_objfile (objfile);
4072   int total = (dwarf2_per_objfile->all_comp_units.size ()
4073                + dwarf2_per_objfile->all_type_units.size ());
4074   int count = 0;
4075
4076   for (int i = 0; i < total; ++i)
4077     {
4078       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4079
4080       if (!per_cu->v.quick->compunit_symtab)
4081         ++count;
4082     }
4083   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4084   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4085 }
4086
4087 /* This dumps minimal information about the index.
4088    It is called via "mt print objfiles".
4089    One use is to verify .gdb_index has been loaded by the
4090    gdb.dwarf2/gdb-index.exp testcase.  */
4091
4092 static void
4093 dw2_dump (struct objfile *objfile)
4094 {
4095   struct dwarf2_per_objfile *dwarf2_per_objfile
4096     = get_dwarf2_per_objfile (objfile);
4097
4098   gdb_assert (dwarf2_per_objfile->using_index);
4099   printf_filtered (".gdb_index:");
4100   if (dwarf2_per_objfile->index_table != NULL)
4101     {
4102       printf_filtered (" version %d\n",
4103                        dwarf2_per_objfile->index_table->version);
4104     }
4105   else
4106     printf_filtered (" faked for \"readnow\"\n");
4107   printf_filtered ("\n");
4108 }
4109
4110 static void
4111 dw2_expand_symtabs_for_function (struct objfile *objfile,
4112                                  const char *func_name)
4113 {
4114   struct dwarf2_per_objfile *dwarf2_per_objfile
4115     = get_dwarf2_per_objfile (objfile);
4116
4117   struct dw2_symtab_iterator iter;
4118   struct dwarf2_per_cu_data *per_cu;
4119
4120   /* Note: It doesn't matter what we pass for block_index here.  */
4121   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4122                         func_name);
4123
4124   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4125     dw2_instantiate_symtab (per_cu, false);
4126
4127 }
4128
4129 static void
4130 dw2_expand_all_symtabs (struct objfile *objfile)
4131 {
4132   struct dwarf2_per_objfile *dwarf2_per_objfile
4133     = get_dwarf2_per_objfile (objfile);
4134   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4135                      + dwarf2_per_objfile->all_type_units.size ());
4136
4137   for (int i = 0; i < total_units; ++i)
4138     {
4139       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4140
4141       /* We don't want to directly expand a partial CU, because if we
4142          read it with the wrong language, then assertion failures can
4143          be triggered later on.  See PR symtab/23010.  So, tell
4144          dw2_instantiate_symtab to skip partial CUs -- any important
4145          partial CU will be read via DW_TAG_imported_unit anyway.  */
4146       dw2_instantiate_symtab (per_cu, true);
4147     }
4148 }
4149
4150 static void
4151 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4152                                   const char *fullname)
4153 {
4154   struct dwarf2_per_objfile *dwarf2_per_objfile
4155     = get_dwarf2_per_objfile (objfile);
4156
4157   /* We don't need to consider type units here.
4158      This is only called for examining code, e.g. expand_line_sal.
4159      There can be an order of magnitude (or more) more type units
4160      than comp units, and we avoid them if we can.  */
4161
4162   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4163     {
4164       /* We only need to look at symtabs not already expanded.  */
4165       if (per_cu->v.quick->compunit_symtab)
4166         continue;
4167
4168       quick_file_names *file_data = dw2_get_file_names (per_cu);
4169       if (file_data == NULL)
4170         continue;
4171
4172       for (int j = 0; j < file_data->num_file_names; ++j)
4173         {
4174           const char *this_fullname = file_data->file_names[j];
4175
4176           if (filename_cmp (this_fullname, fullname) == 0)
4177             {
4178               dw2_instantiate_symtab (per_cu, false);
4179               break;
4180             }
4181         }
4182     }
4183 }
4184
4185 static void
4186 dw2_map_matching_symbols (struct objfile *objfile,
4187                           const char * name, domain_enum domain,
4188                           int global,
4189                           int (*callback) (const struct block *,
4190                                            struct symbol *, void *),
4191                           void *data, symbol_name_match_type match,
4192                           symbol_compare_ftype *ordered_compare)
4193 {
4194   /* Currently unimplemented; used for Ada.  The function can be called if the
4195      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4196      does not look for non-Ada symbols this function should just return.  */
4197 }
4198
4199 /* Symbol name matcher for .gdb_index names.
4200
4201    Symbol names in .gdb_index have a few particularities:
4202
4203    - There's no indication of which is the language of each symbol.
4204
4205      Since each language has its own symbol name matching algorithm,
4206      and we don't know which language is the right one, we must match
4207      each symbol against all languages.  This would be a potential
4208      performance problem if it were not mitigated by the
4209      mapped_index::name_components lookup table, which significantly
4210      reduces the number of times we need to call into this matcher,
4211      making it a non-issue.
4212
4213    - Symbol names in the index have no overload (parameter)
4214      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4215      appear as "foo" in the index, for example.
4216
4217      This means that the lookup names passed to the symbol name
4218      matcher functions must have no parameter information either
4219      because (e.g.) symbol search name "foo" does not match
4220      lookup-name "foo(int)" [while swapping search name for lookup
4221      name would match].
4222 */
4223 class gdb_index_symbol_name_matcher
4224 {
4225 public:
4226   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4227   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4228
4229   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4230      Returns true if any matcher matches.  */
4231   bool matches (const char *symbol_name);
4232
4233 private:
4234   /* A reference to the lookup name we're matching against.  */
4235   const lookup_name_info &m_lookup_name;
4236
4237   /* A vector holding all the different symbol name matchers, for all
4238      languages.  */
4239   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4240 };
4241
4242 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4243   (const lookup_name_info &lookup_name)
4244     : m_lookup_name (lookup_name)
4245 {
4246   /* Prepare the vector of comparison functions upfront, to avoid
4247      doing the same work for each symbol.  Care is taken to avoid
4248      matching with the same matcher more than once if/when multiple
4249      languages use the same matcher function.  */
4250   auto &matchers = m_symbol_name_matcher_funcs;
4251   matchers.reserve (nr_languages);
4252
4253   matchers.push_back (default_symbol_name_matcher);
4254
4255   for (int i = 0; i < nr_languages; i++)
4256     {
4257       const language_defn *lang = language_def ((enum language) i);
4258       symbol_name_matcher_ftype *name_matcher
4259         = get_symbol_name_matcher (lang, m_lookup_name);
4260
4261       /* Don't insert the same comparison routine more than once.
4262          Note that we do this linear walk instead of a seemingly
4263          cheaper sorted insert, or use a std::set or something like
4264          that, because relative order of function addresses is not
4265          stable.  This is not a problem in practice because the number
4266          of supported languages is low, and the cost here is tiny
4267          compared to the number of searches we'll do afterwards using
4268          this object.  */
4269       if (name_matcher != default_symbol_name_matcher
4270           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4271               == matchers.end ()))
4272         matchers.push_back (name_matcher);
4273     }
4274 }
4275
4276 bool
4277 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4278 {
4279   for (auto matches_name : m_symbol_name_matcher_funcs)
4280     if (matches_name (symbol_name, m_lookup_name, NULL))
4281       return true;
4282
4283   return false;
4284 }
4285
4286 /* Starting from a search name, return the string that finds the upper
4287    bound of all strings that start with SEARCH_NAME in a sorted name
4288    list.  Returns the empty string to indicate that the upper bound is
4289    the end of the list.  */
4290
4291 static std::string
4292 make_sort_after_prefix_name (const char *search_name)
4293 {
4294   /* When looking to complete "func", we find the upper bound of all
4295      symbols that start with "func" by looking for where we'd insert
4296      the closest string that would follow "func" in lexicographical
4297      order.  Usually, that's "func"-with-last-character-incremented,
4298      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4299      will be UTF-8 multi-byte sequences, but we can't be certain.
4300      Especially mind the 0xff character, which is a valid character in
4301      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4302      rule out compilers allowing it in identifiers.  Note that
4303      conveniently, strcmp/strcasecmp are specified to compare
4304      characters interpreted as unsigned char.  So what we do is treat
4305      the whole string as a base 256 number composed of a sequence of
4306      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4307      to 0, and carries 1 to the following more-significant position.
4308      If the very first character in SEARCH_NAME ends up incremented
4309      and carries/overflows, then the upper bound is the end of the
4310      list.  The string after the empty string is also the empty
4311      string.
4312
4313      Some examples of this operation:
4314
4315        SEARCH_NAME  => "+1" RESULT
4316
4317        "abc"              => "abd"
4318        "ab\xff"           => "ac"
4319        "\xff" "a" "\xff"  => "\xff" "b"
4320        "\xff"             => ""
4321        "\xff\xff"         => ""
4322        ""                 => ""
4323
4324      Then, with these symbols for example:
4325
4326       func
4327       func1
4328       fund
4329
4330      completing "func" looks for symbols between "func" and
4331      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4332      which finds "func" and "func1", but not "fund".
4333
4334      And with:
4335
4336       funcÿ     (Latin1 'ÿ' [0xff])
4337       funcÿ1
4338       fund
4339
4340      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4341      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4342
4343      And with:
4344
4345       ÿÿ        (Latin1 'ÿ' [0xff])
4346       ÿÿ1
4347
4348      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4349      the end of the list.
4350   */
4351   std::string after = search_name;
4352   while (!after.empty () && (unsigned char) after.back () == 0xff)
4353     after.pop_back ();
4354   if (!after.empty ())
4355     after.back () = (unsigned char) after.back () + 1;
4356   return after;
4357 }
4358
4359 /* See declaration.  */
4360
4361 std::pair<std::vector<name_component>::const_iterator,
4362           std::vector<name_component>::const_iterator>
4363 mapped_index_base::find_name_components_bounds
4364   (const lookup_name_info &lookup_name_without_params) const
4365 {
4366   auto *name_cmp
4367     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4368
4369   const char *cplus
4370     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4371
4372   /* Comparison function object for lower_bound that matches against a
4373      given symbol name.  */
4374   auto lookup_compare_lower = [&] (const name_component &elem,
4375                                    const char *name)
4376     {
4377       const char *elem_qualified = this->symbol_name_at (elem.idx);
4378       const char *elem_name = elem_qualified + elem.name_offset;
4379       return name_cmp (elem_name, name) < 0;
4380     };
4381
4382   /* Comparison function object for upper_bound that matches against a
4383      given symbol name.  */
4384   auto lookup_compare_upper = [&] (const char *name,
4385                                    const name_component &elem)
4386     {
4387       const char *elem_qualified = this->symbol_name_at (elem.idx);
4388       const char *elem_name = elem_qualified + elem.name_offset;
4389       return name_cmp (name, elem_name) < 0;
4390     };
4391
4392   auto begin = this->name_components.begin ();
4393   auto end = this->name_components.end ();
4394
4395   /* Find the lower bound.  */
4396   auto lower = [&] ()
4397     {
4398       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4399         return begin;
4400       else
4401         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4402     } ();
4403
4404   /* Find the upper bound.  */
4405   auto upper = [&] ()
4406     {
4407       if (lookup_name_without_params.completion_mode ())
4408         {
4409           /* In completion mode, we want UPPER to point past all
4410              symbols names that have the same prefix.  I.e., with
4411              these symbols, and completing "func":
4412
4413               function        << lower bound
4414               function1
4415               other_function  << upper bound
4416
4417              We find the upper bound by looking for the insertion
4418              point of "func"-with-last-character-incremented,
4419              i.e. "fund".  */
4420           std::string after = make_sort_after_prefix_name (cplus);
4421           if (after.empty ())
4422             return end;
4423           return std::lower_bound (lower, end, after.c_str (),
4424                                    lookup_compare_lower);
4425         }
4426       else
4427         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4428     } ();
4429
4430   return {lower, upper};
4431 }
4432
4433 /* See declaration.  */
4434
4435 void
4436 mapped_index_base::build_name_components ()
4437 {
4438   if (!this->name_components.empty ())
4439     return;
4440
4441   this->name_components_casing = case_sensitivity;
4442   auto *name_cmp
4443     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4444
4445   /* The code below only knows how to break apart components of C++
4446      symbol names (and other languages that use '::' as
4447      namespace/module separator).  If we add support for wild matching
4448      to some language that uses some other operator (E.g., Ada, Go and
4449      D use '.'), then we'll need to try splitting the symbol name
4450      according to that language too.  Note that Ada does support wild
4451      matching, but doesn't currently support .gdb_index.  */
4452   auto count = this->symbol_name_count ();
4453   for (offset_type idx = 0; idx < count; idx++)
4454     {
4455       if (this->symbol_name_slot_invalid (idx))
4456         continue;
4457
4458       const char *name = this->symbol_name_at (idx);
4459
4460       /* Add each name component to the name component table.  */
4461       unsigned int previous_len = 0;
4462       for (unsigned int current_len = cp_find_first_component (name);
4463            name[current_len] != '\0';
4464            current_len += cp_find_first_component (name + current_len))
4465         {
4466           gdb_assert (name[current_len] == ':');
4467           this->name_components.push_back ({previous_len, idx});
4468           /* Skip the '::'.  */
4469           current_len += 2;
4470           previous_len = current_len;
4471         }
4472       this->name_components.push_back ({previous_len, idx});
4473     }
4474
4475   /* Sort name_components elements by name.  */
4476   auto name_comp_compare = [&] (const name_component &left,
4477                                 const name_component &right)
4478     {
4479       const char *left_qualified = this->symbol_name_at (left.idx);
4480       const char *right_qualified = this->symbol_name_at (right.idx);
4481
4482       const char *left_name = left_qualified + left.name_offset;
4483       const char *right_name = right_qualified + right.name_offset;
4484
4485       return name_cmp (left_name, right_name) < 0;
4486     };
4487
4488   std::sort (this->name_components.begin (),
4489              this->name_components.end (),
4490              name_comp_compare);
4491 }
4492
4493 /* Helper for dw2_expand_symtabs_matching that works with a
4494    mapped_index_base instead of the containing objfile.  This is split
4495    to a separate function in order to be able to unit test the
4496    name_components matching using a mock mapped_index_base.  For each
4497    symbol name that matches, calls MATCH_CALLBACK, passing it the
4498    symbol's index in the mapped_index_base symbol table.  */
4499
4500 static void
4501 dw2_expand_symtabs_matching_symbol
4502   (mapped_index_base &index,
4503    const lookup_name_info &lookup_name_in,
4504    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4505    enum search_domain kind,
4506    gdb::function_view<void (offset_type)> match_callback)
4507 {
4508   lookup_name_info lookup_name_without_params
4509     = lookup_name_in.make_ignore_params ();
4510   gdb_index_symbol_name_matcher lookup_name_matcher
4511     (lookup_name_without_params);
4512
4513   /* Build the symbol name component sorted vector, if we haven't
4514      yet.  */
4515   index.build_name_components ();
4516
4517   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4518
4519   /* Now for each symbol name in range, check to see if we have a name
4520      match, and if so, call the MATCH_CALLBACK callback.  */
4521
4522   /* The same symbol may appear more than once in the range though.
4523      E.g., if we're looking for symbols that complete "w", and we have
4524      a symbol named "w1::w2", we'll find the two name components for
4525      that same symbol in the range.  To be sure we only call the
4526      callback once per symbol, we first collect the symbol name
4527      indexes that matched in a temporary vector and ignore
4528      duplicates.  */
4529   std::vector<offset_type> matches;
4530   matches.reserve (std::distance (bounds.first, bounds.second));
4531
4532   for (; bounds.first != bounds.second; ++bounds.first)
4533     {
4534       const char *qualified = index.symbol_name_at (bounds.first->idx);
4535
4536       if (!lookup_name_matcher.matches (qualified)
4537           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4538         continue;
4539
4540       matches.push_back (bounds.first->idx);
4541     }
4542
4543   std::sort (matches.begin (), matches.end ());
4544
4545   /* Finally call the callback, once per match.  */
4546   ULONGEST prev = -1;
4547   for (offset_type idx : matches)
4548     {
4549       if (prev != idx)
4550         {
4551           match_callback (idx);
4552           prev = idx;
4553         }
4554     }
4555
4556   /* Above we use a type wider than idx's for 'prev', since 0 and
4557      (offset_type)-1 are both possible values.  */
4558   static_assert (sizeof (prev) > sizeof (offset_type), "");
4559 }
4560
4561 #if GDB_SELF_TEST
4562
4563 namespace selftests { namespace dw2_expand_symtabs_matching {
4564
4565 /* A mock .gdb_index/.debug_names-like name index table, enough to
4566    exercise dw2_expand_symtabs_matching_symbol, which works with the
4567    mapped_index_base interface.  Builds an index from the symbol list
4568    passed as parameter to the constructor.  */
4569 class mock_mapped_index : public mapped_index_base
4570 {
4571 public:
4572   mock_mapped_index (gdb::array_view<const char *> symbols)
4573     : m_symbol_table (symbols)
4574   {}
4575
4576   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4577
4578   /* Return the number of names in the symbol table.  */
4579   size_t symbol_name_count () const override
4580   {
4581     return m_symbol_table.size ();
4582   }
4583
4584   /* Get the name of the symbol at IDX in the symbol table.  */
4585   const char *symbol_name_at (offset_type idx) const override
4586   {
4587     return m_symbol_table[idx];
4588   }
4589
4590 private:
4591   gdb::array_view<const char *> m_symbol_table;
4592 };
4593
4594 /* Convenience function that converts a NULL pointer to a "<null>"
4595    string, to pass to print routines.  */
4596
4597 static const char *
4598 string_or_null (const char *str)
4599 {
4600   return str != NULL ? str : "<null>";
4601 }
4602
4603 /* Check if a lookup_name_info built from
4604    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4605    index.  EXPECTED_LIST is the list of expected matches, in expected
4606    matching order.  If no match expected, then an empty list is
4607    specified.  Returns true on success.  On failure prints a warning
4608    indicating the file:line that failed, and returns false.  */
4609
4610 static bool
4611 check_match (const char *file, int line,
4612              mock_mapped_index &mock_index,
4613              const char *name, symbol_name_match_type match_type,
4614              bool completion_mode,
4615              std::initializer_list<const char *> expected_list)
4616 {
4617   lookup_name_info lookup_name (name, match_type, completion_mode);
4618
4619   bool matched = true;
4620
4621   auto mismatch = [&] (const char *expected_str,
4622                        const char *got)
4623   {
4624     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4625                "expected=\"%s\", got=\"%s\"\n"),
4626              file, line,
4627              (match_type == symbol_name_match_type::FULL
4628               ? "FULL" : "WILD"),
4629              name, string_or_null (expected_str), string_or_null (got));
4630     matched = false;
4631   };
4632
4633   auto expected_it = expected_list.begin ();
4634   auto expected_end = expected_list.end ();
4635
4636   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4637                                       NULL, ALL_DOMAIN,
4638                                       [&] (offset_type idx)
4639   {
4640     const char *matched_name = mock_index.symbol_name_at (idx);
4641     const char *expected_str
4642       = expected_it == expected_end ? NULL : *expected_it++;
4643
4644     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4645       mismatch (expected_str, matched_name);
4646   });
4647
4648   const char *expected_str
4649   = expected_it == expected_end ? NULL : *expected_it++;
4650   if (expected_str != NULL)
4651     mismatch (expected_str, NULL);
4652
4653   return matched;
4654 }
4655
4656 /* The symbols added to the mock mapped_index for testing (in
4657    canonical form).  */
4658 static const char *test_symbols[] = {
4659   "function",
4660   "std::bar",
4661   "std::zfunction",
4662   "std::zfunction2",
4663   "w1::w2",
4664   "ns::foo<char*>",
4665   "ns::foo<int>",
4666   "ns::foo<long>",
4667   "ns2::tmpl<int>::foo2",
4668   "(anonymous namespace)::A::B::C",
4669
4670   /* These are used to check that the increment-last-char in the
4671      matching algorithm for completion doesn't match "t1_fund" when
4672      completing "t1_func".  */
4673   "t1_func",
4674   "t1_func1",
4675   "t1_fund",
4676   "t1_fund1",
4677
4678   /* A UTF-8 name with multi-byte sequences to make sure that
4679      cp-name-parser understands this as a single identifier ("função"
4680      is "function" in PT).  */
4681   u8"u8função",
4682
4683   /* \377 (0xff) is Latin1 'ÿ'.  */
4684   "yfunc\377",
4685
4686   /* \377 (0xff) is Latin1 'ÿ'.  */
4687   "\377",
4688   "\377\377123",
4689
4690   /* A name with all sorts of complications.  Starts with "z" to make
4691      it easier for the completion tests below.  */
4692 #define Z_SYM_NAME \
4693   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4694     "::tuple<(anonymous namespace)::ui*, " \
4695     "std::default_delete<(anonymous namespace)::ui>, void>"
4696
4697   Z_SYM_NAME
4698 };
4699
4700 /* Returns true if the mapped_index_base::find_name_component_bounds
4701    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4702    in completion mode.  */
4703
4704 static bool
4705 check_find_bounds_finds (mapped_index_base &index,
4706                          const char *search_name,
4707                          gdb::array_view<const char *> expected_syms)
4708 {
4709   lookup_name_info lookup_name (search_name,
4710                                 symbol_name_match_type::FULL, true);
4711
4712   auto bounds = index.find_name_components_bounds (lookup_name);
4713
4714   size_t distance = std::distance (bounds.first, bounds.second);
4715   if (distance != expected_syms.size ())
4716     return false;
4717
4718   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4719     {
4720       auto nc_elem = bounds.first + exp_elem;
4721       const char *qualified = index.symbol_name_at (nc_elem->idx);
4722       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4723         return false;
4724     }
4725
4726   return true;
4727 }
4728
4729 /* Test the lower-level mapped_index::find_name_component_bounds
4730    method.  */
4731
4732 static void
4733 test_mapped_index_find_name_component_bounds ()
4734 {
4735   mock_mapped_index mock_index (test_symbols);
4736
4737   mock_index.build_name_components ();
4738
4739   /* Test the lower-level mapped_index::find_name_component_bounds
4740      method in completion mode.  */
4741   {
4742     static const char *expected_syms[] = {
4743       "t1_func",
4744       "t1_func1",
4745     };
4746
4747     SELF_CHECK (check_find_bounds_finds (mock_index,
4748                                          "t1_func", expected_syms));
4749   }
4750
4751   /* Check that the increment-last-char in the name matching algorithm
4752      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4753   {
4754     static const char *expected_syms1[] = {
4755       "\377",
4756       "\377\377123",
4757     };
4758     SELF_CHECK (check_find_bounds_finds (mock_index,
4759                                          "\377", expected_syms1));
4760
4761     static const char *expected_syms2[] = {
4762       "\377\377123",
4763     };
4764     SELF_CHECK (check_find_bounds_finds (mock_index,
4765                                          "\377\377", expected_syms2));
4766   }
4767 }
4768
4769 /* Test dw2_expand_symtabs_matching_symbol.  */
4770
4771 static void
4772 test_dw2_expand_symtabs_matching_symbol ()
4773 {
4774   mock_mapped_index mock_index (test_symbols);
4775
4776   /* We let all tests run until the end even if some fails, for debug
4777      convenience.  */
4778   bool any_mismatch = false;
4779
4780   /* Create the expected symbols list (an initializer_list).  Needed
4781      because lists have commas, and we need to pass them to CHECK,
4782      which is a macro.  */
4783 #define EXPECT(...) { __VA_ARGS__ }
4784
4785   /* Wrapper for check_match that passes down the current
4786      __FILE__/__LINE__.  */
4787 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4788   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4789                                 mock_index,                             \
4790                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4791                                 EXPECTED_LIST)
4792
4793   /* Identity checks.  */
4794   for (const char *sym : test_symbols)
4795     {
4796       /* Should be able to match all existing symbols.  */
4797       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4798                    EXPECT (sym));
4799
4800       /* Should be able to match all existing symbols with
4801          parameters.  */
4802       std::string with_params = std::string (sym) + "(int)";
4803       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4804                    EXPECT (sym));
4805
4806       /* Should be able to match all existing symbols with
4807          parameters and qualifiers.  */
4808       with_params = std::string (sym) + " ( int ) const";
4809       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4810                    EXPECT (sym));
4811
4812       /* This should really find sym, but cp-name-parser.y doesn't
4813          know about lvalue/rvalue qualifiers yet.  */
4814       with_params = std::string (sym) + " ( int ) &&";
4815       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4816                    {});
4817     }
4818
4819   /* Check that the name matching algorithm for completion doesn't get
4820      confused with Latin1 'ÿ' / 0xff.  */
4821   {
4822     static const char str[] = "\377";
4823     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4824                  EXPECT ("\377", "\377\377123"));
4825   }
4826
4827   /* Check that the increment-last-char in the matching algorithm for
4828      completion doesn't match "t1_fund" when completing "t1_func".  */
4829   {
4830     static const char str[] = "t1_func";
4831     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4832                  EXPECT ("t1_func", "t1_func1"));
4833   }
4834
4835   /* Check that completion mode works at each prefix of the expected
4836      symbol name.  */
4837   {
4838     static const char str[] = "function(int)";
4839     size_t len = strlen (str);
4840     std::string lookup;
4841
4842     for (size_t i = 1; i < len; i++)
4843       {
4844         lookup.assign (str, i);
4845         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4846                      EXPECT ("function"));
4847       }
4848   }
4849
4850   /* While "w" is a prefix of both components, the match function
4851      should still only be called once.  */
4852   {
4853     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4854                  EXPECT ("w1::w2"));
4855     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4856                  EXPECT ("w1::w2"));
4857   }
4858
4859   /* Same, with a "complicated" symbol.  */
4860   {
4861     static const char str[] = Z_SYM_NAME;
4862     size_t len = strlen (str);
4863     std::string lookup;
4864
4865     for (size_t i = 1; i < len; i++)
4866       {
4867         lookup.assign (str, i);
4868         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4869                      EXPECT (Z_SYM_NAME));
4870       }
4871   }
4872
4873   /* In FULL mode, an incomplete symbol doesn't match.  */
4874   {
4875     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4876                  {});
4877   }
4878
4879   /* A complete symbol with parameters matches any overload, since the
4880      index has no overload info.  */
4881   {
4882     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4883                  EXPECT ("std::zfunction", "std::zfunction2"));
4884     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4885                  EXPECT ("std::zfunction", "std::zfunction2"));
4886     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4887                  EXPECT ("std::zfunction", "std::zfunction2"));
4888   }
4889
4890   /* Check that whitespace is ignored appropriately.  A symbol with a
4891      template argument list. */
4892   {
4893     static const char expected[] = "ns::foo<int>";
4894     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4895                  EXPECT (expected));
4896     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4897                  EXPECT (expected));
4898   }
4899
4900   /* Check that whitespace is ignored appropriately.  A symbol with a
4901      template argument list that includes a pointer.  */
4902   {
4903     static const char expected[] = "ns::foo<char*>";
4904     /* Try both completion and non-completion modes.  */
4905     static const bool completion_mode[2] = {false, true};
4906     for (size_t i = 0; i < 2; i++)
4907       {
4908         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4909                      completion_mode[i], EXPECT (expected));
4910         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4911                      completion_mode[i], EXPECT (expected));
4912
4913         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4914                      completion_mode[i], EXPECT (expected));
4915         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4916                      completion_mode[i], EXPECT (expected));
4917       }
4918   }
4919
4920   {
4921     /* Check method qualifiers are ignored.  */
4922     static const char expected[] = "ns::foo<char*>";
4923     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4924                  symbol_name_match_type::FULL, true, EXPECT (expected));
4925     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4926                  symbol_name_match_type::FULL, true, EXPECT (expected));
4927     CHECK_MATCH ("foo < char * >  ( int ) const",
4928                  symbol_name_match_type::WILD, true, EXPECT (expected));
4929     CHECK_MATCH ("foo < char * >  ( int ) &&",
4930                  symbol_name_match_type::WILD, true, EXPECT (expected));
4931   }
4932
4933   /* Test lookup names that don't match anything.  */
4934   {
4935     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4936                  {});
4937
4938     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4939                  {});
4940   }
4941
4942   /* Some wild matching tests, exercising "(anonymous namespace)",
4943      which should not be confused with a parameter list.  */
4944   {
4945     static const char *syms[] = {
4946       "A::B::C",
4947       "B::C",
4948       "C",
4949       "A :: B :: C ( int )",
4950       "B :: C ( int )",
4951       "C ( int )",
4952     };
4953
4954     for (const char *s : syms)
4955       {
4956         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4957                      EXPECT ("(anonymous namespace)::A::B::C"));
4958       }
4959   }
4960
4961   {
4962     static const char expected[] = "ns2::tmpl<int>::foo2";
4963     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4964                  EXPECT (expected));
4965     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4966                  EXPECT (expected));
4967   }
4968
4969   SELF_CHECK (!any_mismatch);
4970
4971 #undef EXPECT
4972 #undef CHECK_MATCH
4973 }
4974
4975 static void
4976 run_test ()
4977 {
4978   test_mapped_index_find_name_component_bounds ();
4979   test_dw2_expand_symtabs_matching_symbol ();
4980 }
4981
4982 }} // namespace selftests::dw2_expand_symtabs_matching
4983
4984 #endif /* GDB_SELF_TEST */
4985
4986 /* If FILE_MATCHER is NULL or if PER_CU has
4987    dwarf2_per_cu_quick_data::MARK set (see
4988    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4989    EXPANSION_NOTIFY on it.  */
4990
4991 static void
4992 dw2_expand_symtabs_matching_one
4993   (struct dwarf2_per_cu_data *per_cu,
4994    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4995    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4996 {
4997   if (file_matcher == NULL || per_cu->v.quick->mark)
4998     {
4999       bool symtab_was_null
5000         = (per_cu->v.quick->compunit_symtab == NULL);
5001
5002       dw2_instantiate_symtab (per_cu, false);
5003
5004       if (expansion_notify != NULL
5005           && symtab_was_null
5006           && per_cu->v.quick->compunit_symtab != NULL)
5007         expansion_notify (per_cu->v.quick->compunit_symtab);
5008     }
5009 }
5010
5011 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5012    matched, to expand corresponding CUs that were marked.  IDX is the
5013    index of the symbol name that matched.  */
5014
5015 static void
5016 dw2_expand_marked_cus
5017   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5018    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5019    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5020    search_domain kind)
5021 {
5022   offset_type *vec, vec_len, vec_idx;
5023   bool global_seen = false;
5024   mapped_index &index = *dwarf2_per_objfile->index_table;
5025
5026   vec = (offset_type *) (index.constant_pool
5027                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5028   vec_len = MAYBE_SWAP (vec[0]);
5029   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5030     {
5031       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5032       /* This value is only valid for index versions >= 7.  */
5033       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5034       gdb_index_symbol_kind symbol_kind =
5035         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5036       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5037       /* Only check the symbol attributes if they're present.
5038          Indices prior to version 7 don't record them,
5039          and indices >= 7 may elide them for certain symbols
5040          (gold does this).  */
5041       int attrs_valid =
5042         (index.version >= 7
5043          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5044
5045       /* Work around gold/15646.  */
5046       if (attrs_valid)
5047         {
5048           if (!is_static && global_seen)
5049             continue;
5050           if (!is_static)
5051             global_seen = true;
5052         }
5053
5054       /* Only check the symbol's kind if it has one.  */
5055       if (attrs_valid)
5056         {
5057           switch (kind)
5058             {
5059             case VARIABLES_DOMAIN:
5060               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5061                 continue;
5062               break;
5063             case FUNCTIONS_DOMAIN:
5064               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5065                 continue;
5066               break;
5067             case TYPES_DOMAIN:
5068               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5069                 continue;
5070               break;
5071             default:
5072               break;
5073             }
5074         }
5075
5076       /* Don't crash on bad data.  */
5077       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5078                        + dwarf2_per_objfile->all_type_units.size ()))
5079         {
5080           complaint (_(".gdb_index entry has bad CU index"
5081                        " [in module %s]"),
5082                        objfile_name (dwarf2_per_objfile->objfile));
5083           continue;
5084         }
5085
5086       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5087       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5088                                        expansion_notify);
5089     }
5090 }
5091
5092 /* If FILE_MATCHER is non-NULL, set all the
5093    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5094    that match FILE_MATCHER.  */
5095
5096 static void
5097 dw_expand_symtabs_matching_file_matcher
5098   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5099    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5100 {
5101   if (file_matcher == NULL)
5102     return;
5103
5104   objfile *const objfile = dwarf2_per_objfile->objfile;
5105
5106   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5107                                             htab_eq_pointer,
5108                                             NULL, xcalloc, xfree));
5109   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5110                                                 htab_eq_pointer,
5111                                                 NULL, xcalloc, xfree));
5112
5113   /* The rule is CUs specify all the files, including those used by
5114      any TU, so there's no need to scan TUs here.  */
5115
5116   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5117     {
5118       QUIT;
5119
5120       per_cu->v.quick->mark = 0;
5121
5122       /* We only need to look at symtabs not already expanded.  */
5123       if (per_cu->v.quick->compunit_symtab)
5124         continue;
5125
5126       quick_file_names *file_data = dw2_get_file_names (per_cu);
5127       if (file_data == NULL)
5128         continue;
5129
5130       if (htab_find (visited_not_found.get (), file_data) != NULL)
5131         continue;
5132       else if (htab_find (visited_found.get (), file_data) != NULL)
5133         {
5134           per_cu->v.quick->mark = 1;
5135           continue;
5136         }
5137
5138       for (int j = 0; j < file_data->num_file_names; ++j)
5139         {
5140           const char *this_real_name;
5141
5142           if (file_matcher (file_data->file_names[j], false))
5143             {
5144               per_cu->v.quick->mark = 1;
5145               break;
5146             }
5147
5148           /* Before we invoke realpath, which can get expensive when many
5149              files are involved, do a quick comparison of the basenames.  */
5150           if (!basenames_may_differ
5151               && !file_matcher (lbasename (file_data->file_names[j]),
5152                                 true))
5153             continue;
5154
5155           this_real_name = dw2_get_real_path (objfile, file_data, j);
5156           if (file_matcher (this_real_name, false))
5157             {
5158               per_cu->v.quick->mark = 1;
5159               break;
5160             }
5161         }
5162
5163       void **slot = htab_find_slot (per_cu->v.quick->mark
5164                                     ? visited_found.get ()
5165                                     : visited_not_found.get (),
5166                                     file_data, INSERT);
5167       *slot = file_data;
5168     }
5169 }
5170
5171 static void
5172 dw2_expand_symtabs_matching
5173   (struct objfile *objfile,
5174    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5175    const lookup_name_info &lookup_name,
5176    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5177    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5178    enum search_domain kind)
5179 {
5180   struct dwarf2_per_objfile *dwarf2_per_objfile
5181     = get_dwarf2_per_objfile (objfile);
5182
5183   /* index_table is NULL if OBJF_READNOW.  */
5184   if (!dwarf2_per_objfile->index_table)
5185     return;
5186
5187   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5188
5189   mapped_index &index = *dwarf2_per_objfile->index_table;
5190
5191   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5192                                       symbol_matcher,
5193                                       kind, [&] (offset_type idx)
5194     {
5195       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5196                              expansion_notify, kind);
5197     });
5198 }
5199
5200 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5201    symtab.  */
5202
5203 static struct compunit_symtab *
5204 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5205                                           CORE_ADDR pc)
5206 {
5207   int i;
5208
5209   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5210       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5211     return cust;
5212
5213   if (cust->includes == NULL)
5214     return NULL;
5215
5216   for (i = 0; cust->includes[i]; ++i)
5217     {
5218       struct compunit_symtab *s = cust->includes[i];
5219
5220       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5221       if (s != NULL)
5222         return s;
5223     }
5224
5225   return NULL;
5226 }
5227
5228 static struct compunit_symtab *
5229 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5230                                   struct bound_minimal_symbol msymbol,
5231                                   CORE_ADDR pc,
5232                                   struct obj_section *section,
5233                                   int warn_if_readin)
5234 {
5235   struct dwarf2_per_cu_data *data;
5236   struct compunit_symtab *result;
5237
5238   if (!objfile->partial_symtabs->psymtabs_addrmap)
5239     return NULL;
5240
5241   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5242                                  SECT_OFF_TEXT (objfile));
5243   data = (struct dwarf2_per_cu_data *) addrmap_find
5244     (objfile->partial_symtabs->psymtabs_addrmap, pc - baseaddr);
5245   if (!data)
5246     return NULL;
5247
5248   if (warn_if_readin && data->v.quick->compunit_symtab)
5249     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5250              paddress (get_objfile_arch (objfile), pc));
5251
5252   result
5253     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5254                                                                         false),
5255                                                 pc);
5256   gdb_assert (result != NULL);
5257   return result;
5258 }
5259
5260 static void
5261 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5262                           void *data, int need_fullname)
5263 {
5264   struct dwarf2_per_objfile *dwarf2_per_objfile
5265     = get_dwarf2_per_objfile (objfile);
5266
5267   if (!dwarf2_per_objfile->filenames_cache)
5268     {
5269       dwarf2_per_objfile->filenames_cache.emplace ();
5270
5271       htab_up visited (htab_create_alloc (10,
5272                                           htab_hash_pointer, htab_eq_pointer,
5273                                           NULL, xcalloc, xfree));
5274
5275       /* The rule is CUs specify all the files, including those used
5276          by any TU, so there's no need to scan TUs here.  We can
5277          ignore file names coming from already-expanded CUs.  */
5278
5279       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5280         {
5281           if (per_cu->v.quick->compunit_symtab)
5282             {
5283               void **slot = htab_find_slot (visited.get (),
5284                                             per_cu->v.quick->file_names,
5285                                             INSERT);
5286
5287               *slot = per_cu->v.quick->file_names;
5288             }
5289         }
5290
5291       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5292         {
5293           /* We only need to look at symtabs not already expanded.  */
5294           if (per_cu->v.quick->compunit_symtab)
5295             continue;
5296
5297           quick_file_names *file_data = dw2_get_file_names (per_cu);
5298           if (file_data == NULL)
5299             continue;
5300
5301           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5302           if (*slot)
5303             {
5304               /* Already visited.  */
5305               continue;
5306             }
5307           *slot = file_data;
5308
5309           for (int j = 0; j < file_data->num_file_names; ++j)
5310             {
5311               const char *filename = file_data->file_names[j];
5312               dwarf2_per_objfile->filenames_cache->seen (filename);
5313             }
5314         }
5315     }
5316
5317   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5318     {
5319       gdb::unique_xmalloc_ptr<char> this_real_name;
5320
5321       if (need_fullname)
5322         this_real_name = gdb_realpath (filename);
5323       (*fun) (filename, this_real_name.get (), data);
5324     });
5325 }
5326
5327 static int
5328 dw2_has_symbols (struct objfile *objfile)
5329 {
5330   return 1;
5331 }
5332
5333 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5334 {
5335   dw2_has_symbols,
5336   dw2_find_last_source_symtab,
5337   dw2_forget_cached_source_info,
5338   dw2_map_symtabs_matching_filename,
5339   dw2_lookup_symbol,
5340   dw2_print_stats,
5341   dw2_dump,
5342   dw2_expand_symtabs_for_function,
5343   dw2_expand_all_symtabs,
5344   dw2_expand_symtabs_with_fullname,
5345   dw2_map_matching_symbols,
5346   dw2_expand_symtabs_matching,
5347   dw2_find_pc_sect_compunit_symtab,
5348   NULL,
5349   dw2_map_symbol_filenames
5350 };
5351
5352 /* DWARF-5 debug_names reader.  */
5353
5354 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5355 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5356
5357 /* A helper function that reads the .debug_names section in SECTION
5358    and fills in MAP.  FILENAME is the name of the file containing the
5359    section; it is used for error reporting.
5360
5361    Returns true if all went well, false otherwise.  */
5362
5363 static bool
5364 read_debug_names_from_section (struct objfile *objfile,
5365                                const char *filename,
5366                                struct dwarf2_section_info *section,
5367                                mapped_debug_names &map)
5368 {
5369   if (dwarf2_section_empty_p (section))
5370     return false;
5371
5372   /* Older elfutils strip versions could keep the section in the main
5373      executable while splitting it for the separate debug info file.  */
5374   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5375     return false;
5376
5377   dwarf2_read_section (objfile, section);
5378
5379   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5380
5381   const gdb_byte *addr = section->buffer;
5382
5383   bfd *const abfd = get_section_bfd_owner (section);
5384
5385   unsigned int bytes_read;
5386   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5387   addr += bytes_read;
5388
5389   map.dwarf5_is_dwarf64 = bytes_read != 4;
5390   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5391   if (bytes_read + length != section->size)
5392     {
5393       /* There may be multiple per-CU indices.  */
5394       warning (_("Section .debug_names in %s length %s does not match "
5395                  "section length %s, ignoring .debug_names."),
5396                filename, plongest (bytes_read + length),
5397                pulongest (section->size));
5398       return false;
5399     }
5400
5401   /* The version number.  */
5402   uint16_t version = read_2_bytes (abfd, addr);
5403   addr += 2;
5404   if (version != 5)
5405     {
5406       warning (_("Section .debug_names in %s has unsupported version %d, "
5407                  "ignoring .debug_names."),
5408                filename, version);
5409       return false;
5410     }
5411
5412   /* Padding.  */
5413   uint16_t padding = read_2_bytes (abfd, addr);
5414   addr += 2;
5415   if (padding != 0)
5416     {
5417       warning (_("Section .debug_names in %s has unsupported padding %d, "
5418                  "ignoring .debug_names."),
5419                filename, padding);
5420       return false;
5421     }
5422
5423   /* comp_unit_count - The number of CUs in the CU list.  */
5424   map.cu_count = read_4_bytes (abfd, addr);
5425   addr += 4;
5426
5427   /* local_type_unit_count - The number of TUs in the local TU
5428      list.  */
5429   map.tu_count = read_4_bytes (abfd, addr);
5430   addr += 4;
5431
5432   /* foreign_type_unit_count - The number of TUs in the foreign TU
5433      list.  */
5434   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5435   addr += 4;
5436   if (foreign_tu_count != 0)
5437     {
5438       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5439                  "ignoring .debug_names."),
5440                filename, static_cast<unsigned long> (foreign_tu_count));
5441       return false;
5442     }
5443
5444   /* bucket_count - The number of hash buckets in the hash lookup
5445      table.  */
5446   map.bucket_count = read_4_bytes (abfd, addr);
5447   addr += 4;
5448
5449   /* name_count - The number of unique names in the index.  */
5450   map.name_count = read_4_bytes (abfd, addr);
5451   addr += 4;
5452
5453   /* abbrev_table_size - The size in bytes of the abbreviations
5454      table.  */
5455   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5456   addr += 4;
5457
5458   /* augmentation_string_size - The size in bytes of the augmentation
5459      string.  This value is rounded up to a multiple of 4.  */
5460   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5461   addr += 4;
5462   map.augmentation_is_gdb = ((augmentation_string_size
5463                               == sizeof (dwarf5_augmentation))
5464                              && memcmp (addr, dwarf5_augmentation,
5465                                         sizeof (dwarf5_augmentation)) == 0);
5466   augmentation_string_size += (-augmentation_string_size) & 3;
5467   addr += augmentation_string_size;
5468
5469   /* List of CUs */
5470   map.cu_table_reordered = addr;
5471   addr += map.cu_count * map.offset_size;
5472
5473   /* List of Local TUs */
5474   map.tu_table_reordered = addr;
5475   addr += map.tu_count * map.offset_size;
5476
5477   /* Hash Lookup Table */
5478   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5479   addr += map.bucket_count * 4;
5480   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5481   addr += map.name_count * 4;
5482
5483   /* Name Table */
5484   map.name_table_string_offs_reordered = addr;
5485   addr += map.name_count * map.offset_size;
5486   map.name_table_entry_offs_reordered = addr;
5487   addr += map.name_count * map.offset_size;
5488
5489   const gdb_byte *abbrev_table_start = addr;
5490   for (;;)
5491     {
5492       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5493       addr += bytes_read;
5494       if (index_num == 0)
5495         break;
5496
5497       const auto insertpair
5498         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5499       if (!insertpair.second)
5500         {
5501           warning (_("Section .debug_names in %s has duplicate index %s, "
5502                      "ignoring .debug_names."),
5503                    filename, pulongest (index_num));
5504           return false;
5505         }
5506       mapped_debug_names::index_val &indexval = insertpair.first->second;
5507       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5508       addr += bytes_read;
5509
5510       for (;;)
5511         {
5512           mapped_debug_names::index_val::attr attr;
5513           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5514           addr += bytes_read;
5515           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5516           addr += bytes_read;
5517           if (attr.form == DW_FORM_implicit_const)
5518             {
5519               attr.implicit_const = read_signed_leb128 (abfd, addr,
5520                                                         &bytes_read);
5521               addr += bytes_read;
5522             }
5523           if (attr.dw_idx == 0 && attr.form == 0)
5524             break;
5525           indexval.attr_vec.push_back (std::move (attr));
5526         }
5527     }
5528   if (addr != abbrev_table_start + abbrev_table_size)
5529     {
5530       warning (_("Section .debug_names in %s has abbreviation_table "
5531                  "of size %zu vs. written as %u, ignoring .debug_names."),
5532                filename, addr - abbrev_table_start, abbrev_table_size);
5533       return false;
5534     }
5535   map.entry_pool = addr;
5536
5537   return true;
5538 }
5539
5540 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5541    list.  */
5542
5543 static void
5544 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5545                                   const mapped_debug_names &map,
5546                                   dwarf2_section_info &section,
5547                                   bool is_dwz)
5548 {
5549   sect_offset sect_off_prev;
5550   for (uint32_t i = 0; i <= map.cu_count; ++i)
5551     {
5552       sect_offset sect_off_next;
5553       if (i < map.cu_count)
5554         {
5555           sect_off_next
5556             = (sect_offset) (extract_unsigned_integer
5557                              (map.cu_table_reordered + i * map.offset_size,
5558                               map.offset_size,
5559                               map.dwarf5_byte_order));
5560         }
5561       else
5562         sect_off_next = (sect_offset) section.size;
5563       if (i >= 1)
5564         {
5565           const ULONGEST length = sect_off_next - sect_off_prev;
5566           dwarf2_per_cu_data *per_cu
5567             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5568                                          sect_off_prev, length);
5569           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5570         }
5571       sect_off_prev = sect_off_next;
5572     }
5573 }
5574
5575 /* Read the CU list from the mapped index, and use it to create all
5576    the CU objects for this dwarf2_per_objfile.  */
5577
5578 static void
5579 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5580                              const mapped_debug_names &map,
5581                              const mapped_debug_names &dwz_map)
5582 {
5583   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5584   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5585
5586   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5587                                     dwarf2_per_objfile->info,
5588                                     false /* is_dwz */);
5589
5590   if (dwz_map.cu_count == 0)
5591     return;
5592
5593   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5594   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5595                                     true /* is_dwz */);
5596 }
5597
5598 /* Read .debug_names.  If everything went ok, initialize the "quick"
5599    elements of all the CUs and return true.  Otherwise, return false.  */
5600
5601 static bool
5602 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5603 {
5604   std::unique_ptr<mapped_debug_names> map
5605     (new mapped_debug_names (dwarf2_per_objfile));
5606   mapped_debug_names dwz_map (dwarf2_per_objfile);
5607   struct objfile *objfile = dwarf2_per_objfile->objfile;
5608
5609   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5610                                       &dwarf2_per_objfile->debug_names,
5611                                       *map))
5612     return false;
5613
5614   /* Don't use the index if it's empty.  */
5615   if (map->name_count == 0)
5616     return false;
5617
5618   /* If there is a .dwz file, read it so we can get its CU list as
5619      well.  */
5620   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5621   if (dwz != NULL)
5622     {
5623       if (!read_debug_names_from_section (objfile,
5624                                           bfd_get_filename (dwz->dwz_bfd),
5625                                           &dwz->debug_names, dwz_map))
5626         {
5627           warning (_("could not read '.debug_names' section from %s; skipping"),
5628                    bfd_get_filename (dwz->dwz_bfd));
5629           return false;
5630         }
5631     }
5632
5633   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5634
5635   if (map->tu_count != 0)
5636     {
5637       /* We can only handle a single .debug_types when we have an
5638          index.  */
5639       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5640         return false;
5641
5642       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5643                                                 dwarf2_per_objfile->types, 0);
5644
5645       create_signatured_type_table_from_debug_names
5646         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5647     }
5648
5649   create_addrmap_from_aranges (dwarf2_per_objfile,
5650                                &dwarf2_per_objfile->debug_aranges);
5651
5652   dwarf2_per_objfile->debug_names_table = std::move (map);
5653   dwarf2_per_objfile->using_index = 1;
5654   dwarf2_per_objfile->quick_file_names_table =
5655     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5656
5657   return true;
5658 }
5659
5660 /* Type used to manage iterating over all CUs looking for a symbol for
5661    .debug_names.  */
5662
5663 class dw2_debug_names_iterator
5664 {
5665 public:
5666   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5667      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5668   dw2_debug_names_iterator (const mapped_debug_names &map,
5669                             bool want_specific_block,
5670                             block_enum block_index, domain_enum domain,
5671                             const char *name)
5672     : m_map (map), m_want_specific_block (want_specific_block),
5673       m_block_index (block_index), m_domain (domain),
5674       m_addr (find_vec_in_debug_names (map, name))
5675   {}
5676
5677   dw2_debug_names_iterator (const mapped_debug_names &map,
5678                             search_domain search, uint32_t namei)
5679     : m_map (map),
5680       m_search (search),
5681       m_addr (find_vec_in_debug_names (map, namei))
5682   {}
5683
5684   /* Return the next matching CU or NULL if there are no more.  */
5685   dwarf2_per_cu_data *next ();
5686
5687 private:
5688   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5689                                                   const char *name);
5690   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5691                                                   uint32_t namei);
5692
5693   /* The internalized form of .debug_names.  */
5694   const mapped_debug_names &m_map;
5695
5696   /* If true, only look for symbols that match BLOCK_INDEX.  */
5697   const bool m_want_specific_block = false;
5698
5699   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5700      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5701      value.  */
5702   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5703
5704   /* The kind of symbol we're looking for.  */
5705   const domain_enum m_domain = UNDEF_DOMAIN;
5706   const search_domain m_search = ALL_DOMAIN;
5707
5708   /* The list of CUs from the index entry of the symbol, or NULL if
5709      not found.  */
5710   const gdb_byte *m_addr;
5711 };
5712
5713 const char *
5714 mapped_debug_names::namei_to_name (uint32_t namei) const
5715 {
5716   const ULONGEST namei_string_offs
5717     = extract_unsigned_integer ((name_table_string_offs_reordered
5718                                  + namei * offset_size),
5719                                 offset_size,
5720                                 dwarf5_byte_order);
5721   return read_indirect_string_at_offset
5722     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5723 }
5724
5725 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5726    found, return pointer to its pool data.  If NAME cannot be found,
5727    return NULL.  */
5728
5729 const gdb_byte *
5730 dw2_debug_names_iterator::find_vec_in_debug_names
5731   (const mapped_debug_names &map, const char *name)
5732 {
5733   int (*cmp) (const char *, const char *);
5734
5735   if (current_language->la_language == language_cplus
5736       || current_language->la_language == language_fortran
5737       || current_language->la_language == language_d)
5738     {
5739       /* NAME is already canonical.  Drop any qualifiers as
5740          .debug_names does not contain any.  */
5741
5742       if (strchr (name, '(') != NULL)
5743         {
5744           gdb::unique_xmalloc_ptr<char> without_params
5745             = cp_remove_params (name);
5746
5747           if (without_params != NULL)
5748             {
5749               name = without_params.get();
5750             }
5751         }
5752     }
5753
5754   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5755
5756   const uint32_t full_hash = dwarf5_djb_hash (name);
5757   uint32_t namei
5758     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5759                                 (map.bucket_table_reordered
5760                                  + (full_hash % map.bucket_count)), 4,
5761                                 map.dwarf5_byte_order);
5762   if (namei == 0)
5763     return NULL;
5764   --namei;
5765   if (namei >= map.name_count)
5766     {
5767       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5768                    "[in module %s]"),
5769                  namei, map.name_count,
5770                  objfile_name (map.dwarf2_per_objfile->objfile));
5771       return NULL;
5772     }
5773
5774   for (;;)
5775     {
5776       const uint32_t namei_full_hash
5777         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5778                                     (map.hash_table_reordered + namei), 4,
5779                                     map.dwarf5_byte_order);
5780       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5781         return NULL;
5782
5783       if (full_hash == namei_full_hash)
5784         {
5785           const char *const namei_string = map.namei_to_name (namei);
5786
5787 #if 0 /* An expensive sanity check.  */
5788           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5789             {
5790               complaint (_("Wrong .debug_names hash for string at index %u "
5791                            "[in module %s]"),
5792                          namei, objfile_name (dwarf2_per_objfile->objfile));
5793               return NULL;
5794             }
5795 #endif
5796
5797           if (cmp (namei_string, name) == 0)
5798             {
5799               const ULONGEST namei_entry_offs
5800                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5801                                              + namei * map.offset_size),
5802                                             map.offset_size, map.dwarf5_byte_order);
5803               return map.entry_pool + namei_entry_offs;
5804             }
5805         }
5806
5807       ++namei;
5808       if (namei >= map.name_count)
5809         return NULL;
5810     }
5811 }
5812
5813 const gdb_byte *
5814 dw2_debug_names_iterator::find_vec_in_debug_names
5815   (const mapped_debug_names &map, uint32_t namei)
5816 {
5817   if (namei >= map.name_count)
5818     {
5819       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5820                    "[in module %s]"),
5821                  namei, map.name_count,
5822                  objfile_name (map.dwarf2_per_objfile->objfile));
5823       return NULL;
5824     }
5825
5826   const ULONGEST namei_entry_offs
5827     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5828                                  + namei * map.offset_size),
5829                                 map.offset_size, map.dwarf5_byte_order);
5830   return map.entry_pool + namei_entry_offs;
5831 }
5832
5833 /* See dw2_debug_names_iterator.  */
5834
5835 dwarf2_per_cu_data *
5836 dw2_debug_names_iterator::next ()
5837 {
5838   if (m_addr == NULL)
5839     return NULL;
5840
5841   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5842   struct objfile *objfile = dwarf2_per_objfile->objfile;
5843   bfd *const abfd = objfile->obfd;
5844
5845  again:
5846
5847   unsigned int bytes_read;
5848   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5849   m_addr += bytes_read;
5850   if (abbrev == 0)
5851     return NULL;
5852
5853   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5854   if (indexval_it == m_map.abbrev_map.cend ())
5855     {
5856       complaint (_("Wrong .debug_names undefined abbrev code %s "
5857                    "[in module %s]"),
5858                  pulongest (abbrev), objfile_name (objfile));
5859       return NULL;
5860     }
5861   const mapped_debug_names::index_val &indexval = indexval_it->second;
5862   bool have_is_static = false;
5863   bool is_static;
5864   dwarf2_per_cu_data *per_cu = NULL;
5865   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5866     {
5867       ULONGEST ull;
5868       switch (attr.form)
5869         {
5870         case DW_FORM_implicit_const:
5871           ull = attr.implicit_const;
5872           break;
5873         case DW_FORM_flag_present:
5874           ull = 1;
5875           break;
5876         case DW_FORM_udata:
5877           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5878           m_addr += bytes_read;
5879           break;
5880         default:
5881           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5882                      dwarf_form_name (attr.form),
5883                      objfile_name (objfile));
5884           return NULL;
5885         }
5886       switch (attr.dw_idx)
5887         {
5888         case DW_IDX_compile_unit:
5889           /* Don't crash on bad data.  */
5890           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5891             {
5892               complaint (_(".debug_names entry has bad CU index %s"
5893                            " [in module %s]"),
5894                          pulongest (ull),
5895                          objfile_name (dwarf2_per_objfile->objfile));
5896               continue;
5897             }
5898           per_cu = dwarf2_per_objfile->get_cutu (ull);
5899           break;
5900         case DW_IDX_type_unit:
5901           /* Don't crash on bad data.  */
5902           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5903             {
5904               complaint (_(".debug_names entry has bad TU index %s"
5905                            " [in module %s]"),
5906                          pulongest (ull),
5907                          objfile_name (dwarf2_per_objfile->objfile));
5908               continue;
5909             }
5910           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5911           break;
5912         case DW_IDX_GNU_internal:
5913           if (!m_map.augmentation_is_gdb)
5914             break;
5915           have_is_static = true;
5916           is_static = true;
5917           break;
5918         case DW_IDX_GNU_external:
5919           if (!m_map.augmentation_is_gdb)
5920             break;
5921           have_is_static = true;
5922           is_static = false;
5923           break;
5924         }
5925     }
5926
5927   /* Skip if already read in.  */
5928   if (per_cu->v.quick->compunit_symtab)
5929     goto again;
5930
5931   /* Check static vs global.  */
5932   if (have_is_static)
5933     {
5934       const bool want_static = m_block_index != GLOBAL_BLOCK;
5935       if (m_want_specific_block && want_static != is_static)
5936         goto again;
5937     }
5938
5939   /* Match dw2_symtab_iter_next, symbol_kind
5940      and debug_names::psymbol_tag.  */
5941   switch (m_domain)
5942     {
5943     case VAR_DOMAIN:
5944       switch (indexval.dwarf_tag)
5945         {
5946         case DW_TAG_variable:
5947         case DW_TAG_subprogram:
5948         /* Some types are also in VAR_DOMAIN.  */
5949         case DW_TAG_typedef:
5950         case DW_TAG_structure_type:
5951           break;
5952         default:
5953           goto again;
5954         }
5955       break;
5956     case STRUCT_DOMAIN:
5957       switch (indexval.dwarf_tag)
5958         {
5959         case DW_TAG_typedef:
5960         case DW_TAG_structure_type:
5961           break;
5962         default:
5963           goto again;
5964         }
5965       break;
5966     case LABEL_DOMAIN:
5967       switch (indexval.dwarf_tag)
5968         {
5969         case 0:
5970         case DW_TAG_variable:
5971           break;
5972         default:
5973           goto again;
5974         }
5975       break;
5976     default:
5977       break;
5978     }
5979
5980   /* Match dw2_expand_symtabs_matching, symbol_kind and
5981      debug_names::psymbol_tag.  */
5982   switch (m_search)
5983     {
5984     case VARIABLES_DOMAIN:
5985       switch (indexval.dwarf_tag)
5986         {
5987         case DW_TAG_variable:
5988           break;
5989         default:
5990           goto again;
5991         }
5992       break;
5993     case FUNCTIONS_DOMAIN:
5994       switch (indexval.dwarf_tag)
5995         {
5996         case DW_TAG_subprogram:
5997           break;
5998         default:
5999           goto again;
6000         }
6001       break;
6002     case TYPES_DOMAIN:
6003       switch (indexval.dwarf_tag)
6004         {
6005         case DW_TAG_typedef:
6006         case DW_TAG_structure_type:
6007           break;
6008         default:
6009           goto again;
6010         }
6011       break;
6012     default:
6013       break;
6014     }
6015
6016   return per_cu;
6017 }
6018
6019 static struct compunit_symtab *
6020 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6021                                const char *name, domain_enum domain)
6022 {
6023   const block_enum block_index = static_cast<block_enum> (block_index_int);
6024   struct dwarf2_per_objfile *dwarf2_per_objfile
6025     = get_dwarf2_per_objfile (objfile);
6026
6027   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6028   if (!mapp)
6029     {
6030       /* index is NULL if OBJF_READNOW.  */
6031       return NULL;
6032     }
6033   const auto &map = *mapp;
6034
6035   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6036                                  block_index, domain, name);
6037
6038   struct compunit_symtab *stab_best = NULL;
6039   struct dwarf2_per_cu_data *per_cu;
6040   while ((per_cu = iter.next ()) != NULL)
6041     {
6042       struct symbol *sym, *with_opaque = NULL;
6043       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6044       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6045       const struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6046
6047       sym = block_find_symbol (block, name, domain,
6048                                block_find_non_opaque_type_preferred,
6049                                &with_opaque);
6050
6051       /* Some caution must be observed with overloaded functions and
6052          methods, since the index will not contain any overload
6053          information (but NAME might contain it).  */
6054
6055       if (sym != NULL
6056           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6057         return stab;
6058       if (with_opaque != NULL
6059           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6060         stab_best = stab;
6061
6062       /* Keep looking through other CUs.  */
6063     }
6064
6065   return stab_best;
6066 }
6067
6068 /* This dumps minimal information about .debug_names.  It is called
6069    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6070    uses this to verify that .debug_names has been loaded.  */
6071
6072 static void
6073 dw2_debug_names_dump (struct objfile *objfile)
6074 {
6075   struct dwarf2_per_objfile *dwarf2_per_objfile
6076     = get_dwarf2_per_objfile (objfile);
6077
6078   gdb_assert (dwarf2_per_objfile->using_index);
6079   printf_filtered (".debug_names:");
6080   if (dwarf2_per_objfile->debug_names_table)
6081     printf_filtered (" exists\n");
6082   else
6083     printf_filtered (" faked for \"readnow\"\n");
6084   printf_filtered ("\n");
6085 }
6086
6087 static void
6088 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6089                                              const char *func_name)
6090 {
6091   struct dwarf2_per_objfile *dwarf2_per_objfile
6092     = get_dwarf2_per_objfile (objfile);
6093
6094   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6095   if (dwarf2_per_objfile->debug_names_table)
6096     {
6097       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6098
6099       /* Note: It doesn't matter what we pass for block_index here.  */
6100       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6101                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6102
6103       struct dwarf2_per_cu_data *per_cu;
6104       while ((per_cu = iter.next ()) != NULL)
6105         dw2_instantiate_symtab (per_cu, false);
6106     }
6107 }
6108
6109 static void
6110 dw2_debug_names_expand_symtabs_matching
6111   (struct objfile *objfile,
6112    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6113    const lookup_name_info &lookup_name,
6114    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6115    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6116    enum search_domain kind)
6117 {
6118   struct dwarf2_per_objfile *dwarf2_per_objfile
6119     = get_dwarf2_per_objfile (objfile);
6120
6121   /* debug_names_table is NULL if OBJF_READNOW.  */
6122   if (!dwarf2_per_objfile->debug_names_table)
6123     return;
6124
6125   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6126
6127   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6128
6129   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6130                                       symbol_matcher,
6131                                       kind, [&] (offset_type namei)
6132     {
6133       /* The name was matched, now expand corresponding CUs that were
6134          marked.  */
6135       dw2_debug_names_iterator iter (map, kind, namei);
6136
6137       struct dwarf2_per_cu_data *per_cu;
6138       while ((per_cu = iter.next ()) != NULL)
6139         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6140                                          expansion_notify);
6141     });
6142 }
6143
6144 const struct quick_symbol_functions dwarf2_debug_names_functions =
6145 {
6146   dw2_has_symbols,
6147   dw2_find_last_source_symtab,
6148   dw2_forget_cached_source_info,
6149   dw2_map_symtabs_matching_filename,
6150   dw2_debug_names_lookup_symbol,
6151   dw2_print_stats,
6152   dw2_debug_names_dump,
6153   dw2_debug_names_expand_symtabs_for_function,
6154   dw2_expand_all_symtabs,
6155   dw2_expand_symtabs_with_fullname,
6156   dw2_map_matching_symbols,
6157   dw2_debug_names_expand_symtabs_matching,
6158   dw2_find_pc_sect_compunit_symtab,
6159   NULL,
6160   dw2_map_symbol_filenames
6161 };
6162
6163 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
6164    to either a dwarf2_per_objfile or dwz_file object.  */
6165
6166 template <typename T>
6167 static gdb::array_view<const gdb_byte>
6168 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
6169 {
6170   dwarf2_section_info *section = &section_owner->gdb_index;
6171
6172   if (dwarf2_section_empty_p (section))
6173     return {};
6174
6175   /* Older elfutils strip versions could keep the section in the main
6176      executable while splitting it for the separate debug info file.  */
6177   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
6178     return {};
6179
6180   dwarf2_read_section (obj, section);
6181
6182   /* dwarf2_section_info::size is a bfd_size_type, while
6183      gdb::array_view works with size_t.  On 32-bit hosts, with
6184      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
6185      is 32-bit.  So we need an explicit narrowing conversion here.
6186      This is fine, because it's impossible to allocate or mmap an
6187      array/buffer larger than what size_t can represent.  */
6188   return gdb::make_array_view (section->buffer, section->size);
6189 }
6190
6191 /* Lookup the index cache for the contents of the index associated to
6192    DWARF2_OBJ.  */
6193
6194 static gdb::array_view<const gdb_byte>
6195 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
6196 {
6197   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
6198   if (build_id == nullptr)
6199     return {};
6200
6201   return global_index_cache.lookup_gdb_index (build_id,
6202                                               &dwarf2_obj->index_cache_res);
6203 }
6204
6205 /* Same as the above, but for DWZ.  */
6206
6207 static gdb::array_view<const gdb_byte>
6208 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
6209 {
6210   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
6211   if (build_id == nullptr)
6212     return {};
6213
6214   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
6215 }
6216
6217 /* See symfile.h.  */
6218
6219 bool
6220 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6221 {
6222   struct dwarf2_per_objfile *dwarf2_per_objfile
6223     = get_dwarf2_per_objfile (objfile);
6224
6225   /* If we're about to read full symbols, don't bother with the
6226      indices.  In this case we also don't care if some other debug
6227      format is making psymtabs, because they are all about to be
6228      expanded anyway.  */
6229   if ((objfile->flags & OBJF_READNOW))
6230     {
6231       dwarf2_per_objfile->using_index = 1;
6232       create_all_comp_units (dwarf2_per_objfile);
6233       create_all_type_units (dwarf2_per_objfile);
6234       dwarf2_per_objfile->quick_file_names_table
6235         = create_quick_file_names_table
6236             (dwarf2_per_objfile->all_comp_units.size ());
6237
6238       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6239                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6240         {
6241           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6242
6243           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6244                                             struct dwarf2_per_cu_quick_data);
6245         }
6246
6247       /* Return 1 so that gdb sees the "quick" functions.  However,
6248          these functions will be no-ops because we will have expanded
6249          all symtabs.  */
6250       *index_kind = dw_index_kind::GDB_INDEX;
6251       return true;
6252     }
6253
6254   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6255     {
6256       *index_kind = dw_index_kind::DEBUG_NAMES;
6257       return true;
6258     }
6259
6260   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6261                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6262                              get_gdb_index_contents_from_section<dwz_file>))
6263     {
6264       *index_kind = dw_index_kind::GDB_INDEX;
6265       return true;
6266     }
6267
6268   /* ... otherwise, try to find the index in the index cache.  */
6269   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6270                              get_gdb_index_contents_from_cache,
6271                              get_gdb_index_contents_from_cache_dwz))
6272     {
6273       global_index_cache.hit ();
6274       *index_kind = dw_index_kind::GDB_INDEX;
6275       return true;
6276     }
6277
6278   global_index_cache.miss ();
6279   return false;
6280 }
6281
6282 \f
6283
6284 /* Build a partial symbol table.  */
6285
6286 void
6287 dwarf2_build_psymtabs (struct objfile *objfile)
6288 {
6289   struct dwarf2_per_objfile *dwarf2_per_objfile
6290     = get_dwarf2_per_objfile (objfile);
6291
6292   init_psymbol_list (objfile, 1024);
6293
6294   try
6295     {
6296       /* This isn't really ideal: all the data we allocate on the
6297          objfile's obstack is still uselessly kept around.  However,
6298          freeing it seems unsafe.  */
6299       psymtab_discarder psymtabs (objfile);
6300       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6301       psymtabs.keep ();
6302
6303       /* (maybe) store an index in the cache.  */
6304       global_index_cache.store (dwarf2_per_objfile);
6305     }
6306   catch (const gdb_exception_error &except)
6307     {
6308       exception_print (gdb_stderr, except);
6309     }
6310 }
6311
6312 /* Return the total length of the CU described by HEADER.  */
6313
6314 static unsigned int
6315 get_cu_length (const struct comp_unit_head *header)
6316 {
6317   return header->initial_length_size + header->length;
6318 }
6319
6320 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6321
6322 static inline bool
6323 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6324 {
6325   sect_offset bottom = cu_header->sect_off;
6326   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6327
6328   return sect_off >= bottom && sect_off < top;
6329 }
6330
6331 /* Find the base address of the compilation unit for range lists and
6332    location lists.  It will normally be specified by DW_AT_low_pc.
6333    In DWARF-3 draft 4, the base address could be overridden by
6334    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6335    compilation units with discontinuous ranges.  */
6336
6337 static void
6338 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6339 {
6340   struct attribute *attr;
6341
6342   cu->base_known = 0;
6343   cu->base_address = 0;
6344
6345   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6346   if (attr)
6347     {
6348       cu->base_address = attr_value_as_address (attr);
6349       cu->base_known = 1;
6350     }
6351   else
6352     {
6353       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6354       if (attr)
6355         {
6356           cu->base_address = attr_value_as_address (attr);
6357           cu->base_known = 1;
6358         }
6359     }
6360 }
6361
6362 /* Read in the comp unit header information from the debug_info at info_ptr.
6363    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6364    NOTE: This leaves members offset, first_die_offset to be filled in
6365    by the caller.  */
6366
6367 static const gdb_byte *
6368 read_comp_unit_head (struct comp_unit_head *cu_header,
6369                      const gdb_byte *info_ptr,
6370                      struct dwarf2_section_info *section,
6371                      rcuh_kind section_kind)
6372 {
6373   int signed_addr;
6374   unsigned int bytes_read;
6375   const char *filename = get_section_file_name (section);
6376   bfd *abfd = get_section_bfd_owner (section);
6377
6378   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6379   cu_header->initial_length_size = bytes_read;
6380   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6381   info_ptr += bytes_read;
6382   cu_header->version = read_2_bytes (abfd, info_ptr);
6383   if (cu_header->version < 2 || cu_header->version > 5)
6384     error (_("Dwarf Error: wrong version in compilation unit header "
6385            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6386            cu_header->version, filename);
6387   info_ptr += 2;
6388   if (cu_header->version < 5)
6389     switch (section_kind)
6390       {
6391       case rcuh_kind::COMPILE:
6392         cu_header->unit_type = DW_UT_compile;
6393         break;
6394       case rcuh_kind::TYPE:
6395         cu_header->unit_type = DW_UT_type;
6396         break;
6397       default:
6398         internal_error (__FILE__, __LINE__,
6399                         _("read_comp_unit_head: invalid section_kind"));
6400       }
6401   else
6402     {
6403       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6404                                                  (read_1_byte (abfd, info_ptr));
6405       info_ptr += 1;
6406       switch (cu_header->unit_type)
6407         {
6408         case DW_UT_compile:
6409           if (section_kind != rcuh_kind::COMPILE)
6410             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6411                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6412                    filename);
6413           break;
6414         case DW_UT_type:
6415           section_kind = rcuh_kind::TYPE;
6416           break;
6417         default:
6418           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6419                  "(is %d, should be %d or %d) [in module %s]"),
6420                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6421         }
6422
6423       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6424       info_ptr += 1;
6425     }
6426   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6427                                                           cu_header,
6428                                                           &bytes_read);
6429   info_ptr += bytes_read;
6430   if (cu_header->version < 5)
6431     {
6432       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6433       info_ptr += 1;
6434     }
6435   signed_addr = bfd_get_sign_extend_vma (abfd);
6436   if (signed_addr < 0)
6437     internal_error (__FILE__, __LINE__,
6438                     _("read_comp_unit_head: dwarf from non elf file"));
6439   cu_header->signed_addr_p = signed_addr;
6440
6441   if (section_kind == rcuh_kind::TYPE)
6442     {
6443       LONGEST type_offset;
6444
6445       cu_header->signature = read_8_bytes (abfd, info_ptr);
6446       info_ptr += 8;
6447
6448       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6449       info_ptr += bytes_read;
6450       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6451       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6452         error (_("Dwarf Error: Too big type_offset in compilation unit "
6453                "header (is %s) [in module %s]"), plongest (type_offset),
6454                filename);
6455     }
6456
6457   return info_ptr;
6458 }
6459
6460 /* Helper function that returns the proper abbrev section for
6461    THIS_CU.  */
6462
6463 static struct dwarf2_section_info *
6464 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6465 {
6466   struct dwarf2_section_info *abbrev;
6467   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6468
6469   if (this_cu->is_dwz)
6470     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6471   else
6472     abbrev = &dwarf2_per_objfile->abbrev;
6473
6474   return abbrev;
6475 }
6476
6477 /* Subroutine of read_and_check_comp_unit_head and
6478    read_and_check_type_unit_head to simplify them.
6479    Perform various error checking on the header.  */
6480
6481 static void
6482 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6483                             struct comp_unit_head *header,
6484                             struct dwarf2_section_info *section,
6485                             struct dwarf2_section_info *abbrev_section)
6486 {
6487   const char *filename = get_section_file_name (section);
6488
6489   if (to_underlying (header->abbrev_sect_off)
6490       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6491     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6492            "(offset %s + 6) [in module %s]"),
6493            sect_offset_str (header->abbrev_sect_off),
6494            sect_offset_str (header->sect_off),
6495            filename);
6496
6497   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6498      avoid potential 32-bit overflow.  */
6499   if (((ULONGEST) header->sect_off + get_cu_length (header))
6500       > section->size)
6501     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6502            "(offset %s + 0) [in module %s]"),
6503            header->length, sect_offset_str (header->sect_off),
6504            filename);
6505 }
6506
6507 /* Read in a CU/TU header and perform some basic error checking.
6508    The contents of the header are stored in HEADER.
6509    The result is a pointer to the start of the first DIE.  */
6510
6511 static const gdb_byte *
6512 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6513                                struct comp_unit_head *header,
6514                                struct dwarf2_section_info *section,
6515                                struct dwarf2_section_info *abbrev_section,
6516                                const gdb_byte *info_ptr,
6517                                rcuh_kind section_kind)
6518 {
6519   const gdb_byte *beg_of_comp_unit = info_ptr;
6520
6521   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6522
6523   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6524
6525   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6526
6527   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6528                               abbrev_section);
6529
6530   return info_ptr;
6531 }
6532
6533 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6534
6535 static sect_offset
6536 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6537                     struct dwarf2_section_info *section,
6538                     sect_offset sect_off)
6539 {
6540   bfd *abfd = get_section_bfd_owner (section);
6541   const gdb_byte *info_ptr;
6542   unsigned int initial_length_size, offset_size;
6543   uint16_t version;
6544
6545   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6546   info_ptr = section->buffer + to_underlying (sect_off);
6547   read_initial_length (abfd, info_ptr, &initial_length_size);
6548   offset_size = initial_length_size == 4 ? 4 : 8;
6549   info_ptr += initial_length_size;
6550
6551   version = read_2_bytes (abfd, info_ptr);
6552   info_ptr += 2;
6553   if (version >= 5)
6554     {
6555       /* Skip unit type and address size.  */
6556       info_ptr += 2;
6557     }
6558
6559   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6560 }
6561
6562 /* Allocate a new partial symtab for file named NAME and mark this new
6563    partial symtab as being an include of PST.  */
6564
6565 static void
6566 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6567                                struct objfile *objfile)
6568 {
6569   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6570
6571   if (!IS_ABSOLUTE_PATH (subpst->filename))
6572     {
6573       /* It shares objfile->objfile_obstack.  */
6574       subpst->dirname = pst->dirname;
6575     }
6576
6577   subpst->dependencies = objfile->partial_symtabs->allocate_dependencies (1);
6578   subpst->dependencies[0] = pst;
6579   subpst->number_of_dependencies = 1;
6580
6581   subpst->read_symtab = pst->read_symtab;
6582
6583   /* No private part is necessary for include psymtabs.  This property
6584      can be used to differentiate between such include psymtabs and
6585      the regular ones.  */
6586   subpst->read_symtab_private = NULL;
6587 }
6588
6589 /* Read the Line Number Program data and extract the list of files
6590    included by the source file represented by PST.  Build an include
6591    partial symtab for each of these included files.  */
6592
6593 static void
6594 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6595                                struct die_info *die,
6596                                struct partial_symtab *pst)
6597 {
6598   line_header_up lh;
6599   struct attribute *attr;
6600
6601   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6602   if (attr)
6603     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6604   if (lh == NULL)
6605     return;  /* No linetable, so no includes.  */
6606
6607   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6608      that we pass in the raw text_low here; that is ok because we're
6609      only decoding the line table to make include partial symtabs, and
6610      so the addresses aren't really used.  */
6611   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6612                       pst->raw_text_low (), 1);
6613 }
6614
6615 static hashval_t
6616 hash_signatured_type (const void *item)
6617 {
6618   const struct signatured_type *sig_type
6619     = (const struct signatured_type *) item;
6620
6621   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6622   return sig_type->signature;
6623 }
6624
6625 static int
6626 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6627 {
6628   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6629   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6630
6631   return lhs->signature == rhs->signature;
6632 }
6633
6634 /* Allocate a hash table for signatured types.  */
6635
6636 static htab_t
6637 allocate_signatured_type_table (struct objfile *objfile)
6638 {
6639   return htab_create_alloc_ex (41,
6640                                hash_signatured_type,
6641                                eq_signatured_type,
6642                                NULL,
6643                                &objfile->objfile_obstack,
6644                                hashtab_obstack_allocate,
6645                                dummy_obstack_deallocate);
6646 }
6647
6648 /* A helper function to add a signatured type CU to a table.  */
6649
6650 static int
6651 add_signatured_type_cu_to_table (void **slot, void *datum)
6652 {
6653   struct signatured_type *sigt = (struct signatured_type *) *slot;
6654   std::vector<signatured_type *> *all_type_units
6655     = (std::vector<signatured_type *> *) datum;
6656
6657   all_type_units->push_back (sigt);
6658
6659   return 1;
6660 }
6661
6662 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6663    and fill them into TYPES_HTAB.  It will process only type units,
6664    therefore DW_UT_type.  */
6665
6666 static void
6667 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6668                               struct dwo_file *dwo_file,
6669                               dwarf2_section_info *section, htab_t &types_htab,
6670                               rcuh_kind section_kind)
6671 {
6672   struct objfile *objfile = dwarf2_per_objfile->objfile;
6673   struct dwarf2_section_info *abbrev_section;
6674   bfd *abfd;
6675   const gdb_byte *info_ptr, *end_ptr;
6676
6677   abbrev_section = (dwo_file != NULL
6678                     ? &dwo_file->sections.abbrev
6679                     : &dwarf2_per_objfile->abbrev);
6680
6681   if (dwarf_read_debug)
6682     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6683                         get_section_name (section),
6684                         get_section_file_name (abbrev_section));
6685
6686   dwarf2_read_section (objfile, section);
6687   info_ptr = section->buffer;
6688
6689   if (info_ptr == NULL)
6690     return;
6691
6692   /* We can't set abfd until now because the section may be empty or
6693      not present, in which case the bfd is unknown.  */
6694   abfd = get_section_bfd_owner (section);
6695
6696   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6697      because we don't need to read any dies: the signature is in the
6698      header.  */
6699
6700   end_ptr = info_ptr + section->size;
6701   while (info_ptr < end_ptr)
6702     {
6703       struct signatured_type *sig_type;
6704       struct dwo_unit *dwo_tu;
6705       void **slot;
6706       const gdb_byte *ptr = info_ptr;
6707       struct comp_unit_head header;
6708       unsigned int length;
6709
6710       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6711
6712       /* Initialize it due to a false compiler warning.  */
6713       header.signature = -1;
6714       header.type_cu_offset_in_tu = (cu_offset) -1;
6715
6716       /* We need to read the type's signature in order to build the hash
6717          table, but we don't need anything else just yet.  */
6718
6719       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6720                                            abbrev_section, ptr, section_kind);
6721
6722       length = get_cu_length (&header);
6723
6724       /* Skip dummy type units.  */
6725       if (ptr >= info_ptr + length
6726           || peek_abbrev_code (abfd, ptr) == 0
6727           || header.unit_type != DW_UT_type)
6728         {
6729           info_ptr += length;
6730           continue;
6731         }
6732
6733       if (types_htab == NULL)
6734         {
6735           if (dwo_file)
6736             types_htab = allocate_dwo_unit_table (objfile);
6737           else
6738             types_htab = allocate_signatured_type_table (objfile);
6739         }
6740
6741       if (dwo_file)
6742         {
6743           sig_type = NULL;
6744           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6745                                    struct dwo_unit);
6746           dwo_tu->dwo_file = dwo_file;
6747           dwo_tu->signature = header.signature;
6748           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6749           dwo_tu->section = section;
6750           dwo_tu->sect_off = sect_off;
6751           dwo_tu->length = length;
6752         }
6753       else
6754         {
6755           /* N.B.: type_offset is not usable if this type uses a DWO file.
6756              The real type_offset is in the DWO file.  */
6757           dwo_tu = NULL;
6758           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6759                                      struct signatured_type);
6760           sig_type->signature = header.signature;
6761           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6762           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6763           sig_type->per_cu.is_debug_types = 1;
6764           sig_type->per_cu.section = section;
6765           sig_type->per_cu.sect_off = sect_off;
6766           sig_type->per_cu.length = length;
6767         }
6768
6769       slot = htab_find_slot (types_htab,
6770                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6771                              INSERT);
6772       gdb_assert (slot != NULL);
6773       if (*slot != NULL)
6774         {
6775           sect_offset dup_sect_off;
6776
6777           if (dwo_file)
6778             {
6779               const struct dwo_unit *dup_tu
6780                 = (const struct dwo_unit *) *slot;
6781
6782               dup_sect_off = dup_tu->sect_off;
6783             }
6784           else
6785             {
6786               const struct signatured_type *dup_tu
6787                 = (const struct signatured_type *) *slot;
6788
6789               dup_sect_off = dup_tu->per_cu.sect_off;
6790             }
6791
6792           complaint (_("debug type entry at offset %s is duplicate to"
6793                        " the entry at offset %s, signature %s"),
6794                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6795                      hex_string (header.signature));
6796         }
6797       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6798
6799       if (dwarf_read_debug > 1)
6800         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6801                             sect_offset_str (sect_off),
6802                             hex_string (header.signature));
6803
6804       info_ptr += length;
6805     }
6806 }
6807
6808 /* Create the hash table of all entries in the .debug_types
6809    (or .debug_types.dwo) section(s).
6810    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6811    otherwise it is NULL.
6812
6813    The result is a pointer to the hash table or NULL if there are no types.
6814
6815    Note: This function processes DWO files only, not DWP files.  */
6816
6817 static void
6818 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6819                                struct dwo_file *dwo_file,
6820                                VEC (dwarf2_section_info_def) *types,
6821                                htab_t &types_htab)
6822 {
6823   int ix;
6824   struct dwarf2_section_info *section;
6825
6826   if (VEC_empty (dwarf2_section_info_def, types))
6827     return;
6828
6829   for (ix = 0;
6830        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6831        ++ix)
6832     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6833                                   types_htab, rcuh_kind::TYPE);
6834 }
6835
6836 /* Create the hash table of all entries in the .debug_types section,
6837    and initialize all_type_units.
6838    The result is zero if there is an error (e.g. missing .debug_types section),
6839    otherwise non-zero.  */
6840
6841 static int
6842 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6843 {
6844   htab_t types_htab = NULL;
6845
6846   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6847                                 &dwarf2_per_objfile->info, types_htab,
6848                                 rcuh_kind::COMPILE);
6849   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6850                                  dwarf2_per_objfile->types, types_htab);
6851   if (types_htab == NULL)
6852     {
6853       dwarf2_per_objfile->signatured_types = NULL;
6854       return 0;
6855     }
6856
6857   dwarf2_per_objfile->signatured_types = types_htab;
6858
6859   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6860   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6861
6862   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6863                           &dwarf2_per_objfile->all_type_units);
6864
6865   return 1;
6866 }
6867
6868 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6869    If SLOT is non-NULL, it is the entry to use in the hash table.
6870    Otherwise we find one.  */
6871
6872 static struct signatured_type *
6873 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6874                void **slot)
6875 {
6876   struct objfile *objfile = dwarf2_per_objfile->objfile;
6877
6878   if (dwarf2_per_objfile->all_type_units.size ()
6879       == dwarf2_per_objfile->all_type_units.capacity ())
6880     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6881
6882   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6883                                               struct signatured_type);
6884
6885   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6886   sig_type->signature = sig;
6887   sig_type->per_cu.is_debug_types = 1;
6888   if (dwarf2_per_objfile->using_index)
6889     {
6890       sig_type->per_cu.v.quick =
6891         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6892                         struct dwarf2_per_cu_quick_data);
6893     }
6894
6895   if (slot == NULL)
6896     {
6897       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6898                              sig_type, INSERT);
6899     }
6900   gdb_assert (*slot == NULL);
6901   *slot = sig_type;
6902   /* The rest of sig_type must be filled in by the caller.  */
6903   return sig_type;
6904 }
6905
6906 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6907    Fill in SIG_ENTRY with DWO_ENTRY.  */
6908
6909 static void
6910 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6911                                   struct signatured_type *sig_entry,
6912                                   struct dwo_unit *dwo_entry)
6913 {
6914   /* Make sure we're not clobbering something we don't expect to.  */
6915   gdb_assert (! sig_entry->per_cu.queued);
6916   gdb_assert (sig_entry->per_cu.cu == NULL);
6917   if (dwarf2_per_objfile->using_index)
6918     {
6919       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6920       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6921     }
6922   else
6923       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6924   gdb_assert (sig_entry->signature == dwo_entry->signature);
6925   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6926   gdb_assert (sig_entry->type_unit_group == NULL);
6927   gdb_assert (sig_entry->dwo_unit == NULL);
6928
6929   sig_entry->per_cu.section = dwo_entry->section;
6930   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6931   sig_entry->per_cu.length = dwo_entry->length;
6932   sig_entry->per_cu.reading_dwo_directly = 1;
6933   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6934   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6935   sig_entry->dwo_unit = dwo_entry;
6936 }
6937
6938 /* Subroutine of lookup_signatured_type.
6939    If we haven't read the TU yet, create the signatured_type data structure
6940    for a TU to be read in directly from a DWO file, bypassing the stub.
6941    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6942    using .gdb_index, then when reading a CU we want to stay in the DWO file
6943    containing that CU.  Otherwise we could end up reading several other DWO
6944    files (due to comdat folding) to process the transitive closure of all the
6945    mentioned TUs, and that can be slow.  The current DWO file will have every
6946    type signature that it needs.
6947    We only do this for .gdb_index because in the psymtab case we already have
6948    to read all the DWOs to build the type unit groups.  */
6949
6950 static struct signatured_type *
6951 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6952 {
6953   struct dwarf2_per_objfile *dwarf2_per_objfile
6954     = cu->per_cu->dwarf2_per_objfile;
6955   struct objfile *objfile = dwarf2_per_objfile->objfile;
6956   struct dwo_file *dwo_file;
6957   struct dwo_unit find_dwo_entry, *dwo_entry;
6958   struct signatured_type find_sig_entry, *sig_entry;
6959   void **slot;
6960
6961   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6962
6963   /* If TU skeletons have been removed then we may not have read in any
6964      TUs yet.  */
6965   if (dwarf2_per_objfile->signatured_types == NULL)
6966     {
6967       dwarf2_per_objfile->signatured_types
6968         = allocate_signatured_type_table (objfile);
6969     }
6970
6971   /* We only ever need to read in one copy of a signatured type.
6972      Use the global signatured_types array to do our own comdat-folding
6973      of types.  If this is the first time we're reading this TU, and
6974      the TU has an entry in .gdb_index, replace the recorded data from
6975      .gdb_index with this TU.  */
6976
6977   find_sig_entry.signature = sig;
6978   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6979                          &find_sig_entry, INSERT);
6980   sig_entry = (struct signatured_type *) *slot;
6981
6982   /* We can get here with the TU already read, *or* in the process of being
6983      read.  Don't reassign the global entry to point to this DWO if that's
6984      the case.  Also note that if the TU is already being read, it may not
6985      have come from a DWO, the program may be a mix of Fission-compiled
6986      code and non-Fission-compiled code.  */
6987
6988   /* Have we already tried to read this TU?
6989      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6990      needn't exist in the global table yet).  */
6991   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6992     return sig_entry;
6993
6994   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6995      dwo_unit of the TU itself.  */
6996   dwo_file = cu->dwo_unit->dwo_file;
6997
6998   /* Ok, this is the first time we're reading this TU.  */
6999   if (dwo_file->tus == NULL)
7000     return NULL;
7001   find_dwo_entry.signature = sig;
7002   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7003   if (dwo_entry == NULL)
7004     return NULL;
7005
7006   /* If the global table doesn't have an entry for this TU, add one.  */
7007   if (sig_entry == NULL)
7008     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7009
7010   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7011   sig_entry->per_cu.tu_read = 1;
7012   return sig_entry;
7013 }
7014
7015 /* Subroutine of lookup_signatured_type.
7016    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7017    then try the DWP file.  If the TU stub (skeleton) has been removed then
7018    it won't be in .gdb_index.  */
7019
7020 static struct signatured_type *
7021 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7022 {
7023   struct dwarf2_per_objfile *dwarf2_per_objfile
7024     = cu->per_cu->dwarf2_per_objfile;
7025   struct objfile *objfile = dwarf2_per_objfile->objfile;
7026   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7027   struct dwo_unit *dwo_entry;
7028   struct signatured_type find_sig_entry, *sig_entry;
7029   void **slot;
7030
7031   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7032   gdb_assert (dwp_file != NULL);
7033
7034   /* If TU skeletons have been removed then we may not have read in any
7035      TUs yet.  */
7036   if (dwarf2_per_objfile->signatured_types == NULL)
7037     {
7038       dwarf2_per_objfile->signatured_types
7039         = allocate_signatured_type_table (objfile);
7040     }
7041
7042   find_sig_entry.signature = sig;
7043   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7044                          &find_sig_entry, INSERT);
7045   sig_entry = (struct signatured_type *) *slot;
7046
7047   /* Have we already tried to read this TU?
7048      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7049      needn't exist in the global table yet).  */
7050   if (sig_entry != NULL)
7051     return sig_entry;
7052
7053   if (dwp_file->tus == NULL)
7054     return NULL;
7055   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7056                                       sig, 1 /* is_debug_types */);
7057   if (dwo_entry == NULL)
7058     return NULL;
7059
7060   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7061   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7062
7063   return sig_entry;
7064 }
7065
7066 /* Lookup a signature based type for DW_FORM_ref_sig8.
7067    Returns NULL if signature SIG is not present in the table.
7068    It is up to the caller to complain about this.  */
7069
7070 static struct signatured_type *
7071 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7072 {
7073   struct dwarf2_per_objfile *dwarf2_per_objfile
7074     = cu->per_cu->dwarf2_per_objfile;
7075
7076   if (cu->dwo_unit
7077       && dwarf2_per_objfile->using_index)
7078     {
7079       /* We're in a DWO/DWP file, and we're using .gdb_index.
7080          These cases require special processing.  */
7081       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7082         return lookup_dwo_signatured_type (cu, sig);
7083       else
7084         return lookup_dwp_signatured_type (cu, sig);
7085     }
7086   else
7087     {
7088       struct signatured_type find_entry, *entry;
7089
7090       if (dwarf2_per_objfile->signatured_types == NULL)
7091         return NULL;
7092       find_entry.signature = sig;
7093       entry = ((struct signatured_type *)
7094                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7095       return entry;
7096     }
7097 }
7098 \f
7099 /* Low level DIE reading support.  */
7100
7101 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7102
7103 static void
7104 init_cu_die_reader (struct die_reader_specs *reader,
7105                     struct dwarf2_cu *cu,
7106                     struct dwarf2_section_info *section,
7107                     struct dwo_file *dwo_file,
7108                     struct abbrev_table *abbrev_table)
7109 {
7110   gdb_assert (section->readin && section->buffer != NULL);
7111   reader->abfd = get_section_bfd_owner (section);
7112   reader->cu = cu;
7113   reader->dwo_file = dwo_file;
7114   reader->die_section = section;
7115   reader->buffer = section->buffer;
7116   reader->buffer_end = section->buffer + section->size;
7117   reader->comp_dir = NULL;
7118   reader->abbrev_table = abbrev_table;
7119 }
7120
7121 /* Subroutine of init_cutu_and_read_dies to simplify it.
7122    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7123    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7124    already.
7125
7126    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7127    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7128    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7129    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7130    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7131    STUB_COMP_DIR may be non-NULL.
7132    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7133    are filled in with the info of the DIE from the DWO file.
7134    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7135    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7136    kept around for at least as long as *RESULT_READER.
7137
7138    The result is non-zero if a valid (non-dummy) DIE was found.  */
7139
7140 static int
7141 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7142                         struct dwo_unit *dwo_unit,
7143                         struct die_info *stub_comp_unit_die,
7144                         const char *stub_comp_dir,
7145                         struct die_reader_specs *result_reader,
7146                         const gdb_byte **result_info_ptr,
7147                         struct die_info **result_comp_unit_die,
7148                         int *result_has_children,
7149                         abbrev_table_up *result_dwo_abbrev_table)
7150 {
7151   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7152   struct objfile *objfile = dwarf2_per_objfile->objfile;
7153   struct dwarf2_cu *cu = this_cu->cu;
7154   bfd *abfd;
7155   const gdb_byte *begin_info_ptr, *info_ptr;
7156   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7157   int i,num_extra_attrs;
7158   struct dwarf2_section_info *dwo_abbrev_section;
7159   struct attribute *attr;
7160   struct die_info *comp_unit_die;
7161
7162   /* At most one of these may be provided.  */
7163   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7164
7165   /* These attributes aren't processed until later:
7166      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7167      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7168      referenced later.  However, these attributes are found in the stub
7169      which we won't have later.  In order to not impose this complication
7170      on the rest of the code, we read them here and copy them to the
7171      DWO CU/TU die.  */
7172
7173   stmt_list = NULL;
7174   low_pc = NULL;
7175   high_pc = NULL;
7176   ranges = NULL;
7177   comp_dir = NULL;
7178
7179   if (stub_comp_unit_die != NULL)
7180     {
7181       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7182          DWO file.  */
7183       if (! this_cu->is_debug_types)
7184         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7185       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7186       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7187       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7188       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7189
7190       /* There should be a DW_AT_addr_base attribute here (if needed).
7191          We need the value before we can process DW_FORM_GNU_addr_index
7192          or DW_FORM_addrx.  */
7193       cu->addr_base = 0;
7194       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7195       if (attr)
7196         cu->addr_base = DW_UNSND (attr);
7197
7198       /* There should be a DW_AT_ranges_base attribute here (if needed).
7199          We need the value before we can process DW_AT_ranges.  */
7200       cu->ranges_base = 0;
7201       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7202       if (attr)
7203         cu->ranges_base = DW_UNSND (attr);
7204     }
7205   else if (stub_comp_dir != NULL)
7206     {
7207       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7208       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7209       comp_dir->name = DW_AT_comp_dir;
7210       comp_dir->form = DW_FORM_string;
7211       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7212       DW_STRING (comp_dir) = stub_comp_dir;
7213     }
7214
7215   /* Set up for reading the DWO CU/TU.  */
7216   cu->dwo_unit = dwo_unit;
7217   dwarf2_section_info *section = dwo_unit->section;
7218   dwarf2_read_section (objfile, section);
7219   abfd = get_section_bfd_owner (section);
7220   begin_info_ptr = info_ptr = (section->buffer
7221                                + to_underlying (dwo_unit->sect_off));
7222   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7223
7224   if (this_cu->is_debug_types)
7225     {
7226       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7227
7228       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7229                                                 &cu->header, section,
7230                                                 dwo_abbrev_section,
7231                                                 info_ptr, rcuh_kind::TYPE);
7232       /* This is not an assert because it can be caused by bad debug info.  */
7233       if (sig_type->signature != cu->header.signature)
7234         {
7235           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7236                    " TU at offset %s [in module %s]"),
7237                  hex_string (sig_type->signature),
7238                  hex_string (cu->header.signature),
7239                  sect_offset_str (dwo_unit->sect_off),
7240                  bfd_get_filename (abfd));
7241         }
7242       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7243       /* For DWOs coming from DWP files, we don't know the CU length
7244          nor the type's offset in the TU until now.  */
7245       dwo_unit->length = get_cu_length (&cu->header);
7246       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7247
7248       /* Establish the type offset that can be used to lookup the type.
7249          For DWO files, we don't know it until now.  */
7250       sig_type->type_offset_in_section
7251         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7252     }
7253   else
7254     {
7255       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7256                                                 &cu->header, section,
7257                                                 dwo_abbrev_section,
7258                                                 info_ptr, rcuh_kind::COMPILE);
7259       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7260       /* For DWOs coming from DWP files, we don't know the CU length
7261          until now.  */
7262       dwo_unit->length = get_cu_length (&cu->header);
7263     }
7264
7265   *result_dwo_abbrev_table
7266     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7267                                cu->header.abbrev_sect_off);
7268   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7269                       result_dwo_abbrev_table->get ());
7270
7271   /* Read in the die, but leave space to copy over the attributes
7272      from the stub.  This has the benefit of simplifying the rest of
7273      the code - all the work to maintain the illusion of a single
7274      DW_TAG_{compile,type}_unit DIE is done here.  */
7275   num_extra_attrs = ((stmt_list != NULL)
7276                      + (low_pc != NULL)
7277                      + (high_pc != NULL)
7278                      + (ranges != NULL)
7279                      + (comp_dir != NULL));
7280   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7281                               result_has_children, num_extra_attrs);
7282
7283   /* Copy over the attributes from the stub to the DIE we just read in.  */
7284   comp_unit_die = *result_comp_unit_die;
7285   i = comp_unit_die->num_attrs;
7286   if (stmt_list != NULL)
7287     comp_unit_die->attrs[i++] = *stmt_list;
7288   if (low_pc != NULL)
7289     comp_unit_die->attrs[i++] = *low_pc;
7290   if (high_pc != NULL)
7291     comp_unit_die->attrs[i++] = *high_pc;
7292   if (ranges != NULL)
7293     comp_unit_die->attrs[i++] = *ranges;
7294   if (comp_dir != NULL)
7295     comp_unit_die->attrs[i++] = *comp_dir;
7296   comp_unit_die->num_attrs += num_extra_attrs;
7297
7298   if (dwarf_die_debug)
7299     {
7300       fprintf_unfiltered (gdb_stdlog,
7301                           "Read die from %s@0x%x of %s:\n",
7302                           get_section_name (section),
7303                           (unsigned) (begin_info_ptr - section->buffer),
7304                           bfd_get_filename (abfd));
7305       dump_die (comp_unit_die, dwarf_die_debug);
7306     }
7307
7308   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7309      TUs by skipping the stub and going directly to the entry in the DWO file.
7310      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7311      to get it via circuitous means.  Blech.  */
7312   if (comp_dir != NULL)
7313     result_reader->comp_dir = DW_STRING (comp_dir);
7314
7315   /* Skip dummy compilation units.  */
7316   if (info_ptr >= begin_info_ptr + dwo_unit->length
7317       || peek_abbrev_code (abfd, info_ptr) == 0)
7318     return 0;
7319
7320   *result_info_ptr = info_ptr;
7321   return 1;
7322 }
7323
7324 /* Subroutine of init_cutu_and_read_dies to simplify it.
7325    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7326    Returns NULL if the specified DWO unit cannot be found.  */
7327
7328 static struct dwo_unit *
7329 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7330                  struct die_info *comp_unit_die)
7331 {
7332   struct dwarf2_cu *cu = this_cu->cu;
7333   ULONGEST signature;
7334   struct dwo_unit *dwo_unit;
7335   const char *comp_dir, *dwo_name;
7336
7337   gdb_assert (cu != NULL);
7338
7339   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7340   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7341   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7342
7343   if (this_cu->is_debug_types)
7344     {
7345       struct signatured_type *sig_type;
7346
7347       /* Since this_cu is the first member of struct signatured_type,
7348          we can go from a pointer to one to a pointer to the other.  */
7349       sig_type = (struct signatured_type *) this_cu;
7350       signature = sig_type->signature;
7351       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7352     }
7353   else
7354     {
7355       struct attribute *attr;
7356
7357       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7358       if (! attr)
7359         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7360                  " [in module %s]"),
7361                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7362       signature = DW_UNSND (attr);
7363       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7364                                        signature);
7365     }
7366
7367   return dwo_unit;
7368 }
7369
7370 /* Subroutine of init_cutu_and_read_dies to simplify it.
7371    See it for a description of the parameters.
7372    Read a TU directly from a DWO file, bypassing the stub.  */
7373
7374 static void
7375 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7376                            int use_existing_cu, int keep,
7377                            die_reader_func_ftype *die_reader_func,
7378                            void *data)
7379 {
7380   std::unique_ptr<dwarf2_cu> new_cu;
7381   struct signatured_type *sig_type;
7382   struct die_reader_specs reader;
7383   const gdb_byte *info_ptr;
7384   struct die_info *comp_unit_die;
7385   int has_children;
7386   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7387
7388   /* Verify we can do the following downcast, and that we have the
7389      data we need.  */
7390   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7391   sig_type = (struct signatured_type *) this_cu;
7392   gdb_assert (sig_type->dwo_unit != NULL);
7393
7394   if (use_existing_cu && this_cu->cu != NULL)
7395     {
7396       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7397       /* There's no need to do the rereading_dwo_cu handling that
7398          init_cutu_and_read_dies does since we don't read the stub.  */
7399     }
7400   else
7401     {
7402       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7403       gdb_assert (this_cu->cu == NULL);
7404       new_cu.reset (new dwarf2_cu (this_cu));
7405     }
7406
7407   /* A future optimization, if needed, would be to use an existing
7408      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7409      could share abbrev tables.  */
7410
7411   /* The abbreviation table used by READER, this must live at least as long as
7412      READER.  */
7413   abbrev_table_up dwo_abbrev_table;
7414
7415   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7416                               NULL /* stub_comp_unit_die */,
7417                               sig_type->dwo_unit->dwo_file->comp_dir,
7418                               &reader, &info_ptr,
7419                               &comp_unit_die, &has_children,
7420                               &dwo_abbrev_table) == 0)
7421     {
7422       /* Dummy die.  */
7423       return;
7424     }
7425
7426   /* All the "real" work is done here.  */
7427   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7428
7429   /* This duplicates the code in init_cutu_and_read_dies,
7430      but the alternative is making the latter more complex.
7431      This function is only for the special case of using DWO files directly:
7432      no point in overly complicating the general case just to handle this.  */
7433   if (new_cu != NULL && keep)
7434     {
7435       /* Link this CU into read_in_chain.  */
7436       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7437       dwarf2_per_objfile->read_in_chain = this_cu;
7438       /* The chain owns it now.  */
7439       new_cu.release ();
7440     }
7441 }
7442
7443 /* Initialize a CU (or TU) and read its DIEs.
7444    If the CU defers to a DWO file, read the DWO file as well.
7445
7446    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7447    Otherwise the table specified in the comp unit header is read in and used.
7448    This is an optimization for when we already have the abbrev table.
7449
7450    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7451    Otherwise, a new CU is allocated with xmalloc.
7452
7453    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7454    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7455
7456    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7457    linker) then DIE_READER_FUNC will not get called.  */
7458
7459 static void
7460 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7461                          struct abbrev_table *abbrev_table,
7462                          int use_existing_cu, int keep,
7463                          bool skip_partial,
7464                          die_reader_func_ftype *die_reader_func,
7465                          void *data)
7466 {
7467   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7468   struct objfile *objfile = dwarf2_per_objfile->objfile;
7469   struct dwarf2_section_info *section = this_cu->section;
7470   bfd *abfd = get_section_bfd_owner (section);
7471   struct dwarf2_cu *cu;
7472   const gdb_byte *begin_info_ptr, *info_ptr;
7473   struct die_reader_specs reader;
7474   struct die_info *comp_unit_die;
7475   int has_children;
7476   struct attribute *attr;
7477   struct signatured_type *sig_type = NULL;
7478   struct dwarf2_section_info *abbrev_section;
7479   /* Non-zero if CU currently points to a DWO file and we need to
7480      reread it.  When this happens we need to reread the skeleton die
7481      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7482   int rereading_dwo_cu = 0;
7483
7484   if (dwarf_die_debug)
7485     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7486                         this_cu->is_debug_types ? "type" : "comp",
7487                         sect_offset_str (this_cu->sect_off));
7488
7489   if (use_existing_cu)
7490     gdb_assert (keep);
7491
7492   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7493      file (instead of going through the stub), short-circuit all of this.  */
7494   if (this_cu->reading_dwo_directly)
7495     {
7496       /* Narrow down the scope of possibilities to have to understand.  */
7497       gdb_assert (this_cu->is_debug_types);
7498       gdb_assert (abbrev_table == NULL);
7499       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7500                                  die_reader_func, data);
7501       return;
7502     }
7503
7504   /* This is cheap if the section is already read in.  */
7505   dwarf2_read_section (objfile, section);
7506
7507   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7508
7509   abbrev_section = get_abbrev_section_for_cu (this_cu);
7510
7511   std::unique_ptr<dwarf2_cu> new_cu;
7512   if (use_existing_cu && this_cu->cu != NULL)
7513     {
7514       cu = this_cu->cu;
7515       /* If this CU is from a DWO file we need to start over, we need to
7516          refetch the attributes from the skeleton CU.
7517          This could be optimized by retrieving those attributes from when we
7518          were here the first time: the previous comp_unit_die was stored in
7519          comp_unit_obstack.  But there's no data yet that we need this
7520          optimization.  */
7521       if (cu->dwo_unit != NULL)
7522         rereading_dwo_cu = 1;
7523     }
7524   else
7525     {
7526       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7527       gdb_assert (this_cu->cu == NULL);
7528       new_cu.reset (new dwarf2_cu (this_cu));
7529       cu = new_cu.get ();
7530     }
7531
7532   /* Get the header.  */
7533   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7534     {
7535       /* We already have the header, there's no need to read it in again.  */
7536       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7537     }
7538   else
7539     {
7540       if (this_cu->is_debug_types)
7541         {
7542           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7543                                                     &cu->header, section,
7544                                                     abbrev_section, info_ptr,
7545                                                     rcuh_kind::TYPE);
7546
7547           /* Since per_cu is the first member of struct signatured_type,
7548              we can go from a pointer to one to a pointer to the other.  */
7549           sig_type = (struct signatured_type *) this_cu;
7550           gdb_assert (sig_type->signature == cu->header.signature);
7551           gdb_assert (sig_type->type_offset_in_tu
7552                       == cu->header.type_cu_offset_in_tu);
7553           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7554
7555           /* LENGTH has not been set yet for type units if we're
7556              using .gdb_index.  */
7557           this_cu->length = get_cu_length (&cu->header);
7558
7559           /* Establish the type offset that can be used to lookup the type.  */
7560           sig_type->type_offset_in_section =
7561             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7562
7563           this_cu->dwarf_version = cu->header.version;
7564         }
7565       else
7566         {
7567           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7568                                                     &cu->header, section,
7569                                                     abbrev_section,
7570                                                     info_ptr,
7571                                                     rcuh_kind::COMPILE);
7572
7573           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7574           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7575           this_cu->dwarf_version = cu->header.version;
7576         }
7577     }
7578
7579   /* Skip dummy compilation units.  */
7580   if (info_ptr >= begin_info_ptr + this_cu->length
7581       || peek_abbrev_code (abfd, info_ptr) == 0)
7582     return;
7583
7584   /* If we don't have them yet, read the abbrevs for this compilation unit.
7585      And if we need to read them now, make sure they're freed when we're
7586      done (own the table through ABBREV_TABLE_HOLDER).  */
7587   abbrev_table_up abbrev_table_holder;
7588   if (abbrev_table != NULL)
7589     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7590   else
7591     {
7592       abbrev_table_holder
7593         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7594                                    cu->header.abbrev_sect_off);
7595       abbrev_table = abbrev_table_holder.get ();
7596     }
7597
7598   /* Read the top level CU/TU die.  */
7599   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7600   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7601
7602   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7603     return;
7604
7605   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7606      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7607      table from the DWO file and pass the ownership over to us.  It will be
7608      referenced from READER, so we must make sure to free it after we're done
7609      with READER.
7610
7611      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7612      DWO CU, that this test will fail (the attribute will not be present).  */
7613   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7614   abbrev_table_up dwo_abbrev_table;
7615   if (attr)
7616     {
7617       struct dwo_unit *dwo_unit;
7618       struct die_info *dwo_comp_unit_die;
7619
7620       if (has_children)
7621         {
7622           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7623                        " has children (offset %s) [in module %s]"),
7624                      sect_offset_str (this_cu->sect_off),
7625                      bfd_get_filename (abfd));
7626         }
7627       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7628       if (dwo_unit != NULL)
7629         {
7630           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7631                                       comp_unit_die, NULL,
7632                                       &reader, &info_ptr,
7633                                       &dwo_comp_unit_die, &has_children,
7634                                       &dwo_abbrev_table) == 0)
7635             {
7636               /* Dummy die.  */
7637               return;
7638             }
7639           comp_unit_die = dwo_comp_unit_die;
7640         }
7641       else
7642         {
7643           /* Yikes, we couldn't find the rest of the DIE, we only have
7644              the stub.  A complaint has already been logged.  There's
7645              not much more we can do except pass on the stub DIE to
7646              die_reader_func.  We don't want to throw an error on bad
7647              debug info.  */
7648         }
7649     }
7650
7651   /* All of the above is setup for this call.  Yikes.  */
7652   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7653
7654   /* Done, clean up.  */
7655   if (new_cu != NULL && keep)
7656     {
7657       /* Link this CU into read_in_chain.  */
7658       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7659       dwarf2_per_objfile->read_in_chain = this_cu;
7660       /* The chain owns it now.  */
7661       new_cu.release ();
7662     }
7663 }
7664
7665 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7666    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7667    to have already done the lookup to find the DWO file).
7668
7669    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7670    THIS_CU->is_debug_types, but nothing else.
7671
7672    We fill in THIS_CU->length.
7673
7674    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7675    linker) then DIE_READER_FUNC will not get called.
7676
7677    THIS_CU->cu is always freed when done.
7678    This is done in order to not leave THIS_CU->cu in a state where we have
7679    to care whether it refers to the "main" CU or the DWO CU.  */
7680
7681 static void
7682 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7683                                    struct dwo_file *dwo_file,
7684                                    die_reader_func_ftype *die_reader_func,
7685                                    void *data)
7686 {
7687   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7688   struct objfile *objfile = dwarf2_per_objfile->objfile;
7689   struct dwarf2_section_info *section = this_cu->section;
7690   bfd *abfd = get_section_bfd_owner (section);
7691   struct dwarf2_section_info *abbrev_section;
7692   const gdb_byte *begin_info_ptr, *info_ptr;
7693   struct die_reader_specs reader;
7694   struct die_info *comp_unit_die;
7695   int has_children;
7696
7697   if (dwarf_die_debug)
7698     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7699                         this_cu->is_debug_types ? "type" : "comp",
7700                         sect_offset_str (this_cu->sect_off));
7701
7702   gdb_assert (this_cu->cu == NULL);
7703
7704   abbrev_section = (dwo_file != NULL
7705                     ? &dwo_file->sections.abbrev
7706                     : get_abbrev_section_for_cu (this_cu));
7707
7708   /* This is cheap if the section is already read in.  */
7709   dwarf2_read_section (objfile, section);
7710
7711   struct dwarf2_cu cu (this_cu);
7712
7713   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7714   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7715                                             &cu.header, section,
7716                                             abbrev_section, info_ptr,
7717                                             (this_cu->is_debug_types
7718                                              ? rcuh_kind::TYPE
7719                                              : rcuh_kind::COMPILE));
7720
7721   this_cu->length = get_cu_length (&cu.header);
7722
7723   /* Skip dummy compilation units.  */
7724   if (info_ptr >= begin_info_ptr + this_cu->length
7725       || peek_abbrev_code (abfd, info_ptr) == 0)
7726     return;
7727
7728   abbrev_table_up abbrev_table
7729     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7730                                cu.header.abbrev_sect_off);
7731
7732   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7733   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7734
7735   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7736 }
7737
7738 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7739    does not lookup the specified DWO file.
7740    This cannot be used to read DWO files.
7741
7742    THIS_CU->cu is always freed when done.
7743    This is done in order to not leave THIS_CU->cu in a state where we have
7744    to care whether it refers to the "main" CU or the DWO CU.
7745    We can revisit this if the data shows there's a performance issue.  */
7746
7747 static void
7748 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7749                                 die_reader_func_ftype *die_reader_func,
7750                                 void *data)
7751 {
7752   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7753 }
7754 \f
7755 /* Type Unit Groups.
7756
7757    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7758    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7759    so that all types coming from the same compilation (.o file) are grouped
7760    together.  A future step could be to put the types in the same symtab as
7761    the CU the types ultimately came from.  */
7762
7763 static hashval_t
7764 hash_type_unit_group (const void *item)
7765 {
7766   const struct type_unit_group *tu_group
7767     = (const struct type_unit_group *) item;
7768
7769   return hash_stmt_list_entry (&tu_group->hash);
7770 }
7771
7772 static int
7773 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7774 {
7775   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7776   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7777
7778   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7779 }
7780
7781 /* Allocate a hash table for type unit groups.  */
7782
7783 static htab_t
7784 allocate_type_unit_groups_table (struct objfile *objfile)
7785 {
7786   return htab_create_alloc_ex (3,
7787                                hash_type_unit_group,
7788                                eq_type_unit_group,
7789                                NULL,
7790                                &objfile->objfile_obstack,
7791                                hashtab_obstack_allocate,
7792                                dummy_obstack_deallocate);
7793 }
7794
7795 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7796    partial symtabs.  We combine several TUs per psymtab to not let the size
7797    of any one psymtab grow too big.  */
7798 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7799 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7800
7801 /* Helper routine for get_type_unit_group.
7802    Create the type_unit_group object used to hold one or more TUs.  */
7803
7804 static struct type_unit_group *
7805 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7806 {
7807   struct dwarf2_per_objfile *dwarf2_per_objfile
7808     = cu->per_cu->dwarf2_per_objfile;
7809   struct objfile *objfile = dwarf2_per_objfile->objfile;
7810   struct dwarf2_per_cu_data *per_cu;
7811   struct type_unit_group *tu_group;
7812
7813   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7814                              struct type_unit_group);
7815   per_cu = &tu_group->per_cu;
7816   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7817
7818   if (dwarf2_per_objfile->using_index)
7819     {
7820       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7821                                         struct dwarf2_per_cu_quick_data);
7822     }
7823   else
7824     {
7825       unsigned int line_offset = to_underlying (line_offset_struct);
7826       struct partial_symtab *pst;
7827       std::string name;
7828
7829       /* Give the symtab a useful name for debug purposes.  */
7830       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7831         name = string_printf ("<type_units_%d>",
7832                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7833       else
7834         name = string_printf ("<type_units_at_0x%x>", line_offset);
7835
7836       pst = create_partial_symtab (per_cu, name.c_str ());
7837       pst->anonymous = 1;
7838     }
7839
7840   tu_group->hash.dwo_unit = cu->dwo_unit;
7841   tu_group->hash.line_sect_off = line_offset_struct;
7842
7843   return tu_group;
7844 }
7845
7846 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7847    STMT_LIST is a DW_AT_stmt_list attribute.  */
7848
7849 static struct type_unit_group *
7850 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7851 {
7852   struct dwarf2_per_objfile *dwarf2_per_objfile
7853     = cu->per_cu->dwarf2_per_objfile;
7854   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7855   struct type_unit_group *tu_group;
7856   void **slot;
7857   unsigned int line_offset;
7858   struct type_unit_group type_unit_group_for_lookup;
7859
7860   if (dwarf2_per_objfile->type_unit_groups == NULL)
7861     {
7862       dwarf2_per_objfile->type_unit_groups =
7863         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7864     }
7865
7866   /* Do we need to create a new group, or can we use an existing one?  */
7867
7868   if (stmt_list)
7869     {
7870       line_offset = DW_UNSND (stmt_list);
7871       ++tu_stats->nr_symtab_sharers;
7872     }
7873   else
7874     {
7875       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7876          We can do various things here like create one group per TU or
7877          spread them over multiple groups to split up the expansion work.
7878          To avoid worst case scenarios (too many groups or too large groups)
7879          we, umm, group them in bunches.  */
7880       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7881                      | (tu_stats->nr_stmt_less_type_units
7882                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7883       ++tu_stats->nr_stmt_less_type_units;
7884     }
7885
7886   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7887   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7888   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7889                          &type_unit_group_for_lookup, INSERT);
7890   if (*slot != NULL)
7891     {
7892       tu_group = (struct type_unit_group *) *slot;
7893       gdb_assert (tu_group != NULL);
7894     }
7895   else
7896     {
7897       sect_offset line_offset_struct = (sect_offset) line_offset;
7898       tu_group = create_type_unit_group (cu, line_offset_struct);
7899       *slot = tu_group;
7900       ++tu_stats->nr_symtabs;
7901     }
7902
7903   return tu_group;
7904 }
7905 \f
7906 /* Partial symbol tables.  */
7907
7908 /* Create a psymtab named NAME and assign it to PER_CU.
7909
7910    The caller must fill in the following details:
7911    dirname, textlow, texthigh.  */
7912
7913 static struct partial_symtab *
7914 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7915 {
7916   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7917   struct partial_symtab *pst;
7918
7919   pst = start_psymtab_common (objfile, name, 0);
7920
7921   pst->psymtabs_addrmap_supported = 1;
7922
7923   /* This is the glue that links PST into GDB's symbol API.  */
7924   pst->read_symtab_private = per_cu;
7925   pst->read_symtab = dwarf2_read_symtab;
7926   per_cu->v.psymtab = pst;
7927
7928   return pst;
7929 }
7930
7931 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7932    type.  */
7933
7934 struct process_psymtab_comp_unit_data
7935 {
7936   /* True if we are reading a DW_TAG_partial_unit.  */
7937
7938   int want_partial_unit;
7939
7940   /* The "pretend" language that is used if the CU doesn't declare a
7941      language.  */
7942
7943   enum language pretend_language;
7944 };
7945
7946 /* die_reader_func for process_psymtab_comp_unit.  */
7947
7948 static void
7949 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7950                                   const gdb_byte *info_ptr,
7951                                   struct die_info *comp_unit_die,
7952                                   int has_children,
7953                                   void *data)
7954 {
7955   struct dwarf2_cu *cu = reader->cu;
7956   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7957   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7958   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7959   CORE_ADDR baseaddr;
7960   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7961   struct partial_symtab *pst;
7962   enum pc_bounds_kind cu_bounds_kind;
7963   const char *filename;
7964   struct process_psymtab_comp_unit_data *info
7965     = (struct process_psymtab_comp_unit_data *) data;
7966
7967   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7968     return;
7969
7970   gdb_assert (! per_cu->is_debug_types);
7971
7972   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7973
7974   /* Allocate a new partial symbol table structure.  */
7975   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7976   if (filename == NULL)
7977     filename = "";
7978
7979   pst = create_partial_symtab (per_cu, filename);
7980
7981   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7982   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7983
7984   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7985
7986   dwarf2_find_base_address (comp_unit_die, cu);
7987
7988   /* Possibly set the default values of LOWPC and HIGHPC from
7989      `DW_AT_ranges'.  */
7990   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7991                                          &best_highpc, cu, pst);
7992   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7993     {
7994       CORE_ADDR low
7995         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7996            - baseaddr);
7997       CORE_ADDR high
7998         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7999            - baseaddr - 1);
8000       /* Store the contiguous range if it is not empty; it can be
8001          empty for CUs with no code.  */
8002       addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
8003                          low, high, pst);
8004     }
8005
8006   /* Check if comp unit has_children.
8007      If so, read the rest of the partial symbols from this comp unit.
8008      If not, there's no more debug_info for this comp unit.  */
8009   if (has_children)
8010     {
8011       struct partial_die_info *first_die;
8012       CORE_ADDR lowpc, highpc;
8013
8014       lowpc = ((CORE_ADDR) -1);
8015       highpc = ((CORE_ADDR) 0);
8016
8017       first_die = load_partial_dies (reader, info_ptr, 1);
8018
8019       scan_partial_symbols (first_die, &lowpc, &highpc,
8020                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8021
8022       /* If we didn't find a lowpc, set it to highpc to avoid
8023          complaints from `maint check'.  */
8024       if (lowpc == ((CORE_ADDR) -1))
8025         lowpc = highpc;
8026
8027       /* If the compilation unit didn't have an explicit address range,
8028          then use the information extracted from its child dies.  */
8029       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8030         {
8031           best_lowpc = lowpc;
8032           best_highpc = highpc;
8033         }
8034     }
8035   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
8036                                                  best_lowpc + baseaddr)
8037                      - baseaddr);
8038   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
8039                                                   best_highpc + baseaddr)
8040                       - baseaddr);
8041
8042   end_psymtab_common (objfile, pst);
8043
8044   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8045     {
8046       int i;
8047       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8048       struct dwarf2_per_cu_data *iter;
8049
8050       /* Fill in 'dependencies' here; we fill in 'users' in a
8051          post-pass.  */
8052       pst->number_of_dependencies = len;
8053       pst->dependencies
8054         = objfile->partial_symtabs->allocate_dependencies (len);
8055       for (i = 0;
8056            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8057                         i, iter);
8058            ++i)
8059         pst->dependencies[i] = iter->v.psymtab;
8060
8061       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8062     }
8063
8064   /* Get the list of files included in the current compilation unit,
8065      and build a psymtab for each of them.  */
8066   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8067
8068   if (dwarf_read_debug)
8069     fprintf_unfiltered (gdb_stdlog,
8070                         "Psymtab for %s unit @%s: %s - %s"
8071                         ", %d global, %d static syms\n",
8072                         per_cu->is_debug_types ? "type" : "comp",
8073                         sect_offset_str (per_cu->sect_off),
8074                         paddress (gdbarch, pst->text_low (objfile)),
8075                         paddress (gdbarch, pst->text_high (objfile)),
8076                         pst->n_global_syms, pst->n_static_syms);
8077 }
8078
8079 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8080    Process compilation unit THIS_CU for a psymtab.  */
8081
8082 static void
8083 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8084                            int want_partial_unit,
8085                            enum language pretend_language)
8086 {
8087   /* If this compilation unit was already read in, free the
8088      cached copy in order to read it in again.  This is
8089      necessary because we skipped some symbols when we first
8090      read in the compilation unit (see load_partial_dies).
8091      This problem could be avoided, but the benefit is unclear.  */
8092   if (this_cu->cu != NULL)
8093     free_one_cached_comp_unit (this_cu);
8094
8095   if (this_cu->is_debug_types)
8096     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8097                              build_type_psymtabs_reader, NULL);
8098   else
8099     {
8100       process_psymtab_comp_unit_data info;
8101       info.want_partial_unit = want_partial_unit;
8102       info.pretend_language = pretend_language;
8103       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8104                                process_psymtab_comp_unit_reader, &info);
8105     }
8106
8107   /* Age out any secondary CUs.  */
8108   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8109 }
8110
8111 /* Reader function for build_type_psymtabs.  */
8112
8113 static void
8114 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8115                             const gdb_byte *info_ptr,
8116                             struct die_info *type_unit_die,
8117                             int has_children,
8118                             void *data)
8119 {
8120   struct dwarf2_per_objfile *dwarf2_per_objfile
8121     = reader->cu->per_cu->dwarf2_per_objfile;
8122   struct objfile *objfile = dwarf2_per_objfile->objfile;
8123   struct dwarf2_cu *cu = reader->cu;
8124   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8125   struct signatured_type *sig_type;
8126   struct type_unit_group *tu_group;
8127   struct attribute *attr;
8128   struct partial_die_info *first_die;
8129   CORE_ADDR lowpc, highpc;
8130   struct partial_symtab *pst;
8131
8132   gdb_assert (data == NULL);
8133   gdb_assert (per_cu->is_debug_types);
8134   sig_type = (struct signatured_type *) per_cu;
8135
8136   if (! has_children)
8137     return;
8138
8139   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8140   tu_group = get_type_unit_group (cu, attr);
8141
8142   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8143
8144   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8145   pst = create_partial_symtab (per_cu, "");
8146   pst->anonymous = 1;
8147
8148   first_die = load_partial_dies (reader, info_ptr, 1);
8149
8150   lowpc = (CORE_ADDR) -1;
8151   highpc = (CORE_ADDR) 0;
8152   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8153
8154   end_psymtab_common (objfile, pst);
8155 }
8156
8157 /* Struct used to sort TUs by their abbreviation table offset.  */
8158
8159 struct tu_abbrev_offset
8160 {
8161   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8162   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8163   {}
8164
8165   signatured_type *sig_type;
8166   sect_offset abbrev_offset;
8167 };
8168
8169 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8170
8171 static bool
8172 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8173                           const struct tu_abbrev_offset &b)
8174 {
8175   return a.abbrev_offset < b.abbrev_offset;
8176 }
8177
8178 /* Efficiently read all the type units.
8179    This does the bulk of the work for build_type_psymtabs.
8180
8181    The efficiency is because we sort TUs by the abbrev table they use and
8182    only read each abbrev table once.  In one program there are 200K TUs
8183    sharing 8K abbrev tables.
8184
8185    The main purpose of this function is to support building the
8186    dwarf2_per_objfile->type_unit_groups table.
8187    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8188    can collapse the search space by grouping them by stmt_list.
8189    The savings can be significant, in the same program from above the 200K TUs
8190    share 8K stmt_list tables.
8191
8192    FUNC is expected to call get_type_unit_group, which will create the
8193    struct type_unit_group if necessary and add it to
8194    dwarf2_per_objfile->type_unit_groups.  */
8195
8196 static void
8197 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8198 {
8199   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8200   abbrev_table_up abbrev_table;
8201   sect_offset abbrev_offset;
8202
8203   /* It's up to the caller to not call us multiple times.  */
8204   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8205
8206   if (dwarf2_per_objfile->all_type_units.empty ())
8207     return;
8208
8209   /* TUs typically share abbrev tables, and there can be way more TUs than
8210      abbrev tables.  Sort by abbrev table to reduce the number of times we
8211      read each abbrev table in.
8212      Alternatives are to punt or to maintain a cache of abbrev tables.
8213      This is simpler and efficient enough for now.
8214
8215      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8216      symtab to use).  Typically TUs with the same abbrev offset have the same
8217      stmt_list value too so in practice this should work well.
8218
8219      The basic algorithm here is:
8220
8221       sort TUs by abbrev table
8222       for each TU with same abbrev table:
8223         read abbrev table if first user
8224         read TU top level DIE
8225           [IWBN if DWO skeletons had DW_AT_stmt_list]
8226         call FUNC  */
8227
8228   if (dwarf_read_debug)
8229     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8230
8231   /* Sort in a separate table to maintain the order of all_type_units
8232      for .gdb_index: TU indices directly index all_type_units.  */
8233   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8234   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8235
8236   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8237     sorted_by_abbrev.emplace_back
8238       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8239                                      sig_type->per_cu.section,
8240                                      sig_type->per_cu.sect_off));
8241
8242   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8243              sort_tu_by_abbrev_offset);
8244
8245   abbrev_offset = (sect_offset) ~(unsigned) 0;
8246
8247   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8248     {
8249       /* Switch to the next abbrev table if necessary.  */
8250       if (abbrev_table == NULL
8251           || tu.abbrev_offset != abbrev_offset)
8252         {
8253           abbrev_offset = tu.abbrev_offset;
8254           abbrev_table =
8255             abbrev_table_read_table (dwarf2_per_objfile,
8256                                      &dwarf2_per_objfile->abbrev,
8257                                      abbrev_offset);
8258           ++tu_stats->nr_uniq_abbrev_tables;
8259         }
8260
8261       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8262                                0, 0, false, build_type_psymtabs_reader, NULL);
8263     }
8264 }
8265
8266 /* Print collected type unit statistics.  */
8267
8268 static void
8269 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8270 {
8271   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8272
8273   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8274   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8275                       dwarf2_per_objfile->all_type_units.size ());
8276   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8277                       tu_stats->nr_uniq_abbrev_tables);
8278   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8279                       tu_stats->nr_symtabs);
8280   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8281                       tu_stats->nr_symtab_sharers);
8282   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8283                       tu_stats->nr_stmt_less_type_units);
8284   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8285                       tu_stats->nr_all_type_units_reallocs);
8286 }
8287
8288 /* Traversal function for build_type_psymtabs.  */
8289
8290 static int
8291 build_type_psymtab_dependencies (void **slot, void *info)
8292 {
8293   struct dwarf2_per_objfile *dwarf2_per_objfile
8294     = (struct dwarf2_per_objfile *) info;
8295   struct objfile *objfile = dwarf2_per_objfile->objfile;
8296   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8297   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8298   struct partial_symtab *pst = per_cu->v.psymtab;
8299   int len = VEC_length (sig_type_ptr, tu_group->tus);
8300   struct signatured_type *iter;
8301   int i;
8302
8303   gdb_assert (len > 0);
8304   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8305
8306   pst->number_of_dependencies = len;
8307   pst->dependencies = objfile->partial_symtabs->allocate_dependencies (len);
8308   for (i = 0;
8309        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8310        ++i)
8311     {
8312       gdb_assert (iter->per_cu.is_debug_types);
8313       pst->dependencies[i] = iter->per_cu.v.psymtab;
8314       iter->type_unit_group = tu_group;
8315     }
8316
8317   VEC_free (sig_type_ptr, tu_group->tus);
8318
8319   return 1;
8320 }
8321
8322 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8323    Build partial symbol tables for the .debug_types comp-units.  */
8324
8325 static void
8326 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8327 {
8328   if (! create_all_type_units (dwarf2_per_objfile))
8329     return;
8330
8331   build_type_psymtabs_1 (dwarf2_per_objfile);
8332 }
8333
8334 /* Traversal function for process_skeletonless_type_unit.
8335    Read a TU in a DWO file and build partial symbols for it.  */
8336
8337 static int
8338 process_skeletonless_type_unit (void **slot, void *info)
8339 {
8340   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8341   struct dwarf2_per_objfile *dwarf2_per_objfile
8342     = (struct dwarf2_per_objfile *) info;
8343   struct signatured_type find_entry, *entry;
8344
8345   /* If this TU doesn't exist in the global table, add it and read it in.  */
8346
8347   if (dwarf2_per_objfile->signatured_types == NULL)
8348     {
8349       dwarf2_per_objfile->signatured_types
8350         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8351     }
8352
8353   find_entry.signature = dwo_unit->signature;
8354   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8355                          INSERT);
8356   /* If we've already seen this type there's nothing to do.  What's happening
8357      is we're doing our own version of comdat-folding here.  */
8358   if (*slot != NULL)
8359     return 1;
8360
8361   /* This does the job that create_all_type_units would have done for
8362      this TU.  */
8363   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8364   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8365   *slot = entry;
8366
8367   /* This does the job that build_type_psymtabs_1 would have done.  */
8368   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8369                            build_type_psymtabs_reader, NULL);
8370
8371   return 1;
8372 }
8373
8374 /* Traversal function for process_skeletonless_type_units.  */
8375
8376 static int
8377 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8378 {
8379   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8380
8381   if (dwo_file->tus != NULL)
8382     {
8383       htab_traverse_noresize (dwo_file->tus,
8384                               process_skeletonless_type_unit, info);
8385     }
8386
8387   return 1;
8388 }
8389
8390 /* Scan all TUs of DWO files, verifying we've processed them.
8391    This is needed in case a TU was emitted without its skeleton.
8392    Note: This can't be done until we know what all the DWO files are.  */
8393
8394 static void
8395 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8396 {
8397   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8398   if (get_dwp_file (dwarf2_per_objfile) == NULL
8399       && dwarf2_per_objfile->dwo_files != NULL)
8400     {
8401       htab_traverse_noresize (dwarf2_per_objfile->dwo_files.get (),
8402                               process_dwo_file_for_skeletonless_type_units,
8403                               dwarf2_per_objfile);
8404     }
8405 }
8406
8407 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8408
8409 static void
8410 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8411 {
8412   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8413     {
8414       struct partial_symtab *pst = per_cu->v.psymtab;
8415
8416       if (pst == NULL)
8417         continue;
8418
8419       for (int j = 0; j < pst->number_of_dependencies; ++j)
8420         {
8421           /* Set the 'user' field only if it is not already set.  */
8422           if (pst->dependencies[j]->user == NULL)
8423             pst->dependencies[j]->user = pst;
8424         }
8425     }
8426 }
8427
8428 /* Build the partial symbol table by doing a quick pass through the
8429    .debug_info and .debug_abbrev sections.  */
8430
8431 static void
8432 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8433 {
8434   struct objfile *objfile = dwarf2_per_objfile->objfile;
8435
8436   if (dwarf_read_debug)
8437     {
8438       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8439                           objfile_name (objfile));
8440     }
8441
8442   dwarf2_per_objfile->reading_partial_symbols = 1;
8443
8444   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8445
8446   /* Any cached compilation units will be linked by the per-objfile
8447      read_in_chain.  Make sure to free them when we're done.  */
8448   free_cached_comp_units freer (dwarf2_per_objfile);
8449
8450   build_type_psymtabs (dwarf2_per_objfile);
8451
8452   create_all_comp_units (dwarf2_per_objfile);
8453
8454   /* Create a temporary address map on a temporary obstack.  We later
8455      copy this to the final obstack.  */
8456   auto_obstack temp_obstack;
8457
8458   scoped_restore save_psymtabs_addrmap
8459     = make_scoped_restore (&objfile->partial_symtabs->psymtabs_addrmap,
8460                            addrmap_create_mutable (&temp_obstack));
8461
8462   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8463     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8464
8465   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8466   process_skeletonless_type_units (dwarf2_per_objfile);
8467
8468   /* Now that all TUs have been processed we can fill in the dependencies.  */
8469   if (dwarf2_per_objfile->type_unit_groups != NULL)
8470     {
8471       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8472                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8473     }
8474
8475   if (dwarf_read_debug)
8476     print_tu_stats (dwarf2_per_objfile);
8477
8478   set_partial_user (dwarf2_per_objfile);
8479
8480   objfile->partial_symtabs->psymtabs_addrmap
8481     = addrmap_create_fixed (objfile->partial_symtabs->psymtabs_addrmap,
8482                             objfile->partial_symtabs->obstack ());
8483   /* At this point we want to keep the address map.  */
8484   save_psymtabs_addrmap.release ();
8485
8486   if (dwarf_read_debug)
8487     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8488                         objfile_name (objfile));
8489 }
8490
8491 /* die_reader_func for load_partial_comp_unit.  */
8492
8493 static void
8494 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8495                                const gdb_byte *info_ptr,
8496                                struct die_info *comp_unit_die,
8497                                int has_children,
8498                                void *data)
8499 {
8500   struct dwarf2_cu *cu = reader->cu;
8501
8502   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8503
8504   /* Check if comp unit has_children.
8505      If so, read the rest of the partial symbols from this comp unit.
8506      If not, there's no more debug_info for this comp unit.  */
8507   if (has_children)
8508     load_partial_dies (reader, info_ptr, 0);
8509 }
8510
8511 /* Load the partial DIEs for a secondary CU into memory.
8512    This is also used when rereading a primary CU with load_all_dies.  */
8513
8514 static void
8515 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8516 {
8517   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8518                            load_partial_comp_unit_reader, NULL);
8519 }
8520
8521 static void
8522 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8523                               struct dwarf2_section_info *section,
8524                               struct dwarf2_section_info *abbrev_section,
8525                               unsigned int is_dwz)
8526 {
8527   const gdb_byte *info_ptr;
8528   struct objfile *objfile = dwarf2_per_objfile->objfile;
8529
8530   if (dwarf_read_debug)
8531     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8532                         get_section_name (section),
8533                         get_section_file_name (section));
8534
8535   dwarf2_read_section (objfile, section);
8536
8537   info_ptr = section->buffer;
8538
8539   while (info_ptr < section->buffer + section->size)
8540     {
8541       struct dwarf2_per_cu_data *this_cu;
8542
8543       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8544
8545       comp_unit_head cu_header;
8546       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8547                                      abbrev_section, info_ptr,
8548                                      rcuh_kind::COMPILE);
8549
8550       /* Save the compilation unit for later lookup.  */
8551       if (cu_header.unit_type != DW_UT_type)
8552         {
8553           this_cu = XOBNEW (&objfile->objfile_obstack,
8554                             struct dwarf2_per_cu_data);
8555           memset (this_cu, 0, sizeof (*this_cu));
8556         }
8557       else
8558         {
8559           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8560                                   struct signatured_type);
8561           memset (sig_type, 0, sizeof (*sig_type));
8562           sig_type->signature = cu_header.signature;
8563           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8564           this_cu = &sig_type->per_cu;
8565         }
8566       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8567       this_cu->sect_off = sect_off;
8568       this_cu->length = cu_header.length + cu_header.initial_length_size;
8569       this_cu->is_dwz = is_dwz;
8570       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8571       this_cu->section = section;
8572
8573       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8574
8575       info_ptr = info_ptr + this_cu->length;
8576     }
8577 }
8578
8579 /* Create a list of all compilation units in OBJFILE.
8580    This is only done for -readnow and building partial symtabs.  */
8581
8582 static void
8583 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8584 {
8585   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8586   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8587                                 &dwarf2_per_objfile->abbrev, 0);
8588
8589   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8590   if (dwz != NULL)
8591     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8592                                   1);
8593 }
8594
8595 /* Process all loaded DIEs for compilation unit CU, starting at
8596    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8597    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8598    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8599    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8600
8601 static void
8602 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8603                       CORE_ADDR *highpc, int set_addrmap,
8604                       struct dwarf2_cu *cu)
8605 {
8606   struct partial_die_info *pdi;
8607
8608   /* Now, march along the PDI's, descending into ones which have
8609      interesting children but skipping the children of the other ones,
8610      until we reach the end of the compilation unit.  */
8611
8612   pdi = first_die;
8613
8614   while (pdi != NULL)
8615     {
8616       pdi->fixup (cu);
8617
8618       /* Anonymous namespaces or modules have no name but have interesting
8619          children, so we need to look at them.  Ditto for anonymous
8620          enums.  */
8621
8622       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8623           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8624           || pdi->tag == DW_TAG_imported_unit
8625           || pdi->tag == DW_TAG_inlined_subroutine)
8626         {
8627           switch (pdi->tag)
8628             {
8629             case DW_TAG_subprogram:
8630             case DW_TAG_inlined_subroutine:
8631               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8632               break;
8633             case DW_TAG_constant:
8634             case DW_TAG_variable:
8635             case DW_TAG_typedef:
8636             case DW_TAG_union_type:
8637               if (!pdi->is_declaration)
8638                 {
8639                   add_partial_symbol (pdi, cu);
8640                 }
8641               break;
8642             case DW_TAG_class_type:
8643             case DW_TAG_interface_type:
8644             case DW_TAG_structure_type:
8645               if (!pdi->is_declaration)
8646                 {
8647                   add_partial_symbol (pdi, cu);
8648                 }
8649               if ((cu->language == language_rust
8650                    || cu->language == language_cplus) && pdi->has_children)
8651                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8652                                       set_addrmap, cu);
8653               break;
8654             case DW_TAG_enumeration_type:
8655               if (!pdi->is_declaration)
8656                 add_partial_enumeration (pdi, cu);
8657               break;
8658             case DW_TAG_base_type:
8659             case DW_TAG_subrange_type:
8660               /* File scope base type definitions are added to the partial
8661                  symbol table.  */
8662               add_partial_symbol (pdi, cu);
8663               break;
8664             case DW_TAG_namespace:
8665               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8666               break;
8667             case DW_TAG_module:
8668               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8669               break;
8670             case DW_TAG_imported_unit:
8671               {
8672                 struct dwarf2_per_cu_data *per_cu;
8673
8674                 /* For now we don't handle imported units in type units.  */
8675                 if (cu->per_cu->is_debug_types)
8676                   {
8677                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8678                              " supported in type units [in module %s]"),
8679                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8680                   }
8681
8682                 per_cu = dwarf2_find_containing_comp_unit
8683                            (pdi->d.sect_off, pdi->is_dwz,
8684                             cu->per_cu->dwarf2_per_objfile);
8685
8686                 /* Go read the partial unit, if needed.  */
8687                 if (per_cu->v.psymtab == NULL)
8688                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8689
8690                 VEC_safe_push (dwarf2_per_cu_ptr,
8691                                cu->per_cu->imported_symtabs, per_cu);
8692               }
8693               break;
8694             case DW_TAG_imported_declaration:
8695               add_partial_symbol (pdi, cu);
8696               break;
8697             default:
8698               break;
8699             }
8700         }
8701
8702       /* If the die has a sibling, skip to the sibling.  */
8703
8704       pdi = pdi->die_sibling;
8705     }
8706 }
8707
8708 /* Functions used to compute the fully scoped name of a partial DIE.
8709
8710    Normally, this is simple.  For C++, the parent DIE's fully scoped
8711    name is concatenated with "::" and the partial DIE's name.
8712    Enumerators are an exception; they use the scope of their parent
8713    enumeration type, i.e. the name of the enumeration type is not
8714    prepended to the enumerator.
8715
8716    There are two complexities.  One is DW_AT_specification; in this
8717    case "parent" means the parent of the target of the specification,
8718    instead of the direct parent of the DIE.  The other is compilers
8719    which do not emit DW_TAG_namespace; in this case we try to guess
8720    the fully qualified name of structure types from their members'
8721    linkage names.  This must be done using the DIE's children rather
8722    than the children of any DW_AT_specification target.  We only need
8723    to do this for structures at the top level, i.e. if the target of
8724    any DW_AT_specification (if any; otherwise the DIE itself) does not
8725    have a parent.  */
8726
8727 /* Compute the scope prefix associated with PDI's parent, in
8728    compilation unit CU.  The result will be allocated on CU's
8729    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8730    field.  NULL is returned if no prefix is necessary.  */
8731 static const char *
8732 partial_die_parent_scope (struct partial_die_info *pdi,
8733                           struct dwarf2_cu *cu)
8734 {
8735   const char *grandparent_scope;
8736   struct partial_die_info *parent, *real_pdi;
8737
8738   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8739      then this means the parent of the specification DIE.  */
8740
8741   real_pdi = pdi;
8742   while (real_pdi->has_specification)
8743     {
8744       auto res = find_partial_die (real_pdi->spec_offset,
8745                                    real_pdi->spec_is_dwz, cu);
8746       real_pdi = res.pdi;
8747       cu = res.cu;
8748     }
8749
8750   parent = real_pdi->die_parent;
8751   if (parent == NULL)
8752     return NULL;
8753
8754   if (parent->scope_set)
8755     return parent->scope;
8756
8757   parent->fixup (cu);
8758
8759   grandparent_scope = partial_die_parent_scope (parent, cu);
8760
8761   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8762      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8763      Work around this problem here.  */
8764   if (cu->language == language_cplus
8765       && parent->tag == DW_TAG_namespace
8766       && strcmp (parent->name, "::") == 0
8767       && grandparent_scope == NULL)
8768     {
8769       parent->scope = NULL;
8770       parent->scope_set = 1;
8771       return NULL;
8772     }
8773
8774   if (pdi->tag == DW_TAG_enumerator)
8775     /* Enumerators should not get the name of the enumeration as a prefix.  */
8776     parent->scope = grandparent_scope;
8777   else if (parent->tag == DW_TAG_namespace
8778       || parent->tag == DW_TAG_module
8779       || parent->tag == DW_TAG_structure_type
8780       || parent->tag == DW_TAG_class_type
8781       || parent->tag == DW_TAG_interface_type
8782       || parent->tag == DW_TAG_union_type
8783       || parent->tag == DW_TAG_enumeration_type)
8784     {
8785       if (grandparent_scope == NULL)
8786         parent->scope = parent->name;
8787       else
8788         parent->scope = typename_concat (&cu->comp_unit_obstack,
8789                                          grandparent_scope,
8790                                          parent->name, 0, cu);
8791     }
8792   else
8793     {
8794       /* FIXME drow/2004-04-01: What should we be doing with
8795          function-local names?  For partial symbols, we should probably be
8796          ignoring them.  */
8797       complaint (_("unhandled containing DIE tag %s for DIE at %s"),
8798                  dwarf_tag_name (parent->tag),
8799                  sect_offset_str (pdi->sect_off));
8800       parent->scope = grandparent_scope;
8801     }
8802
8803   parent->scope_set = 1;
8804   return parent->scope;
8805 }
8806
8807 /* Return the fully scoped name associated with PDI, from compilation unit
8808    CU.  The result will be allocated with malloc.  */
8809
8810 static char *
8811 partial_die_full_name (struct partial_die_info *pdi,
8812                        struct dwarf2_cu *cu)
8813 {
8814   const char *parent_scope;
8815
8816   /* If this is a template instantiation, we can not work out the
8817      template arguments from partial DIEs.  So, unfortunately, we have
8818      to go through the full DIEs.  At least any work we do building
8819      types here will be reused if full symbols are loaded later.  */
8820   if (pdi->has_template_arguments)
8821     {
8822       pdi->fixup (cu);
8823
8824       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8825         {
8826           struct die_info *die;
8827           struct attribute attr;
8828           struct dwarf2_cu *ref_cu = cu;
8829
8830           /* DW_FORM_ref_addr is using section offset.  */
8831           attr.name = (enum dwarf_attribute) 0;
8832           attr.form = DW_FORM_ref_addr;
8833           attr.u.unsnd = to_underlying (pdi->sect_off);
8834           die = follow_die_ref (NULL, &attr, &ref_cu);
8835
8836           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8837         }
8838     }
8839
8840   parent_scope = partial_die_parent_scope (pdi, cu);
8841   if (parent_scope == NULL)
8842     return NULL;
8843   else
8844     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8845 }
8846
8847 static void
8848 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8849 {
8850   struct dwarf2_per_objfile *dwarf2_per_objfile
8851     = cu->per_cu->dwarf2_per_objfile;
8852   struct objfile *objfile = dwarf2_per_objfile->objfile;
8853   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8854   CORE_ADDR addr = 0;
8855   const char *actual_name = NULL;
8856   CORE_ADDR baseaddr;
8857   char *built_actual_name;
8858
8859   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8860
8861   built_actual_name = partial_die_full_name (pdi, cu);
8862   if (built_actual_name != NULL)
8863     actual_name = built_actual_name;
8864
8865   if (actual_name == NULL)
8866     actual_name = pdi->name;
8867
8868   switch (pdi->tag)
8869     {
8870     case DW_TAG_inlined_subroutine:
8871     case DW_TAG_subprogram:
8872       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8873               - baseaddr);
8874       if (pdi->is_external || cu->language == language_ada)
8875         {
8876           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8877              of the global scope.  But in Ada, we want to be able to access
8878              nested procedures globally.  So all Ada subprograms are stored
8879              in the global scope.  */
8880           add_psymbol_to_list (actual_name, strlen (actual_name),
8881                                built_actual_name != NULL,
8882                                VAR_DOMAIN, LOC_BLOCK,
8883                                SECT_OFF_TEXT (objfile),
8884                                psymbol_placement::GLOBAL,
8885                                addr,
8886                                cu->language, objfile);
8887         }
8888       else
8889         {
8890           add_psymbol_to_list (actual_name, strlen (actual_name),
8891                                built_actual_name != NULL,
8892                                VAR_DOMAIN, LOC_BLOCK,
8893                                SECT_OFF_TEXT (objfile),
8894                                psymbol_placement::STATIC,
8895                                addr, cu->language, objfile);
8896         }
8897
8898       if (pdi->main_subprogram && actual_name != NULL)
8899         set_objfile_main_name (objfile, actual_name, cu->language);
8900       break;
8901     case DW_TAG_constant:
8902       add_psymbol_to_list (actual_name, strlen (actual_name),
8903                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8904                            -1, (pdi->is_external
8905                                 ? psymbol_placement::GLOBAL
8906                                 : psymbol_placement::STATIC),
8907                            0, cu->language, objfile);
8908       break;
8909     case DW_TAG_variable:
8910       if (pdi->d.locdesc)
8911         addr = decode_locdesc (pdi->d.locdesc, cu);
8912
8913       if (pdi->d.locdesc
8914           && addr == 0
8915           && !dwarf2_per_objfile->has_section_at_zero)
8916         {
8917           /* A global or static variable may also have been stripped
8918              out by the linker if unused, in which case its address
8919              will be nullified; do not add such variables into partial
8920              symbol table then.  */
8921         }
8922       else if (pdi->is_external)
8923         {
8924           /* Global Variable.
8925              Don't enter into the minimal symbol tables as there is
8926              a minimal symbol table entry from the ELF symbols already.
8927              Enter into partial symbol table if it has a location
8928              descriptor or a type.
8929              If the location descriptor is missing, new_symbol will create
8930              a LOC_UNRESOLVED symbol, the address of the variable will then
8931              be determined from the minimal symbol table whenever the variable
8932              is referenced.
8933              The address for the partial symbol table entry is not
8934              used by GDB, but it comes in handy for debugging partial symbol
8935              table building.  */
8936
8937           if (pdi->d.locdesc || pdi->has_type)
8938             add_psymbol_to_list (actual_name, strlen (actual_name),
8939                                  built_actual_name != NULL,
8940                                  VAR_DOMAIN, LOC_STATIC,
8941                                  SECT_OFF_TEXT (objfile),
8942                                  psymbol_placement::GLOBAL,
8943                                  addr, cu->language, objfile);
8944         }
8945       else
8946         {
8947           int has_loc = pdi->d.locdesc != NULL;
8948
8949           /* Static Variable.  Skip symbols whose value we cannot know (those
8950              without location descriptors or constant values).  */
8951           if (!has_loc && !pdi->has_const_value)
8952             {
8953               xfree (built_actual_name);
8954               return;
8955             }
8956
8957           add_psymbol_to_list (actual_name, strlen (actual_name),
8958                                built_actual_name != NULL,
8959                                VAR_DOMAIN, LOC_STATIC,
8960                                SECT_OFF_TEXT (objfile),
8961                                psymbol_placement::STATIC,
8962                                has_loc ? addr : 0,
8963                                cu->language, objfile);
8964         }
8965       break;
8966     case DW_TAG_typedef:
8967     case DW_TAG_base_type:
8968     case DW_TAG_subrange_type:
8969       add_psymbol_to_list (actual_name, strlen (actual_name),
8970                            built_actual_name != NULL,
8971                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8972                            psymbol_placement::STATIC,
8973                            0, cu->language, objfile);
8974       break;
8975     case DW_TAG_imported_declaration:
8976     case DW_TAG_namespace:
8977       add_psymbol_to_list (actual_name, strlen (actual_name),
8978                            built_actual_name != NULL,
8979                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8980                            psymbol_placement::GLOBAL,
8981                            0, cu->language, objfile);
8982       break;
8983     case DW_TAG_module:
8984       /* With Fortran 77 there might be a "BLOCK DATA" module
8985          available without any name.  If so, we skip the module as it
8986          doesn't bring any value.  */
8987       if (actual_name != nullptr)
8988         add_psymbol_to_list (actual_name, strlen (actual_name),
8989                              built_actual_name != NULL,
8990                              MODULE_DOMAIN, LOC_TYPEDEF, -1,
8991                              psymbol_placement::GLOBAL,
8992                              0, cu->language, objfile);
8993       break;
8994     case DW_TAG_class_type:
8995     case DW_TAG_interface_type:
8996     case DW_TAG_structure_type:
8997     case DW_TAG_union_type:
8998     case DW_TAG_enumeration_type:
8999       /* Skip external references.  The DWARF standard says in the section
9000          about "Structure, Union, and Class Type Entries": "An incomplete
9001          structure, union or class type is represented by a structure,
9002          union or class entry that does not have a byte size attribute
9003          and that has a DW_AT_declaration attribute."  */
9004       if (!pdi->has_byte_size && pdi->is_declaration)
9005         {
9006           xfree (built_actual_name);
9007           return;
9008         }
9009
9010       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9011          static vs. global.  */
9012       add_psymbol_to_list (actual_name, strlen (actual_name),
9013                            built_actual_name != NULL,
9014                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
9015                            cu->language == language_cplus
9016                            ? psymbol_placement::GLOBAL
9017                            : psymbol_placement::STATIC,
9018                            0, cu->language, objfile);
9019
9020       break;
9021     case DW_TAG_enumerator:
9022       add_psymbol_to_list (actual_name, strlen (actual_name),
9023                            built_actual_name != NULL,
9024                            VAR_DOMAIN, LOC_CONST, -1,
9025                            cu->language == language_cplus
9026                            ? psymbol_placement::GLOBAL
9027                            : psymbol_placement::STATIC,
9028                            0, cu->language, objfile);
9029       break;
9030     default:
9031       break;
9032     }
9033
9034   xfree (built_actual_name);
9035 }
9036
9037 /* Read a partial die corresponding to a namespace; also, add a symbol
9038    corresponding to that namespace to the symbol table.  NAMESPACE is
9039    the name of the enclosing namespace.  */
9040
9041 static void
9042 add_partial_namespace (struct partial_die_info *pdi,
9043                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9044                        int set_addrmap, struct dwarf2_cu *cu)
9045 {
9046   /* Add a symbol for the namespace.  */
9047
9048   add_partial_symbol (pdi, cu);
9049
9050   /* Now scan partial symbols in that namespace.  */
9051
9052   if (pdi->has_children)
9053     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9054 }
9055
9056 /* Read a partial die corresponding to a Fortran module.  */
9057
9058 static void
9059 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9060                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9061 {
9062   /* Add a symbol for the namespace.  */
9063
9064   add_partial_symbol (pdi, cu);
9065
9066   /* Now scan partial symbols in that module.  */
9067
9068   if (pdi->has_children)
9069     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9070 }
9071
9072 /* Read a partial die corresponding to a subprogram or an inlined
9073    subprogram and create a partial symbol for that subprogram.
9074    When the CU language allows it, this routine also defines a partial
9075    symbol for each nested subprogram that this subprogram contains.
9076    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9077    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9078
9079    PDI may also be a lexical block, in which case we simply search
9080    recursively for subprograms defined inside that lexical block.
9081    Again, this is only performed when the CU language allows this
9082    type of definitions.  */
9083
9084 static void
9085 add_partial_subprogram (struct partial_die_info *pdi,
9086                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9087                         int set_addrmap, struct dwarf2_cu *cu)
9088 {
9089   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9090     {
9091       if (pdi->has_pc_info)
9092         {
9093           if (pdi->lowpc < *lowpc)
9094             *lowpc = pdi->lowpc;
9095           if (pdi->highpc > *highpc)
9096             *highpc = pdi->highpc;
9097           if (set_addrmap)
9098             {
9099               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9100               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9101               CORE_ADDR baseaddr;
9102               CORE_ADDR this_highpc;
9103               CORE_ADDR this_lowpc;
9104
9105               baseaddr = ANOFFSET (objfile->section_offsets,
9106                                    SECT_OFF_TEXT (objfile));
9107               this_lowpc
9108                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9109                                                pdi->lowpc + baseaddr)
9110                    - baseaddr);
9111               this_highpc
9112                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9113                                                pdi->highpc + baseaddr)
9114                    - baseaddr);
9115               addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
9116                                  this_lowpc, this_highpc - 1,
9117                                  cu->per_cu->v.psymtab);
9118             }
9119         }
9120
9121       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9122         {
9123           if (!pdi->is_declaration)
9124             /* Ignore subprogram DIEs that do not have a name, they are
9125                illegal.  Do not emit a complaint at this point, we will
9126                do so when we convert this psymtab into a symtab.  */
9127             if (pdi->name)
9128               add_partial_symbol (pdi, cu);
9129         }
9130     }
9131
9132   if (! pdi->has_children)
9133     return;
9134
9135   if (cu->language == language_ada)
9136     {
9137       pdi = pdi->die_child;
9138       while (pdi != NULL)
9139         {
9140           pdi->fixup (cu);
9141           if (pdi->tag == DW_TAG_subprogram
9142               || pdi->tag == DW_TAG_inlined_subroutine
9143               || pdi->tag == DW_TAG_lexical_block)
9144             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9145           pdi = pdi->die_sibling;
9146         }
9147     }
9148 }
9149
9150 /* Read a partial die corresponding to an enumeration type.  */
9151
9152 static void
9153 add_partial_enumeration (struct partial_die_info *enum_pdi,
9154                          struct dwarf2_cu *cu)
9155 {
9156   struct partial_die_info *pdi;
9157
9158   if (enum_pdi->name != NULL)
9159     add_partial_symbol (enum_pdi, cu);
9160
9161   pdi = enum_pdi->die_child;
9162   while (pdi)
9163     {
9164       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9165         complaint (_("malformed enumerator DIE ignored"));
9166       else
9167         add_partial_symbol (pdi, cu);
9168       pdi = pdi->die_sibling;
9169     }
9170 }
9171
9172 /* Return the initial uleb128 in the die at INFO_PTR.  */
9173
9174 static unsigned int
9175 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9176 {
9177   unsigned int bytes_read;
9178
9179   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9180 }
9181
9182 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9183    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9184
9185    Return the corresponding abbrev, or NULL if the number is zero (indicating
9186    an empty DIE).  In either case *BYTES_READ will be set to the length of
9187    the initial number.  */
9188
9189 static struct abbrev_info *
9190 peek_die_abbrev (const die_reader_specs &reader,
9191                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9192 {
9193   dwarf2_cu *cu = reader.cu;
9194   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9195   unsigned int abbrev_number
9196     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9197
9198   if (abbrev_number == 0)
9199     return NULL;
9200
9201   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9202   if (!abbrev)
9203     {
9204       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9205                " at offset %s [in module %s]"),
9206              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9207              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9208     }
9209
9210   return abbrev;
9211 }
9212
9213 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9214    Returns a pointer to the end of a series of DIEs, terminated by an empty
9215    DIE.  Any children of the skipped DIEs will also be skipped.  */
9216
9217 static const gdb_byte *
9218 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9219 {
9220   while (1)
9221     {
9222       unsigned int bytes_read;
9223       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9224
9225       if (abbrev == NULL)
9226         return info_ptr + bytes_read;
9227       else
9228         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9229     }
9230 }
9231
9232 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9233    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9234    abbrev corresponding to that skipped uleb128 should be passed in
9235    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9236    children.  */
9237
9238 static const gdb_byte *
9239 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9240               struct abbrev_info *abbrev)
9241 {
9242   unsigned int bytes_read;
9243   struct attribute attr;
9244   bfd *abfd = reader->abfd;
9245   struct dwarf2_cu *cu = reader->cu;
9246   const gdb_byte *buffer = reader->buffer;
9247   const gdb_byte *buffer_end = reader->buffer_end;
9248   unsigned int form, i;
9249
9250   for (i = 0; i < abbrev->num_attrs; i++)
9251     {
9252       /* The only abbrev we care about is DW_AT_sibling.  */
9253       if (abbrev->attrs[i].name == DW_AT_sibling)
9254         {
9255           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9256           if (attr.form == DW_FORM_ref_addr)
9257             complaint (_("ignoring absolute DW_AT_sibling"));
9258           else
9259             {
9260               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9261               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9262
9263               if (sibling_ptr < info_ptr)
9264                 complaint (_("DW_AT_sibling points backwards"));
9265               else if (sibling_ptr > reader->buffer_end)
9266                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9267               else
9268                 return sibling_ptr;
9269             }
9270         }
9271
9272       /* If it isn't DW_AT_sibling, skip this attribute.  */
9273       form = abbrev->attrs[i].form;
9274     skip_attribute:
9275       switch (form)
9276         {
9277         case DW_FORM_ref_addr:
9278           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9279              and later it is offset sized.  */
9280           if (cu->header.version == 2)
9281             info_ptr += cu->header.addr_size;
9282           else
9283             info_ptr += cu->header.offset_size;
9284           break;
9285         case DW_FORM_GNU_ref_alt:
9286           info_ptr += cu->header.offset_size;
9287           break;
9288         case DW_FORM_addr:
9289           info_ptr += cu->header.addr_size;
9290           break;
9291         case DW_FORM_data1:
9292         case DW_FORM_ref1:
9293         case DW_FORM_flag:
9294           info_ptr += 1;
9295           break;
9296         case DW_FORM_flag_present:
9297         case DW_FORM_implicit_const:
9298           break;
9299         case DW_FORM_data2:
9300         case DW_FORM_ref2:
9301           info_ptr += 2;
9302           break;
9303         case DW_FORM_data4:
9304         case DW_FORM_ref4:
9305           info_ptr += 4;
9306           break;
9307         case DW_FORM_data8:
9308         case DW_FORM_ref8:
9309         case DW_FORM_ref_sig8:
9310           info_ptr += 8;
9311           break;
9312         case DW_FORM_data16:
9313           info_ptr += 16;
9314           break;
9315         case DW_FORM_string:
9316           read_direct_string (abfd, info_ptr, &bytes_read);
9317           info_ptr += bytes_read;
9318           break;
9319         case DW_FORM_sec_offset:
9320         case DW_FORM_strp:
9321         case DW_FORM_GNU_strp_alt:
9322           info_ptr += cu->header.offset_size;
9323           break;
9324         case DW_FORM_exprloc:
9325         case DW_FORM_block:
9326           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9327           info_ptr += bytes_read;
9328           break;
9329         case DW_FORM_block1:
9330           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9331           break;
9332         case DW_FORM_block2:
9333           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9334           break;
9335         case DW_FORM_block4:
9336           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9337           break;
9338         case DW_FORM_addrx:
9339         case DW_FORM_strx:
9340         case DW_FORM_sdata:
9341         case DW_FORM_udata:
9342         case DW_FORM_ref_udata:
9343         case DW_FORM_GNU_addr_index:
9344         case DW_FORM_GNU_str_index:
9345           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9346           break;
9347         case DW_FORM_indirect:
9348           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9349           info_ptr += bytes_read;
9350           /* We need to continue parsing from here, so just go back to
9351              the top.  */
9352           goto skip_attribute;
9353
9354         default:
9355           error (_("Dwarf Error: Cannot handle %s "
9356                    "in DWARF reader [in module %s]"),
9357                  dwarf_form_name (form),
9358                  bfd_get_filename (abfd));
9359         }
9360     }
9361
9362   if (abbrev->has_children)
9363     return skip_children (reader, info_ptr);
9364   else
9365     return info_ptr;
9366 }
9367
9368 /* Locate ORIG_PDI's sibling.
9369    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9370
9371 static const gdb_byte *
9372 locate_pdi_sibling (const struct die_reader_specs *reader,
9373                     struct partial_die_info *orig_pdi,
9374                     const gdb_byte *info_ptr)
9375 {
9376   /* Do we know the sibling already?  */
9377
9378   if (orig_pdi->sibling)
9379     return orig_pdi->sibling;
9380
9381   /* Are there any children to deal with?  */
9382
9383   if (!orig_pdi->has_children)
9384     return info_ptr;
9385
9386   /* Skip the children the long way.  */
9387
9388   return skip_children (reader, info_ptr);
9389 }
9390
9391 /* Expand this partial symbol table into a full symbol table.  SELF is
9392    not NULL.  */
9393
9394 static void
9395 dwarf2_read_symtab (struct partial_symtab *self,
9396                     struct objfile *objfile)
9397 {
9398   struct dwarf2_per_objfile *dwarf2_per_objfile
9399     = get_dwarf2_per_objfile (objfile);
9400
9401   if (self->readin)
9402     {
9403       warning (_("bug: psymtab for %s is already read in."),
9404                self->filename);
9405     }
9406   else
9407     {
9408       if (info_verbose)
9409         {
9410           printf_filtered (_("Reading in symbols for %s..."),
9411                            self->filename);
9412           gdb_flush (gdb_stdout);
9413         }
9414
9415       /* If this psymtab is constructed from a debug-only objfile, the
9416          has_section_at_zero flag will not necessarily be correct.  We
9417          can get the correct value for this flag by looking at the data
9418          associated with the (presumably stripped) associated objfile.  */
9419       if (objfile->separate_debug_objfile_backlink)
9420         {
9421           struct dwarf2_per_objfile *dpo_backlink
9422             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9423
9424           dwarf2_per_objfile->has_section_at_zero
9425             = dpo_backlink->has_section_at_zero;
9426         }
9427
9428       dwarf2_per_objfile->reading_partial_symbols = 0;
9429
9430       psymtab_to_symtab_1 (self);
9431
9432       /* Finish up the debug error message.  */
9433       if (info_verbose)
9434         printf_filtered (_("done.\n"));
9435     }
9436
9437   process_cu_includes (dwarf2_per_objfile);
9438 }
9439 \f
9440 /* Reading in full CUs.  */
9441
9442 /* Add PER_CU to the queue.  */
9443
9444 static void
9445 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9446                  enum language pretend_language)
9447 {
9448   struct dwarf2_queue_item *item;
9449
9450   per_cu->queued = 1;
9451   item = XNEW (struct dwarf2_queue_item);
9452   item->per_cu = per_cu;
9453   item->pretend_language = pretend_language;
9454   item->next = NULL;
9455
9456   if (dwarf2_queue == NULL)
9457     dwarf2_queue = item;
9458   else
9459     dwarf2_queue_tail->next = item;
9460
9461   dwarf2_queue_tail = item;
9462 }
9463
9464 /* If PER_CU is not yet queued, add it to the queue.
9465    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9466    dependency.
9467    The result is non-zero if PER_CU was queued, otherwise the result is zero
9468    meaning either PER_CU is already queued or it is already loaded.
9469
9470    N.B. There is an invariant here that if a CU is queued then it is loaded.
9471    The caller is required to load PER_CU if we return non-zero.  */
9472
9473 static int
9474 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9475                        struct dwarf2_per_cu_data *per_cu,
9476                        enum language pretend_language)
9477 {
9478   /* We may arrive here during partial symbol reading, if we need full
9479      DIEs to process an unusual case (e.g. template arguments).  Do
9480      not queue PER_CU, just tell our caller to load its DIEs.  */
9481   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9482     {
9483       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9484         return 1;
9485       return 0;
9486     }
9487
9488   /* Mark the dependence relation so that we don't flush PER_CU
9489      too early.  */
9490   if (dependent_cu != NULL)
9491     dwarf2_add_dependence (dependent_cu, per_cu);
9492
9493   /* If it's already on the queue, we have nothing to do.  */
9494   if (per_cu->queued)
9495     return 0;
9496
9497   /* If the compilation unit is already loaded, just mark it as
9498      used.  */
9499   if (per_cu->cu != NULL)
9500     {
9501       per_cu->cu->last_used = 0;
9502       return 0;
9503     }
9504
9505   /* Add it to the queue.  */
9506   queue_comp_unit (per_cu, pretend_language);
9507
9508   return 1;
9509 }
9510
9511 /* Process the queue.  */
9512
9513 static void
9514 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9515 {
9516   struct dwarf2_queue_item *item, *next_item;
9517
9518   if (dwarf_read_debug)
9519     {
9520       fprintf_unfiltered (gdb_stdlog,
9521                           "Expanding one or more symtabs of objfile %s ...\n",
9522                           objfile_name (dwarf2_per_objfile->objfile));
9523     }
9524
9525   /* The queue starts out with one item, but following a DIE reference
9526      may load a new CU, adding it to the end of the queue.  */
9527   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9528     {
9529       if ((dwarf2_per_objfile->using_index
9530            ? !item->per_cu->v.quick->compunit_symtab
9531            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9532           /* Skip dummy CUs.  */
9533           && item->per_cu->cu != NULL)
9534         {
9535           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9536           unsigned int debug_print_threshold;
9537           char buf[100];
9538
9539           if (per_cu->is_debug_types)
9540             {
9541               struct signatured_type *sig_type =
9542                 (struct signatured_type *) per_cu;
9543
9544               sprintf (buf, "TU %s at offset %s",
9545                        hex_string (sig_type->signature),
9546                        sect_offset_str (per_cu->sect_off));
9547               /* There can be 100s of TUs.
9548                  Only print them in verbose mode.  */
9549               debug_print_threshold = 2;
9550             }
9551           else
9552             {
9553               sprintf (buf, "CU at offset %s",
9554                        sect_offset_str (per_cu->sect_off));
9555               debug_print_threshold = 1;
9556             }
9557
9558           if (dwarf_read_debug >= debug_print_threshold)
9559             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9560
9561           if (per_cu->is_debug_types)
9562             process_full_type_unit (per_cu, item->pretend_language);
9563           else
9564             process_full_comp_unit (per_cu, item->pretend_language);
9565
9566           if (dwarf_read_debug >= debug_print_threshold)
9567             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9568         }
9569
9570       item->per_cu->queued = 0;
9571       next_item = item->next;
9572       xfree (item);
9573     }
9574
9575   dwarf2_queue_tail = NULL;
9576
9577   if (dwarf_read_debug)
9578     {
9579       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9580                           objfile_name (dwarf2_per_objfile->objfile));
9581     }
9582 }
9583
9584 /* Read in full symbols for PST, and anything it depends on.  */
9585
9586 static void
9587 psymtab_to_symtab_1 (struct partial_symtab *pst)
9588 {
9589   struct dwarf2_per_cu_data *per_cu;
9590   int i;
9591
9592   if (pst->readin)
9593     return;
9594
9595   for (i = 0; i < pst->number_of_dependencies; i++)
9596     if (!pst->dependencies[i]->readin
9597         && pst->dependencies[i]->user == NULL)
9598       {
9599         /* Inform about additional files that need to be read in.  */
9600         if (info_verbose)
9601           {
9602             /* FIXME: i18n: Need to make this a single string.  */
9603             fputs_filtered (" ", gdb_stdout);
9604             wrap_here ("");
9605             fputs_filtered ("and ", gdb_stdout);
9606             wrap_here ("");
9607             printf_filtered ("%s...", pst->dependencies[i]->filename);
9608             wrap_here ("");     /* Flush output.  */
9609             gdb_flush (gdb_stdout);
9610           }
9611         psymtab_to_symtab_1 (pst->dependencies[i]);
9612       }
9613
9614   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9615
9616   if (per_cu == NULL)
9617     {
9618       /* It's an include file, no symbols to read for it.
9619          Everything is in the parent symtab.  */
9620       pst->readin = 1;
9621       return;
9622     }
9623
9624   dw2_do_instantiate_symtab (per_cu, false);
9625 }
9626
9627 /* Trivial hash function for die_info: the hash value of a DIE
9628    is its offset in .debug_info for this objfile.  */
9629
9630 static hashval_t
9631 die_hash (const void *item)
9632 {
9633   const struct die_info *die = (const struct die_info *) item;
9634
9635   return to_underlying (die->sect_off);
9636 }
9637
9638 /* Trivial comparison function for die_info structures: two DIEs
9639    are equal if they have the same offset.  */
9640
9641 static int
9642 die_eq (const void *item_lhs, const void *item_rhs)
9643 {
9644   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9645   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9646
9647   return die_lhs->sect_off == die_rhs->sect_off;
9648 }
9649
9650 /* die_reader_func for load_full_comp_unit.
9651    This is identical to read_signatured_type_reader,
9652    but is kept separate for now.  */
9653
9654 static void
9655 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9656                             const gdb_byte *info_ptr,
9657                             struct die_info *comp_unit_die,
9658                             int has_children,
9659                             void *data)
9660 {
9661   struct dwarf2_cu *cu = reader->cu;
9662   enum language *language_ptr = (enum language *) data;
9663
9664   gdb_assert (cu->die_hash == NULL);
9665   cu->die_hash =
9666     htab_create_alloc_ex (cu->header.length / 12,
9667                           die_hash,
9668                           die_eq,
9669                           NULL,
9670                           &cu->comp_unit_obstack,
9671                           hashtab_obstack_allocate,
9672                           dummy_obstack_deallocate);
9673
9674   if (has_children)
9675     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9676                                                   &info_ptr, comp_unit_die);
9677   cu->dies = comp_unit_die;
9678   /* comp_unit_die is not stored in die_hash, no need.  */
9679
9680   /* We try not to read any attributes in this function, because not
9681      all CUs needed for references have been loaded yet, and symbol
9682      table processing isn't initialized.  But we have to set the CU language,
9683      or we won't be able to build types correctly.
9684      Similarly, if we do not read the producer, we can not apply
9685      producer-specific interpretation.  */
9686   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9687 }
9688
9689 /* Load the DIEs associated with PER_CU into memory.  */
9690
9691 static void
9692 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9693                      bool skip_partial,
9694                      enum language pretend_language)
9695 {
9696   gdb_assert (! this_cu->is_debug_types);
9697
9698   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9699                            load_full_comp_unit_reader, &pretend_language);
9700 }
9701
9702 /* Add a DIE to the delayed physname list.  */
9703
9704 static void
9705 add_to_method_list (struct type *type, int fnfield_index, int index,
9706                     const char *name, struct die_info *die,
9707                     struct dwarf2_cu *cu)
9708 {
9709   struct delayed_method_info mi;
9710   mi.type = type;
9711   mi.fnfield_index = fnfield_index;
9712   mi.index = index;
9713   mi.name = name;
9714   mi.die = die;
9715   cu->method_list.push_back (mi);
9716 }
9717
9718 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9719    "const" / "volatile".  If so, decrements LEN by the length of the
9720    modifier and return true.  Otherwise return false.  */
9721
9722 template<size_t N>
9723 static bool
9724 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9725 {
9726   size_t mod_len = sizeof (mod) - 1;
9727   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9728     {
9729       len -= mod_len;
9730       return true;
9731     }
9732   return false;
9733 }
9734
9735 /* Compute the physnames of any methods on the CU's method list.
9736
9737    The computation of method physnames is delayed in order to avoid the
9738    (bad) condition that one of the method's formal parameters is of an as yet
9739    incomplete type.  */
9740
9741 static void
9742 compute_delayed_physnames (struct dwarf2_cu *cu)
9743 {
9744   /* Only C++ delays computing physnames.  */
9745   if (cu->method_list.empty ())
9746     return;
9747   gdb_assert (cu->language == language_cplus);
9748
9749   for (const delayed_method_info &mi : cu->method_list)
9750     {
9751       const char *physname;
9752       struct fn_fieldlist *fn_flp
9753         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9754       physname = dwarf2_physname (mi.name, mi.die, cu);
9755       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9756         = physname ? physname : "";
9757
9758       /* Since there's no tag to indicate whether a method is a
9759          const/volatile overload, extract that information out of the
9760          demangled name.  */
9761       if (physname != NULL)
9762         {
9763           size_t len = strlen (physname);
9764
9765           while (1)
9766             {
9767               if (physname[len] == ')') /* shortcut */
9768                 break;
9769               else if (check_modifier (physname, len, " const"))
9770                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9771               else if (check_modifier (physname, len, " volatile"))
9772                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9773               else
9774                 break;
9775             }
9776         }
9777     }
9778
9779   /* The list is no longer needed.  */
9780   cu->method_list.clear ();
9781 }
9782
9783 /* Go objects should be embedded in a DW_TAG_module DIE,
9784    and it's not clear if/how imported objects will appear.
9785    To keep Go support simple until that's worked out,
9786    go back through what we've read and create something usable.
9787    We could do this while processing each DIE, and feels kinda cleaner,
9788    but that way is more invasive.
9789    This is to, for example, allow the user to type "p var" or "b main"
9790    without having to specify the package name, and allow lookups
9791    of module.object to work in contexts that use the expression
9792    parser.  */
9793
9794 static void
9795 fixup_go_packaging (struct dwarf2_cu *cu)
9796 {
9797   char *package_name = NULL;
9798   struct pending *list;
9799   int i;
9800
9801   for (list = *cu->get_builder ()->get_global_symbols ();
9802        list != NULL;
9803        list = list->next)
9804     {
9805       for (i = 0; i < list->nsyms; ++i)
9806         {
9807           struct symbol *sym = list->symbol[i];
9808
9809           if (SYMBOL_LANGUAGE (sym) == language_go
9810               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9811             {
9812               char *this_package_name = go_symbol_package_name (sym);
9813
9814               if (this_package_name == NULL)
9815                 continue;
9816               if (package_name == NULL)
9817                 package_name = this_package_name;
9818               else
9819                 {
9820                   struct objfile *objfile
9821                     = cu->per_cu->dwarf2_per_objfile->objfile;
9822                   if (strcmp (package_name, this_package_name) != 0)
9823                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9824                                (symbol_symtab (sym) != NULL
9825                                 ? symtab_to_filename_for_display
9826                                     (symbol_symtab (sym))
9827                                 : objfile_name (objfile)),
9828                                this_package_name, package_name);
9829                   xfree (this_package_name);
9830                 }
9831             }
9832         }
9833     }
9834
9835   if (package_name != NULL)
9836     {
9837       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9838       const char *saved_package_name
9839         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9840                                         package_name,
9841                                         strlen (package_name));
9842       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9843                                      saved_package_name);
9844       struct symbol *sym;
9845
9846       sym = allocate_symbol (objfile);
9847       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9848       SYMBOL_SET_NAMES (sym, saved_package_name,
9849                         strlen (saved_package_name), 0, objfile);
9850       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9851          e.g., "main" finds the "main" module and not C's main().  */
9852       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9853       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9854       SYMBOL_TYPE (sym) = type;
9855
9856       add_symbol_to_list (sym, cu->get_builder ()->get_global_symbols ());
9857
9858       xfree (package_name);
9859     }
9860 }
9861
9862 /* Allocate a fully-qualified name consisting of the two parts on the
9863    obstack.  */
9864
9865 static const char *
9866 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9867 {
9868   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9869 }
9870
9871 /* A helper that allocates a struct discriminant_info to attach to a
9872    union type.  */
9873
9874 static struct discriminant_info *
9875 alloc_discriminant_info (struct type *type, int discriminant_index,
9876                          int default_index)
9877 {
9878   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9879   gdb_assert (discriminant_index == -1
9880               || (discriminant_index >= 0
9881                   && discriminant_index < TYPE_NFIELDS (type)));
9882   gdb_assert (default_index == -1
9883               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9884
9885   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9886
9887   struct discriminant_info *disc
9888     = ((struct discriminant_info *)
9889        TYPE_ZALLOC (type,
9890                     offsetof (struct discriminant_info, discriminants)
9891                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9892   disc->default_index = default_index;
9893   disc->discriminant_index = discriminant_index;
9894
9895   struct dynamic_prop prop;
9896   prop.kind = PROP_UNDEFINED;
9897   prop.data.baton = disc;
9898
9899   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9900
9901   return disc;
9902 }
9903
9904 /* Some versions of rustc emitted enums in an unusual way.
9905
9906    Ordinary enums were emitted as unions.  The first element of each
9907    structure in the union was named "RUST$ENUM$DISR".  This element
9908    held the discriminant.
9909
9910    These versions of Rust also implemented the "non-zero"
9911    optimization.  When the enum had two values, and one is empty and
9912    the other holds a pointer that cannot be zero, the pointer is used
9913    as the discriminant, with a zero value meaning the empty variant.
9914    Here, the union's first member is of the form
9915    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9916    where the fieldnos are the indices of the fields that should be
9917    traversed in order to find the field (which may be several fields deep)
9918    and the variantname is the name of the variant of the case when the
9919    field is zero.
9920
9921    This function recognizes whether TYPE is of one of these forms,
9922    and, if so, smashes it to be a variant type.  */
9923
9924 static void
9925 quirk_rust_enum (struct type *type, struct objfile *objfile)
9926 {
9927   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9928
9929   /* We don't need to deal with empty enums.  */
9930   if (TYPE_NFIELDS (type) == 0)
9931     return;
9932
9933 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9934   if (TYPE_NFIELDS (type) == 1
9935       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9936     {
9937       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9938
9939       /* Decode the field name to find the offset of the
9940          discriminant.  */
9941       ULONGEST bit_offset = 0;
9942       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9943       while (name[0] >= '0' && name[0] <= '9')
9944         {
9945           char *tail;
9946           unsigned long index = strtoul (name, &tail, 10);
9947           name = tail;
9948           if (*name != '$'
9949               || index >= TYPE_NFIELDS (field_type)
9950               || (TYPE_FIELD_LOC_KIND (field_type, index)
9951                   != FIELD_LOC_KIND_BITPOS))
9952             {
9953               complaint (_("Could not parse Rust enum encoding string \"%s\""
9954                            "[in module %s]"),
9955                          TYPE_FIELD_NAME (type, 0),
9956                          objfile_name (objfile));
9957               return;
9958             }
9959           ++name;
9960
9961           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9962           field_type = TYPE_FIELD_TYPE (field_type, index);
9963         }
9964
9965       /* Make a union to hold the variants.  */
9966       struct type *union_type = alloc_type (objfile);
9967       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9968       TYPE_NFIELDS (union_type) = 3;
9969       TYPE_FIELDS (union_type)
9970         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9971       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9972       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9973
9974       /* Put the discriminant must at index 0.  */
9975       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9976       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9977       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9978       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9979
9980       /* The order of fields doesn't really matter, so put the real
9981          field at index 1 and the data-less field at index 2.  */
9982       struct discriminant_info *disc
9983         = alloc_discriminant_info (union_type, 0, 1);
9984       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9985       TYPE_FIELD_NAME (union_type, 1)
9986         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9987       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9988         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9989                               TYPE_FIELD_NAME (union_type, 1));
9990
9991       const char *dataless_name
9992         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9993                               name);
9994       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9995                                               dataless_name);
9996       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9997       /* NAME points into the original discriminant name, which
9998          already has the correct lifetime.  */
9999       TYPE_FIELD_NAME (union_type, 2) = name;
10000       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10001       disc->discriminants[2] = 0;
10002
10003       /* Smash this type to be a structure type.  We have to do this
10004          because the type has already been recorded.  */
10005       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10006       TYPE_NFIELDS (type) = 1;
10007       TYPE_FIELDS (type)
10008         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10009
10010       /* Install the variant part.  */
10011       TYPE_FIELD_TYPE (type, 0) = union_type;
10012       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10013       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10014     }
10015   else if (TYPE_NFIELDS (type) == 1)
10016     {
10017       /* We assume that a union with a single field is a univariant
10018          enum.  */
10019       /* Smash this type to be a structure type.  We have to do this
10020          because the type has already been recorded.  */
10021       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10022
10023       /* Make a union to hold the variants.  */
10024       struct type *union_type = alloc_type (objfile);
10025       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10026       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10027       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10028       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10029       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10030
10031       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10032       const char *variant_name
10033         = rust_last_path_segment (TYPE_NAME (field_type));
10034       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10035       TYPE_NAME (field_type)
10036         = rust_fully_qualify (&objfile->objfile_obstack,
10037                               TYPE_NAME (type), variant_name);
10038
10039       /* Install the union in the outer struct type.  */
10040       TYPE_NFIELDS (type) = 1;
10041       TYPE_FIELDS (type)
10042         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10043       TYPE_FIELD_TYPE (type, 0) = union_type;
10044       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10045       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10046
10047       alloc_discriminant_info (union_type, -1, 0);
10048     }
10049   else
10050     {
10051       struct type *disr_type = nullptr;
10052       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10053         {
10054           disr_type = TYPE_FIELD_TYPE (type, i);
10055
10056           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10057             {
10058               /* All fields of a true enum will be structs.  */
10059               return;
10060             }
10061           else if (TYPE_NFIELDS (disr_type) == 0)
10062             {
10063               /* Could be data-less variant, so keep going.  */
10064               disr_type = nullptr;
10065             }
10066           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10067                            "RUST$ENUM$DISR") != 0)
10068             {
10069               /* Not a Rust enum.  */
10070               return;
10071             }
10072           else
10073             {
10074               /* Found one.  */
10075               break;
10076             }
10077         }
10078
10079       /* If we got here without a discriminant, then it's probably
10080          just a union.  */
10081       if (disr_type == nullptr)
10082         return;
10083
10084       /* Smash this type to be a structure type.  We have to do this
10085          because the type has already been recorded.  */
10086       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10087
10088       /* Make a union to hold the variants.  */
10089       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10090       struct type *union_type = alloc_type (objfile);
10091       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10092       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10093       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10094       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10095       TYPE_FIELDS (union_type)
10096         = (struct field *) TYPE_ZALLOC (union_type,
10097                                         (TYPE_NFIELDS (union_type)
10098                                          * sizeof (struct field)));
10099
10100       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10101               TYPE_NFIELDS (type) * sizeof (struct field));
10102
10103       /* Install the discriminant at index 0 in the union.  */
10104       TYPE_FIELD (union_type, 0) = *disr_field;
10105       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10106       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10107
10108       /* Install the union in the outer struct type.  */
10109       TYPE_FIELD_TYPE (type, 0) = union_type;
10110       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10111       TYPE_NFIELDS (type) = 1;
10112
10113       /* Set the size and offset of the union type.  */
10114       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10115
10116       /* We need a way to find the correct discriminant given a
10117          variant name.  For convenience we build a map here.  */
10118       struct type *enum_type = FIELD_TYPE (*disr_field);
10119       std::unordered_map<std::string, ULONGEST> discriminant_map;
10120       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10121         {
10122           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10123             {
10124               const char *name
10125                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10126               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10127             }
10128         }
10129
10130       int n_fields = TYPE_NFIELDS (union_type);
10131       struct discriminant_info *disc
10132         = alloc_discriminant_info (union_type, 0, -1);
10133       /* Skip the discriminant here.  */
10134       for (int i = 1; i < n_fields; ++i)
10135         {
10136           /* Find the final word in the name of this variant's type.
10137              That name can be used to look up the correct
10138              discriminant.  */
10139           const char *variant_name
10140             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10141                                                                   i)));
10142
10143           auto iter = discriminant_map.find (variant_name);
10144           if (iter != discriminant_map.end ())
10145             disc->discriminants[i] = iter->second;
10146
10147           /* Remove the discriminant field, if it exists.  */
10148           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10149           if (TYPE_NFIELDS (sub_type) > 0)
10150             {
10151               --TYPE_NFIELDS (sub_type);
10152               ++TYPE_FIELDS (sub_type);
10153             }
10154           TYPE_FIELD_NAME (union_type, i) = variant_name;
10155           TYPE_NAME (sub_type)
10156             = rust_fully_qualify (&objfile->objfile_obstack,
10157                                   TYPE_NAME (type), variant_name);
10158         }
10159     }
10160 }
10161
10162 /* Rewrite some Rust unions to be structures with variants parts.  */
10163
10164 static void
10165 rust_union_quirks (struct dwarf2_cu *cu)
10166 {
10167   gdb_assert (cu->language == language_rust);
10168   for (type *type_ : cu->rust_unions)
10169     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10170   /* We don't need this any more.  */
10171   cu->rust_unions.clear ();
10172 }
10173
10174 /* Return the symtab for PER_CU.  This works properly regardless of
10175    whether we're using the index or psymtabs.  */
10176
10177 static struct compunit_symtab *
10178 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10179 {
10180   return (per_cu->dwarf2_per_objfile->using_index
10181           ? per_cu->v.quick->compunit_symtab
10182           : per_cu->v.psymtab->compunit_symtab);
10183 }
10184
10185 /* A helper function for computing the list of all symbol tables
10186    included by PER_CU.  */
10187
10188 static void
10189 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
10190                                 htab_t all_children, htab_t all_type_symtabs,
10191                                 struct dwarf2_per_cu_data *per_cu,
10192                                 struct compunit_symtab *immediate_parent)
10193 {
10194   void **slot;
10195   int ix;
10196   struct compunit_symtab *cust;
10197   struct dwarf2_per_cu_data *iter;
10198
10199   slot = htab_find_slot (all_children, per_cu, INSERT);
10200   if (*slot != NULL)
10201     {
10202       /* This inclusion and its children have been processed.  */
10203       return;
10204     }
10205
10206   *slot = per_cu;
10207   /* Only add a CU if it has a symbol table.  */
10208   cust = get_compunit_symtab (per_cu);
10209   if (cust != NULL)
10210     {
10211       /* If this is a type unit only add its symbol table if we haven't
10212          seen it yet (type unit per_cu's can share symtabs).  */
10213       if (per_cu->is_debug_types)
10214         {
10215           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10216           if (*slot == NULL)
10217             {
10218               *slot = cust;
10219               result->push_back (cust);
10220               if (cust->user == NULL)
10221                 cust->user = immediate_parent;
10222             }
10223         }
10224       else
10225         {
10226           result->push_back (cust);
10227           if (cust->user == NULL)
10228             cust->user = immediate_parent;
10229         }
10230     }
10231
10232   for (ix = 0;
10233        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10234        ++ix)
10235     {
10236       recursively_compute_inclusions (result, all_children,
10237                                       all_type_symtabs, iter, cust);
10238     }
10239 }
10240
10241 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10242    PER_CU.  */
10243
10244 static void
10245 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10246 {
10247   gdb_assert (! per_cu->is_debug_types);
10248
10249   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10250     {
10251       int ix, len;
10252       struct dwarf2_per_cu_data *per_cu_iter;
10253       std::vector<compunit_symtab *> result_symtabs;
10254       htab_t all_children, all_type_symtabs;
10255       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10256
10257       /* If we don't have a symtab, we can just skip this case.  */
10258       if (cust == NULL)
10259         return;
10260
10261       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10262                                         NULL, xcalloc, xfree);
10263       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10264                                             NULL, xcalloc, xfree);
10265
10266       for (ix = 0;
10267            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10268                         ix, per_cu_iter);
10269            ++ix)
10270         {
10271           recursively_compute_inclusions (&result_symtabs, all_children,
10272                                           all_type_symtabs, per_cu_iter,
10273                                           cust);
10274         }
10275
10276       /* Now we have a transitive closure of all the included symtabs.  */
10277       len = result_symtabs.size ();
10278       cust->includes
10279         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10280                      struct compunit_symtab *, len + 1);
10281       memcpy (cust->includes, result_symtabs.data (),
10282               len * sizeof (compunit_symtab *));
10283       cust->includes[len] = NULL;
10284
10285       htab_delete (all_children);
10286       htab_delete (all_type_symtabs);
10287     }
10288 }
10289
10290 /* Compute the 'includes' field for the symtabs of all the CUs we just
10291    read.  */
10292
10293 static void
10294 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10295 {
10296   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10297     {
10298       if (! iter->is_debug_types)
10299         compute_compunit_symtab_includes (iter);
10300     }
10301
10302   dwarf2_per_objfile->just_read_cus.clear ();
10303 }
10304
10305 /* Generate full symbol information for PER_CU, whose DIEs have
10306    already been loaded into memory.  */
10307
10308 static void
10309 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10310                         enum language pretend_language)
10311 {
10312   struct dwarf2_cu *cu = per_cu->cu;
10313   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10314   struct objfile *objfile = dwarf2_per_objfile->objfile;
10315   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10316   CORE_ADDR lowpc, highpc;
10317   struct compunit_symtab *cust;
10318   CORE_ADDR baseaddr;
10319   struct block *static_block;
10320   CORE_ADDR addr;
10321
10322   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10323
10324   /* Clear the list here in case something was left over.  */
10325   cu->method_list.clear ();
10326
10327   cu->language = pretend_language;
10328   cu->language_defn = language_def (cu->language);
10329
10330   /* Do line number decoding in read_file_scope () */
10331   process_die (cu->dies, cu);
10332
10333   /* For now fudge the Go package.  */
10334   if (cu->language == language_go)
10335     fixup_go_packaging (cu);
10336
10337   /* Now that we have processed all the DIEs in the CU, all the types 
10338      should be complete, and it should now be safe to compute all of the
10339      physnames.  */
10340   compute_delayed_physnames (cu);
10341
10342   if (cu->language == language_rust)
10343     rust_union_quirks (cu);
10344
10345   /* Some compilers don't define a DW_AT_high_pc attribute for the
10346      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10347      it, by scanning the DIE's below the compilation unit.  */
10348   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10349
10350   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10351   static_block = cu->get_builder ()->end_symtab_get_static_block (addr, 0, 1);
10352
10353   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10354      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10355      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10356      addrmap to help ensure it has an accurate map of pc values belonging to
10357      this comp unit.  */
10358   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10359
10360   cust = cu->get_builder ()->end_symtab_from_static_block (static_block,
10361                                                     SECT_OFF_TEXT (objfile),
10362                                                     0);
10363
10364   if (cust != NULL)
10365     {
10366       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10367
10368       /* Set symtab language to language from DW_AT_language.  If the
10369          compilation is from a C file generated by language preprocessors, do
10370          not set the language if it was already deduced by start_subfile.  */
10371       if (!(cu->language == language_c
10372             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10373         COMPUNIT_FILETABS (cust)->language = cu->language;
10374
10375       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10376          produce DW_AT_location with location lists but it can be possibly
10377          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10378          there were bugs in prologue debug info, fixed later in GCC-4.5
10379          by "unwind info for epilogues" patch (which is not directly related).
10380
10381          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10382          needed, it would be wrong due to missing DW_AT_producer there.
10383
10384          Still one can confuse GDB by using non-standard GCC compilation
10385          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10386          */ 
10387       if (cu->has_loclist && gcc_4_minor >= 5)
10388         cust->locations_valid = 1;
10389
10390       if (gcc_4_minor >= 5)
10391         cust->epilogue_unwind_valid = 1;
10392
10393       cust->call_site_htab = cu->call_site_htab;
10394     }
10395
10396   if (dwarf2_per_objfile->using_index)
10397     per_cu->v.quick->compunit_symtab = cust;
10398   else
10399     {
10400       struct partial_symtab *pst = per_cu->v.psymtab;
10401       pst->compunit_symtab = cust;
10402       pst->readin = 1;
10403     }
10404
10405   /* Push it for inclusion processing later.  */
10406   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10407
10408   /* Not needed any more.  */
10409   cu->reset_builder ();
10410 }
10411
10412 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10413    already been loaded into memory.  */
10414
10415 static void
10416 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10417                         enum language pretend_language)
10418 {
10419   struct dwarf2_cu *cu = per_cu->cu;
10420   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10421   struct objfile *objfile = dwarf2_per_objfile->objfile;
10422   struct compunit_symtab *cust;
10423   struct signatured_type *sig_type;
10424
10425   gdb_assert (per_cu->is_debug_types);
10426   sig_type = (struct signatured_type *) per_cu;
10427
10428   /* Clear the list here in case something was left over.  */
10429   cu->method_list.clear ();
10430
10431   cu->language = pretend_language;
10432   cu->language_defn = language_def (cu->language);
10433
10434   /* The symbol tables are set up in read_type_unit_scope.  */
10435   process_die (cu->dies, cu);
10436
10437   /* For now fudge the Go package.  */
10438   if (cu->language == language_go)
10439     fixup_go_packaging (cu);
10440
10441   /* Now that we have processed all the DIEs in the CU, all the types 
10442      should be complete, and it should now be safe to compute all of the
10443      physnames.  */
10444   compute_delayed_physnames (cu);
10445
10446   if (cu->language == language_rust)
10447     rust_union_quirks (cu);
10448
10449   /* TUs share symbol tables.
10450      If this is the first TU to use this symtab, complete the construction
10451      of it with end_expandable_symtab.  Otherwise, complete the addition of
10452      this TU's symbols to the existing symtab.  */
10453   if (sig_type->type_unit_group->compunit_symtab == NULL)
10454     {
10455       buildsym_compunit *builder = cu->get_builder ();
10456       cust = builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10457       sig_type->type_unit_group->compunit_symtab = cust;
10458
10459       if (cust != NULL)
10460         {
10461           /* Set symtab language to language from DW_AT_language.  If the
10462              compilation is from a C file generated by language preprocessors,
10463              do not set the language if it was already deduced by
10464              start_subfile.  */
10465           if (!(cu->language == language_c
10466                 && COMPUNIT_FILETABS (cust)->language != language_c))
10467             COMPUNIT_FILETABS (cust)->language = cu->language;
10468         }
10469     }
10470   else
10471     {
10472       cu->get_builder ()->augment_type_symtab ();
10473       cust = sig_type->type_unit_group->compunit_symtab;
10474     }
10475
10476   if (dwarf2_per_objfile->using_index)
10477     per_cu->v.quick->compunit_symtab = cust;
10478   else
10479     {
10480       struct partial_symtab *pst = per_cu->v.psymtab;
10481       pst->compunit_symtab = cust;
10482       pst->readin = 1;
10483     }
10484
10485   /* Not needed any more.  */
10486   cu->reset_builder ();
10487 }
10488
10489 /* Process an imported unit DIE.  */
10490
10491 static void
10492 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10493 {
10494   struct attribute *attr;
10495
10496   /* For now we don't handle imported units in type units.  */
10497   if (cu->per_cu->is_debug_types)
10498     {
10499       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10500                " supported in type units [in module %s]"),
10501              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10502     }
10503
10504   attr = dwarf2_attr (die, DW_AT_import, cu);
10505   if (attr != NULL)
10506     {
10507       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10508       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10509       dwarf2_per_cu_data *per_cu
10510         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10511                                             cu->per_cu->dwarf2_per_objfile);
10512
10513       /* If necessary, add it to the queue and load its DIEs.  */
10514       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10515         load_full_comp_unit (per_cu, false, cu->language);
10516
10517       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10518                      per_cu);
10519     }
10520 }
10521
10522 /* RAII object that represents a process_die scope: i.e.,
10523    starts/finishes processing a DIE.  */
10524 class process_die_scope
10525 {
10526 public:
10527   process_die_scope (die_info *die, dwarf2_cu *cu)
10528     : m_die (die), m_cu (cu)
10529   {
10530     /* We should only be processing DIEs not already in process.  */
10531     gdb_assert (!m_die->in_process);
10532     m_die->in_process = true;
10533   }
10534
10535   ~process_die_scope ()
10536   {
10537     m_die->in_process = false;
10538
10539     /* If we're done processing the DIE for the CU that owns the line
10540        header, we don't need the line header anymore.  */
10541     if (m_cu->line_header_die_owner == m_die)
10542       {
10543         delete m_cu->line_header;
10544         m_cu->line_header = NULL;
10545         m_cu->line_header_die_owner = NULL;
10546       }
10547   }
10548
10549 private:
10550   die_info *m_die;
10551   dwarf2_cu *m_cu;
10552 };
10553
10554 /* Process a die and its children.  */
10555
10556 static void
10557 process_die (struct die_info *die, struct dwarf2_cu *cu)
10558 {
10559   process_die_scope scope (die, cu);
10560
10561   switch (die->tag)
10562     {
10563     case DW_TAG_padding:
10564       break;
10565     case DW_TAG_compile_unit:
10566     case DW_TAG_partial_unit:
10567       read_file_scope (die, cu);
10568       break;
10569     case DW_TAG_type_unit:
10570       read_type_unit_scope (die, cu);
10571       break;
10572     case DW_TAG_subprogram:
10573     case DW_TAG_inlined_subroutine:
10574       read_func_scope (die, cu);
10575       break;
10576     case DW_TAG_lexical_block:
10577     case DW_TAG_try_block:
10578     case DW_TAG_catch_block:
10579       read_lexical_block_scope (die, cu);
10580       break;
10581     case DW_TAG_call_site:
10582     case DW_TAG_GNU_call_site:
10583       read_call_site_scope (die, cu);
10584       break;
10585     case DW_TAG_class_type:
10586     case DW_TAG_interface_type:
10587     case DW_TAG_structure_type:
10588     case DW_TAG_union_type:
10589       process_structure_scope (die, cu);
10590       break;
10591     case DW_TAG_enumeration_type:
10592       process_enumeration_scope (die, cu);
10593       break;
10594
10595     /* These dies have a type, but processing them does not create
10596        a symbol or recurse to process the children.  Therefore we can
10597        read them on-demand through read_type_die.  */
10598     case DW_TAG_subroutine_type:
10599     case DW_TAG_set_type:
10600     case DW_TAG_array_type:
10601     case DW_TAG_pointer_type:
10602     case DW_TAG_ptr_to_member_type:
10603     case DW_TAG_reference_type:
10604     case DW_TAG_rvalue_reference_type:
10605     case DW_TAG_string_type:
10606       break;
10607
10608     case DW_TAG_base_type:
10609     case DW_TAG_subrange_type:
10610     case DW_TAG_typedef:
10611       /* Add a typedef symbol for the type definition, if it has a
10612          DW_AT_name.  */
10613       new_symbol (die, read_type_die (die, cu), cu);
10614       break;
10615     case DW_TAG_common_block:
10616       read_common_block (die, cu);
10617       break;
10618     case DW_TAG_common_inclusion:
10619       break;
10620     case DW_TAG_namespace:
10621       cu->processing_has_namespace_info = true;
10622       read_namespace (die, cu);
10623       break;
10624     case DW_TAG_module:
10625       cu->processing_has_namespace_info = true;
10626       read_module (die, cu);
10627       break;
10628     case DW_TAG_imported_declaration:
10629       cu->processing_has_namespace_info = true;
10630       if (read_namespace_alias (die, cu))
10631         break;
10632       /* The declaration is not a global namespace alias.  */
10633       /* Fall through.  */
10634     case DW_TAG_imported_module:
10635       cu->processing_has_namespace_info = true;
10636       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10637                                  || cu->language != language_fortran))
10638         complaint (_("Tag '%s' has unexpected children"),
10639                    dwarf_tag_name (die->tag));
10640       read_import_statement (die, cu);
10641       break;
10642
10643     case DW_TAG_imported_unit:
10644       process_imported_unit_die (die, cu);
10645       break;
10646
10647     case DW_TAG_variable:
10648       read_variable (die, cu);
10649       break;
10650
10651     default:
10652       new_symbol (die, NULL, cu);
10653       break;
10654     }
10655 }
10656 \f
10657 /* DWARF name computation.  */
10658
10659 /* A helper function for dwarf2_compute_name which determines whether DIE
10660    needs to have the name of the scope prepended to the name listed in the
10661    die.  */
10662
10663 static int
10664 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10665 {
10666   struct attribute *attr;
10667
10668   switch (die->tag)
10669     {
10670     case DW_TAG_namespace:
10671     case DW_TAG_typedef:
10672     case DW_TAG_class_type:
10673     case DW_TAG_interface_type:
10674     case DW_TAG_structure_type:
10675     case DW_TAG_union_type:
10676     case DW_TAG_enumeration_type:
10677     case DW_TAG_enumerator:
10678     case DW_TAG_subprogram:
10679     case DW_TAG_inlined_subroutine:
10680     case DW_TAG_member:
10681     case DW_TAG_imported_declaration:
10682       return 1;
10683
10684     case DW_TAG_variable:
10685     case DW_TAG_constant:
10686       /* We only need to prefix "globally" visible variables.  These include
10687          any variable marked with DW_AT_external or any variable that
10688          lives in a namespace.  [Variables in anonymous namespaces
10689          require prefixing, but they are not DW_AT_external.]  */
10690
10691       if (dwarf2_attr (die, DW_AT_specification, cu))
10692         {
10693           struct dwarf2_cu *spec_cu = cu;
10694
10695           return die_needs_namespace (die_specification (die, &spec_cu),
10696                                       spec_cu);
10697         }
10698
10699       attr = dwarf2_attr (die, DW_AT_external, cu);
10700       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10701           && die->parent->tag != DW_TAG_module)
10702         return 0;
10703       /* A variable in a lexical block of some kind does not need a
10704          namespace, even though in C++ such variables may be external
10705          and have a mangled name.  */
10706       if (die->parent->tag ==  DW_TAG_lexical_block
10707           || die->parent->tag ==  DW_TAG_try_block
10708           || die->parent->tag ==  DW_TAG_catch_block
10709           || die->parent->tag == DW_TAG_subprogram)
10710         return 0;
10711       return 1;
10712
10713     default:
10714       return 0;
10715     }
10716 }
10717
10718 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10719    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10720    defined for the given DIE.  */
10721
10722 static struct attribute *
10723 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10724 {
10725   struct attribute *attr;
10726
10727   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10728   if (attr == NULL)
10729     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10730
10731   return attr;
10732 }
10733
10734 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10735    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10736    defined for the given DIE.  */
10737
10738 static const char *
10739 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10740 {
10741   const char *linkage_name;
10742
10743   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10744   if (linkage_name == NULL)
10745     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10746
10747   return linkage_name;
10748 }
10749
10750 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10751    compute the physname for the object, which include a method's:
10752    - formal parameters (C++),
10753    - receiver type (Go),
10754
10755    The term "physname" is a bit confusing.
10756    For C++, for example, it is the demangled name.
10757    For Go, for example, it's the mangled name.
10758
10759    For Ada, return the DIE's linkage name rather than the fully qualified
10760    name.  PHYSNAME is ignored..
10761
10762    The result is allocated on the objfile_obstack and canonicalized.  */
10763
10764 static const char *
10765 dwarf2_compute_name (const char *name,
10766                      struct die_info *die, struct dwarf2_cu *cu,
10767                      int physname)
10768 {
10769   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10770
10771   if (name == NULL)
10772     name = dwarf2_name (die, cu);
10773
10774   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10775      but otherwise compute it by typename_concat inside GDB.
10776      FIXME: Actually this is not really true, or at least not always true.
10777      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10778      Fortran names because there is no mangling standard.  So new_symbol
10779      will set the demangled name to the result of dwarf2_full_name, and it is
10780      the demangled name that GDB uses if it exists.  */
10781   if (cu->language == language_ada
10782       || (cu->language == language_fortran && physname))
10783     {
10784       /* For Ada unit, we prefer the linkage name over the name, as
10785          the former contains the exported name, which the user expects
10786          to be able to reference.  Ideally, we want the user to be able
10787          to reference this entity using either natural or linkage name,
10788          but we haven't started looking at this enhancement yet.  */
10789       const char *linkage_name = dw2_linkage_name (die, cu);
10790
10791       if (linkage_name != NULL)
10792         return linkage_name;
10793     }
10794
10795   /* These are the only languages we know how to qualify names in.  */
10796   if (name != NULL
10797       && (cu->language == language_cplus
10798           || cu->language == language_fortran || cu->language == language_d
10799           || cu->language == language_rust))
10800     {
10801       if (die_needs_namespace (die, cu))
10802         {
10803           const char *prefix;
10804           const char *canonical_name = NULL;
10805
10806           string_file buf;
10807
10808           prefix = determine_prefix (die, cu);
10809           if (*prefix != '\0')
10810             {
10811               char *prefixed_name = typename_concat (NULL, prefix, name,
10812                                                      physname, cu);
10813
10814               buf.puts (prefixed_name);
10815               xfree (prefixed_name);
10816             }
10817           else
10818             buf.puts (name);
10819
10820           /* Template parameters may be specified in the DIE's DW_AT_name, or
10821              as children with DW_TAG_template_type_param or
10822              DW_TAG_value_type_param.  If the latter, add them to the name
10823              here.  If the name already has template parameters, then
10824              skip this step; some versions of GCC emit both, and
10825              it is more efficient to use the pre-computed name.
10826
10827              Something to keep in mind about this process: it is very
10828              unlikely, or in some cases downright impossible, to produce
10829              something that will match the mangled name of a function.
10830              If the definition of the function has the same debug info,
10831              we should be able to match up with it anyway.  But fallbacks
10832              using the minimal symbol, for instance to find a method
10833              implemented in a stripped copy of libstdc++, will not work.
10834              If we do not have debug info for the definition, we will have to
10835              match them up some other way.
10836
10837              When we do name matching there is a related problem with function
10838              templates; two instantiated function templates are allowed to
10839              differ only by their return types, which we do not add here.  */
10840
10841           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10842             {
10843               struct attribute *attr;
10844               struct die_info *child;
10845               int first = 1;
10846
10847               die->building_fullname = 1;
10848
10849               for (child = die->child; child != NULL; child = child->sibling)
10850                 {
10851                   struct type *type;
10852                   LONGEST value;
10853                   const gdb_byte *bytes;
10854                   struct dwarf2_locexpr_baton *baton;
10855                   struct value *v;
10856
10857                   if (child->tag != DW_TAG_template_type_param
10858                       && child->tag != DW_TAG_template_value_param)
10859                     continue;
10860
10861                   if (first)
10862                     {
10863                       buf.puts ("<");
10864                       first = 0;
10865                     }
10866                   else
10867                     buf.puts (", ");
10868
10869                   attr = dwarf2_attr (child, DW_AT_type, cu);
10870                   if (attr == NULL)
10871                     {
10872                       complaint (_("template parameter missing DW_AT_type"));
10873                       buf.puts ("UNKNOWN_TYPE");
10874                       continue;
10875                     }
10876                   type = die_type (child, cu);
10877
10878                   if (child->tag == DW_TAG_template_type_param)
10879                     {
10880                       c_print_type (type, "", &buf, -1, 0, cu->language,
10881                                     &type_print_raw_options);
10882                       continue;
10883                     }
10884
10885                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10886                   if (attr == NULL)
10887                     {
10888                       complaint (_("template parameter missing "
10889                                    "DW_AT_const_value"));
10890                       buf.puts ("UNKNOWN_VALUE");
10891                       continue;
10892                     }
10893
10894                   dwarf2_const_value_attr (attr, type, name,
10895                                            &cu->comp_unit_obstack, cu,
10896                                            &value, &bytes, &baton);
10897
10898                   if (TYPE_NOSIGN (type))
10899                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10900                        changed, this can use value_print instead.  */
10901                     c_printchar (value, type, &buf);
10902                   else
10903                     {
10904                       struct value_print_options opts;
10905
10906                       if (baton != NULL)
10907                         v = dwarf2_evaluate_loc_desc (type, NULL,
10908                                                       baton->data,
10909                                                       baton->size,
10910                                                       baton->per_cu);
10911                       else if (bytes != NULL)
10912                         {
10913                           v = allocate_value (type);
10914                           memcpy (value_contents_writeable (v), bytes,
10915                                   TYPE_LENGTH (type));
10916                         }
10917                       else
10918                         v = value_from_longest (type, value);
10919
10920                       /* Specify decimal so that we do not depend on
10921                          the radix.  */
10922                       get_formatted_print_options (&opts, 'd');
10923                       opts.raw = 1;
10924                       value_print (v, &buf, &opts);
10925                       release_value (v);
10926                     }
10927                 }
10928
10929               die->building_fullname = 0;
10930
10931               if (!first)
10932                 {
10933                   /* Close the argument list, with a space if necessary
10934                      (nested templates).  */
10935                   if (!buf.empty () && buf.string ().back () == '>')
10936                     buf.puts (" >");
10937                   else
10938                     buf.puts (">");
10939                 }
10940             }
10941
10942           /* For C++ methods, append formal parameter type
10943              information, if PHYSNAME.  */
10944
10945           if (physname && die->tag == DW_TAG_subprogram
10946               && cu->language == language_cplus)
10947             {
10948               struct type *type = read_type_die (die, cu);
10949
10950               c_type_print_args (type, &buf, 1, cu->language,
10951                                  &type_print_raw_options);
10952
10953               if (cu->language == language_cplus)
10954                 {
10955                   /* Assume that an artificial first parameter is
10956                      "this", but do not crash if it is not.  RealView
10957                      marks unnamed (and thus unused) parameters as
10958                      artificial; there is no way to differentiate
10959                      the two cases.  */
10960                   if (TYPE_NFIELDS (type) > 0
10961                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10962                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10963                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10964                                                                         0))))
10965                     buf.puts (" const");
10966                 }
10967             }
10968
10969           const std::string &intermediate_name = buf.string ();
10970
10971           if (cu->language == language_cplus)
10972             canonical_name
10973               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10974                                           &objfile->per_bfd->storage_obstack);
10975
10976           /* If we only computed INTERMEDIATE_NAME, or if
10977              INTERMEDIATE_NAME is already canonical, then we need to
10978              copy it to the appropriate obstack.  */
10979           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10980             name = ((const char *)
10981                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10982                                    intermediate_name.c_str (),
10983                                    intermediate_name.length ()));
10984           else
10985             name = canonical_name;
10986         }
10987     }
10988
10989   return name;
10990 }
10991
10992 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10993    If scope qualifiers are appropriate they will be added.  The result
10994    will be allocated on the storage_obstack, or NULL if the DIE does
10995    not have a name.  NAME may either be from a previous call to
10996    dwarf2_name or NULL.
10997
10998    The output string will be canonicalized (if C++).  */
10999
11000 static const char *
11001 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11002 {
11003   return dwarf2_compute_name (name, die, cu, 0);
11004 }
11005
11006 /* Construct a physname for the given DIE in CU.  NAME may either be
11007    from a previous call to dwarf2_name or NULL.  The result will be
11008    allocated on the objfile_objstack or NULL if the DIE does not have a
11009    name.
11010
11011    The output string will be canonicalized (if C++).  */
11012
11013 static const char *
11014 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11015 {
11016   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11017   const char *retval, *mangled = NULL, *canon = NULL;
11018   int need_copy = 1;
11019
11020   /* In this case dwarf2_compute_name is just a shortcut not building anything
11021      on its own.  */
11022   if (!die_needs_namespace (die, cu))
11023     return dwarf2_compute_name (name, die, cu, 1);
11024
11025   mangled = dw2_linkage_name (die, cu);
11026
11027   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11028      See https://github.com/rust-lang/rust/issues/32925.  */
11029   if (cu->language == language_rust && mangled != NULL
11030       && strchr (mangled, '{') != NULL)
11031     mangled = NULL;
11032
11033   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11034      has computed.  */
11035   gdb::unique_xmalloc_ptr<char> demangled;
11036   if (mangled != NULL)
11037     {
11038
11039       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11040         {
11041           /* Do nothing (do not demangle the symbol name).  */
11042         }
11043       else if (cu->language == language_go)
11044         {
11045           /* This is a lie, but we already lie to the caller new_symbol.
11046              new_symbol assumes we return the mangled name.
11047              This just undoes that lie until things are cleaned up.  */
11048         }
11049       else
11050         {
11051           /* Use DMGL_RET_DROP for C++ template functions to suppress
11052              their return type.  It is easier for GDB users to search
11053              for such functions as `name(params)' than `long name(params)'.
11054              In such case the minimal symbol names do not match the full
11055              symbol names but for template functions there is never a need
11056              to look up their definition from their declaration so
11057              the only disadvantage remains the minimal symbol variant
11058              `long name(params)' does not have the proper inferior type.  */
11059           demangled.reset (gdb_demangle (mangled,
11060                                          (DMGL_PARAMS | DMGL_ANSI
11061                                           | DMGL_RET_DROP)));
11062         }
11063       if (demangled)
11064         canon = demangled.get ();
11065       else
11066         {
11067           canon = mangled;
11068           need_copy = 0;
11069         }
11070     }
11071
11072   if (canon == NULL || check_physname)
11073     {
11074       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11075
11076       if (canon != NULL && strcmp (physname, canon) != 0)
11077         {
11078           /* It may not mean a bug in GDB.  The compiler could also
11079              compute DW_AT_linkage_name incorrectly.  But in such case
11080              GDB would need to be bug-to-bug compatible.  */
11081
11082           complaint (_("Computed physname <%s> does not match demangled <%s> "
11083                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11084                      physname, canon, mangled, sect_offset_str (die->sect_off),
11085                      objfile_name (objfile));
11086
11087           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11088              is available here - over computed PHYSNAME.  It is safer
11089              against both buggy GDB and buggy compilers.  */
11090
11091           retval = canon;
11092         }
11093       else
11094         {
11095           retval = physname;
11096           need_copy = 0;
11097         }
11098     }
11099   else
11100     retval = canon;
11101
11102   if (need_copy)
11103     retval = ((const char *)
11104               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11105                              retval, strlen (retval)));
11106
11107   return retval;
11108 }
11109
11110 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11111    a new symbol for it.
11112
11113    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11114
11115 static int
11116 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11117 {
11118   struct attribute *attr;
11119
11120   /* If the die does not have a name, this is not a namespace
11121      alias.  */
11122   attr = dwarf2_attr (die, DW_AT_name, cu);
11123   if (attr != NULL)
11124     {
11125       int num;
11126       struct die_info *d = die;
11127       struct dwarf2_cu *imported_cu = cu;
11128
11129       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11130          keep inspecting DIEs until we hit the underlying import.  */
11131 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11132       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11133         {
11134           attr = dwarf2_attr (d, DW_AT_import, cu);
11135           if (attr == NULL)
11136             break;
11137
11138           d = follow_die_ref (d, attr, &imported_cu);
11139           if (d->tag != DW_TAG_imported_declaration)
11140             break;
11141         }
11142
11143       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11144         {
11145           complaint (_("DIE at %s has too many recursively imported "
11146                        "declarations"), sect_offset_str (d->sect_off));
11147           return 0;
11148         }
11149
11150       if (attr != NULL)
11151         {
11152           struct type *type;
11153           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11154
11155           type = get_die_type_at_offset (sect_off, cu->per_cu);
11156           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11157             {
11158               /* This declaration is a global namespace alias.  Add
11159                  a symbol for it whose type is the aliased namespace.  */
11160               new_symbol (die, type, cu);
11161               return 1;
11162             }
11163         }
11164     }
11165
11166   return 0;
11167 }
11168
11169 /* Return the using directives repository (global or local?) to use in the
11170    current context for CU.
11171
11172    For Ada, imported declarations can materialize renamings, which *may* be
11173    global.  However it is impossible (for now?) in DWARF to distinguish
11174    "external" imported declarations and "static" ones.  As all imported
11175    declarations seem to be static in all other languages, make them all CU-wide
11176    global only in Ada.  */
11177
11178 static struct using_direct **
11179 using_directives (struct dwarf2_cu *cu)
11180 {
11181   if (cu->language == language_ada
11182       && cu->get_builder ()->outermost_context_p ())
11183     return cu->get_builder ()->get_global_using_directives ();
11184   else
11185     return cu->get_builder ()->get_local_using_directives ();
11186 }
11187
11188 /* Read the import statement specified by the given die and record it.  */
11189
11190 static void
11191 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11192 {
11193   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11194   struct attribute *import_attr;
11195   struct die_info *imported_die, *child_die;
11196   struct dwarf2_cu *imported_cu;
11197   const char *imported_name;
11198   const char *imported_name_prefix;
11199   const char *canonical_name;
11200   const char *import_alias;
11201   const char *imported_declaration = NULL;
11202   const char *import_prefix;
11203   std::vector<const char *> excludes;
11204
11205   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11206   if (import_attr == NULL)
11207     {
11208       complaint (_("Tag '%s' has no DW_AT_import"),
11209                  dwarf_tag_name (die->tag));
11210       return;
11211     }
11212
11213   imported_cu = cu;
11214   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11215   imported_name = dwarf2_name (imported_die, imported_cu);
11216   if (imported_name == NULL)
11217     {
11218       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11219
11220         The import in the following code:
11221         namespace A
11222           {
11223             typedef int B;
11224           }
11225
11226         int main ()
11227           {
11228             using A::B;
11229             B b;
11230             return b;
11231           }
11232
11233         ...
11234          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11235             <52>   DW_AT_decl_file   : 1
11236             <53>   DW_AT_decl_line   : 6
11237             <54>   DW_AT_import      : <0x75>
11238          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11239             <59>   DW_AT_name        : B
11240             <5b>   DW_AT_decl_file   : 1
11241             <5c>   DW_AT_decl_line   : 2
11242             <5d>   DW_AT_type        : <0x6e>
11243         ...
11244          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11245             <76>   DW_AT_byte_size   : 4
11246             <77>   DW_AT_encoding    : 5        (signed)
11247
11248         imports the wrong die ( 0x75 instead of 0x58 ).
11249         This case will be ignored until the gcc bug is fixed.  */
11250       return;
11251     }
11252
11253   /* Figure out the local name after import.  */
11254   import_alias = dwarf2_name (die, cu);
11255
11256   /* Figure out where the statement is being imported to.  */
11257   import_prefix = determine_prefix (die, cu);
11258
11259   /* Figure out what the scope of the imported die is and prepend it
11260      to the name of the imported die.  */
11261   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11262
11263   if (imported_die->tag != DW_TAG_namespace
11264       && imported_die->tag != DW_TAG_module)
11265     {
11266       imported_declaration = imported_name;
11267       canonical_name = imported_name_prefix;
11268     }
11269   else if (strlen (imported_name_prefix) > 0)
11270     canonical_name = obconcat (&objfile->objfile_obstack,
11271                                imported_name_prefix,
11272                                (cu->language == language_d ? "." : "::"),
11273                                imported_name, (char *) NULL);
11274   else
11275     canonical_name = imported_name;
11276
11277   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11278     for (child_die = die->child; child_die && child_die->tag;
11279          child_die = sibling_die (child_die))
11280       {
11281         /* DWARF-4: A Fortran use statement with a “rename list” may be
11282            represented by an imported module entry with an import attribute
11283            referring to the module and owned entries corresponding to those
11284            entities that are renamed as part of being imported.  */
11285
11286         if (child_die->tag != DW_TAG_imported_declaration)
11287           {
11288             complaint (_("child DW_TAG_imported_declaration expected "
11289                          "- DIE at %s [in module %s]"),
11290                        sect_offset_str (child_die->sect_off),
11291                        objfile_name (objfile));
11292             continue;
11293           }
11294
11295         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11296         if (import_attr == NULL)
11297           {
11298             complaint (_("Tag '%s' has no DW_AT_import"),
11299                        dwarf_tag_name (child_die->tag));
11300             continue;
11301           }
11302
11303         imported_cu = cu;
11304         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11305                                               &imported_cu);
11306         imported_name = dwarf2_name (imported_die, imported_cu);
11307         if (imported_name == NULL)
11308           {
11309             complaint (_("child DW_TAG_imported_declaration has unknown "
11310                          "imported name - DIE at %s [in module %s]"),
11311                        sect_offset_str (child_die->sect_off),
11312                        objfile_name (objfile));
11313             continue;
11314           }
11315
11316         excludes.push_back (imported_name);
11317
11318         process_die (child_die, cu);
11319       }
11320
11321   add_using_directive (using_directives (cu),
11322                        import_prefix,
11323                        canonical_name,
11324                        import_alias,
11325                        imported_declaration,
11326                        excludes,
11327                        0,
11328                        &objfile->objfile_obstack);
11329 }
11330
11331 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11332    types, but gives them a size of zero.  Starting with version 14,
11333    ICC is compatible with GCC.  */
11334
11335 static bool
11336 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11337 {
11338   if (!cu->checked_producer)
11339     check_producer (cu);
11340
11341   return cu->producer_is_icc_lt_14;
11342 }
11343
11344 /* ICC generates a DW_AT_type for C void functions.  This was observed on
11345    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
11346    which says that void functions should not have a DW_AT_type.  */
11347
11348 static bool
11349 producer_is_icc (struct dwarf2_cu *cu)
11350 {
11351   if (!cu->checked_producer)
11352     check_producer (cu);
11353
11354   return cu->producer_is_icc;
11355 }
11356
11357 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11358    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11359    this, it was first present in GCC release 4.3.0.  */
11360
11361 static bool
11362 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11363 {
11364   if (!cu->checked_producer)
11365     check_producer (cu);
11366
11367   return cu->producer_is_gcc_lt_4_3;
11368 }
11369
11370 static file_and_directory
11371 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11372 {
11373   file_and_directory res;
11374
11375   /* Find the filename.  Do not use dwarf2_name here, since the filename
11376      is not a source language identifier.  */
11377   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11378   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11379
11380   if (res.comp_dir == NULL
11381       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11382       && IS_ABSOLUTE_PATH (res.name))
11383     {
11384       res.comp_dir_storage = ldirname (res.name);
11385       if (!res.comp_dir_storage.empty ())
11386         res.comp_dir = res.comp_dir_storage.c_str ();
11387     }
11388   if (res.comp_dir != NULL)
11389     {
11390       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11391          directory, get rid of it.  */
11392       const char *cp = strchr (res.comp_dir, ':');
11393
11394       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11395         res.comp_dir = cp + 1;
11396     }
11397
11398   if (res.name == NULL)
11399     res.name = "<unknown>";
11400
11401   return res;
11402 }
11403
11404 /* Handle DW_AT_stmt_list for a compilation unit.
11405    DIE is the DW_TAG_compile_unit die for CU.
11406    COMP_DIR is the compilation directory.  LOWPC is passed to
11407    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11408
11409 static void
11410 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11411                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11412 {
11413   struct dwarf2_per_objfile *dwarf2_per_objfile
11414     = cu->per_cu->dwarf2_per_objfile;
11415   struct objfile *objfile = dwarf2_per_objfile->objfile;
11416   struct attribute *attr;
11417   struct line_header line_header_local;
11418   hashval_t line_header_local_hash;
11419   void **slot;
11420   int decode_mapping;
11421
11422   gdb_assert (! cu->per_cu->is_debug_types);
11423
11424   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11425   if (attr == NULL)
11426     return;
11427
11428   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11429
11430   /* The line header hash table is only created if needed (it exists to
11431      prevent redundant reading of the line table for partial_units).
11432      If we're given a partial_unit, we'll need it.  If we're given a
11433      compile_unit, then use the line header hash table if it's already
11434      created, but don't create one just yet.  */
11435
11436   if (dwarf2_per_objfile->line_header_hash == NULL
11437       && die->tag == DW_TAG_partial_unit)
11438     {
11439       dwarf2_per_objfile->line_header_hash
11440         = htab_create_alloc_ex (127, line_header_hash_voidp,
11441                                 line_header_eq_voidp,
11442                                 free_line_header_voidp,
11443                                 &objfile->objfile_obstack,
11444                                 hashtab_obstack_allocate,
11445                                 dummy_obstack_deallocate);
11446     }
11447
11448   line_header_local.sect_off = line_offset;
11449   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11450   line_header_local_hash = line_header_hash (&line_header_local);
11451   if (dwarf2_per_objfile->line_header_hash != NULL)
11452     {
11453       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11454                                        &line_header_local,
11455                                        line_header_local_hash, NO_INSERT);
11456
11457       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11458          is not present in *SLOT (since if there is something in *SLOT then
11459          it will be for a partial_unit).  */
11460       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11461         {
11462           gdb_assert (*slot != NULL);
11463           cu->line_header = (struct line_header *) *slot;
11464           return;
11465         }
11466     }
11467
11468   /* dwarf_decode_line_header does not yet provide sufficient information.
11469      We always have to call also dwarf_decode_lines for it.  */
11470   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11471   if (lh == NULL)
11472     return;
11473
11474   cu->line_header = lh.release ();
11475   cu->line_header_die_owner = die;
11476
11477   if (dwarf2_per_objfile->line_header_hash == NULL)
11478     slot = NULL;
11479   else
11480     {
11481       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11482                                        &line_header_local,
11483                                        line_header_local_hash, INSERT);
11484       gdb_assert (slot != NULL);
11485     }
11486   if (slot != NULL && *slot == NULL)
11487     {
11488       /* This newly decoded line number information unit will be owned
11489          by line_header_hash hash table.  */
11490       *slot = cu->line_header;
11491       cu->line_header_die_owner = NULL;
11492     }
11493   else
11494     {
11495       /* We cannot free any current entry in (*slot) as that struct line_header
11496          may be already used by multiple CUs.  Create only temporary decoded
11497          line_header for this CU - it may happen at most once for each line
11498          number information unit.  And if we're not using line_header_hash
11499          then this is what we want as well.  */
11500       gdb_assert (die->tag != DW_TAG_partial_unit);
11501     }
11502   decode_mapping = (die->tag != DW_TAG_partial_unit);
11503   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11504                       decode_mapping);
11505
11506 }
11507
11508 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11509
11510 static void
11511 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11512 {
11513   struct dwarf2_per_objfile *dwarf2_per_objfile
11514     = cu->per_cu->dwarf2_per_objfile;
11515   struct objfile *objfile = dwarf2_per_objfile->objfile;
11516   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11517   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11518   CORE_ADDR highpc = ((CORE_ADDR) 0);
11519   struct attribute *attr;
11520   struct die_info *child_die;
11521   CORE_ADDR baseaddr;
11522
11523   prepare_one_comp_unit (cu, die, cu->language);
11524   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11525
11526   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11527
11528   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11529      from finish_block.  */
11530   if (lowpc == ((CORE_ADDR) -1))
11531     lowpc = highpc;
11532   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11533
11534   file_and_directory fnd = find_file_and_directory (die, cu);
11535
11536   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11537      standardised yet.  As a workaround for the language detection we fall
11538      back to the DW_AT_producer string.  */
11539   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11540     cu->language = language_opencl;
11541
11542   /* Similar hack for Go.  */
11543   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11544     set_cu_language (DW_LANG_Go, cu);
11545
11546   cu->start_symtab (fnd.name, fnd.comp_dir, lowpc);
11547
11548   /* Decode line number information if present.  We do this before
11549      processing child DIEs, so that the line header table is available
11550      for DW_AT_decl_file.  */
11551   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11552
11553   /* Process all dies in compilation unit.  */
11554   if (die->child != NULL)
11555     {
11556       child_die = die->child;
11557       while (child_die && child_die->tag)
11558         {
11559           process_die (child_die, cu);
11560           child_die = sibling_die (child_die);
11561         }
11562     }
11563
11564   /* Decode macro information, if present.  Dwarf 2 macro information
11565      refers to information in the line number info statement program
11566      header, so we can only read it if we've read the header
11567      successfully.  */
11568   attr = dwarf2_attr (die, DW_AT_macros, cu);
11569   if (attr == NULL)
11570     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11571   if (attr && cu->line_header)
11572     {
11573       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11574         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11575
11576       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11577     }
11578   else
11579     {
11580       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11581       if (attr && cu->line_header)
11582         {
11583           unsigned int macro_offset = DW_UNSND (attr);
11584
11585           dwarf_decode_macros (cu, macro_offset, 0);
11586         }
11587     }
11588 }
11589
11590 void
11591 dwarf2_cu::setup_type_unit_groups (struct die_info *die)
11592 {
11593   struct type_unit_group *tu_group;
11594   int first_time;
11595   struct attribute *attr;
11596   unsigned int i;
11597   struct signatured_type *sig_type;
11598
11599   gdb_assert (per_cu->is_debug_types);
11600   sig_type = (struct signatured_type *) per_cu;
11601
11602   attr = dwarf2_attr (die, DW_AT_stmt_list, this);
11603
11604   /* If we're using .gdb_index (includes -readnow) then
11605      per_cu->type_unit_group may not have been set up yet.  */
11606   if (sig_type->type_unit_group == NULL)
11607     sig_type->type_unit_group = get_type_unit_group (this, attr);
11608   tu_group = sig_type->type_unit_group;
11609
11610   /* If we've already processed this stmt_list there's no real need to
11611      do it again, we could fake it and just recreate the part we need
11612      (file name,index -> symtab mapping).  If data shows this optimization
11613      is useful we can do it then.  */
11614   first_time = tu_group->compunit_symtab == NULL;
11615
11616   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11617      debug info.  */
11618   line_header_up lh;
11619   if (attr != NULL)
11620     {
11621       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11622       lh = dwarf_decode_line_header (line_offset, this);
11623     }
11624   if (lh == NULL)
11625     {
11626       if (first_time)
11627         start_symtab ("", NULL, 0);
11628       else
11629         {
11630           gdb_assert (tu_group->symtabs == NULL);
11631           gdb_assert (m_builder == nullptr);
11632           struct compunit_symtab *cust = tu_group->compunit_symtab;
11633           m_builder.reset (new struct buildsym_compunit
11634                            (COMPUNIT_OBJFILE (cust), "",
11635                             COMPUNIT_DIRNAME (cust),
11636                             compunit_language (cust),
11637                             0, cust));
11638         }
11639       return;
11640     }
11641
11642   line_header = lh.release ();
11643   line_header_die_owner = die;
11644
11645   if (first_time)
11646     {
11647       struct compunit_symtab *cust = start_symtab ("", NULL, 0);
11648
11649       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11650          still initializing it, and our caller (a few levels up)
11651          process_full_type_unit still needs to know if this is the first
11652          time.  */
11653
11654       tu_group->num_symtabs = line_header->file_names.size ();
11655       tu_group->symtabs = XNEWVEC (struct symtab *,
11656                                    line_header->file_names.size ());
11657
11658       for (i = 0; i < line_header->file_names.size (); ++i)
11659         {
11660           file_entry &fe = line_header->file_names[i];
11661
11662           dwarf2_start_subfile (this, fe.name,
11663                                 fe.include_dir (line_header));
11664           buildsym_compunit *b = get_builder ();
11665           if (b->get_current_subfile ()->symtab == NULL)
11666             {
11667               /* NOTE: start_subfile will recognize when it's been
11668                  passed a file it has already seen.  So we can't
11669                  assume there's a simple mapping from
11670                  cu->line_header->file_names to subfiles, plus
11671                  cu->line_header->file_names may contain dups.  */
11672               b->get_current_subfile ()->symtab
11673                 = allocate_symtab (cust, b->get_current_subfile ()->name);
11674             }
11675
11676           fe.symtab = b->get_current_subfile ()->symtab;
11677           tu_group->symtabs[i] = fe.symtab;
11678         }
11679     }
11680   else
11681     {
11682       gdb_assert (m_builder == nullptr);
11683       struct compunit_symtab *cust = tu_group->compunit_symtab;
11684       m_builder.reset (new struct buildsym_compunit
11685                        (COMPUNIT_OBJFILE (cust), "",
11686                         COMPUNIT_DIRNAME (cust),
11687                         compunit_language (cust),
11688                         0, cust));
11689
11690       for (i = 0; i < line_header->file_names.size (); ++i)
11691         {
11692           file_entry &fe = line_header->file_names[i];
11693
11694           fe.symtab = tu_group->symtabs[i];
11695         }
11696     }
11697
11698   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11699      so they don't have a "real" (so to speak) symtab anyway.
11700      There is later code that will assign the main symtab to all symbols
11701      that don't have one.  We need to handle the case of a symbol with a
11702      missing symtab (DW_AT_decl_file) anyway.  */
11703 }
11704
11705 /* Process DW_TAG_type_unit.
11706    For TUs we want to skip the first top level sibling if it's not the
11707    actual type being defined by this TU.  In this case the first top
11708    level sibling is there to provide context only.  */
11709
11710 static void
11711 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11712 {
11713   struct die_info *child_die;
11714
11715   prepare_one_comp_unit (cu, die, language_minimal);
11716
11717   /* Initialize (or reinitialize) the machinery for building symtabs.
11718      We do this before processing child DIEs, so that the line header table
11719      is available for DW_AT_decl_file.  */
11720   cu->setup_type_unit_groups (die);
11721
11722   if (die->child != NULL)
11723     {
11724       child_die = die->child;
11725       while (child_die && child_die->tag)
11726         {
11727           process_die (child_die, cu);
11728           child_die = sibling_die (child_die);
11729         }
11730     }
11731 }
11732 \f
11733 /* DWO/DWP files.
11734
11735    http://gcc.gnu.org/wiki/DebugFission
11736    http://gcc.gnu.org/wiki/DebugFissionDWP
11737
11738    To simplify handling of both DWO files ("object" files with the DWARF info)
11739    and DWP files (a file with the DWOs packaged up into one file), we treat
11740    DWP files as having a collection of virtual DWO files.  */
11741
11742 static hashval_t
11743 hash_dwo_file (const void *item)
11744 {
11745   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11746   hashval_t hash;
11747
11748   hash = htab_hash_string (dwo_file->dwo_name);
11749   if (dwo_file->comp_dir != NULL)
11750     hash += htab_hash_string (dwo_file->comp_dir);
11751   return hash;
11752 }
11753
11754 static int
11755 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11756 {
11757   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11758   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11759
11760   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11761     return 0;
11762   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11763     return lhs->comp_dir == rhs->comp_dir;
11764   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11765 }
11766
11767 /* Allocate a hash table for DWO files.  */
11768
11769 static htab_up
11770 allocate_dwo_file_hash_table (struct objfile *objfile)
11771 {
11772   auto delete_dwo_file = [] (void *item)
11773     {
11774       struct dwo_file *dwo_file = (struct dwo_file *) item;
11775
11776       delete dwo_file;
11777     };
11778
11779   return htab_up (htab_create_alloc_ex (41,
11780                                         hash_dwo_file,
11781                                         eq_dwo_file,
11782                                         delete_dwo_file,
11783                                         &objfile->objfile_obstack,
11784                                         hashtab_obstack_allocate,
11785                                         dummy_obstack_deallocate));
11786 }
11787
11788 /* Lookup DWO file DWO_NAME.  */
11789
11790 static void **
11791 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11792                       const char *dwo_name,
11793                       const char *comp_dir)
11794 {
11795   struct dwo_file find_entry;
11796   void **slot;
11797
11798   if (dwarf2_per_objfile->dwo_files == NULL)
11799     dwarf2_per_objfile->dwo_files
11800       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11801
11802   find_entry.dwo_name = dwo_name;
11803   find_entry.comp_dir = comp_dir;
11804   slot = htab_find_slot (dwarf2_per_objfile->dwo_files.get (), &find_entry,
11805                          INSERT);
11806
11807   return slot;
11808 }
11809
11810 static hashval_t
11811 hash_dwo_unit (const void *item)
11812 {
11813   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11814
11815   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11816   return dwo_unit->signature;
11817 }
11818
11819 static int
11820 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11821 {
11822   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11823   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11824
11825   /* The signature is assumed to be unique within the DWO file.
11826      So while object file CU dwo_id's always have the value zero,
11827      that's OK, assuming each object file DWO file has only one CU,
11828      and that's the rule for now.  */
11829   return lhs->signature == rhs->signature;
11830 }
11831
11832 /* Allocate a hash table for DWO CUs,TUs.
11833    There is one of these tables for each of CUs,TUs for each DWO file.  */
11834
11835 static htab_t
11836 allocate_dwo_unit_table (struct objfile *objfile)
11837 {
11838   /* Start out with a pretty small number.
11839      Generally DWO files contain only one CU and maybe some TUs.  */
11840   return htab_create_alloc_ex (3,
11841                                hash_dwo_unit,
11842                                eq_dwo_unit,
11843                                NULL,
11844                                &objfile->objfile_obstack,
11845                                hashtab_obstack_allocate,
11846                                dummy_obstack_deallocate);
11847 }
11848
11849 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11850
11851 struct create_dwo_cu_data
11852 {
11853   struct dwo_file *dwo_file;
11854   struct dwo_unit dwo_unit;
11855 };
11856
11857 /* die_reader_func for create_dwo_cu.  */
11858
11859 static void
11860 create_dwo_cu_reader (const struct die_reader_specs *reader,
11861                       const gdb_byte *info_ptr,
11862                       struct die_info *comp_unit_die,
11863                       int has_children,
11864                       void *datap)
11865 {
11866   struct dwarf2_cu *cu = reader->cu;
11867   sect_offset sect_off = cu->per_cu->sect_off;
11868   struct dwarf2_section_info *section = cu->per_cu->section;
11869   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11870   struct dwo_file *dwo_file = data->dwo_file;
11871   struct dwo_unit *dwo_unit = &data->dwo_unit;
11872   struct attribute *attr;
11873
11874   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11875   if (attr == NULL)
11876     {
11877       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11878                    " its dwo_id [in module %s]"),
11879                  sect_offset_str (sect_off), dwo_file->dwo_name);
11880       return;
11881     }
11882
11883   dwo_unit->dwo_file = dwo_file;
11884   dwo_unit->signature = DW_UNSND (attr);
11885   dwo_unit->section = section;
11886   dwo_unit->sect_off = sect_off;
11887   dwo_unit->length = cu->per_cu->length;
11888
11889   if (dwarf_read_debug)
11890     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11891                         sect_offset_str (sect_off),
11892                         hex_string (dwo_unit->signature));
11893 }
11894
11895 /* Create the dwo_units for the CUs in a DWO_FILE.
11896    Note: This function processes DWO files only, not DWP files.  */
11897
11898 static void
11899 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11900                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11901                        htab_t &cus_htab)
11902 {
11903   struct objfile *objfile = dwarf2_per_objfile->objfile;
11904   const gdb_byte *info_ptr, *end_ptr;
11905
11906   dwarf2_read_section (objfile, &section);
11907   info_ptr = section.buffer;
11908
11909   if (info_ptr == NULL)
11910     return;
11911
11912   if (dwarf_read_debug)
11913     {
11914       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11915                           get_section_name (&section),
11916                           get_section_file_name (&section));
11917     }
11918
11919   end_ptr = info_ptr + section.size;
11920   while (info_ptr < end_ptr)
11921     {
11922       struct dwarf2_per_cu_data per_cu;
11923       struct create_dwo_cu_data create_dwo_cu_data;
11924       struct dwo_unit *dwo_unit;
11925       void **slot;
11926       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11927
11928       memset (&create_dwo_cu_data.dwo_unit, 0,
11929               sizeof (create_dwo_cu_data.dwo_unit));
11930       memset (&per_cu, 0, sizeof (per_cu));
11931       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11932       per_cu.is_debug_types = 0;
11933       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11934       per_cu.section = &section;
11935       create_dwo_cu_data.dwo_file = &dwo_file;
11936
11937       init_cutu_and_read_dies_no_follow (
11938           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11939       info_ptr += per_cu.length;
11940
11941       // If the unit could not be parsed, skip it.
11942       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11943         continue;
11944
11945       if (cus_htab == NULL)
11946         cus_htab = allocate_dwo_unit_table (objfile);
11947
11948       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11949       *dwo_unit = create_dwo_cu_data.dwo_unit;
11950       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11951       gdb_assert (slot != NULL);
11952       if (*slot != NULL)
11953         {
11954           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11955           sect_offset dup_sect_off = dup_cu->sect_off;
11956
11957           complaint (_("debug cu entry at offset %s is duplicate to"
11958                        " the entry at offset %s, signature %s"),
11959                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11960                      hex_string (dwo_unit->signature));
11961         }
11962       *slot = (void *)dwo_unit;
11963     }
11964 }
11965
11966 /* DWP file .debug_{cu,tu}_index section format:
11967    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11968
11969    DWP Version 1:
11970
11971    Both index sections have the same format, and serve to map a 64-bit
11972    signature to a set of section numbers.  Each section begins with a header,
11973    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11974    indexes, and a pool of 32-bit section numbers.  The index sections will be
11975    aligned at 8-byte boundaries in the file.
11976
11977    The index section header consists of:
11978
11979     V, 32 bit version number
11980     -, 32 bits unused
11981     N, 32 bit number of compilation units or type units in the index
11982     M, 32 bit number of slots in the hash table
11983
11984    Numbers are recorded using the byte order of the application binary.
11985
11986    The hash table begins at offset 16 in the section, and consists of an array
11987    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11988    order of the application binary).  Unused slots in the hash table are 0.
11989    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11990
11991    The parallel table begins immediately after the hash table
11992    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11993    array of 32-bit indexes (using the byte order of the application binary),
11994    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11995    table contains a 32-bit index into the pool of section numbers.  For unused
11996    hash table slots, the corresponding entry in the parallel table will be 0.
11997
11998    The pool of section numbers begins immediately following the hash table
11999    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12000    section numbers consists of an array of 32-bit words (using the byte order
12001    of the application binary).  Each item in the array is indexed starting
12002    from 0.  The hash table entry provides the index of the first section
12003    number in the set.  Additional section numbers in the set follow, and the
12004    set is terminated by a 0 entry (section number 0 is not used in ELF).
12005
12006    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12007    section must be the first entry in the set, and the .debug_abbrev.dwo must
12008    be the second entry. Other members of the set may follow in any order.
12009
12010    ---
12011
12012    DWP Version 2:
12013
12014    DWP Version 2 combines all the .debug_info, etc. sections into one,
12015    and the entries in the index tables are now offsets into these sections.
12016    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12017    section.
12018
12019    Index Section Contents:
12020     Header
12021     Hash Table of Signatures   dwp_hash_table.hash_table
12022     Parallel Table of Indices  dwp_hash_table.unit_table
12023     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12024     Table of Section Sizes     dwp_hash_table.v2.sizes
12025
12026    The index section header consists of:
12027
12028     V, 32 bit version number
12029     L, 32 bit number of columns in the table of section offsets
12030     N, 32 bit number of compilation units or type units in the index
12031     M, 32 bit number of slots in the hash table
12032
12033    Numbers are recorded using the byte order of the application binary.
12034
12035    The hash table has the same format as version 1.
12036    The parallel table of indices has the same format as version 1,
12037    except that the entries are origin-1 indices into the table of sections
12038    offsets and the table of section sizes.
12039
12040    The table of offsets begins immediately following the parallel table
12041    (at offset 16 + 12 * M from the beginning of the section).  The table is
12042    a two-dimensional array of 32-bit words (using the byte order of the
12043    application binary), with L columns and N+1 rows, in row-major order.
12044    Each row in the array is indexed starting from 0.  The first row provides
12045    a key to the remaining rows: each column in this row provides an identifier
12046    for a debug section, and the offsets in the same column of subsequent rows
12047    refer to that section.  The section identifiers are:
12048
12049     DW_SECT_INFO         1  .debug_info.dwo
12050     DW_SECT_TYPES        2  .debug_types.dwo
12051     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12052     DW_SECT_LINE         4  .debug_line.dwo
12053     DW_SECT_LOC          5  .debug_loc.dwo
12054     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12055     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12056     DW_SECT_MACRO        8  .debug_macro.dwo
12057
12058    The offsets provided by the CU and TU index sections are the base offsets
12059    for the contributions made by each CU or TU to the corresponding section
12060    in the package file.  Each CU and TU header contains an abbrev_offset
12061    field, used to find the abbreviations table for that CU or TU within the
12062    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12063    be interpreted as relative to the base offset given in the index section.
12064    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12065    should be interpreted as relative to the base offset for .debug_line.dwo,
12066    and offsets into other debug sections obtained from DWARF attributes should
12067    also be interpreted as relative to the corresponding base offset.
12068
12069    The table of sizes begins immediately following the table of offsets.
12070    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12071    with L columns and N rows, in row-major order.  Each row in the array is
12072    indexed starting from 1 (row 0 is shared by the two tables).
12073
12074    ---
12075
12076    Hash table lookup is handled the same in version 1 and 2:
12077
12078    We assume that N and M will not exceed 2^32 - 1.
12079    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12080
12081    Given a 64-bit compilation unit signature or a type signature S, an entry
12082    in the hash table is located as follows:
12083
12084    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12085       the low-order k bits all set to 1.
12086
12087    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12088
12089    3) If the hash table entry at index H matches the signature, use that
12090       entry.  If the hash table entry at index H is unused (all zeroes),
12091       terminate the search: the signature is not present in the table.
12092
12093    4) Let H = (H + H') modulo M. Repeat at Step 3.
12094
12095    Because M > N and H' and M are relatively prime, the search is guaranteed
12096    to stop at an unused slot or find the match.  */
12097
12098 /* Create a hash table to map DWO IDs to their CU/TU entry in
12099    .debug_{info,types}.dwo in DWP_FILE.
12100    Returns NULL if there isn't one.
12101    Note: This function processes DWP files only, not DWO files.  */
12102
12103 static struct dwp_hash_table *
12104 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12105                        struct dwp_file *dwp_file, int is_debug_types)
12106 {
12107   struct objfile *objfile = dwarf2_per_objfile->objfile;
12108   bfd *dbfd = dwp_file->dbfd.get ();
12109   const gdb_byte *index_ptr, *index_end;
12110   struct dwarf2_section_info *index;
12111   uint32_t version, nr_columns, nr_units, nr_slots;
12112   struct dwp_hash_table *htab;
12113
12114   if (is_debug_types)
12115     index = &dwp_file->sections.tu_index;
12116   else
12117     index = &dwp_file->sections.cu_index;
12118
12119   if (dwarf2_section_empty_p (index))
12120     return NULL;
12121   dwarf2_read_section (objfile, index);
12122
12123   index_ptr = index->buffer;
12124   index_end = index_ptr + index->size;
12125
12126   version = read_4_bytes (dbfd, index_ptr);
12127   index_ptr += 4;
12128   if (version == 2)
12129     nr_columns = read_4_bytes (dbfd, index_ptr);
12130   else
12131     nr_columns = 0;
12132   index_ptr += 4;
12133   nr_units = read_4_bytes (dbfd, index_ptr);
12134   index_ptr += 4;
12135   nr_slots = read_4_bytes (dbfd, index_ptr);
12136   index_ptr += 4;
12137
12138   if (version != 1 && version != 2)
12139     {
12140       error (_("Dwarf Error: unsupported DWP file version (%s)"
12141                " [in module %s]"),
12142              pulongest (version), dwp_file->name);
12143     }
12144   if (nr_slots != (nr_slots & -nr_slots))
12145     {
12146       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12147                " is not power of 2 [in module %s]"),
12148              pulongest (nr_slots), dwp_file->name);
12149     }
12150
12151   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12152   htab->version = version;
12153   htab->nr_columns = nr_columns;
12154   htab->nr_units = nr_units;
12155   htab->nr_slots = nr_slots;
12156   htab->hash_table = index_ptr;
12157   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12158
12159   /* Exit early if the table is empty.  */
12160   if (nr_slots == 0 || nr_units == 0
12161       || (version == 2 && nr_columns == 0))
12162     {
12163       /* All must be zero.  */
12164       if (nr_slots != 0 || nr_units != 0
12165           || (version == 2 && nr_columns != 0))
12166         {
12167           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12168                        " all zero [in modules %s]"),
12169                      dwp_file->name);
12170         }
12171       return htab;
12172     }
12173
12174   if (version == 1)
12175     {
12176       htab->section_pool.v1.indices =
12177         htab->unit_table + sizeof (uint32_t) * nr_slots;
12178       /* It's harder to decide whether the section is too small in v1.
12179          V1 is deprecated anyway so we punt.  */
12180     }
12181   else
12182     {
12183       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12184       int *ids = htab->section_pool.v2.section_ids;
12185       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
12186       /* Reverse map for error checking.  */
12187       int ids_seen[DW_SECT_MAX + 1];
12188       int i;
12189
12190       if (nr_columns < 2)
12191         {
12192           error (_("Dwarf Error: bad DWP hash table, too few columns"
12193                    " in section table [in module %s]"),
12194                  dwp_file->name);
12195         }
12196       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12197         {
12198           error (_("Dwarf Error: bad DWP hash table, too many columns"
12199                    " in section table [in module %s]"),
12200                  dwp_file->name);
12201         }
12202       memset (ids, 255, sizeof_ids);
12203       memset (ids_seen, 255, sizeof (ids_seen));
12204       for (i = 0; i < nr_columns; ++i)
12205         {
12206           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12207
12208           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12209             {
12210               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12211                        " in section table [in module %s]"),
12212                      id, dwp_file->name);
12213             }
12214           if (ids_seen[id] != -1)
12215             {
12216               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12217                        " id %d in section table [in module %s]"),
12218                      id, dwp_file->name);
12219             }
12220           ids_seen[id] = i;
12221           ids[i] = id;
12222         }
12223       /* Must have exactly one info or types section.  */
12224       if (((ids_seen[DW_SECT_INFO] != -1)
12225            + (ids_seen[DW_SECT_TYPES] != -1))
12226           != 1)
12227         {
12228           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12229                    " DWO info/types section [in module %s]"),
12230                  dwp_file->name);
12231         }
12232       /* Must have an abbrev section.  */
12233       if (ids_seen[DW_SECT_ABBREV] == -1)
12234         {
12235           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12236                    " section [in module %s]"),
12237                  dwp_file->name);
12238         }
12239       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12240       htab->section_pool.v2.sizes =
12241         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12242                                          * nr_units * nr_columns);
12243       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12244                                           * nr_units * nr_columns))
12245           > index_end)
12246         {
12247           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12248                    " [in module %s]"),
12249                  dwp_file->name);
12250         }
12251     }
12252
12253   return htab;
12254 }
12255
12256 /* Update SECTIONS with the data from SECTP.
12257
12258    This function is like the other "locate" section routines that are
12259    passed to bfd_map_over_sections, but in this context the sections to
12260    read comes from the DWP V1 hash table, not the full ELF section table.
12261
12262    The result is non-zero for success, or zero if an error was found.  */
12263
12264 static int
12265 locate_v1_virtual_dwo_sections (asection *sectp,
12266                                 struct virtual_v1_dwo_sections *sections)
12267 {
12268   const struct dwop_section_names *names = &dwop_section_names;
12269
12270   if (section_is_p (sectp->name, &names->abbrev_dwo))
12271     {
12272       /* There can be only one.  */
12273       if (sections->abbrev.s.section != NULL)
12274         return 0;
12275       sections->abbrev.s.section = sectp;
12276       sections->abbrev.size = bfd_get_section_size (sectp);
12277     }
12278   else if (section_is_p (sectp->name, &names->info_dwo)
12279            || section_is_p (sectp->name, &names->types_dwo))
12280     {
12281       /* There can be only one.  */
12282       if (sections->info_or_types.s.section != NULL)
12283         return 0;
12284       sections->info_or_types.s.section = sectp;
12285       sections->info_or_types.size = bfd_get_section_size (sectp);
12286     }
12287   else if (section_is_p (sectp->name, &names->line_dwo))
12288     {
12289       /* There can be only one.  */
12290       if (sections->line.s.section != NULL)
12291         return 0;
12292       sections->line.s.section = sectp;
12293       sections->line.size = bfd_get_section_size (sectp);
12294     }
12295   else if (section_is_p (sectp->name, &names->loc_dwo))
12296     {
12297       /* There can be only one.  */
12298       if (sections->loc.s.section != NULL)
12299         return 0;
12300       sections->loc.s.section = sectp;
12301       sections->loc.size = bfd_get_section_size (sectp);
12302     }
12303   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12304     {
12305       /* There can be only one.  */
12306       if (sections->macinfo.s.section != NULL)
12307         return 0;
12308       sections->macinfo.s.section = sectp;
12309       sections->macinfo.size = bfd_get_section_size (sectp);
12310     }
12311   else if (section_is_p (sectp->name, &names->macro_dwo))
12312     {
12313       /* There can be only one.  */
12314       if (sections->macro.s.section != NULL)
12315         return 0;
12316       sections->macro.s.section = sectp;
12317       sections->macro.size = bfd_get_section_size (sectp);
12318     }
12319   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12320     {
12321       /* There can be only one.  */
12322       if (sections->str_offsets.s.section != NULL)
12323         return 0;
12324       sections->str_offsets.s.section = sectp;
12325       sections->str_offsets.size = bfd_get_section_size (sectp);
12326     }
12327   else
12328     {
12329       /* No other kind of section is valid.  */
12330       return 0;
12331     }
12332
12333   return 1;
12334 }
12335
12336 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12337    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12338    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12339    This is for DWP version 1 files.  */
12340
12341 static struct dwo_unit *
12342 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12343                            struct dwp_file *dwp_file,
12344                            uint32_t unit_index,
12345                            const char *comp_dir,
12346                            ULONGEST signature, int is_debug_types)
12347 {
12348   struct objfile *objfile = dwarf2_per_objfile->objfile;
12349   const struct dwp_hash_table *dwp_htab =
12350     is_debug_types ? dwp_file->tus : dwp_file->cus;
12351   bfd *dbfd = dwp_file->dbfd.get ();
12352   const char *kind = is_debug_types ? "TU" : "CU";
12353   struct dwo_file *dwo_file;
12354   struct dwo_unit *dwo_unit;
12355   struct virtual_v1_dwo_sections sections;
12356   void **dwo_file_slot;
12357   int i;
12358
12359   gdb_assert (dwp_file->version == 1);
12360
12361   if (dwarf_read_debug)
12362     {
12363       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12364                           kind,
12365                           pulongest (unit_index), hex_string (signature),
12366                           dwp_file->name);
12367     }
12368
12369   /* Fetch the sections of this DWO unit.
12370      Put a limit on the number of sections we look for so that bad data
12371      doesn't cause us to loop forever.  */
12372
12373 #define MAX_NR_V1_DWO_SECTIONS \
12374   (1 /* .debug_info or .debug_types */ \
12375    + 1 /* .debug_abbrev */ \
12376    + 1 /* .debug_line */ \
12377    + 1 /* .debug_loc */ \
12378    + 1 /* .debug_str_offsets */ \
12379    + 1 /* .debug_macro or .debug_macinfo */ \
12380    + 1 /* trailing zero */)
12381
12382   memset (&sections, 0, sizeof (sections));
12383
12384   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12385     {
12386       asection *sectp;
12387       uint32_t section_nr =
12388         read_4_bytes (dbfd,
12389                       dwp_htab->section_pool.v1.indices
12390                       + (unit_index + i) * sizeof (uint32_t));
12391
12392       if (section_nr == 0)
12393         break;
12394       if (section_nr >= dwp_file->num_sections)
12395         {
12396           error (_("Dwarf Error: bad DWP hash table, section number too large"
12397                    " [in module %s]"),
12398                  dwp_file->name);
12399         }
12400
12401       sectp = dwp_file->elf_sections[section_nr];
12402       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12403         {
12404           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12405                    " [in module %s]"),
12406                  dwp_file->name);
12407         }
12408     }
12409
12410   if (i < 2
12411       || dwarf2_section_empty_p (&sections.info_or_types)
12412       || dwarf2_section_empty_p (&sections.abbrev))
12413     {
12414       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12415                " [in module %s]"),
12416              dwp_file->name);
12417     }
12418   if (i == MAX_NR_V1_DWO_SECTIONS)
12419     {
12420       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12421                " [in module %s]"),
12422              dwp_file->name);
12423     }
12424
12425   /* It's easier for the rest of the code if we fake a struct dwo_file and
12426      have dwo_unit "live" in that.  At least for now.
12427
12428      The DWP file can be made up of a random collection of CUs and TUs.
12429      However, for each CU + set of TUs that came from the same original DWO
12430      file, we can combine them back into a virtual DWO file to save space
12431      (fewer struct dwo_file objects to allocate).  Remember that for really
12432      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12433
12434   std::string virtual_dwo_name =
12435     string_printf ("virtual-dwo/%d-%d-%d-%d",
12436                    get_section_id (&sections.abbrev),
12437                    get_section_id (&sections.line),
12438                    get_section_id (&sections.loc),
12439                    get_section_id (&sections.str_offsets));
12440   /* Can we use an existing virtual DWO file?  */
12441   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12442                                         virtual_dwo_name.c_str (),
12443                                         comp_dir);
12444   /* Create one if necessary.  */
12445   if (*dwo_file_slot == NULL)
12446     {
12447       if (dwarf_read_debug)
12448         {
12449           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12450                               virtual_dwo_name.c_str ());
12451         }
12452       dwo_file = new struct dwo_file;
12453       dwo_file->dwo_name
12454         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12455                                         virtual_dwo_name.c_str (),
12456                                         virtual_dwo_name.size ());
12457       dwo_file->comp_dir = comp_dir;
12458       dwo_file->sections.abbrev = sections.abbrev;
12459       dwo_file->sections.line = sections.line;
12460       dwo_file->sections.loc = sections.loc;
12461       dwo_file->sections.macinfo = sections.macinfo;
12462       dwo_file->sections.macro = sections.macro;
12463       dwo_file->sections.str_offsets = sections.str_offsets;
12464       /* The "str" section is global to the entire DWP file.  */
12465       dwo_file->sections.str = dwp_file->sections.str;
12466       /* The info or types section is assigned below to dwo_unit,
12467          there's no need to record it in dwo_file.
12468          Also, we can't simply record type sections in dwo_file because
12469          we record a pointer into the vector in dwo_unit.  As we collect more
12470          types we'll grow the vector and eventually have to reallocate space
12471          for it, invalidating all copies of pointers into the previous
12472          contents.  */
12473       *dwo_file_slot = dwo_file;
12474     }
12475   else
12476     {
12477       if (dwarf_read_debug)
12478         {
12479           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12480                               virtual_dwo_name.c_str ());
12481         }
12482       dwo_file = (struct dwo_file *) *dwo_file_slot;
12483     }
12484
12485   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12486   dwo_unit->dwo_file = dwo_file;
12487   dwo_unit->signature = signature;
12488   dwo_unit->section =
12489     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12490   *dwo_unit->section = sections.info_or_types;
12491   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12492
12493   return dwo_unit;
12494 }
12495
12496 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12497    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12498    piece within that section used by a TU/CU, return a virtual section
12499    of just that piece.  */
12500
12501 static struct dwarf2_section_info
12502 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12503                        struct dwarf2_section_info *section,
12504                        bfd_size_type offset, bfd_size_type size)
12505 {
12506   struct dwarf2_section_info result;
12507   asection *sectp;
12508
12509   gdb_assert (section != NULL);
12510   gdb_assert (!section->is_virtual);
12511
12512   memset (&result, 0, sizeof (result));
12513   result.s.containing_section = section;
12514   result.is_virtual = true;
12515
12516   if (size == 0)
12517     return result;
12518
12519   sectp = get_section_bfd_section (section);
12520
12521   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12522      bounds of the real section.  This is a pretty-rare event, so just
12523      flag an error (easier) instead of a warning and trying to cope.  */
12524   if (sectp == NULL
12525       || offset + size > bfd_get_section_size (sectp))
12526     {
12527       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12528                " in section %s [in module %s]"),
12529              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12530              objfile_name (dwarf2_per_objfile->objfile));
12531     }
12532
12533   result.virtual_offset = offset;
12534   result.size = size;
12535   return result;
12536 }
12537
12538 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12539    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12540    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12541    This is for DWP version 2 files.  */
12542
12543 static struct dwo_unit *
12544 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12545                            struct dwp_file *dwp_file,
12546                            uint32_t unit_index,
12547                            const char *comp_dir,
12548                            ULONGEST signature, int is_debug_types)
12549 {
12550   struct objfile *objfile = dwarf2_per_objfile->objfile;
12551   const struct dwp_hash_table *dwp_htab =
12552     is_debug_types ? dwp_file->tus : dwp_file->cus;
12553   bfd *dbfd = dwp_file->dbfd.get ();
12554   const char *kind = is_debug_types ? "TU" : "CU";
12555   struct dwo_file *dwo_file;
12556   struct dwo_unit *dwo_unit;
12557   struct virtual_v2_dwo_sections sections;
12558   void **dwo_file_slot;
12559   int i;
12560
12561   gdb_assert (dwp_file->version == 2);
12562
12563   if (dwarf_read_debug)
12564     {
12565       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12566                           kind,
12567                           pulongest (unit_index), hex_string (signature),
12568                           dwp_file->name);
12569     }
12570
12571   /* Fetch the section offsets of this DWO unit.  */
12572
12573   memset (&sections, 0, sizeof (sections));
12574
12575   for (i = 0; i < dwp_htab->nr_columns; ++i)
12576     {
12577       uint32_t offset = read_4_bytes (dbfd,
12578                                       dwp_htab->section_pool.v2.offsets
12579                                       + (((unit_index - 1) * dwp_htab->nr_columns
12580                                           + i)
12581                                          * sizeof (uint32_t)));
12582       uint32_t size = read_4_bytes (dbfd,
12583                                     dwp_htab->section_pool.v2.sizes
12584                                     + (((unit_index - 1) * dwp_htab->nr_columns
12585                                         + i)
12586                                        * sizeof (uint32_t)));
12587
12588       switch (dwp_htab->section_pool.v2.section_ids[i])
12589         {
12590         case DW_SECT_INFO:
12591         case DW_SECT_TYPES:
12592           sections.info_or_types_offset = offset;
12593           sections.info_or_types_size = size;
12594           break;
12595         case DW_SECT_ABBREV:
12596           sections.abbrev_offset = offset;
12597           sections.abbrev_size = size;
12598           break;
12599         case DW_SECT_LINE:
12600           sections.line_offset = offset;
12601           sections.line_size = size;
12602           break;
12603         case DW_SECT_LOC:
12604           sections.loc_offset = offset;
12605           sections.loc_size = size;
12606           break;
12607         case DW_SECT_STR_OFFSETS:
12608           sections.str_offsets_offset = offset;
12609           sections.str_offsets_size = size;
12610           break;
12611         case DW_SECT_MACINFO:
12612           sections.macinfo_offset = offset;
12613           sections.macinfo_size = size;
12614           break;
12615         case DW_SECT_MACRO:
12616           sections.macro_offset = offset;
12617           sections.macro_size = size;
12618           break;
12619         }
12620     }
12621
12622   /* It's easier for the rest of the code if we fake a struct dwo_file and
12623      have dwo_unit "live" in that.  At least for now.
12624
12625      The DWP file can be made up of a random collection of CUs and TUs.
12626      However, for each CU + set of TUs that came from the same original DWO
12627      file, we can combine them back into a virtual DWO file to save space
12628      (fewer struct dwo_file objects to allocate).  Remember that for really
12629      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12630
12631   std::string virtual_dwo_name =
12632     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12633                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12634                    (long) (sections.line_size ? sections.line_offset : 0),
12635                    (long) (sections.loc_size ? sections.loc_offset : 0),
12636                    (long) (sections.str_offsets_size
12637                            ? sections.str_offsets_offset : 0));
12638   /* Can we use an existing virtual DWO file?  */
12639   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12640                                         virtual_dwo_name.c_str (),
12641                                         comp_dir);
12642   /* Create one if necessary.  */
12643   if (*dwo_file_slot == NULL)
12644     {
12645       if (dwarf_read_debug)
12646         {
12647           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12648                               virtual_dwo_name.c_str ());
12649         }
12650       dwo_file = new struct dwo_file;
12651       dwo_file->dwo_name
12652         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12653                                         virtual_dwo_name.c_str (),
12654                                         virtual_dwo_name.size ());
12655       dwo_file->comp_dir = comp_dir;
12656       dwo_file->sections.abbrev =
12657         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12658                                sections.abbrev_offset, sections.abbrev_size);
12659       dwo_file->sections.line =
12660         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12661                                sections.line_offset, sections.line_size);
12662       dwo_file->sections.loc =
12663         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12664                                sections.loc_offset, sections.loc_size);
12665       dwo_file->sections.macinfo =
12666         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12667                                sections.macinfo_offset, sections.macinfo_size);
12668       dwo_file->sections.macro =
12669         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12670                                sections.macro_offset, sections.macro_size);
12671       dwo_file->sections.str_offsets =
12672         create_dwp_v2_section (dwarf2_per_objfile,
12673                                &dwp_file->sections.str_offsets,
12674                                sections.str_offsets_offset,
12675                                sections.str_offsets_size);
12676       /* The "str" section is global to the entire DWP file.  */
12677       dwo_file->sections.str = dwp_file->sections.str;
12678       /* The info or types section is assigned below to dwo_unit,
12679          there's no need to record it in dwo_file.
12680          Also, we can't simply record type sections in dwo_file because
12681          we record a pointer into the vector in dwo_unit.  As we collect more
12682          types we'll grow the vector and eventually have to reallocate space
12683          for it, invalidating all copies of pointers into the previous
12684          contents.  */
12685       *dwo_file_slot = dwo_file;
12686     }
12687   else
12688     {
12689       if (dwarf_read_debug)
12690         {
12691           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12692                               virtual_dwo_name.c_str ());
12693         }
12694       dwo_file = (struct dwo_file *) *dwo_file_slot;
12695     }
12696
12697   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12698   dwo_unit->dwo_file = dwo_file;
12699   dwo_unit->signature = signature;
12700   dwo_unit->section =
12701     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12702   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12703                                               is_debug_types
12704                                               ? &dwp_file->sections.types
12705                                               : &dwp_file->sections.info,
12706                                               sections.info_or_types_offset,
12707                                               sections.info_or_types_size);
12708   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12709
12710   return dwo_unit;
12711 }
12712
12713 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12714    Returns NULL if the signature isn't found.  */
12715
12716 static struct dwo_unit *
12717 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12718                         struct dwp_file *dwp_file, const char *comp_dir,
12719                         ULONGEST signature, int is_debug_types)
12720 {
12721   const struct dwp_hash_table *dwp_htab =
12722     is_debug_types ? dwp_file->tus : dwp_file->cus;
12723   bfd *dbfd = dwp_file->dbfd.get ();
12724   uint32_t mask = dwp_htab->nr_slots - 1;
12725   uint32_t hash = signature & mask;
12726   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12727   unsigned int i;
12728   void **slot;
12729   struct dwo_unit find_dwo_cu;
12730
12731   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12732   find_dwo_cu.signature = signature;
12733   slot = htab_find_slot (is_debug_types
12734                          ? dwp_file->loaded_tus
12735                          : dwp_file->loaded_cus,
12736                          &find_dwo_cu, INSERT);
12737
12738   if (*slot != NULL)
12739     return (struct dwo_unit *) *slot;
12740
12741   /* Use a for loop so that we don't loop forever on bad debug info.  */
12742   for (i = 0; i < dwp_htab->nr_slots; ++i)
12743     {
12744       ULONGEST signature_in_table;
12745
12746       signature_in_table =
12747         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12748       if (signature_in_table == signature)
12749         {
12750           uint32_t unit_index =
12751             read_4_bytes (dbfd,
12752                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12753
12754           if (dwp_file->version == 1)
12755             {
12756               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12757                                                  dwp_file, unit_index,
12758                                                  comp_dir, signature,
12759                                                  is_debug_types);
12760             }
12761           else
12762             {
12763               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12764                                                  dwp_file, unit_index,
12765                                                  comp_dir, signature,
12766                                                  is_debug_types);
12767             }
12768           return (struct dwo_unit *) *slot;
12769         }
12770       if (signature_in_table == 0)
12771         return NULL;
12772       hash = (hash + hash2) & mask;
12773     }
12774
12775   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12776            " [in module %s]"),
12777          dwp_file->name);
12778 }
12779
12780 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12781    Open the file specified by FILE_NAME and hand it off to BFD for
12782    preliminary analysis.  Return a newly initialized bfd *, which
12783    includes a canonicalized copy of FILE_NAME.
12784    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12785    SEARCH_CWD is true if the current directory is to be searched.
12786    It will be searched before debug-file-directory.
12787    If successful, the file is added to the bfd include table of the
12788    objfile's bfd (see gdb_bfd_record_inclusion).
12789    If unable to find/open the file, return NULL.
12790    NOTE: This function is derived from symfile_bfd_open.  */
12791
12792 static gdb_bfd_ref_ptr
12793 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12794                     const char *file_name, int is_dwp, int search_cwd)
12795 {
12796   int desc;
12797   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12798      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12799      to debug_file_directory.  */
12800   const char *search_path;
12801   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12802
12803   gdb::unique_xmalloc_ptr<char> search_path_holder;
12804   if (search_cwd)
12805     {
12806       if (*debug_file_directory != '\0')
12807         {
12808           search_path_holder.reset (concat (".", dirname_separator_string,
12809                                             debug_file_directory,
12810                                             (char *) NULL));
12811           search_path = search_path_holder.get ();
12812         }
12813       else
12814         search_path = ".";
12815     }
12816   else
12817     search_path = debug_file_directory;
12818
12819   openp_flags flags = OPF_RETURN_REALPATH;
12820   if (is_dwp)
12821     flags |= OPF_SEARCH_IN_PATH;
12822
12823   gdb::unique_xmalloc_ptr<char> absolute_name;
12824   desc = openp (search_path, flags, file_name,
12825                 O_RDONLY | O_BINARY, &absolute_name);
12826   if (desc < 0)
12827     return NULL;
12828
12829   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12830                                          gnutarget, desc));
12831   if (sym_bfd == NULL)
12832     return NULL;
12833   bfd_set_cacheable (sym_bfd.get (), 1);
12834
12835   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12836     return NULL;
12837
12838   /* Success.  Record the bfd as having been included by the objfile's bfd.
12839      This is important because things like demangled_names_hash lives in the
12840      objfile's per_bfd space and may have references to things like symbol
12841      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12842   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12843
12844   return sym_bfd;
12845 }
12846
12847 /* Try to open DWO file FILE_NAME.
12848    COMP_DIR is the DW_AT_comp_dir attribute.
12849    The result is the bfd handle of the file.
12850    If there is a problem finding or opening the file, return NULL.
12851    Upon success, the canonicalized path of the file is stored in the bfd,
12852    same as symfile_bfd_open.  */
12853
12854 static gdb_bfd_ref_ptr
12855 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12856                const char *file_name, const char *comp_dir)
12857 {
12858   if (IS_ABSOLUTE_PATH (file_name))
12859     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12860                                0 /*is_dwp*/, 0 /*search_cwd*/);
12861
12862   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12863
12864   if (comp_dir != NULL)
12865     {
12866       char *path_to_try = concat (comp_dir, SLASH_STRING,
12867                                   file_name, (char *) NULL);
12868
12869       /* NOTE: If comp_dir is a relative path, this will also try the
12870          search path, which seems useful.  */
12871       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12872                                                 path_to_try,
12873                                                 0 /*is_dwp*/,
12874                                                 1 /*search_cwd*/));
12875       xfree (path_to_try);
12876       if (abfd != NULL)
12877         return abfd;
12878     }
12879
12880   /* That didn't work, try debug-file-directory, which, despite its name,
12881      is a list of paths.  */
12882
12883   if (*debug_file_directory == '\0')
12884     return NULL;
12885
12886   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12887                              0 /*is_dwp*/, 1 /*search_cwd*/);
12888 }
12889
12890 /* This function is mapped across the sections and remembers the offset and
12891    size of each of the DWO debugging sections we are interested in.  */
12892
12893 static void
12894 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12895 {
12896   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12897   const struct dwop_section_names *names = &dwop_section_names;
12898
12899   if (section_is_p (sectp->name, &names->abbrev_dwo))
12900     {
12901       dwo_sections->abbrev.s.section = sectp;
12902       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12903     }
12904   else if (section_is_p (sectp->name, &names->info_dwo))
12905     {
12906       dwo_sections->info.s.section = sectp;
12907       dwo_sections->info.size = bfd_get_section_size (sectp);
12908     }
12909   else if (section_is_p (sectp->name, &names->line_dwo))
12910     {
12911       dwo_sections->line.s.section = sectp;
12912       dwo_sections->line.size = bfd_get_section_size (sectp);
12913     }
12914   else if (section_is_p (sectp->name, &names->loc_dwo))
12915     {
12916       dwo_sections->loc.s.section = sectp;
12917       dwo_sections->loc.size = bfd_get_section_size (sectp);
12918     }
12919   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12920     {
12921       dwo_sections->macinfo.s.section = sectp;
12922       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12923     }
12924   else if (section_is_p (sectp->name, &names->macro_dwo))
12925     {
12926       dwo_sections->macro.s.section = sectp;
12927       dwo_sections->macro.size = bfd_get_section_size (sectp);
12928     }
12929   else if (section_is_p (sectp->name, &names->str_dwo))
12930     {
12931       dwo_sections->str.s.section = sectp;
12932       dwo_sections->str.size = bfd_get_section_size (sectp);
12933     }
12934   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12935     {
12936       dwo_sections->str_offsets.s.section = sectp;
12937       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12938     }
12939   else if (section_is_p (sectp->name, &names->types_dwo))
12940     {
12941       struct dwarf2_section_info type_section;
12942
12943       memset (&type_section, 0, sizeof (type_section));
12944       type_section.s.section = sectp;
12945       type_section.size = bfd_get_section_size (sectp);
12946       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12947                      &type_section);
12948     }
12949 }
12950
12951 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12952    by PER_CU.  This is for the non-DWP case.
12953    The result is NULL if DWO_NAME can't be found.  */
12954
12955 static struct dwo_file *
12956 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12957                         const char *dwo_name, const char *comp_dir)
12958 {
12959   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12960
12961   gdb_bfd_ref_ptr dbfd = open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir);
12962   if (dbfd == NULL)
12963     {
12964       if (dwarf_read_debug)
12965         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12966       return NULL;
12967     }
12968
12969   dwo_file_up dwo_file (new struct dwo_file);
12970   dwo_file->dwo_name = dwo_name;
12971   dwo_file->comp_dir = comp_dir;
12972   dwo_file->dbfd = std::move (dbfd);
12973
12974   bfd_map_over_sections (dwo_file->dbfd.get (), dwarf2_locate_dwo_sections,
12975                          &dwo_file->sections);
12976
12977   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12978                          dwo_file->cus);
12979
12980   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12981                                  dwo_file->sections.types, dwo_file->tus);
12982
12983   if (dwarf_read_debug)
12984     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12985
12986   return dwo_file.release ();
12987 }
12988
12989 /* This function is mapped across the sections and remembers the offset and
12990    size of each of the DWP debugging sections common to version 1 and 2 that
12991    we are interested in.  */
12992
12993 static void
12994 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12995                                    void *dwp_file_ptr)
12996 {
12997   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12998   const struct dwop_section_names *names = &dwop_section_names;
12999   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13000
13001   /* Record the ELF section number for later lookup: this is what the
13002      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13003   gdb_assert (elf_section_nr < dwp_file->num_sections);
13004   dwp_file->elf_sections[elf_section_nr] = sectp;
13005
13006   /* Look for specific sections that we need.  */
13007   if (section_is_p (sectp->name, &names->str_dwo))
13008     {
13009       dwp_file->sections.str.s.section = sectp;
13010       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13011     }
13012   else if (section_is_p (sectp->name, &names->cu_index))
13013     {
13014       dwp_file->sections.cu_index.s.section = sectp;
13015       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13016     }
13017   else if (section_is_p (sectp->name, &names->tu_index))
13018     {
13019       dwp_file->sections.tu_index.s.section = sectp;
13020       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13021     }
13022 }
13023
13024 /* This function is mapped across the sections and remembers the offset and
13025    size of each of the DWP version 2 debugging sections that we are interested
13026    in.  This is split into a separate function because we don't know if we
13027    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13028
13029 static void
13030 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13031 {
13032   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13033   const struct dwop_section_names *names = &dwop_section_names;
13034   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13035
13036   /* Record the ELF section number for later lookup: this is what the
13037      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13038   gdb_assert (elf_section_nr < dwp_file->num_sections);
13039   dwp_file->elf_sections[elf_section_nr] = sectp;
13040
13041   /* Look for specific sections that we need.  */
13042   if (section_is_p (sectp->name, &names->abbrev_dwo))
13043     {
13044       dwp_file->sections.abbrev.s.section = sectp;
13045       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13046     }
13047   else if (section_is_p (sectp->name, &names->info_dwo))
13048     {
13049       dwp_file->sections.info.s.section = sectp;
13050       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13051     }
13052   else if (section_is_p (sectp->name, &names->line_dwo))
13053     {
13054       dwp_file->sections.line.s.section = sectp;
13055       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13056     }
13057   else if (section_is_p (sectp->name, &names->loc_dwo))
13058     {
13059       dwp_file->sections.loc.s.section = sectp;
13060       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13061     }
13062   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13063     {
13064       dwp_file->sections.macinfo.s.section = sectp;
13065       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13066     }
13067   else if (section_is_p (sectp->name, &names->macro_dwo))
13068     {
13069       dwp_file->sections.macro.s.section = sectp;
13070       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13071     }
13072   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13073     {
13074       dwp_file->sections.str_offsets.s.section = sectp;
13075       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13076     }
13077   else if (section_is_p (sectp->name, &names->types_dwo))
13078     {
13079       dwp_file->sections.types.s.section = sectp;
13080       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13081     }
13082 }
13083
13084 /* Hash function for dwp_file loaded CUs/TUs.  */
13085
13086 static hashval_t
13087 hash_dwp_loaded_cutus (const void *item)
13088 {
13089   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13090
13091   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13092   return dwo_unit->signature;
13093 }
13094
13095 /* Equality function for dwp_file loaded CUs/TUs.  */
13096
13097 static int
13098 eq_dwp_loaded_cutus (const void *a, const void *b)
13099 {
13100   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13101   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13102
13103   return dua->signature == dub->signature;
13104 }
13105
13106 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13107
13108 static htab_t
13109 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13110 {
13111   return htab_create_alloc_ex (3,
13112                                hash_dwp_loaded_cutus,
13113                                eq_dwp_loaded_cutus,
13114                                NULL,
13115                                &objfile->objfile_obstack,
13116                                hashtab_obstack_allocate,
13117                                dummy_obstack_deallocate);
13118 }
13119
13120 /* Try to open DWP file FILE_NAME.
13121    The result is the bfd handle of the file.
13122    If there is a problem finding or opening the file, return NULL.
13123    Upon success, the canonicalized path of the file is stored in the bfd,
13124    same as symfile_bfd_open.  */
13125
13126 static gdb_bfd_ref_ptr
13127 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13128                const char *file_name)
13129 {
13130   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13131                                             1 /*is_dwp*/,
13132                                             1 /*search_cwd*/));
13133   if (abfd != NULL)
13134     return abfd;
13135
13136   /* Work around upstream bug 15652.
13137      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13138      [Whether that's a "bug" is debatable, but it is getting in our way.]
13139      We have no real idea where the dwp file is, because gdb's realpath-ing
13140      of the executable's path may have discarded the needed info.
13141      [IWBN if the dwp file name was recorded in the executable, akin to
13142      .gnu_debuglink, but that doesn't exist yet.]
13143      Strip the directory from FILE_NAME and search again.  */
13144   if (*debug_file_directory != '\0')
13145     {
13146       /* Don't implicitly search the current directory here.
13147          If the user wants to search "." to handle this case,
13148          it must be added to debug-file-directory.  */
13149       return try_open_dwop_file (dwarf2_per_objfile,
13150                                  lbasename (file_name), 1 /*is_dwp*/,
13151                                  0 /*search_cwd*/);
13152     }
13153
13154   return NULL;
13155 }
13156
13157 /* Initialize the use of the DWP file for the current objfile.
13158    By convention the name of the DWP file is ${objfile}.dwp.
13159    The result is NULL if it can't be found.  */
13160
13161 static std::unique_ptr<struct dwp_file>
13162 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13163 {
13164   struct objfile *objfile = dwarf2_per_objfile->objfile;
13165
13166   /* Try to find first .dwp for the binary file before any symbolic links
13167      resolving.  */
13168
13169   /* If the objfile is a debug file, find the name of the real binary
13170      file and get the name of dwp file from there.  */
13171   std::string dwp_name;
13172   if (objfile->separate_debug_objfile_backlink != NULL)
13173     {
13174       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13175       const char *backlink_basename = lbasename (backlink->original_name);
13176
13177       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13178     }
13179   else
13180     dwp_name = objfile->original_name;
13181
13182   dwp_name += ".dwp";
13183
13184   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13185   if (dbfd == NULL
13186       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13187     {
13188       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13189       dwp_name = objfile_name (objfile);
13190       dwp_name += ".dwp";
13191       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13192     }
13193
13194   if (dbfd == NULL)
13195     {
13196       if (dwarf_read_debug)
13197         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13198       return std::unique_ptr<dwp_file> ();
13199     }
13200
13201   const char *name = bfd_get_filename (dbfd.get ());
13202   std::unique_ptr<struct dwp_file> dwp_file
13203     (new struct dwp_file (name, std::move (dbfd)));
13204
13205   dwp_file->num_sections = elf_numsections (dwp_file->dbfd);
13206   dwp_file->elf_sections =
13207     OBSTACK_CALLOC (&objfile->objfile_obstack,
13208                     dwp_file->num_sections, asection *);
13209
13210   bfd_map_over_sections (dwp_file->dbfd.get (),
13211                          dwarf2_locate_common_dwp_sections,
13212                          dwp_file.get ());
13213
13214   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13215                                          0);
13216
13217   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13218                                          1);
13219
13220   /* The DWP file version is stored in the hash table.  Oh well.  */
13221   if (dwp_file->cus && dwp_file->tus
13222       && dwp_file->cus->version != dwp_file->tus->version)
13223     {
13224       /* Technically speaking, we should try to limp along, but this is
13225          pretty bizarre.  We use pulongest here because that's the established
13226          portability solution (e.g, we cannot use %u for uint32_t).  */
13227       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13228                " TU version %s [in DWP file %s]"),
13229              pulongest (dwp_file->cus->version),
13230              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13231     }
13232
13233   if (dwp_file->cus)
13234     dwp_file->version = dwp_file->cus->version;
13235   else if (dwp_file->tus)
13236     dwp_file->version = dwp_file->tus->version;
13237   else
13238     dwp_file->version = 2;
13239
13240   if (dwp_file->version == 2)
13241     bfd_map_over_sections (dwp_file->dbfd.get (),
13242                            dwarf2_locate_v2_dwp_sections,
13243                            dwp_file.get ());
13244
13245   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13246   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13247
13248   if (dwarf_read_debug)
13249     {
13250       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13251       fprintf_unfiltered (gdb_stdlog,
13252                           "    %s CUs, %s TUs\n",
13253                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13254                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13255     }
13256
13257   return dwp_file;
13258 }
13259
13260 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13261
13262 static struct dwp_file *
13263 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13264 {
13265   if (! dwarf2_per_objfile->dwp_checked)
13266     {
13267       dwarf2_per_objfile->dwp_file
13268         = open_and_init_dwp_file (dwarf2_per_objfile);
13269       dwarf2_per_objfile->dwp_checked = 1;
13270     }
13271   return dwarf2_per_objfile->dwp_file.get ();
13272 }
13273
13274 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13275    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13276    or in the DWP file for the objfile, referenced by THIS_UNIT.
13277    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13278    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13279
13280    This is called, for example, when wanting to read a variable with a
13281    complex location.  Therefore we don't want to do file i/o for every call.
13282    Therefore we don't want to look for a DWO file on every call.
13283    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13284    then we check if we've already seen DWO_NAME, and only THEN do we check
13285    for a DWO file.
13286
13287    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13288    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13289
13290 static struct dwo_unit *
13291 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13292                  const char *dwo_name, const char *comp_dir,
13293                  ULONGEST signature, int is_debug_types)
13294 {
13295   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13296   struct objfile *objfile = dwarf2_per_objfile->objfile;
13297   const char *kind = is_debug_types ? "TU" : "CU";
13298   void **dwo_file_slot;
13299   struct dwo_file *dwo_file;
13300   struct dwp_file *dwp_file;
13301
13302   /* First see if there's a DWP file.
13303      If we have a DWP file but didn't find the DWO inside it, don't
13304      look for the original DWO file.  It makes gdb behave differently
13305      depending on whether one is debugging in the build tree.  */
13306
13307   dwp_file = get_dwp_file (dwarf2_per_objfile);
13308   if (dwp_file != NULL)
13309     {
13310       const struct dwp_hash_table *dwp_htab =
13311         is_debug_types ? dwp_file->tus : dwp_file->cus;
13312
13313       if (dwp_htab != NULL)
13314         {
13315           struct dwo_unit *dwo_cutu =
13316             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13317                                     signature, is_debug_types);
13318
13319           if (dwo_cutu != NULL)
13320             {
13321               if (dwarf_read_debug)
13322                 {
13323                   fprintf_unfiltered (gdb_stdlog,
13324                                       "Virtual DWO %s %s found: @%s\n",
13325                                       kind, hex_string (signature),
13326                                       host_address_to_string (dwo_cutu));
13327                 }
13328               return dwo_cutu;
13329             }
13330         }
13331     }
13332   else
13333     {
13334       /* No DWP file, look for the DWO file.  */
13335
13336       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13337                                             dwo_name, comp_dir);
13338       if (*dwo_file_slot == NULL)
13339         {
13340           /* Read in the file and build a table of the CUs/TUs it contains.  */
13341           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13342         }
13343       /* NOTE: This will be NULL if unable to open the file.  */
13344       dwo_file = (struct dwo_file *) *dwo_file_slot;
13345
13346       if (dwo_file != NULL)
13347         {
13348           struct dwo_unit *dwo_cutu = NULL;
13349
13350           if (is_debug_types && dwo_file->tus)
13351             {
13352               struct dwo_unit find_dwo_cutu;
13353
13354               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13355               find_dwo_cutu.signature = signature;
13356               dwo_cutu
13357                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13358             }
13359           else if (!is_debug_types && dwo_file->cus)
13360             {
13361               struct dwo_unit find_dwo_cutu;
13362
13363               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13364               find_dwo_cutu.signature = signature;
13365               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13366                                                        &find_dwo_cutu);
13367             }
13368
13369           if (dwo_cutu != NULL)
13370             {
13371               if (dwarf_read_debug)
13372                 {
13373                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13374                                       kind, dwo_name, hex_string (signature),
13375                                       host_address_to_string (dwo_cutu));
13376                 }
13377               return dwo_cutu;
13378             }
13379         }
13380     }
13381
13382   /* We didn't find it.  This could mean a dwo_id mismatch, or
13383      someone deleted the DWO/DWP file, or the search path isn't set up
13384      correctly to find the file.  */
13385
13386   if (dwarf_read_debug)
13387     {
13388       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13389                           kind, dwo_name, hex_string (signature));
13390     }
13391
13392   /* This is a warning and not a complaint because it can be caused by
13393      pilot error (e.g., user accidentally deleting the DWO).  */
13394   {
13395     /* Print the name of the DWP file if we looked there, helps the user
13396        better diagnose the problem.  */
13397     std::string dwp_text;
13398
13399     if (dwp_file != NULL)
13400       dwp_text = string_printf (" [in DWP file %s]",
13401                                 lbasename (dwp_file->name));
13402
13403     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13404                " [in module %s]"),
13405              kind, dwo_name, hex_string (signature),
13406              dwp_text.c_str (),
13407              this_unit->is_debug_types ? "TU" : "CU",
13408              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13409   }
13410   return NULL;
13411 }
13412
13413 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13414    See lookup_dwo_cutu_unit for details.  */
13415
13416 static struct dwo_unit *
13417 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13418                       const char *dwo_name, const char *comp_dir,
13419                       ULONGEST signature)
13420 {
13421   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13422 }
13423
13424 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13425    See lookup_dwo_cutu_unit for details.  */
13426
13427 static struct dwo_unit *
13428 lookup_dwo_type_unit (struct signatured_type *this_tu,
13429                       const char *dwo_name, const char *comp_dir)
13430 {
13431   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13432 }
13433
13434 /* Traversal function for queue_and_load_all_dwo_tus.  */
13435
13436 static int
13437 queue_and_load_dwo_tu (void **slot, void *info)
13438 {
13439   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13440   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13441   ULONGEST signature = dwo_unit->signature;
13442   struct signatured_type *sig_type =
13443     lookup_dwo_signatured_type (per_cu->cu, signature);
13444
13445   if (sig_type != NULL)
13446     {
13447       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13448
13449       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13450          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13451          while processing PER_CU.  */
13452       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13453         load_full_type_unit (sig_cu);
13454       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13455     }
13456
13457   return 1;
13458 }
13459
13460 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13461    The DWO may have the only definition of the type, though it may not be
13462    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13463    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13464
13465 static void
13466 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13467 {
13468   struct dwo_unit *dwo_unit;
13469   struct dwo_file *dwo_file;
13470
13471   gdb_assert (!per_cu->is_debug_types);
13472   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13473   gdb_assert (per_cu->cu != NULL);
13474
13475   dwo_unit = per_cu->cu->dwo_unit;
13476   gdb_assert (dwo_unit != NULL);
13477
13478   dwo_file = dwo_unit->dwo_file;
13479   if (dwo_file->tus != NULL)
13480     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13481 }
13482
13483 /* Read in various DIEs.  */
13484
13485 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13486    Inherit only the children of the DW_AT_abstract_origin DIE not being
13487    already referenced by DW_AT_abstract_origin from the children of the
13488    current DIE.  */
13489
13490 static void
13491 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13492 {
13493   struct die_info *child_die;
13494   sect_offset *offsetp;
13495   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13496   struct die_info *origin_die;
13497   /* Iterator of the ORIGIN_DIE children.  */
13498   struct die_info *origin_child_die;
13499   struct attribute *attr;
13500   struct dwarf2_cu *origin_cu;
13501   struct pending **origin_previous_list_in_scope;
13502
13503   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13504   if (!attr)
13505     return;
13506
13507   /* Note that following die references may follow to a die in a
13508      different cu.  */
13509
13510   origin_cu = cu;
13511   origin_die = follow_die_ref (die, attr, &origin_cu);
13512
13513   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13514      symbols in.  */
13515   origin_previous_list_in_scope = origin_cu->list_in_scope;
13516   origin_cu->list_in_scope = cu->list_in_scope;
13517
13518   if (die->tag != origin_die->tag
13519       && !(die->tag == DW_TAG_inlined_subroutine
13520            && origin_die->tag == DW_TAG_subprogram))
13521     complaint (_("DIE %s and its abstract origin %s have different tags"),
13522                sect_offset_str (die->sect_off),
13523                sect_offset_str (origin_die->sect_off));
13524
13525   std::vector<sect_offset> offsets;
13526
13527   for (child_die = die->child;
13528        child_die && child_die->tag;
13529        child_die = sibling_die (child_die))
13530     {
13531       struct die_info *child_origin_die;
13532       struct dwarf2_cu *child_origin_cu;
13533
13534       /* We are trying to process concrete instance entries:
13535          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13536          it's not relevant to our analysis here. i.e. detecting DIEs that are
13537          present in the abstract instance but not referenced in the concrete
13538          one.  */
13539       if (child_die->tag == DW_TAG_call_site
13540           || child_die->tag == DW_TAG_GNU_call_site)
13541         continue;
13542
13543       /* For each CHILD_DIE, find the corresponding child of
13544          ORIGIN_DIE.  If there is more than one layer of
13545          DW_AT_abstract_origin, follow them all; there shouldn't be,
13546          but GCC versions at least through 4.4 generate this (GCC PR
13547          40573).  */
13548       child_origin_die = child_die;
13549       child_origin_cu = cu;
13550       while (1)
13551         {
13552           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13553                               child_origin_cu);
13554           if (attr == NULL)
13555             break;
13556           child_origin_die = follow_die_ref (child_origin_die, attr,
13557                                              &child_origin_cu);
13558         }
13559
13560       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13561          counterpart may exist.  */
13562       if (child_origin_die != child_die)
13563         {
13564           if (child_die->tag != child_origin_die->tag
13565               && !(child_die->tag == DW_TAG_inlined_subroutine
13566                    && child_origin_die->tag == DW_TAG_subprogram))
13567             complaint (_("Child DIE %s and its abstract origin %s have "
13568                          "different tags"),
13569                        sect_offset_str (child_die->sect_off),
13570                        sect_offset_str (child_origin_die->sect_off));
13571           if (child_origin_die->parent != origin_die)
13572             complaint (_("Child DIE %s and its abstract origin %s have "
13573                          "different parents"),
13574                        sect_offset_str (child_die->sect_off),
13575                        sect_offset_str (child_origin_die->sect_off));
13576           else
13577             offsets.push_back (child_origin_die->sect_off);
13578         }
13579     }
13580   std::sort (offsets.begin (), offsets.end ());
13581   sect_offset *offsets_end = offsets.data () + offsets.size ();
13582   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13583     if (offsetp[-1] == *offsetp)
13584       complaint (_("Multiple children of DIE %s refer "
13585                    "to DIE %s as their abstract origin"),
13586                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13587
13588   offsetp = offsets.data ();
13589   origin_child_die = origin_die->child;
13590   while (origin_child_die && origin_child_die->tag)
13591     {
13592       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13593       while (offsetp < offsets_end
13594              && *offsetp < origin_child_die->sect_off)
13595         offsetp++;
13596       if (offsetp >= offsets_end
13597           || *offsetp > origin_child_die->sect_off)
13598         {
13599           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13600              Check whether we're already processing ORIGIN_CHILD_DIE.
13601              This can happen with mutually referenced abstract_origins.
13602              PR 16581.  */
13603           if (!origin_child_die->in_process)
13604             process_die (origin_child_die, origin_cu);
13605         }
13606       origin_child_die = sibling_die (origin_child_die);
13607     }
13608   origin_cu->list_in_scope = origin_previous_list_in_scope;
13609 }
13610
13611 static void
13612 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13613 {
13614   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13615   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13616   struct context_stack *newobj;
13617   CORE_ADDR lowpc;
13618   CORE_ADDR highpc;
13619   struct die_info *child_die;
13620   struct attribute *attr, *call_line, *call_file;
13621   const char *name;
13622   CORE_ADDR baseaddr;
13623   struct block *block;
13624   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13625   std::vector<struct symbol *> template_args;
13626   struct template_symbol *templ_func = NULL;
13627
13628   if (inlined_func)
13629     {
13630       /* If we do not have call site information, we can't show the
13631          caller of this inlined function.  That's too confusing, so
13632          only use the scope for local variables.  */
13633       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13634       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13635       if (call_line == NULL || call_file == NULL)
13636         {
13637           read_lexical_block_scope (die, cu);
13638           return;
13639         }
13640     }
13641
13642   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13643
13644   name = dwarf2_name (die, cu);
13645
13646   /* Ignore functions with missing or empty names.  These are actually
13647      illegal according to the DWARF standard.  */
13648   if (name == NULL)
13649     {
13650       complaint (_("missing name for subprogram DIE at %s"),
13651                  sect_offset_str (die->sect_off));
13652       return;
13653     }
13654
13655   /* Ignore functions with missing or invalid low and high pc attributes.  */
13656   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13657       <= PC_BOUNDS_INVALID)
13658     {
13659       attr = dwarf2_attr (die, DW_AT_external, cu);
13660       if (!attr || !DW_UNSND (attr))
13661         complaint (_("cannot get low and high bounds "
13662                      "for subprogram DIE at %s"),
13663                    sect_offset_str (die->sect_off));
13664       return;
13665     }
13666
13667   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13668   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13669
13670   /* If we have any template arguments, then we must allocate a
13671      different sort of symbol.  */
13672   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13673     {
13674       if (child_die->tag == DW_TAG_template_type_param
13675           || child_die->tag == DW_TAG_template_value_param)
13676         {
13677           templ_func = allocate_template_symbol (objfile);
13678           templ_func->subclass = SYMBOL_TEMPLATE;
13679           break;
13680         }
13681     }
13682
13683   newobj = cu->get_builder ()->push_context (0, lowpc);
13684   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13685                              (struct symbol *) templ_func);
13686
13687   if (dwarf2_flag_true_p (die, DW_AT_main_subprogram, cu))
13688     set_objfile_main_name (objfile, SYMBOL_LINKAGE_NAME (newobj->name),
13689                            cu->language);
13690
13691   /* If there is a location expression for DW_AT_frame_base, record
13692      it.  */
13693   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13694   if (attr)
13695     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13696
13697   /* If there is a location for the static link, record it.  */
13698   newobj->static_link = NULL;
13699   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13700   if (attr)
13701     {
13702       newobj->static_link
13703         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13704       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13705     }
13706
13707   cu->list_in_scope = cu->get_builder ()->get_local_symbols ();
13708
13709   if (die->child != NULL)
13710     {
13711       child_die = die->child;
13712       while (child_die && child_die->tag)
13713         {
13714           if (child_die->tag == DW_TAG_template_type_param
13715               || child_die->tag == DW_TAG_template_value_param)
13716             {
13717               struct symbol *arg = new_symbol (child_die, NULL, cu);
13718
13719               if (arg != NULL)
13720                 template_args.push_back (arg);
13721             }
13722           else
13723             process_die (child_die, cu);
13724           child_die = sibling_die (child_die);
13725         }
13726     }
13727
13728   inherit_abstract_dies (die, cu);
13729
13730   /* If we have a DW_AT_specification, we might need to import using
13731      directives from the context of the specification DIE.  See the
13732      comment in determine_prefix.  */
13733   if (cu->language == language_cplus
13734       && dwarf2_attr (die, DW_AT_specification, cu))
13735     {
13736       struct dwarf2_cu *spec_cu = cu;
13737       struct die_info *spec_die = die_specification (die, &spec_cu);
13738
13739       while (spec_die)
13740         {
13741           child_die = spec_die->child;
13742           while (child_die && child_die->tag)
13743             {
13744               if (child_die->tag == DW_TAG_imported_module)
13745                 process_die (child_die, spec_cu);
13746               child_die = sibling_die (child_die);
13747             }
13748
13749           /* In some cases, GCC generates specification DIEs that
13750              themselves contain DW_AT_specification attributes.  */
13751           spec_die = die_specification (spec_die, &spec_cu);
13752         }
13753     }
13754
13755   struct context_stack cstk = cu->get_builder ()->pop_context ();
13756   /* Make a block for the local symbols within.  */
13757   block = cu->get_builder ()->finish_block (cstk.name, cstk.old_blocks,
13758                                      cstk.static_link, lowpc, highpc);
13759
13760   /* For C++, set the block's scope.  */
13761   if ((cu->language == language_cplus
13762        || cu->language == language_fortran
13763        || cu->language == language_d
13764        || cu->language == language_rust)
13765       && cu->processing_has_namespace_info)
13766     block_set_scope (block, determine_prefix (die, cu),
13767                      &objfile->objfile_obstack);
13768
13769   /* If we have address ranges, record them.  */
13770   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13771
13772   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13773
13774   /* Attach template arguments to function.  */
13775   if (!template_args.empty ())
13776     {
13777       gdb_assert (templ_func != NULL);
13778
13779       templ_func->n_template_arguments = template_args.size ();
13780       templ_func->template_arguments
13781         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13782                      templ_func->n_template_arguments);
13783       memcpy (templ_func->template_arguments,
13784               template_args.data (),
13785               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13786
13787       /* Make sure that the symtab is set on the new symbols.  Even
13788          though they don't appear in this symtab directly, other parts
13789          of gdb assume that symbols do, and this is reasonably
13790          true.  */
13791       for (symbol *sym : template_args)
13792         symbol_set_symtab (sym, symbol_symtab (templ_func));
13793     }
13794
13795   /* In C++, we can have functions nested inside functions (e.g., when
13796      a function declares a class that has methods).  This means that
13797      when we finish processing a function scope, we may need to go
13798      back to building a containing block's symbol lists.  */
13799   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13800   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13801
13802   /* If we've finished processing a top-level function, subsequent
13803      symbols go in the file symbol list.  */
13804   if (cu->get_builder ()->outermost_context_p ())
13805     cu->list_in_scope = cu->get_builder ()->get_file_symbols ();
13806 }
13807
13808 /* Process all the DIES contained within a lexical block scope.  Start
13809    a new scope, process the dies, and then close the scope.  */
13810
13811 static void
13812 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13813 {
13814   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13815   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13816   CORE_ADDR lowpc, highpc;
13817   struct die_info *child_die;
13818   CORE_ADDR baseaddr;
13819
13820   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13821
13822   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13823   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13824      as multiple lexical blocks?  Handling children in a sane way would
13825      be nasty.  Might be easier to properly extend generic blocks to
13826      describe ranges.  */
13827   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13828     {
13829     case PC_BOUNDS_NOT_PRESENT:
13830       /* DW_TAG_lexical_block has no attributes, process its children as if
13831          there was no wrapping by that DW_TAG_lexical_block.
13832          GCC does no longer produces such DWARF since GCC r224161.  */
13833       for (child_die = die->child;
13834            child_die != NULL && child_die->tag;
13835            child_die = sibling_die (child_die))
13836         process_die (child_die, cu);
13837       return;
13838     case PC_BOUNDS_INVALID:
13839       return;
13840     }
13841   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13842   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13843
13844   cu->get_builder ()->push_context (0, lowpc);
13845   if (die->child != NULL)
13846     {
13847       child_die = die->child;
13848       while (child_die && child_die->tag)
13849         {
13850           process_die (child_die, cu);
13851           child_die = sibling_die (child_die);
13852         }
13853     }
13854   inherit_abstract_dies (die, cu);
13855   struct context_stack cstk = cu->get_builder ()->pop_context ();
13856
13857   if (*cu->get_builder ()->get_local_symbols () != NULL
13858       || (*cu->get_builder ()->get_local_using_directives ()) != NULL)
13859     {
13860       struct block *block
13861         = cu->get_builder ()->finish_block (0, cstk.old_blocks, NULL,
13862                                      cstk.start_addr, highpc);
13863
13864       /* Note that recording ranges after traversing children, as we
13865          do here, means that recording a parent's ranges entails
13866          walking across all its children's ranges as they appear in
13867          the address map, which is quadratic behavior.
13868
13869          It would be nicer to record the parent's ranges before
13870          traversing its children, simply overriding whatever you find
13871          there.  But since we don't even decide whether to create a
13872          block until after we've traversed its children, that's hard
13873          to do.  */
13874       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13875     }
13876   *cu->get_builder ()->get_local_symbols () = cstk.locals;
13877   cu->get_builder ()->set_local_using_directives (cstk.local_using_directives);
13878 }
13879
13880 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13881
13882 static void
13883 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13884 {
13885   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13886   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13887   CORE_ADDR pc, baseaddr;
13888   struct attribute *attr;
13889   struct call_site *call_site, call_site_local;
13890   void **slot;
13891   int nparams;
13892   struct die_info *child_die;
13893
13894   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13895
13896   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13897   if (attr == NULL)
13898     {
13899       /* This was a pre-DWARF-5 GNU extension alias
13900          for DW_AT_call_return_pc.  */
13901       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13902     }
13903   if (!attr)
13904     {
13905       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13906                    "DIE %s [in module %s]"),
13907                  sect_offset_str (die->sect_off), objfile_name (objfile));
13908       return;
13909     }
13910   pc = attr_value_as_address (attr) + baseaddr;
13911   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13912
13913   if (cu->call_site_htab == NULL)
13914     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13915                                                NULL, &objfile->objfile_obstack,
13916                                                hashtab_obstack_allocate, NULL);
13917   call_site_local.pc = pc;
13918   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13919   if (*slot != NULL)
13920     {
13921       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13922                    "DIE %s [in module %s]"),
13923                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13924                  objfile_name (objfile));
13925       return;
13926     }
13927
13928   /* Count parameters at the caller.  */
13929
13930   nparams = 0;
13931   for (child_die = die->child; child_die && child_die->tag;
13932        child_die = sibling_die (child_die))
13933     {
13934       if (child_die->tag != DW_TAG_call_site_parameter
13935           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13936         {
13937           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13938                        "DW_TAG_call_site child DIE %s [in module %s]"),
13939                      child_die->tag, sect_offset_str (child_die->sect_off),
13940                      objfile_name (objfile));
13941           continue;
13942         }
13943
13944       nparams++;
13945     }
13946
13947   call_site
13948     = ((struct call_site *)
13949        obstack_alloc (&objfile->objfile_obstack,
13950                       sizeof (*call_site)
13951                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13952   *slot = call_site;
13953   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13954   call_site->pc = pc;
13955
13956   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13957       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13958     {
13959       struct die_info *func_die;
13960
13961       /* Skip also over DW_TAG_inlined_subroutine.  */
13962       for (func_die = die->parent;
13963            func_die && func_die->tag != DW_TAG_subprogram
13964            && func_die->tag != DW_TAG_subroutine_type;
13965            func_die = func_die->parent);
13966
13967       /* DW_AT_call_all_calls is a superset
13968          of DW_AT_call_all_tail_calls.  */
13969       if (func_die
13970           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13971           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13972           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13973           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13974         {
13975           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13976              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13977              both the initial caller containing the real return address PC and
13978              the final callee containing the current PC of a chain of tail
13979              calls do not need to have the tail call list complete.  But any
13980              function candidate for a virtual tail call frame searched via
13981              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13982              determined unambiguously.  */
13983         }
13984       else
13985         {
13986           struct type *func_type = NULL;
13987
13988           if (func_die)
13989             func_type = get_die_type (func_die, cu);
13990           if (func_type != NULL)
13991             {
13992               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13993
13994               /* Enlist this call site to the function.  */
13995               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13996               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13997             }
13998           else
13999             complaint (_("Cannot find function owning DW_TAG_call_site "
14000                          "DIE %s [in module %s]"),
14001                        sect_offset_str (die->sect_off), objfile_name (objfile));
14002         }
14003     }
14004
14005   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14006   if (attr == NULL)
14007     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14008   if (attr == NULL)
14009     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14010   if (attr == NULL)
14011     {
14012       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14013       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14014     }
14015   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14016   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14017     /* Keep NULL DWARF_BLOCK.  */;
14018   else if (attr_form_is_block (attr))
14019     {
14020       struct dwarf2_locexpr_baton *dlbaton;
14021
14022       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14023       dlbaton->data = DW_BLOCK (attr)->data;
14024       dlbaton->size = DW_BLOCK (attr)->size;
14025       dlbaton->per_cu = cu->per_cu;
14026
14027       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14028     }
14029   else if (attr_form_is_ref (attr))
14030     {
14031       struct dwarf2_cu *target_cu = cu;
14032       struct die_info *target_die;
14033
14034       target_die = follow_die_ref (die, attr, &target_cu);
14035       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14036       if (die_is_declaration (target_die, target_cu))
14037         {
14038           const char *target_physname;
14039
14040           /* Prefer the mangled name; otherwise compute the demangled one.  */
14041           target_physname = dw2_linkage_name (target_die, target_cu);
14042           if (target_physname == NULL)
14043             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14044           if (target_physname == NULL)
14045             complaint (_("DW_AT_call_target target DIE has invalid "
14046                          "physname, for referencing DIE %s [in module %s]"),
14047                        sect_offset_str (die->sect_off), objfile_name (objfile));
14048           else
14049             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14050         }
14051       else
14052         {
14053           CORE_ADDR lowpc;
14054
14055           /* DW_AT_entry_pc should be preferred.  */
14056           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14057               <= PC_BOUNDS_INVALID)
14058             complaint (_("DW_AT_call_target target DIE has invalid "
14059                          "low pc, for referencing DIE %s [in module %s]"),
14060                        sect_offset_str (die->sect_off), objfile_name (objfile));
14061           else
14062             {
14063               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14064               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14065             }
14066         }
14067     }
14068   else
14069     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14070                  "block nor reference, for DIE %s [in module %s]"),
14071                sect_offset_str (die->sect_off), objfile_name (objfile));
14072
14073   call_site->per_cu = cu->per_cu;
14074
14075   for (child_die = die->child;
14076        child_die && child_die->tag;
14077        child_die = sibling_die (child_die))
14078     {
14079       struct call_site_parameter *parameter;
14080       struct attribute *loc, *origin;
14081
14082       if (child_die->tag != DW_TAG_call_site_parameter
14083           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14084         {
14085           /* Already printed the complaint above.  */
14086           continue;
14087         }
14088
14089       gdb_assert (call_site->parameter_count < nparams);
14090       parameter = &call_site->parameter[call_site->parameter_count];
14091
14092       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14093          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14094          register is contained in DW_AT_call_value.  */
14095
14096       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14097       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14098       if (origin == NULL)
14099         {
14100           /* This was a pre-DWARF-5 GNU extension alias
14101              for DW_AT_call_parameter.  */
14102           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14103         }
14104       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14105         {
14106           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14107
14108           sect_offset sect_off
14109             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14110           if (!offset_in_cu_p (&cu->header, sect_off))
14111             {
14112               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14113                  binding can be done only inside one CU.  Such referenced DIE
14114                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14115               complaint (_("DW_AT_call_parameter offset is not in CU for "
14116                            "DW_TAG_call_site child DIE %s [in module %s]"),
14117                          sect_offset_str (child_die->sect_off),
14118                          objfile_name (objfile));
14119               continue;
14120             }
14121           parameter->u.param_cu_off
14122             = (cu_offset) (sect_off - cu->header.sect_off);
14123         }
14124       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14125         {
14126           complaint (_("No DW_FORM_block* DW_AT_location for "
14127                        "DW_TAG_call_site child DIE %s [in module %s]"),
14128                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14129           continue;
14130         }
14131       else
14132         {
14133           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14134             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14135           if (parameter->u.dwarf_reg != -1)
14136             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14137           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14138                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14139                                              &parameter->u.fb_offset))
14140             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14141           else
14142             {
14143               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14144                            "for DW_FORM_block* DW_AT_location is supported for "
14145                            "DW_TAG_call_site child DIE %s "
14146                            "[in module %s]"),
14147                          sect_offset_str (child_die->sect_off),
14148                          objfile_name (objfile));
14149               continue;
14150             }
14151         }
14152
14153       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14154       if (attr == NULL)
14155         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14156       if (!attr_form_is_block (attr))
14157         {
14158           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14159                        "DW_TAG_call_site child DIE %s [in module %s]"),
14160                      sect_offset_str (child_die->sect_off),
14161                      objfile_name (objfile));
14162           continue;
14163         }
14164       parameter->value = DW_BLOCK (attr)->data;
14165       parameter->value_size = DW_BLOCK (attr)->size;
14166
14167       /* Parameters are not pre-cleared by memset above.  */
14168       parameter->data_value = NULL;
14169       parameter->data_value_size = 0;
14170       call_site->parameter_count++;
14171
14172       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14173       if (attr == NULL)
14174         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14175       if (attr)
14176         {
14177           if (!attr_form_is_block (attr))
14178             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14179                          "DW_TAG_call_site child DIE %s [in module %s]"),
14180                        sect_offset_str (child_die->sect_off),
14181                        objfile_name (objfile));
14182           else
14183             {
14184               parameter->data_value = DW_BLOCK (attr)->data;
14185               parameter->data_value_size = DW_BLOCK (attr)->size;
14186             }
14187         }
14188     }
14189 }
14190
14191 /* Helper function for read_variable.  If DIE represents a virtual
14192    table, then return the type of the concrete object that is
14193    associated with the virtual table.  Otherwise, return NULL.  */
14194
14195 static struct type *
14196 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14197 {
14198   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14199   if (attr == NULL)
14200     return NULL;
14201
14202   /* Find the type DIE.  */
14203   struct die_info *type_die = NULL;
14204   struct dwarf2_cu *type_cu = cu;
14205
14206   if (attr_form_is_ref (attr))
14207     type_die = follow_die_ref (die, attr, &type_cu);
14208   if (type_die == NULL)
14209     return NULL;
14210
14211   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14212     return NULL;
14213   return die_containing_type (type_die, type_cu);
14214 }
14215
14216 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14217
14218 static void
14219 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14220 {
14221   struct rust_vtable_symbol *storage = NULL;
14222
14223   if (cu->language == language_rust)
14224     {
14225       struct type *containing_type = rust_containing_type (die, cu);
14226
14227       if (containing_type != NULL)
14228         {
14229           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14230
14231           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14232                                     struct rust_vtable_symbol);
14233           initialize_objfile_symbol (storage);
14234           storage->concrete_type = containing_type;
14235           storage->subclass = SYMBOL_RUST_VTABLE;
14236         }
14237     }
14238
14239   struct symbol *res = new_symbol (die, NULL, cu, storage);
14240   struct attribute *abstract_origin
14241     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14242   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
14243   if (res == NULL && loc && abstract_origin)
14244     {
14245       /* We have a variable without a name, but with a location and an abstract
14246          origin.  This may be a concrete instance of an abstract variable
14247          referenced from an DW_OP_GNU_variable_value, so save it to find it back
14248          later.  */
14249       struct dwarf2_cu *origin_cu = cu;
14250       struct die_info *origin_die
14251         = follow_die_ref (die, abstract_origin, &origin_cu);
14252       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
14253       dpo->abstract_to_concrete[origin_die->sect_off].push_back (die->sect_off);
14254     }
14255 }
14256
14257 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14258    reading .debug_rnglists.
14259    Callback's type should be:
14260     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14261    Return true if the attributes are present and valid, otherwise,
14262    return false.  */
14263
14264 template <typename Callback>
14265 static bool
14266 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14267                          Callback &&callback)
14268 {
14269   struct dwarf2_per_objfile *dwarf2_per_objfile
14270     = cu->per_cu->dwarf2_per_objfile;
14271   struct objfile *objfile = dwarf2_per_objfile->objfile;
14272   bfd *obfd = objfile->obfd;
14273   /* Base address selection entry.  */
14274   CORE_ADDR base;
14275   int found_base;
14276   const gdb_byte *buffer;
14277   CORE_ADDR baseaddr;
14278   bool overflow = false;
14279
14280   found_base = cu->base_known;
14281   base = cu->base_address;
14282
14283   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14284   if (offset >= dwarf2_per_objfile->rnglists.size)
14285     {
14286       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14287                  offset);
14288       return false;
14289     }
14290   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14291
14292   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14293
14294   while (1)
14295     {
14296       /* Initialize it due to a false compiler warning.  */
14297       CORE_ADDR range_beginning = 0, range_end = 0;
14298       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14299                                  + dwarf2_per_objfile->rnglists.size);
14300       unsigned int bytes_read;
14301
14302       if (buffer == buf_end)
14303         {
14304           overflow = true;
14305           break;
14306         }
14307       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14308       switch (rlet)
14309         {
14310         case DW_RLE_end_of_list:
14311           break;
14312         case DW_RLE_base_address:
14313           if (buffer + cu->header.addr_size > buf_end)
14314             {
14315               overflow = true;
14316               break;
14317             }
14318           base = read_address (obfd, buffer, cu, &bytes_read);
14319           found_base = 1;
14320           buffer += bytes_read;
14321           break;
14322         case DW_RLE_start_length:
14323           if (buffer + cu->header.addr_size > buf_end)
14324             {
14325               overflow = true;
14326               break;
14327             }
14328           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14329           buffer += bytes_read;
14330           range_end = (range_beginning
14331                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14332           buffer += bytes_read;
14333           if (buffer > buf_end)
14334             {
14335               overflow = true;
14336               break;
14337             }
14338           break;
14339         case DW_RLE_offset_pair:
14340           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14341           buffer += bytes_read;
14342           if (buffer > buf_end)
14343             {
14344               overflow = true;
14345               break;
14346             }
14347           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14348           buffer += bytes_read;
14349           if (buffer > buf_end)
14350             {
14351               overflow = true;
14352               break;
14353             }
14354           break;
14355         case DW_RLE_start_end:
14356           if (buffer + 2 * cu->header.addr_size > buf_end)
14357             {
14358               overflow = true;
14359               break;
14360             }
14361           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14362           buffer += bytes_read;
14363           range_end = read_address (obfd, buffer, cu, &bytes_read);
14364           buffer += bytes_read;
14365           break;
14366         default:
14367           complaint (_("Invalid .debug_rnglists data (no base address)"));
14368           return false;
14369         }
14370       if (rlet == DW_RLE_end_of_list || overflow)
14371         break;
14372       if (rlet == DW_RLE_base_address)
14373         continue;
14374
14375       if (!found_base)
14376         {
14377           /* We have no valid base address for the ranges
14378              data.  */
14379           complaint (_("Invalid .debug_rnglists data (no base address)"));
14380           return false;
14381         }
14382
14383       if (range_beginning > range_end)
14384         {
14385           /* Inverted range entries are invalid.  */
14386           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14387           return false;
14388         }
14389
14390       /* Empty range entries have no effect.  */
14391       if (range_beginning == range_end)
14392         continue;
14393
14394       range_beginning += base;
14395       range_end += base;
14396
14397       /* A not-uncommon case of bad debug info.
14398          Don't pollute the addrmap with bad data.  */
14399       if (range_beginning + baseaddr == 0
14400           && !dwarf2_per_objfile->has_section_at_zero)
14401         {
14402           complaint (_(".debug_rnglists entry has start address of zero"
14403                        " [in module %s]"), objfile_name (objfile));
14404           continue;
14405         }
14406
14407       callback (range_beginning, range_end);
14408     }
14409
14410   if (overflow)
14411     {
14412       complaint (_("Offset %d is not terminated "
14413                    "for DW_AT_ranges attribute"),
14414                  offset);
14415       return false;
14416     }
14417
14418   return true;
14419 }
14420
14421 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14422    Callback's type should be:
14423     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14424    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14425
14426 template <typename Callback>
14427 static int
14428 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14429                        Callback &&callback)
14430 {
14431   struct dwarf2_per_objfile *dwarf2_per_objfile
14432       = cu->per_cu->dwarf2_per_objfile;
14433   struct objfile *objfile = dwarf2_per_objfile->objfile;
14434   struct comp_unit_head *cu_header = &cu->header;
14435   bfd *obfd = objfile->obfd;
14436   unsigned int addr_size = cu_header->addr_size;
14437   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14438   /* Base address selection entry.  */
14439   CORE_ADDR base;
14440   int found_base;
14441   unsigned int dummy;
14442   const gdb_byte *buffer;
14443   CORE_ADDR baseaddr;
14444
14445   if (cu_header->version >= 5)
14446     return dwarf2_rnglists_process (offset, cu, callback);
14447
14448   found_base = cu->base_known;
14449   base = cu->base_address;
14450
14451   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14452   if (offset >= dwarf2_per_objfile->ranges.size)
14453     {
14454       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14455                  offset);
14456       return 0;
14457     }
14458   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14459
14460   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14461
14462   while (1)
14463     {
14464       CORE_ADDR range_beginning, range_end;
14465
14466       range_beginning = read_address (obfd, buffer, cu, &dummy);
14467       buffer += addr_size;
14468       range_end = read_address (obfd, buffer, cu, &dummy);
14469       buffer += addr_size;
14470       offset += 2 * addr_size;
14471
14472       /* An end of list marker is a pair of zero addresses.  */
14473       if (range_beginning == 0 && range_end == 0)
14474         /* Found the end of list entry.  */
14475         break;
14476
14477       /* Each base address selection entry is a pair of 2 values.
14478          The first is the largest possible address, the second is
14479          the base address.  Check for a base address here.  */
14480       if ((range_beginning & mask) == mask)
14481         {
14482           /* If we found the largest possible address, then we already
14483              have the base address in range_end.  */
14484           base = range_end;
14485           found_base = 1;
14486           continue;
14487         }
14488
14489       if (!found_base)
14490         {
14491           /* We have no valid base address for the ranges
14492              data.  */
14493           complaint (_("Invalid .debug_ranges data (no base address)"));
14494           return 0;
14495         }
14496
14497       if (range_beginning > range_end)
14498         {
14499           /* Inverted range entries are invalid.  */
14500           complaint (_("Invalid .debug_ranges data (inverted range)"));
14501           return 0;
14502         }
14503
14504       /* Empty range entries have no effect.  */
14505       if (range_beginning == range_end)
14506         continue;
14507
14508       range_beginning += base;
14509       range_end += base;
14510
14511       /* A not-uncommon case of bad debug info.
14512          Don't pollute the addrmap with bad data.  */
14513       if (range_beginning + baseaddr == 0
14514           && !dwarf2_per_objfile->has_section_at_zero)
14515         {
14516           complaint (_(".debug_ranges entry has start address of zero"
14517                        " [in module %s]"), objfile_name (objfile));
14518           continue;
14519         }
14520
14521       callback (range_beginning, range_end);
14522     }
14523
14524   return 1;
14525 }
14526
14527 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14528    Return 1 if the attributes are present and valid, otherwise, return 0.
14529    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14530
14531 static int
14532 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14533                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14534                     struct partial_symtab *ranges_pst)
14535 {
14536   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14537   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14538   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14539                                        SECT_OFF_TEXT (objfile));
14540   int low_set = 0;
14541   CORE_ADDR low = 0;
14542   CORE_ADDR high = 0;
14543   int retval;
14544
14545   retval = dwarf2_ranges_process (offset, cu,
14546     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14547     {
14548       if (ranges_pst != NULL)
14549         {
14550           CORE_ADDR lowpc;
14551           CORE_ADDR highpc;
14552
14553           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14554                                                range_beginning + baseaddr)
14555                    - baseaddr);
14556           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14557                                                 range_end + baseaddr)
14558                     - baseaddr);
14559           addrmap_set_empty (objfile->partial_symtabs->psymtabs_addrmap,
14560                              lowpc, highpc - 1, ranges_pst);
14561         }
14562
14563       /* FIXME: This is recording everything as a low-high
14564          segment of consecutive addresses.  We should have a
14565          data structure for discontiguous block ranges
14566          instead.  */
14567       if (! low_set)
14568         {
14569           low = range_beginning;
14570           high = range_end;
14571           low_set = 1;
14572         }
14573       else
14574         {
14575           if (range_beginning < low)
14576             low = range_beginning;
14577           if (range_end > high)
14578             high = range_end;
14579         }
14580     });
14581   if (!retval)
14582     return 0;
14583
14584   if (! low_set)
14585     /* If the first entry is an end-of-list marker, the range
14586        describes an empty scope, i.e. no instructions.  */
14587     return 0;
14588
14589   if (low_return)
14590     *low_return = low;
14591   if (high_return)
14592     *high_return = high;
14593   return 1;
14594 }
14595
14596 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14597    definition for the return value.  *LOWPC and *HIGHPC are set iff
14598    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14599
14600 static enum pc_bounds_kind
14601 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14602                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14603                       struct partial_symtab *pst)
14604 {
14605   struct dwarf2_per_objfile *dwarf2_per_objfile
14606     = cu->per_cu->dwarf2_per_objfile;
14607   struct attribute *attr;
14608   struct attribute *attr_high;
14609   CORE_ADDR low = 0;
14610   CORE_ADDR high = 0;
14611   enum pc_bounds_kind ret;
14612
14613   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14614   if (attr_high)
14615     {
14616       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14617       if (attr)
14618         {
14619           low = attr_value_as_address (attr);
14620           high = attr_value_as_address (attr_high);
14621           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14622             high += low;
14623         }
14624       else
14625         /* Found high w/o low attribute.  */
14626         return PC_BOUNDS_INVALID;
14627
14628       /* Found consecutive range of addresses.  */
14629       ret = PC_BOUNDS_HIGH_LOW;
14630     }
14631   else
14632     {
14633       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14634       if (attr != NULL)
14635         {
14636           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14637              We take advantage of the fact that DW_AT_ranges does not appear
14638              in DW_TAG_compile_unit of DWO files.  */
14639           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14640           unsigned int ranges_offset = (DW_UNSND (attr)
14641                                         + (need_ranges_base
14642                                            ? cu->ranges_base
14643                                            : 0));
14644
14645           /* Value of the DW_AT_ranges attribute is the offset in the
14646              .debug_ranges section.  */
14647           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14648             return PC_BOUNDS_INVALID;
14649           /* Found discontinuous range of addresses.  */
14650           ret = PC_BOUNDS_RANGES;
14651         }
14652       else
14653         return PC_BOUNDS_NOT_PRESENT;
14654     }
14655
14656   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14657   if (high <= low)
14658     return PC_BOUNDS_INVALID;
14659
14660   /* When using the GNU linker, .gnu.linkonce. sections are used to
14661      eliminate duplicate copies of functions and vtables and such.
14662      The linker will arbitrarily choose one and discard the others.
14663      The AT_*_pc values for such functions refer to local labels in
14664      these sections.  If the section from that file was discarded, the
14665      labels are not in the output, so the relocs get a value of 0.
14666      If this is a discarded function, mark the pc bounds as invalid,
14667      so that GDB will ignore it.  */
14668   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14669     return PC_BOUNDS_INVALID;
14670
14671   *lowpc = low;
14672   if (highpc)
14673     *highpc = high;
14674   return ret;
14675 }
14676
14677 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14678    its low and high PC addresses.  Do nothing if these addresses could not
14679    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14680    and HIGHPC to the high address if greater than HIGHPC.  */
14681
14682 static void
14683 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14684                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14685                                  struct dwarf2_cu *cu)
14686 {
14687   CORE_ADDR low, high;
14688   struct die_info *child = die->child;
14689
14690   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14691     {
14692       *lowpc = std::min (*lowpc, low);
14693       *highpc = std::max (*highpc, high);
14694     }
14695
14696   /* If the language does not allow nested subprograms (either inside
14697      subprograms or lexical blocks), we're done.  */
14698   if (cu->language != language_ada)
14699     return;
14700
14701   /* Check all the children of the given DIE.  If it contains nested
14702      subprograms, then check their pc bounds.  Likewise, we need to
14703      check lexical blocks as well, as they may also contain subprogram
14704      definitions.  */
14705   while (child && child->tag)
14706     {
14707       if (child->tag == DW_TAG_subprogram
14708           || child->tag == DW_TAG_lexical_block)
14709         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14710       child = sibling_die (child);
14711     }
14712 }
14713
14714 /* Get the low and high pc's represented by the scope DIE, and store
14715    them in *LOWPC and *HIGHPC.  If the correct values can't be
14716    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14717
14718 static void
14719 get_scope_pc_bounds (struct die_info *die,
14720                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14721                      struct dwarf2_cu *cu)
14722 {
14723   CORE_ADDR best_low = (CORE_ADDR) -1;
14724   CORE_ADDR best_high = (CORE_ADDR) 0;
14725   CORE_ADDR current_low, current_high;
14726
14727   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14728       >= PC_BOUNDS_RANGES)
14729     {
14730       best_low = current_low;
14731       best_high = current_high;
14732     }
14733   else
14734     {
14735       struct die_info *child = die->child;
14736
14737       while (child && child->tag)
14738         {
14739           switch (child->tag) {
14740           case DW_TAG_subprogram:
14741             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14742             break;
14743           case DW_TAG_namespace:
14744           case DW_TAG_module:
14745             /* FIXME: carlton/2004-01-16: Should we do this for
14746                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14747                that current GCC's always emit the DIEs corresponding
14748                to definitions of methods of classes as children of a
14749                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14750                the DIEs giving the declarations, which could be
14751                anywhere).  But I don't see any reason why the
14752                standards says that they have to be there.  */
14753             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14754
14755             if (current_low != ((CORE_ADDR) -1))
14756               {
14757                 best_low = std::min (best_low, current_low);
14758                 best_high = std::max (best_high, current_high);
14759               }
14760             break;
14761           default:
14762             /* Ignore.  */
14763             break;
14764           }
14765
14766           child = sibling_die (child);
14767         }
14768     }
14769
14770   *lowpc = best_low;
14771   *highpc = best_high;
14772 }
14773
14774 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14775    in DIE.  */
14776
14777 static void
14778 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14779                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14780 {
14781   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14782   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14783   struct attribute *attr;
14784   struct attribute *attr_high;
14785
14786   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14787   if (attr_high)
14788     {
14789       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14790       if (attr)
14791         {
14792           CORE_ADDR low = attr_value_as_address (attr);
14793           CORE_ADDR high = attr_value_as_address (attr_high);
14794
14795           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14796             high += low;
14797
14798           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14799           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14800           cu->get_builder ()->record_block_range (block, low, high - 1);
14801         }
14802     }
14803
14804   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14805   if (attr)
14806     {
14807       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14808          We take advantage of the fact that DW_AT_ranges does not appear
14809          in DW_TAG_compile_unit of DWO files.  */
14810       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14811
14812       /* The value of the DW_AT_ranges attribute is the offset of the
14813          address range list in the .debug_ranges section.  */
14814       unsigned long offset = (DW_UNSND (attr)
14815                               + (need_ranges_base ? cu->ranges_base : 0));
14816
14817       std::vector<blockrange> blockvec;
14818       dwarf2_ranges_process (offset, cu,
14819         [&] (CORE_ADDR start, CORE_ADDR end)
14820         {
14821           start += baseaddr;
14822           end += baseaddr;
14823           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14824           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14825           cu->get_builder ()->record_block_range (block, start, end - 1);
14826           blockvec.emplace_back (start, end);
14827         });
14828
14829       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14830     }
14831 }
14832
14833 /* Check whether the producer field indicates either of GCC < 4.6, or the
14834    Intel C/C++ compiler, and cache the result in CU.  */
14835
14836 static void
14837 check_producer (struct dwarf2_cu *cu)
14838 {
14839   int major, minor;
14840
14841   if (cu->producer == NULL)
14842     {
14843       /* For unknown compilers expect their behavior is DWARF version
14844          compliant.
14845
14846          GCC started to support .debug_types sections by -gdwarf-4 since
14847          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14848          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14849          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14850          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14851     }
14852   else if (producer_is_gcc (cu->producer, &major, &minor))
14853     {
14854       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14855       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14856     }
14857   else if (producer_is_icc (cu->producer, &major, &minor))
14858     {
14859       cu->producer_is_icc = true;
14860       cu->producer_is_icc_lt_14 = major < 14;
14861     }
14862   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14863     cu->producer_is_codewarrior = true;
14864   else
14865     {
14866       /* For other non-GCC compilers, expect their behavior is DWARF version
14867          compliant.  */
14868     }
14869
14870   cu->checked_producer = true;
14871 }
14872
14873 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14874    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14875    during 4.6.0 experimental.  */
14876
14877 static bool
14878 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14879 {
14880   if (!cu->checked_producer)
14881     check_producer (cu);
14882
14883   return cu->producer_is_gxx_lt_4_6;
14884 }
14885
14886
14887 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14888    with incorrect is_stmt attributes.  */
14889
14890 static bool
14891 producer_is_codewarrior (struct dwarf2_cu *cu)
14892 {
14893   if (!cu->checked_producer)
14894     check_producer (cu);
14895
14896   return cu->producer_is_codewarrior;
14897 }
14898
14899 /* Return the default accessibility type if it is not overriden by
14900    DW_AT_accessibility.  */
14901
14902 static enum dwarf_access_attribute
14903 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14904 {
14905   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14906     {
14907       /* The default DWARF 2 accessibility for members is public, the default
14908          accessibility for inheritance is private.  */
14909
14910       if (die->tag != DW_TAG_inheritance)
14911         return DW_ACCESS_public;
14912       else
14913         return DW_ACCESS_private;
14914     }
14915   else
14916     {
14917       /* DWARF 3+ defines the default accessibility a different way.  The same
14918          rules apply now for DW_TAG_inheritance as for the members and it only
14919          depends on the container kind.  */
14920
14921       if (die->parent->tag == DW_TAG_class_type)
14922         return DW_ACCESS_private;
14923       else
14924         return DW_ACCESS_public;
14925     }
14926 }
14927
14928 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14929    offset.  If the attribute was not found return 0, otherwise return
14930    1.  If it was found but could not properly be handled, set *OFFSET
14931    to 0.  */
14932
14933 static int
14934 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14935                              LONGEST *offset)
14936 {
14937   struct attribute *attr;
14938
14939   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14940   if (attr != NULL)
14941     {
14942       *offset = 0;
14943
14944       /* Note that we do not check for a section offset first here.
14945          This is because DW_AT_data_member_location is new in DWARF 4,
14946          so if we see it, we can assume that a constant form is really
14947          a constant and not a section offset.  */
14948       if (attr_form_is_constant (attr))
14949         *offset = dwarf2_get_attr_constant_value (attr, 0);
14950       else if (attr_form_is_section_offset (attr))
14951         dwarf2_complex_location_expr_complaint ();
14952       else if (attr_form_is_block (attr))
14953         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14954       else
14955         dwarf2_complex_location_expr_complaint ();
14956
14957       return 1;
14958     }
14959
14960   return 0;
14961 }
14962
14963 /* Add an aggregate field to the field list.  */
14964
14965 static void
14966 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14967                   struct dwarf2_cu *cu)
14968 {
14969   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14970   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14971   struct nextfield *new_field;
14972   struct attribute *attr;
14973   struct field *fp;
14974   const char *fieldname = "";
14975
14976   if (die->tag == DW_TAG_inheritance)
14977     {
14978       fip->baseclasses.emplace_back ();
14979       new_field = &fip->baseclasses.back ();
14980     }
14981   else
14982     {
14983       fip->fields.emplace_back ();
14984       new_field = &fip->fields.back ();
14985     }
14986
14987   fip->nfields++;
14988
14989   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14990   if (attr)
14991     new_field->accessibility = DW_UNSND (attr);
14992   else
14993     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14994   if (new_field->accessibility != DW_ACCESS_public)
14995     fip->non_public_fields = 1;
14996
14997   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14998   if (attr)
14999     new_field->virtuality = DW_UNSND (attr);
15000   else
15001     new_field->virtuality = DW_VIRTUALITY_none;
15002
15003   fp = &new_field->field;
15004
15005   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15006     {
15007       LONGEST offset;
15008
15009       /* Data member other than a C++ static data member.  */
15010
15011       /* Get type of field.  */
15012       fp->type = die_type (die, cu);
15013
15014       SET_FIELD_BITPOS (*fp, 0);
15015
15016       /* Get bit size of field (zero if none).  */
15017       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15018       if (attr)
15019         {
15020           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15021         }
15022       else
15023         {
15024           FIELD_BITSIZE (*fp) = 0;
15025         }
15026
15027       /* Get bit offset of field.  */
15028       if (handle_data_member_location (die, cu, &offset))
15029         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15030       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15031       if (attr)
15032         {
15033           if (gdbarch_bits_big_endian (gdbarch))
15034             {
15035               /* For big endian bits, the DW_AT_bit_offset gives the
15036                  additional bit offset from the MSB of the containing
15037                  anonymous object to the MSB of the field.  We don't
15038                  have to do anything special since we don't need to
15039                  know the size of the anonymous object.  */
15040               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15041             }
15042           else
15043             {
15044               /* For little endian bits, compute the bit offset to the
15045                  MSB of the anonymous object, subtract off the number of
15046                  bits from the MSB of the field to the MSB of the
15047                  object, and then subtract off the number of bits of
15048                  the field itself.  The result is the bit offset of
15049                  the LSB of the field.  */
15050               int anonymous_size;
15051               int bit_offset = DW_UNSND (attr);
15052
15053               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15054               if (attr)
15055                 {
15056                   /* The size of the anonymous object containing
15057                      the bit field is explicit, so use the
15058                      indicated size (in bytes).  */
15059                   anonymous_size = DW_UNSND (attr);
15060                 }
15061               else
15062                 {
15063                   /* The size of the anonymous object containing
15064                      the bit field must be inferred from the type
15065                      attribute of the data member containing the
15066                      bit field.  */
15067                   anonymous_size = TYPE_LENGTH (fp->type);
15068                 }
15069               SET_FIELD_BITPOS (*fp,
15070                                 (FIELD_BITPOS (*fp)
15071                                  + anonymous_size * bits_per_byte
15072                                  - bit_offset - FIELD_BITSIZE (*fp)));
15073             }
15074         }
15075       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15076       if (attr != NULL)
15077         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15078                                 + dwarf2_get_attr_constant_value (attr, 0)));
15079
15080       /* Get name of field.  */
15081       fieldname = dwarf2_name (die, cu);
15082       if (fieldname == NULL)
15083         fieldname = "";
15084
15085       /* The name is already allocated along with this objfile, so we don't
15086          need to duplicate it for the type.  */
15087       fp->name = fieldname;
15088
15089       /* Change accessibility for artificial fields (e.g. virtual table
15090          pointer or virtual base class pointer) to private.  */
15091       if (dwarf2_attr (die, DW_AT_artificial, cu))
15092         {
15093           FIELD_ARTIFICIAL (*fp) = 1;
15094           new_field->accessibility = DW_ACCESS_private;
15095           fip->non_public_fields = 1;
15096         }
15097     }
15098   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15099     {
15100       /* C++ static member.  */
15101
15102       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15103          is a declaration, but all versions of G++ as of this writing
15104          (so through at least 3.2.1) incorrectly generate
15105          DW_TAG_variable tags.  */
15106
15107       const char *physname;
15108
15109       /* Get name of field.  */
15110       fieldname = dwarf2_name (die, cu);
15111       if (fieldname == NULL)
15112         return;
15113
15114       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15115       if (attr
15116           /* Only create a symbol if this is an external value.
15117              new_symbol checks this and puts the value in the global symbol
15118              table, which we want.  If it is not external, new_symbol
15119              will try to put the value in cu->list_in_scope which is wrong.  */
15120           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15121         {
15122           /* A static const member, not much different than an enum as far as
15123              we're concerned, except that we can support more types.  */
15124           new_symbol (die, NULL, cu);
15125         }
15126
15127       /* Get physical name.  */
15128       physname = dwarf2_physname (fieldname, die, cu);
15129
15130       /* The name is already allocated along with this objfile, so we don't
15131          need to duplicate it for the type.  */
15132       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15133       FIELD_TYPE (*fp) = die_type (die, cu);
15134       FIELD_NAME (*fp) = fieldname;
15135     }
15136   else if (die->tag == DW_TAG_inheritance)
15137     {
15138       LONGEST offset;
15139
15140       /* C++ base class field.  */
15141       if (handle_data_member_location (die, cu, &offset))
15142         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15143       FIELD_BITSIZE (*fp) = 0;
15144       FIELD_TYPE (*fp) = die_type (die, cu);
15145       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15146     }
15147   else if (die->tag == DW_TAG_variant_part)
15148     {
15149       /* process_structure_scope will treat this DIE as a union.  */
15150       process_structure_scope (die, cu);
15151
15152       /* The variant part is relative to the start of the enclosing
15153          structure.  */
15154       SET_FIELD_BITPOS (*fp, 0);
15155       fp->type = get_die_type (die, cu);
15156       fp->artificial = 1;
15157       fp->name = "<<variant>>";
15158
15159       /* Normally a DW_TAG_variant_part won't have a size, but our
15160          representation requires one, so set it to the maximum of the
15161          child sizes.  */
15162       if (TYPE_LENGTH (fp->type) == 0)
15163         {
15164           unsigned max = 0;
15165           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
15166             if (TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)) > max)
15167               max = TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i));
15168           TYPE_LENGTH (fp->type) = max;
15169         }
15170     }
15171   else
15172     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15173 }
15174
15175 /* Can the type given by DIE define another type?  */
15176
15177 static bool
15178 type_can_define_types (const struct die_info *die)
15179 {
15180   switch (die->tag)
15181     {
15182     case DW_TAG_typedef:
15183     case DW_TAG_class_type:
15184     case DW_TAG_structure_type:
15185     case DW_TAG_union_type:
15186     case DW_TAG_enumeration_type:
15187       return true;
15188
15189     default:
15190       return false;
15191     }
15192 }
15193
15194 /* Add a type definition defined in the scope of the FIP's class.  */
15195
15196 static void
15197 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15198                       struct dwarf2_cu *cu)
15199 {
15200   struct decl_field fp;
15201   memset (&fp, 0, sizeof (fp));
15202
15203   gdb_assert (type_can_define_types (die));
15204
15205   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15206   fp.name = dwarf2_name (die, cu);
15207   fp.type = read_type_die (die, cu);
15208
15209   /* Save accessibility.  */
15210   enum dwarf_access_attribute accessibility;
15211   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15212   if (attr != NULL)
15213     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15214   else
15215     accessibility = dwarf2_default_access_attribute (die, cu);
15216   switch (accessibility)
15217     {
15218     case DW_ACCESS_public:
15219       /* The assumed value if neither private nor protected.  */
15220       break;
15221     case DW_ACCESS_private:
15222       fp.is_private = 1;
15223       break;
15224     case DW_ACCESS_protected:
15225       fp.is_protected = 1;
15226       break;
15227     default:
15228       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15229     }
15230
15231   if (die->tag == DW_TAG_typedef)
15232     fip->typedef_field_list.push_back (fp);
15233   else
15234     fip->nested_types_list.push_back (fp);
15235 }
15236
15237 /* Create the vector of fields, and attach it to the type.  */
15238
15239 static void
15240 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15241                               struct dwarf2_cu *cu)
15242 {
15243   int nfields = fip->nfields;
15244
15245   /* Record the field count, allocate space for the array of fields,
15246      and create blank accessibility bitfields if necessary.  */
15247   TYPE_NFIELDS (type) = nfields;
15248   TYPE_FIELDS (type) = (struct field *)
15249     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15250
15251   if (fip->non_public_fields && cu->language != language_ada)
15252     {
15253       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15254
15255       TYPE_FIELD_PRIVATE_BITS (type) =
15256         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15257       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15258
15259       TYPE_FIELD_PROTECTED_BITS (type) =
15260         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15261       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15262
15263       TYPE_FIELD_IGNORE_BITS (type) =
15264         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15265       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15266     }
15267
15268   /* If the type has baseclasses, allocate and clear a bit vector for
15269      TYPE_FIELD_VIRTUAL_BITS.  */
15270   if (!fip->baseclasses.empty () && cu->language != language_ada)
15271     {
15272       int num_bytes = B_BYTES (fip->baseclasses.size ());
15273       unsigned char *pointer;
15274
15275       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15276       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15277       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15278       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15279       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15280     }
15281
15282   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15283     {
15284       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15285
15286       for (int index = 0; index < nfields; ++index)
15287         {
15288           struct nextfield &field = fip->fields[index];
15289
15290           if (field.variant.is_discriminant)
15291             di->discriminant_index = index;
15292           else if (field.variant.default_branch)
15293             di->default_index = index;
15294           else
15295             di->discriminants[index] = field.variant.discriminant_value;
15296         }
15297     }
15298
15299   /* Copy the saved-up fields into the field vector.  */
15300   for (int i = 0; i < nfields; ++i)
15301     {
15302       struct nextfield &field
15303         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15304            : fip->fields[i - fip->baseclasses.size ()]);
15305
15306       TYPE_FIELD (type, i) = field.field;
15307       switch (field.accessibility)
15308         {
15309         case DW_ACCESS_private:
15310           if (cu->language != language_ada)
15311             SET_TYPE_FIELD_PRIVATE (type, i);
15312           break;
15313
15314         case DW_ACCESS_protected:
15315           if (cu->language != language_ada)
15316             SET_TYPE_FIELD_PROTECTED (type, i);
15317           break;
15318
15319         case DW_ACCESS_public:
15320           break;
15321
15322         default:
15323           /* Unknown accessibility.  Complain and treat it as public.  */
15324           {
15325             complaint (_("unsupported accessibility %d"),
15326                        field.accessibility);
15327           }
15328           break;
15329         }
15330       if (i < fip->baseclasses.size ())
15331         {
15332           switch (field.virtuality)
15333             {
15334             case DW_VIRTUALITY_virtual:
15335             case DW_VIRTUALITY_pure_virtual:
15336               if (cu->language == language_ada)
15337                 error (_("unexpected virtuality in component of Ada type"));
15338               SET_TYPE_FIELD_VIRTUAL (type, i);
15339               break;
15340             }
15341         }
15342     }
15343 }
15344
15345 /* Return true if this member function is a constructor, false
15346    otherwise.  */
15347
15348 static int
15349 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15350 {
15351   const char *fieldname;
15352   const char *type_name;
15353   int len;
15354
15355   if (die->parent == NULL)
15356     return 0;
15357
15358   if (die->parent->tag != DW_TAG_structure_type
15359       && die->parent->tag != DW_TAG_union_type
15360       && die->parent->tag != DW_TAG_class_type)
15361     return 0;
15362
15363   fieldname = dwarf2_name (die, cu);
15364   type_name = dwarf2_name (die->parent, cu);
15365   if (fieldname == NULL || type_name == NULL)
15366     return 0;
15367
15368   len = strlen (fieldname);
15369   return (strncmp (fieldname, type_name, len) == 0
15370           && (type_name[len] == '\0' || type_name[len] == '<'));
15371 }
15372
15373 /* Add a member function to the proper fieldlist.  */
15374
15375 static void
15376 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15377                       struct type *type, struct dwarf2_cu *cu)
15378 {
15379   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15380   struct attribute *attr;
15381   int i;
15382   struct fnfieldlist *flp = nullptr;
15383   struct fn_field *fnp;
15384   const char *fieldname;
15385   struct type *this_type;
15386   enum dwarf_access_attribute accessibility;
15387
15388   if (cu->language == language_ada)
15389     error (_("unexpected member function in Ada type"));
15390
15391   /* Get name of member function.  */
15392   fieldname = dwarf2_name (die, cu);
15393   if (fieldname == NULL)
15394     return;
15395
15396   /* Look up member function name in fieldlist.  */
15397   for (i = 0; i < fip->fnfieldlists.size (); i++)
15398     {
15399       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15400         {
15401           flp = &fip->fnfieldlists[i];
15402           break;
15403         }
15404     }
15405
15406   /* Create a new fnfieldlist if necessary.  */
15407   if (flp == nullptr)
15408     {
15409       fip->fnfieldlists.emplace_back ();
15410       flp = &fip->fnfieldlists.back ();
15411       flp->name = fieldname;
15412       i = fip->fnfieldlists.size () - 1;
15413     }
15414
15415   /* Create a new member function field and add it to the vector of
15416      fnfieldlists.  */
15417   flp->fnfields.emplace_back ();
15418   fnp = &flp->fnfields.back ();
15419
15420   /* Delay processing of the physname until later.  */
15421   if (cu->language == language_cplus)
15422     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15423                         die, cu);
15424   else
15425     {
15426       const char *physname = dwarf2_physname (fieldname, die, cu);
15427       fnp->physname = physname ? physname : "";
15428     }
15429
15430   fnp->type = alloc_type (objfile);
15431   this_type = read_type_die (die, cu);
15432   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15433     {
15434       int nparams = TYPE_NFIELDS (this_type);
15435
15436       /* TYPE is the domain of this method, and THIS_TYPE is the type
15437            of the method itself (TYPE_CODE_METHOD).  */
15438       smash_to_method_type (fnp->type, type,
15439                             TYPE_TARGET_TYPE (this_type),
15440                             TYPE_FIELDS (this_type),
15441                             TYPE_NFIELDS (this_type),
15442                             TYPE_VARARGS (this_type));
15443
15444       /* Handle static member functions.
15445          Dwarf2 has no clean way to discern C++ static and non-static
15446          member functions.  G++ helps GDB by marking the first
15447          parameter for non-static member functions (which is the this
15448          pointer) as artificial.  We obtain this information from
15449          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15450       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15451         fnp->voffset = VOFFSET_STATIC;
15452     }
15453   else
15454     complaint (_("member function type missing for '%s'"),
15455                dwarf2_full_name (fieldname, die, cu));
15456
15457   /* Get fcontext from DW_AT_containing_type if present.  */
15458   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15459     fnp->fcontext = die_containing_type (die, cu);
15460
15461   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15462      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15463
15464   /* Get accessibility.  */
15465   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15466   if (attr)
15467     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15468   else
15469     accessibility = dwarf2_default_access_attribute (die, cu);
15470   switch (accessibility)
15471     {
15472     case DW_ACCESS_private:
15473       fnp->is_private = 1;
15474       break;
15475     case DW_ACCESS_protected:
15476       fnp->is_protected = 1;
15477       break;
15478     }
15479
15480   /* Check for artificial methods.  */
15481   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15482   if (attr && DW_UNSND (attr) != 0)
15483     fnp->is_artificial = 1;
15484
15485   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15486
15487   /* Get index in virtual function table if it is a virtual member
15488      function.  For older versions of GCC, this is an offset in the
15489      appropriate virtual table, as specified by DW_AT_containing_type.
15490      For everyone else, it is an expression to be evaluated relative
15491      to the object address.  */
15492
15493   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15494   if (attr)
15495     {
15496       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15497         {
15498           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15499             {
15500               /* Old-style GCC.  */
15501               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15502             }
15503           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15504                    || (DW_BLOCK (attr)->size > 1
15505                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15506                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15507             {
15508               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15509               if ((fnp->voffset % cu->header.addr_size) != 0)
15510                 dwarf2_complex_location_expr_complaint ();
15511               else
15512                 fnp->voffset /= cu->header.addr_size;
15513               fnp->voffset += 2;
15514             }
15515           else
15516             dwarf2_complex_location_expr_complaint ();
15517
15518           if (!fnp->fcontext)
15519             {
15520               /* If there is no `this' field and no DW_AT_containing_type,
15521                  we cannot actually find a base class context for the
15522                  vtable!  */
15523               if (TYPE_NFIELDS (this_type) == 0
15524                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15525                 {
15526                   complaint (_("cannot determine context for virtual member "
15527                                "function \"%s\" (offset %s)"),
15528                              fieldname, sect_offset_str (die->sect_off));
15529                 }
15530               else
15531                 {
15532                   fnp->fcontext
15533                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15534                 }
15535             }
15536         }
15537       else if (attr_form_is_section_offset (attr))
15538         {
15539           dwarf2_complex_location_expr_complaint ();
15540         }
15541       else
15542         {
15543           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15544                                                  fieldname);
15545         }
15546     }
15547   else
15548     {
15549       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15550       if (attr && DW_UNSND (attr))
15551         {
15552           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15553           complaint (_("Member function \"%s\" (offset %s) is virtual "
15554                        "but the vtable offset is not specified"),
15555                      fieldname, sect_offset_str (die->sect_off));
15556           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15557           TYPE_CPLUS_DYNAMIC (type) = 1;
15558         }
15559     }
15560 }
15561
15562 /* Create the vector of member function fields, and attach it to the type.  */
15563
15564 static void
15565 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15566                                  struct dwarf2_cu *cu)
15567 {
15568   if (cu->language == language_ada)
15569     error (_("unexpected member functions in Ada type"));
15570
15571   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15572   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15573     TYPE_ALLOC (type,
15574                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15575
15576   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15577     {
15578       struct fnfieldlist &nf = fip->fnfieldlists[i];
15579       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15580
15581       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15582       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15583       fn_flp->fn_fields = (struct fn_field *)
15584         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15585
15586       for (int k = 0; k < nf.fnfields.size (); ++k)
15587         fn_flp->fn_fields[k] = nf.fnfields[k];
15588     }
15589
15590   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15591 }
15592
15593 /* Returns non-zero if NAME is the name of a vtable member in CU's
15594    language, zero otherwise.  */
15595 static int
15596 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15597 {
15598   static const char vptr[] = "_vptr";
15599
15600   /* Look for the C++ form of the vtable.  */
15601   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15602     return 1;
15603
15604   return 0;
15605 }
15606
15607 /* GCC outputs unnamed structures that are really pointers to member
15608    functions, with the ABI-specified layout.  If TYPE describes
15609    such a structure, smash it into a member function type.
15610
15611    GCC shouldn't do this; it should just output pointer to member DIEs.
15612    This is GCC PR debug/28767.  */
15613
15614 static void
15615 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15616 {
15617   struct type *pfn_type, *self_type, *new_type;
15618
15619   /* Check for a structure with no name and two children.  */
15620   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15621     return;
15622
15623   /* Check for __pfn and __delta members.  */
15624   if (TYPE_FIELD_NAME (type, 0) == NULL
15625       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15626       || TYPE_FIELD_NAME (type, 1) == NULL
15627       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15628     return;
15629
15630   /* Find the type of the method.  */
15631   pfn_type = TYPE_FIELD_TYPE (type, 0);
15632   if (pfn_type == NULL
15633       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15634       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15635     return;
15636
15637   /* Look for the "this" argument.  */
15638   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15639   if (TYPE_NFIELDS (pfn_type) == 0
15640       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15641       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15642     return;
15643
15644   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15645   new_type = alloc_type (objfile);
15646   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15647                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15648                         TYPE_VARARGS (pfn_type));
15649   smash_to_methodptr_type (type, new_type);
15650 }
15651
15652 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15653    appropriate error checking and issuing complaints if there is a
15654    problem.  */
15655
15656 static ULONGEST
15657 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15658 {
15659   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15660
15661   if (attr == nullptr)
15662     return 0;
15663
15664   if (!attr_form_is_constant (attr))
15665     {
15666       complaint (_("DW_AT_alignment must have constant form"
15667                    " - DIE at %s [in module %s]"),
15668                  sect_offset_str (die->sect_off),
15669                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15670       return 0;
15671     }
15672
15673   ULONGEST align;
15674   if (attr->form == DW_FORM_sdata)
15675     {
15676       LONGEST val = DW_SND (attr);
15677       if (val < 0)
15678         {
15679           complaint (_("DW_AT_alignment value must not be negative"
15680                        " - DIE at %s [in module %s]"),
15681                      sect_offset_str (die->sect_off),
15682                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15683           return 0;
15684         }
15685       align = val;
15686     }
15687   else
15688     align = DW_UNSND (attr);
15689
15690   if (align == 0)
15691     {
15692       complaint (_("DW_AT_alignment value must not be zero"
15693                    " - DIE at %s [in module %s]"),
15694                  sect_offset_str (die->sect_off),
15695                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15696       return 0;
15697     }
15698   if ((align & (align - 1)) != 0)
15699     {
15700       complaint (_("DW_AT_alignment value must be a power of 2"
15701                    " - DIE at %s [in module %s]"),
15702                  sect_offset_str (die->sect_off),
15703                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15704       return 0;
15705     }
15706
15707   return align;
15708 }
15709
15710 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15711    the alignment for TYPE.  */
15712
15713 static void
15714 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15715                      struct type *type)
15716 {
15717   if (!set_type_align (type, get_alignment (cu, die)))
15718     complaint (_("DW_AT_alignment value too large"
15719                  " - DIE at %s [in module %s]"),
15720                sect_offset_str (die->sect_off),
15721                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15722 }
15723
15724 /* Called when we find the DIE that starts a structure or union scope
15725    (definition) to create a type for the structure or union.  Fill in
15726    the type's name and general properties; the members will not be
15727    processed until process_structure_scope.  A symbol table entry for
15728    the type will also not be done until process_structure_scope (assuming
15729    the type has a name).
15730
15731    NOTE: we need to call these functions regardless of whether or not the
15732    DIE has a DW_AT_name attribute, since it might be an anonymous
15733    structure or union.  This gets the type entered into our set of
15734    user defined types.  */
15735
15736 static struct type *
15737 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15738 {
15739   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15740   struct type *type;
15741   struct attribute *attr;
15742   const char *name;
15743
15744   /* If the definition of this type lives in .debug_types, read that type.
15745      Don't follow DW_AT_specification though, that will take us back up
15746      the chain and we want to go down.  */
15747   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15748   if (attr)
15749     {
15750       type = get_DW_AT_signature_type (die, attr, cu);
15751
15752       /* The type's CU may not be the same as CU.
15753          Ensure TYPE is recorded with CU in die_type_hash.  */
15754       return set_die_type (die, type, cu);
15755     }
15756
15757   type = alloc_type (objfile);
15758   INIT_CPLUS_SPECIFIC (type);
15759
15760   name = dwarf2_name (die, cu);
15761   if (name != NULL)
15762     {
15763       if (cu->language == language_cplus
15764           || cu->language == language_d
15765           || cu->language == language_rust)
15766         {
15767           const char *full_name = dwarf2_full_name (name, die, cu);
15768
15769           /* dwarf2_full_name might have already finished building the DIE's
15770              type.  If so, there is no need to continue.  */
15771           if (get_die_type (die, cu) != NULL)
15772             return get_die_type (die, cu);
15773
15774           TYPE_NAME (type) = full_name;
15775         }
15776       else
15777         {
15778           /* The name is already allocated along with this objfile, so
15779              we don't need to duplicate it for the type.  */
15780           TYPE_NAME (type) = name;
15781         }
15782     }
15783
15784   if (die->tag == DW_TAG_structure_type)
15785     {
15786       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15787     }
15788   else if (die->tag == DW_TAG_union_type)
15789     {
15790       TYPE_CODE (type) = TYPE_CODE_UNION;
15791     }
15792   else if (die->tag == DW_TAG_variant_part)
15793     {
15794       TYPE_CODE (type) = TYPE_CODE_UNION;
15795       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15796     }
15797   else
15798     {
15799       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15800     }
15801
15802   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15803     TYPE_DECLARED_CLASS (type) = 1;
15804
15805   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15806   if (attr)
15807     {
15808       if (attr_form_is_constant (attr))
15809         TYPE_LENGTH (type) = DW_UNSND (attr);
15810       else
15811         {
15812           /* For the moment, dynamic type sizes are not supported
15813              by GDB's struct type.  The actual size is determined
15814              on-demand when resolving the type of a given object,
15815              so set the type's length to zero for now.  Otherwise,
15816              we record an expression as the length, and that expression
15817              could lead to a very large value, which could eventually
15818              lead to us trying to allocate that much memory when creating
15819              a value of that type.  */
15820           TYPE_LENGTH (type) = 0;
15821         }
15822     }
15823   else
15824     {
15825       TYPE_LENGTH (type) = 0;
15826     }
15827
15828   maybe_set_alignment (cu, die, type);
15829
15830   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15831     {
15832       /* ICC<14 does not output the required DW_AT_declaration on
15833          incomplete types, but gives them a size of zero.  */
15834       TYPE_STUB (type) = 1;
15835     }
15836   else
15837     TYPE_STUB_SUPPORTED (type) = 1;
15838
15839   if (die_is_declaration (die, cu))
15840     TYPE_STUB (type) = 1;
15841   else if (attr == NULL && die->child == NULL
15842            && producer_is_realview (cu->producer))
15843     /* RealView does not output the required DW_AT_declaration
15844        on incomplete types.  */
15845     TYPE_STUB (type) = 1;
15846
15847   /* We need to add the type field to the die immediately so we don't
15848      infinitely recurse when dealing with pointers to the structure
15849      type within the structure itself.  */
15850   set_die_type (die, type, cu);
15851
15852   /* set_die_type should be already done.  */
15853   set_descriptive_type (type, die, cu);
15854
15855   return type;
15856 }
15857
15858 /* A helper for process_structure_scope that handles a single member
15859    DIE.  */
15860
15861 static void
15862 handle_struct_member_die (struct die_info *child_die, struct type *type,
15863                           struct field_info *fi,
15864                           std::vector<struct symbol *> *template_args,
15865                           struct dwarf2_cu *cu)
15866 {
15867   if (child_die->tag == DW_TAG_member
15868       || child_die->tag == DW_TAG_variable
15869       || child_die->tag == DW_TAG_variant_part)
15870     {
15871       /* NOTE: carlton/2002-11-05: A C++ static data member
15872          should be a DW_TAG_member that is a declaration, but
15873          all versions of G++ as of this writing (so through at
15874          least 3.2.1) incorrectly generate DW_TAG_variable
15875          tags for them instead.  */
15876       dwarf2_add_field (fi, child_die, cu);
15877     }
15878   else if (child_die->tag == DW_TAG_subprogram)
15879     {
15880       /* Rust doesn't have member functions in the C++ sense.
15881          However, it does emit ordinary functions as children
15882          of a struct DIE.  */
15883       if (cu->language == language_rust)
15884         read_func_scope (child_die, cu);
15885       else
15886         {
15887           /* C++ member function.  */
15888           dwarf2_add_member_fn (fi, child_die, type, cu);
15889         }
15890     }
15891   else if (child_die->tag == DW_TAG_inheritance)
15892     {
15893       /* C++ base class field.  */
15894       dwarf2_add_field (fi, child_die, cu);
15895     }
15896   else if (type_can_define_types (child_die))
15897     dwarf2_add_type_defn (fi, child_die, cu);
15898   else if (child_die->tag == DW_TAG_template_type_param
15899            || child_die->tag == DW_TAG_template_value_param)
15900     {
15901       struct symbol *arg = new_symbol (child_die, NULL, cu);
15902
15903       if (arg != NULL)
15904         template_args->push_back (arg);
15905     }
15906   else if (child_die->tag == DW_TAG_variant)
15907     {
15908       /* In a variant we want to get the discriminant and also add a
15909          field for our sole member child.  */
15910       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15911
15912       for (die_info *variant_child = child_die->child;
15913            variant_child != NULL;
15914            variant_child = sibling_die (variant_child))
15915         {
15916           if (variant_child->tag == DW_TAG_member)
15917             {
15918               handle_struct_member_die (variant_child, type, fi,
15919                                         template_args, cu);
15920               /* Only handle the one.  */
15921               break;
15922             }
15923         }
15924
15925       /* We don't handle this but we might as well report it if we see
15926          it.  */
15927       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15928           complaint (_("DW_AT_discr_list is not supported yet"
15929                        " - DIE at %s [in module %s]"),
15930                      sect_offset_str (child_die->sect_off),
15931                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15932
15933       /* The first field was just added, so we can stash the
15934          discriminant there.  */
15935       gdb_assert (!fi->fields.empty ());
15936       if (discr == NULL)
15937         fi->fields.back ().variant.default_branch = true;
15938       else
15939         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15940     }
15941 }
15942
15943 /* Finish creating a structure or union type, including filling in
15944    its members and creating a symbol for it.  */
15945
15946 static void
15947 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15948 {
15949   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15950   struct die_info *child_die;
15951   struct type *type;
15952
15953   type = get_die_type (die, cu);
15954   if (type == NULL)
15955     type = read_structure_type (die, cu);
15956
15957   /* When reading a DW_TAG_variant_part, we need to notice when we
15958      read the discriminant member, so we can record it later in the
15959      discriminant_info.  */
15960   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15961   sect_offset discr_offset;
15962   bool has_template_parameters = false;
15963
15964   if (is_variant_part)
15965     {
15966       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15967       if (discr == NULL)
15968         {
15969           /* Maybe it's a univariant form, an extension we support.
15970              In this case arrange not to check the offset.  */
15971           is_variant_part = false;
15972         }
15973       else if (attr_form_is_ref (discr))
15974         {
15975           struct dwarf2_cu *target_cu = cu;
15976           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15977
15978           discr_offset = target_die->sect_off;
15979         }
15980       else
15981         {
15982           complaint (_("DW_AT_discr does not have DIE reference form"
15983                        " - DIE at %s [in module %s]"),
15984                      sect_offset_str (die->sect_off),
15985                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15986           is_variant_part = false;
15987         }
15988     }
15989
15990   if (die->child != NULL && ! die_is_declaration (die, cu))
15991     {
15992       struct field_info fi;
15993       std::vector<struct symbol *> template_args;
15994
15995       child_die = die->child;
15996
15997       while (child_die && child_die->tag)
15998         {
15999           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
16000
16001           if (is_variant_part && discr_offset == child_die->sect_off)
16002             fi.fields.back ().variant.is_discriminant = true;
16003
16004           child_die = sibling_die (child_die);
16005         }
16006
16007       /* Attach template arguments to type.  */
16008       if (!template_args.empty ())
16009         {
16010           has_template_parameters = true;
16011           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16012           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16013           TYPE_TEMPLATE_ARGUMENTS (type)
16014             = XOBNEWVEC (&objfile->objfile_obstack,
16015                          struct symbol *,
16016                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16017           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16018                   template_args.data (),
16019                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16020                    * sizeof (struct symbol *)));
16021         }
16022
16023       /* Attach fields and member functions to the type.  */
16024       if (fi.nfields)
16025         dwarf2_attach_fields_to_type (&fi, type, cu);
16026       if (!fi.fnfieldlists.empty ())
16027         {
16028           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16029
16030           /* Get the type which refers to the base class (possibly this
16031              class itself) which contains the vtable pointer for the current
16032              class from the DW_AT_containing_type attribute.  This use of
16033              DW_AT_containing_type is a GNU extension.  */
16034
16035           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16036             {
16037               struct type *t = die_containing_type (die, cu);
16038
16039               set_type_vptr_basetype (type, t);
16040               if (type == t)
16041                 {
16042                   int i;
16043
16044                   /* Our own class provides vtbl ptr.  */
16045                   for (i = TYPE_NFIELDS (t) - 1;
16046                        i >= TYPE_N_BASECLASSES (t);
16047                        --i)
16048                     {
16049                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16050
16051                       if (is_vtable_name (fieldname, cu))
16052                         {
16053                           set_type_vptr_fieldno (type, i);
16054                           break;
16055                         }
16056                     }
16057
16058                   /* Complain if virtual function table field not found.  */
16059                   if (i < TYPE_N_BASECLASSES (t))
16060                     complaint (_("virtual function table pointer "
16061                                  "not found when defining class '%s'"),
16062                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
16063                 }
16064               else
16065                 {
16066                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16067                 }
16068             }
16069           else if (cu->producer
16070                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16071             {
16072               /* The IBM XLC compiler does not provide direct indication
16073                  of the containing type, but the vtable pointer is
16074                  always named __vfp.  */
16075
16076               int i;
16077
16078               for (i = TYPE_NFIELDS (type) - 1;
16079                    i >= TYPE_N_BASECLASSES (type);
16080                    --i)
16081                 {
16082                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16083                     {
16084                       set_type_vptr_fieldno (type, i);
16085                       set_type_vptr_basetype (type, type);
16086                       break;
16087                     }
16088                 }
16089             }
16090         }
16091
16092       /* Copy fi.typedef_field_list linked list elements content into the
16093          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16094       if (!fi.typedef_field_list.empty ())
16095         {
16096           int count = fi.typedef_field_list.size ();
16097
16098           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16099           TYPE_TYPEDEF_FIELD_ARRAY (type)
16100             = ((struct decl_field *)
16101                TYPE_ALLOC (type,
16102                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16103           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16104
16105           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16106             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16107         }
16108
16109       /* Copy fi.nested_types_list linked list elements content into the
16110          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16111       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16112         {
16113           int count = fi.nested_types_list.size ();
16114
16115           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16116           TYPE_NESTED_TYPES_ARRAY (type)
16117             = ((struct decl_field *)
16118                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16119           TYPE_NESTED_TYPES_COUNT (type) = count;
16120
16121           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16122             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16123         }
16124     }
16125
16126   quirk_gcc_member_function_pointer (type, objfile);
16127   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16128     cu->rust_unions.push_back (type);
16129
16130   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16131      snapshots) has been known to create a die giving a declaration
16132      for a class that has, as a child, a die giving a definition for a
16133      nested class.  So we have to process our children even if the
16134      current die is a declaration.  Normally, of course, a declaration
16135      won't have any children at all.  */
16136
16137   child_die = die->child;
16138
16139   while (child_die != NULL && child_die->tag)
16140     {
16141       if (child_die->tag == DW_TAG_member
16142           || child_die->tag == DW_TAG_variable
16143           || child_die->tag == DW_TAG_inheritance
16144           || child_die->tag == DW_TAG_template_value_param
16145           || child_die->tag == DW_TAG_template_type_param)
16146         {
16147           /* Do nothing.  */
16148         }
16149       else
16150         process_die (child_die, cu);
16151
16152       child_die = sibling_die (child_die);
16153     }
16154
16155   /* Do not consider external references.  According to the DWARF standard,
16156      these DIEs are identified by the fact that they have no byte_size
16157      attribute, and a declaration attribute.  */
16158   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16159       || !die_is_declaration (die, cu))
16160     {
16161       struct symbol *sym = new_symbol (die, type, cu);
16162
16163       if (has_template_parameters)
16164         {
16165           struct symtab *symtab;
16166           if (sym != nullptr)
16167             symtab = symbol_symtab (sym);
16168           else if (cu->line_header != nullptr)
16169             {
16170               /* Any related symtab will do.  */
16171               symtab
16172                 = cu->line_header->file_name_at (file_name_index (1))->symtab;
16173             }
16174           else
16175             {
16176               symtab = nullptr;
16177               complaint (_("could not find suitable "
16178                            "symtab for template parameter"
16179                            " - DIE at %s [in module %s]"),
16180                          sect_offset_str (die->sect_off),
16181                          objfile_name (objfile));
16182             }
16183
16184           if (symtab != nullptr)
16185             {
16186               /* Make sure that the symtab is set on the new symbols.
16187                  Even though they don't appear in this symtab directly,
16188                  other parts of gdb assume that symbols do, and this is
16189                  reasonably true.  */
16190               for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16191                 symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i), symtab);
16192             }
16193         }
16194     }
16195 }
16196
16197 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16198    update TYPE using some information only available in DIE's children.  */
16199
16200 static void
16201 update_enumeration_type_from_children (struct die_info *die,
16202                                        struct type *type,
16203                                        struct dwarf2_cu *cu)
16204 {
16205   struct die_info *child_die;
16206   int unsigned_enum = 1;
16207   int flag_enum = 1;
16208   ULONGEST mask = 0;
16209
16210   auto_obstack obstack;
16211
16212   for (child_die = die->child;
16213        child_die != NULL && child_die->tag;
16214        child_die = sibling_die (child_die))
16215     {
16216       struct attribute *attr;
16217       LONGEST value;
16218       const gdb_byte *bytes;
16219       struct dwarf2_locexpr_baton *baton;
16220       const char *name;
16221
16222       if (child_die->tag != DW_TAG_enumerator)
16223         continue;
16224
16225       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16226       if (attr == NULL)
16227         continue;
16228
16229       name = dwarf2_name (child_die, cu);
16230       if (name == NULL)
16231         name = "<anonymous enumerator>";
16232
16233       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16234                                &value, &bytes, &baton);
16235       if (value < 0)
16236         {
16237           unsigned_enum = 0;
16238           flag_enum = 0;
16239         }
16240       else if ((mask & value) != 0)
16241         flag_enum = 0;
16242       else
16243         mask |= value;
16244
16245       /* If we already know that the enum type is neither unsigned, nor
16246          a flag type, no need to look at the rest of the enumerates.  */
16247       if (!unsigned_enum && !flag_enum)
16248         break;
16249     }
16250
16251   if (unsigned_enum)
16252     TYPE_UNSIGNED (type) = 1;
16253   if (flag_enum)
16254     TYPE_FLAG_ENUM (type) = 1;
16255 }
16256
16257 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16258    complete the type's fields yet, or create any symbols.  */
16259
16260 static struct type *
16261 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16262 {
16263   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16264   struct type *type;
16265   struct attribute *attr;
16266   const char *name;
16267
16268   /* If the definition of this type lives in .debug_types, read that type.
16269      Don't follow DW_AT_specification though, that will take us back up
16270      the chain and we want to go down.  */
16271   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16272   if (attr)
16273     {
16274       type = get_DW_AT_signature_type (die, attr, cu);
16275
16276       /* The type's CU may not be the same as CU.
16277          Ensure TYPE is recorded with CU in die_type_hash.  */
16278       return set_die_type (die, type, cu);
16279     }
16280
16281   type = alloc_type (objfile);
16282
16283   TYPE_CODE (type) = TYPE_CODE_ENUM;
16284   name = dwarf2_full_name (NULL, die, cu);
16285   if (name != NULL)
16286     TYPE_NAME (type) = name;
16287
16288   attr = dwarf2_attr (die, DW_AT_type, cu);
16289   if (attr != NULL)
16290     {
16291       struct type *underlying_type = die_type (die, cu);
16292
16293       TYPE_TARGET_TYPE (type) = underlying_type;
16294     }
16295
16296   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16297   if (attr)
16298     {
16299       TYPE_LENGTH (type) = DW_UNSND (attr);
16300     }
16301   else
16302     {
16303       TYPE_LENGTH (type) = 0;
16304     }
16305
16306   maybe_set_alignment (cu, die, type);
16307
16308   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16309      declared as private in the package spec, and then defined only
16310      inside the package body.  Such types are known as Taft Amendment
16311      Types.  When another package uses such a type, an incomplete DIE
16312      may be generated by the compiler.  */
16313   if (die_is_declaration (die, cu))
16314     TYPE_STUB (type) = 1;
16315
16316   /* Finish the creation of this type by using the enum's children.
16317      We must call this even when the underlying type has been provided
16318      so that we can determine if we're looking at a "flag" enum.  */
16319   update_enumeration_type_from_children (die, type, cu);
16320
16321   /* If this type has an underlying type that is not a stub, then we
16322      may use its attributes.  We always use the "unsigned" attribute
16323      in this situation, because ordinarily we guess whether the type
16324      is unsigned -- but the guess can be wrong and the underlying type
16325      can tell us the reality.  However, we defer to a local size
16326      attribute if one exists, because this lets the compiler override
16327      the underlying type if needed.  */
16328   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16329     {
16330       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16331       if (TYPE_LENGTH (type) == 0)
16332         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16333       if (TYPE_RAW_ALIGN (type) == 0
16334           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16335         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16336     }
16337
16338   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16339
16340   return set_die_type (die, type, cu);
16341 }
16342
16343 /* Given a pointer to a die which begins an enumeration, process all
16344    the dies that define the members of the enumeration, and create the
16345    symbol for the enumeration type.
16346
16347    NOTE: We reverse the order of the element list.  */
16348
16349 static void
16350 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16351 {
16352   struct type *this_type;
16353
16354   this_type = get_die_type (die, cu);
16355   if (this_type == NULL)
16356     this_type = read_enumeration_type (die, cu);
16357
16358   if (die->child != NULL)
16359     {
16360       struct die_info *child_die;
16361       struct symbol *sym;
16362       struct field *fields = NULL;
16363       int num_fields = 0;
16364       const char *name;
16365
16366       child_die = die->child;
16367       while (child_die && child_die->tag)
16368         {
16369           if (child_die->tag != DW_TAG_enumerator)
16370             {
16371               process_die (child_die, cu);
16372             }
16373           else
16374             {
16375               name = dwarf2_name (child_die, cu);
16376               if (name)
16377                 {
16378                   sym = new_symbol (child_die, this_type, cu);
16379
16380                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16381                     {
16382                       fields = (struct field *)
16383                         xrealloc (fields,
16384                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16385                                   * sizeof (struct field));
16386                     }
16387
16388                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16389                   FIELD_TYPE (fields[num_fields]) = NULL;
16390                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16391                   FIELD_BITSIZE (fields[num_fields]) = 0;
16392
16393                   num_fields++;
16394                 }
16395             }
16396
16397           child_die = sibling_die (child_die);
16398         }
16399
16400       if (num_fields)
16401         {
16402           TYPE_NFIELDS (this_type) = num_fields;
16403           TYPE_FIELDS (this_type) = (struct field *)
16404             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16405           memcpy (TYPE_FIELDS (this_type), fields,
16406                   sizeof (struct field) * num_fields);
16407           xfree (fields);
16408         }
16409     }
16410
16411   /* If we are reading an enum from a .debug_types unit, and the enum
16412      is a declaration, and the enum is not the signatured type in the
16413      unit, then we do not want to add a symbol for it.  Adding a
16414      symbol would in some cases obscure the true definition of the
16415      enum, giving users an incomplete type when the definition is
16416      actually available.  Note that we do not want to do this for all
16417      enums which are just declarations, because C++0x allows forward
16418      enum declarations.  */
16419   if (cu->per_cu->is_debug_types
16420       && die_is_declaration (die, cu))
16421     {
16422       struct signatured_type *sig_type;
16423
16424       sig_type = (struct signatured_type *) cu->per_cu;
16425       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16426       if (sig_type->type_offset_in_section != die->sect_off)
16427         return;
16428     }
16429
16430   new_symbol (die, this_type, cu);
16431 }
16432
16433 /* Extract all information from a DW_TAG_array_type DIE and put it in
16434    the DIE's type field.  For now, this only handles one dimensional
16435    arrays.  */
16436
16437 static struct type *
16438 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16439 {
16440   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16441   struct die_info *child_die;
16442   struct type *type;
16443   struct type *element_type, *range_type, *index_type;
16444   struct attribute *attr;
16445   const char *name;
16446   struct dynamic_prop *byte_stride_prop = NULL;
16447   unsigned int bit_stride = 0;
16448
16449   element_type = die_type (die, cu);
16450
16451   /* The die_type call above may have already set the type for this DIE.  */
16452   type = get_die_type (die, cu);
16453   if (type)
16454     return type;
16455
16456   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16457   if (attr != NULL)
16458     {
16459       int stride_ok;
16460
16461       byte_stride_prop
16462         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16463       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16464       if (!stride_ok)
16465         {
16466           complaint (_("unable to read array DW_AT_byte_stride "
16467                        " - DIE at %s [in module %s]"),
16468                      sect_offset_str (die->sect_off),
16469                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16470           /* Ignore this attribute.  We will likely not be able to print
16471              arrays of this type correctly, but there is little we can do
16472              to help if we cannot read the attribute's value.  */
16473           byte_stride_prop = NULL;
16474         }
16475     }
16476
16477   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16478   if (attr != NULL)
16479     bit_stride = DW_UNSND (attr);
16480
16481   /* Irix 6.2 native cc creates array types without children for
16482      arrays with unspecified length.  */
16483   if (die->child == NULL)
16484     {
16485       index_type = objfile_type (objfile)->builtin_int;
16486       range_type = create_static_range_type (NULL, index_type, 0, -1);
16487       type = create_array_type_with_stride (NULL, element_type, range_type,
16488                                             byte_stride_prop, bit_stride);
16489       return set_die_type (die, type, cu);
16490     }
16491
16492   std::vector<struct type *> range_types;
16493   child_die = die->child;
16494   while (child_die && child_die->tag)
16495     {
16496       if (child_die->tag == DW_TAG_subrange_type)
16497         {
16498           struct type *child_type = read_type_die (child_die, cu);
16499
16500           if (child_type != NULL)
16501             {
16502               /* The range type was succesfully read.  Save it for the
16503                  array type creation.  */
16504               range_types.push_back (child_type);
16505             }
16506         }
16507       child_die = sibling_die (child_die);
16508     }
16509
16510   /* Dwarf2 dimensions are output from left to right, create the
16511      necessary array types in backwards order.  */
16512
16513   type = element_type;
16514
16515   if (read_array_order (die, cu) == DW_ORD_col_major)
16516     {
16517       int i = 0;
16518
16519       while (i < range_types.size ())
16520         type = create_array_type_with_stride (NULL, type, range_types[i++],
16521                                               byte_stride_prop, bit_stride);
16522     }
16523   else
16524     {
16525       size_t ndim = range_types.size ();
16526       while (ndim-- > 0)
16527         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16528                                               byte_stride_prop, bit_stride);
16529     }
16530
16531   /* Understand Dwarf2 support for vector types (like they occur on
16532      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16533      array type.  This is not part of the Dwarf2/3 standard yet, but a
16534      custom vendor extension.  The main difference between a regular
16535      array and the vector variant is that vectors are passed by value
16536      to functions.  */
16537   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16538   if (attr)
16539     make_vector_type (type);
16540
16541   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16542      implementation may choose to implement triple vectors using this
16543      attribute.  */
16544   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16545   if (attr)
16546     {
16547       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16548         TYPE_LENGTH (type) = DW_UNSND (attr);
16549       else
16550         complaint (_("DW_AT_byte_size for array type smaller "
16551                      "than the total size of elements"));
16552     }
16553
16554   name = dwarf2_name (die, cu);
16555   if (name)
16556     TYPE_NAME (type) = name;
16557
16558   maybe_set_alignment (cu, die, type);
16559
16560   /* Install the type in the die.  */
16561   set_die_type (die, type, cu);
16562
16563   /* set_die_type should be already done.  */
16564   set_descriptive_type (type, die, cu);
16565
16566   return type;
16567 }
16568
16569 static enum dwarf_array_dim_ordering
16570 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16571 {
16572   struct attribute *attr;
16573
16574   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16575
16576   if (attr)
16577     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16578
16579   /* GNU F77 is a special case, as at 08/2004 array type info is the
16580      opposite order to the dwarf2 specification, but data is still
16581      laid out as per normal fortran.
16582
16583      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16584      version checking.  */
16585
16586   if (cu->language == language_fortran
16587       && cu->producer && strstr (cu->producer, "GNU F77"))
16588     {
16589       return DW_ORD_row_major;
16590     }
16591
16592   switch (cu->language_defn->la_array_ordering)
16593     {
16594     case array_column_major:
16595       return DW_ORD_col_major;
16596     case array_row_major:
16597     default:
16598       return DW_ORD_row_major;
16599     };
16600 }
16601
16602 /* Extract all information from a DW_TAG_set_type DIE and put it in
16603    the DIE's type field.  */
16604
16605 static struct type *
16606 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16607 {
16608   struct type *domain_type, *set_type;
16609   struct attribute *attr;
16610
16611   domain_type = die_type (die, cu);
16612
16613   /* The die_type call above may have already set the type for this DIE.  */
16614   set_type = get_die_type (die, cu);
16615   if (set_type)
16616     return set_type;
16617
16618   set_type = create_set_type (NULL, domain_type);
16619
16620   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16621   if (attr)
16622     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16623
16624   maybe_set_alignment (cu, die, set_type);
16625
16626   return set_die_type (die, set_type, cu);
16627 }
16628
16629 /* A helper for read_common_block that creates a locexpr baton.
16630    SYM is the symbol which we are marking as computed.
16631    COMMON_DIE is the DIE for the common block.
16632    COMMON_LOC is the location expression attribute for the common
16633    block itself.
16634    MEMBER_LOC is the location expression attribute for the particular
16635    member of the common block that we are processing.
16636    CU is the CU from which the above come.  */
16637
16638 static void
16639 mark_common_block_symbol_computed (struct symbol *sym,
16640                                    struct die_info *common_die,
16641                                    struct attribute *common_loc,
16642                                    struct attribute *member_loc,
16643                                    struct dwarf2_cu *cu)
16644 {
16645   struct dwarf2_per_objfile *dwarf2_per_objfile
16646     = cu->per_cu->dwarf2_per_objfile;
16647   struct objfile *objfile = dwarf2_per_objfile->objfile;
16648   struct dwarf2_locexpr_baton *baton;
16649   gdb_byte *ptr;
16650   unsigned int cu_off;
16651   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16652   LONGEST offset = 0;
16653
16654   gdb_assert (common_loc && member_loc);
16655   gdb_assert (attr_form_is_block (common_loc));
16656   gdb_assert (attr_form_is_block (member_loc)
16657               || attr_form_is_constant (member_loc));
16658
16659   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16660   baton->per_cu = cu->per_cu;
16661   gdb_assert (baton->per_cu);
16662
16663   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16664
16665   if (attr_form_is_constant (member_loc))
16666     {
16667       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16668       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16669     }
16670   else
16671     baton->size += DW_BLOCK (member_loc)->size;
16672
16673   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16674   baton->data = ptr;
16675
16676   *ptr++ = DW_OP_call4;
16677   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16678   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16679   ptr += 4;
16680
16681   if (attr_form_is_constant (member_loc))
16682     {
16683       *ptr++ = DW_OP_addr;
16684       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16685       ptr += cu->header.addr_size;
16686     }
16687   else
16688     {
16689       /* We have to copy the data here, because DW_OP_call4 will only
16690          use a DW_AT_location attribute.  */
16691       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16692       ptr += DW_BLOCK (member_loc)->size;
16693     }
16694
16695   *ptr++ = DW_OP_plus;
16696   gdb_assert (ptr - baton->data == baton->size);
16697
16698   SYMBOL_LOCATION_BATON (sym) = baton;
16699   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16700 }
16701
16702 /* Create appropriate locally-scoped variables for all the
16703    DW_TAG_common_block entries.  Also create a struct common_block
16704    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16705    is used to sepate the common blocks name namespace from regular
16706    variable names.  */
16707
16708 static void
16709 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16710 {
16711   struct attribute *attr;
16712
16713   attr = dwarf2_attr (die, DW_AT_location, cu);
16714   if (attr)
16715     {
16716       /* Support the .debug_loc offsets.  */
16717       if (attr_form_is_block (attr))
16718         {
16719           /* Ok.  */
16720         }
16721       else if (attr_form_is_section_offset (attr))
16722         {
16723           dwarf2_complex_location_expr_complaint ();
16724           attr = NULL;
16725         }
16726       else
16727         {
16728           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16729                                                  "common block member");
16730           attr = NULL;
16731         }
16732     }
16733
16734   if (die->child != NULL)
16735     {
16736       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16737       struct die_info *child_die;
16738       size_t n_entries = 0, size;
16739       struct common_block *common_block;
16740       struct symbol *sym;
16741
16742       for (child_die = die->child;
16743            child_die && child_die->tag;
16744            child_die = sibling_die (child_die))
16745         ++n_entries;
16746
16747       size = (sizeof (struct common_block)
16748               + (n_entries - 1) * sizeof (struct symbol *));
16749       common_block
16750         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16751                                                  size);
16752       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16753       common_block->n_entries = 0;
16754
16755       for (child_die = die->child;
16756            child_die && child_die->tag;
16757            child_die = sibling_die (child_die))
16758         {
16759           /* Create the symbol in the DW_TAG_common_block block in the current
16760              symbol scope.  */
16761           sym = new_symbol (child_die, NULL, cu);
16762           if (sym != NULL)
16763             {
16764               struct attribute *member_loc;
16765
16766               common_block->contents[common_block->n_entries++] = sym;
16767
16768               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16769                                         cu);
16770               if (member_loc)
16771                 {
16772                   /* GDB has handled this for a long time, but it is
16773                      not specified by DWARF.  It seems to have been
16774                      emitted by gfortran at least as recently as:
16775                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16776                   complaint (_("Variable in common block has "
16777                                "DW_AT_data_member_location "
16778                                "- DIE at %s [in module %s]"),
16779                                sect_offset_str (child_die->sect_off),
16780                              objfile_name (objfile));
16781
16782                   if (attr_form_is_section_offset (member_loc))
16783                     dwarf2_complex_location_expr_complaint ();
16784                   else if (attr_form_is_constant (member_loc)
16785                            || attr_form_is_block (member_loc))
16786                     {
16787                       if (attr)
16788                         mark_common_block_symbol_computed (sym, die, attr,
16789                                                            member_loc, cu);
16790                     }
16791                   else
16792                     dwarf2_complex_location_expr_complaint ();
16793                 }
16794             }
16795         }
16796
16797       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16798       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16799     }
16800 }
16801
16802 /* Create a type for a C++ namespace.  */
16803
16804 static struct type *
16805 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16806 {
16807   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16808   const char *previous_prefix, *name;
16809   int is_anonymous;
16810   struct type *type;
16811
16812   /* For extensions, reuse the type of the original namespace.  */
16813   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16814     {
16815       struct die_info *ext_die;
16816       struct dwarf2_cu *ext_cu = cu;
16817
16818       ext_die = dwarf2_extension (die, &ext_cu);
16819       type = read_type_die (ext_die, ext_cu);
16820
16821       /* EXT_CU may not be the same as CU.
16822          Ensure TYPE is recorded with CU in die_type_hash.  */
16823       return set_die_type (die, type, cu);
16824     }
16825
16826   name = namespace_name (die, &is_anonymous, cu);
16827
16828   /* Now build the name of the current namespace.  */
16829
16830   previous_prefix = determine_prefix (die, cu);
16831   if (previous_prefix[0] != '\0')
16832     name = typename_concat (&objfile->objfile_obstack,
16833                             previous_prefix, name, 0, cu);
16834
16835   /* Create the type.  */
16836   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16837
16838   return set_die_type (die, type, cu);
16839 }
16840
16841 /* Read a namespace scope.  */
16842
16843 static void
16844 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16845 {
16846   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16847   int is_anonymous;
16848
16849   /* Add a symbol associated to this if we haven't seen the namespace
16850      before.  Also, add a using directive if it's an anonymous
16851      namespace.  */
16852
16853   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16854     {
16855       struct type *type;
16856
16857       type = read_type_die (die, cu);
16858       new_symbol (die, type, cu);
16859
16860       namespace_name (die, &is_anonymous, cu);
16861       if (is_anonymous)
16862         {
16863           const char *previous_prefix = determine_prefix (die, cu);
16864
16865           std::vector<const char *> excludes;
16866           add_using_directive (using_directives (cu),
16867                                previous_prefix, TYPE_NAME (type), NULL,
16868                                NULL, excludes, 0, &objfile->objfile_obstack);
16869         }
16870     }
16871
16872   if (die->child != NULL)
16873     {
16874       struct die_info *child_die = die->child;
16875
16876       while (child_die && child_die->tag)
16877         {
16878           process_die (child_die, cu);
16879           child_die = sibling_die (child_die);
16880         }
16881     }
16882 }
16883
16884 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16885    imported module.  Still we need that type as local Fortran "use ... only"
16886    declaration imports depend on the created type in determine_prefix.  */
16887
16888 static struct type *
16889 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16890 {
16891   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16892   const char *module_name;
16893   struct type *type;
16894
16895   module_name = dwarf2_name (die, cu);
16896   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16897
16898   return set_die_type (die, type, cu);
16899 }
16900
16901 /* Read a Fortran module.  */
16902
16903 static void
16904 read_module (struct die_info *die, struct dwarf2_cu *cu)
16905 {
16906   struct die_info *child_die = die->child;
16907   struct type *type;
16908
16909   type = read_type_die (die, cu);
16910   new_symbol (die, type, cu);
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 /* Return the name of the namespace represented by DIE.  Set
16920    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16921    namespace.  */
16922
16923 static const char *
16924 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16925 {
16926   struct die_info *current_die;
16927   const char *name = NULL;
16928
16929   /* Loop through the extensions until we find a name.  */
16930
16931   for (current_die = die;
16932        current_die != NULL;
16933        current_die = dwarf2_extension (die, &cu))
16934     {
16935       /* We don't use dwarf2_name here so that we can detect the absence
16936          of a name -> anonymous namespace.  */
16937       name = dwarf2_string_attr (die, DW_AT_name, cu);
16938
16939       if (name != NULL)
16940         break;
16941     }
16942
16943   /* Is it an anonymous namespace?  */
16944
16945   *is_anonymous = (name == NULL);
16946   if (*is_anonymous)
16947     name = CP_ANONYMOUS_NAMESPACE_STR;
16948
16949   return name;
16950 }
16951
16952 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16953    the user defined type vector.  */
16954
16955 static struct type *
16956 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16957 {
16958   struct gdbarch *gdbarch
16959     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16960   struct comp_unit_head *cu_header = &cu->header;
16961   struct type *type;
16962   struct attribute *attr_byte_size;
16963   struct attribute *attr_address_class;
16964   int byte_size, addr_class;
16965   struct type *target_type;
16966
16967   target_type = die_type (die, cu);
16968
16969   /* The die_type call above may have already set the type for this DIE.  */
16970   type = get_die_type (die, cu);
16971   if (type)
16972     return type;
16973
16974   type = lookup_pointer_type (target_type);
16975
16976   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16977   if (attr_byte_size)
16978     byte_size = DW_UNSND (attr_byte_size);
16979   else
16980     byte_size = cu_header->addr_size;
16981
16982   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16983   if (attr_address_class)
16984     addr_class = DW_UNSND (attr_address_class);
16985   else
16986     addr_class = DW_ADDR_none;
16987
16988   ULONGEST alignment = get_alignment (cu, die);
16989
16990   /* If the pointer size, alignment, or address class is different
16991      than the default, create a type variant marked as such and set
16992      the length accordingly.  */
16993   if (TYPE_LENGTH (type) != byte_size
16994       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16995           && alignment != TYPE_RAW_ALIGN (type))
16996       || addr_class != DW_ADDR_none)
16997     {
16998       if (gdbarch_address_class_type_flags_p (gdbarch))
16999         {
17000           int type_flags;
17001
17002           type_flags = gdbarch_address_class_type_flags
17003                          (gdbarch, byte_size, addr_class);
17004           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17005                       == 0);
17006           type = make_type_with_address_space (type, type_flags);
17007         }
17008       else if (TYPE_LENGTH (type) != byte_size)
17009         {
17010           complaint (_("invalid pointer size %d"), byte_size);
17011         }
17012       else if (TYPE_RAW_ALIGN (type) != alignment)
17013         {
17014           complaint (_("Invalid DW_AT_alignment"
17015                        " - DIE at %s [in module %s]"),
17016                      sect_offset_str (die->sect_off),
17017                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17018         }
17019       else
17020         {
17021           /* Should we also complain about unhandled address classes?  */
17022         }
17023     }
17024
17025   TYPE_LENGTH (type) = byte_size;
17026   set_type_align (type, alignment);
17027   return set_die_type (die, type, cu);
17028 }
17029
17030 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17031    the user defined type vector.  */
17032
17033 static struct type *
17034 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17035 {
17036   struct type *type;
17037   struct type *to_type;
17038   struct type *domain;
17039
17040   to_type = die_type (die, cu);
17041   domain = die_containing_type (die, cu);
17042
17043   /* The calls above may have already set the type for this DIE.  */
17044   type = get_die_type (die, cu);
17045   if (type)
17046     return type;
17047
17048   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17049     type = lookup_methodptr_type (to_type);
17050   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17051     {
17052       struct type *new_type
17053         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17054
17055       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17056                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17057                             TYPE_VARARGS (to_type));
17058       type = lookup_methodptr_type (new_type);
17059     }
17060   else
17061     type = lookup_memberptr_type (to_type, domain);
17062
17063   return set_die_type (die, type, cu);
17064 }
17065
17066 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17067    the user defined type vector.  */
17068
17069 static struct type *
17070 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17071                           enum type_code refcode)
17072 {
17073   struct comp_unit_head *cu_header = &cu->header;
17074   struct type *type, *target_type;
17075   struct attribute *attr;
17076
17077   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17078
17079   target_type = die_type (die, cu);
17080
17081   /* The die_type call above may have already set the type for this DIE.  */
17082   type = get_die_type (die, cu);
17083   if (type)
17084     return type;
17085
17086   type = lookup_reference_type (target_type, refcode);
17087   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17088   if (attr)
17089     {
17090       TYPE_LENGTH (type) = DW_UNSND (attr);
17091     }
17092   else
17093     {
17094       TYPE_LENGTH (type) = cu_header->addr_size;
17095     }
17096   maybe_set_alignment (cu, die, type);
17097   return set_die_type (die, type, cu);
17098 }
17099
17100 /* Add the given cv-qualifiers to the element type of the array.  GCC
17101    outputs DWARF type qualifiers that apply to an array, not the
17102    element type.  But GDB relies on the array element type to carry
17103    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17104    specification.  */
17105
17106 static struct type *
17107 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17108                    struct type *base_type, int cnst, int voltl)
17109 {
17110   struct type *el_type, *inner_array;
17111
17112   base_type = copy_type (base_type);
17113   inner_array = base_type;
17114
17115   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17116     {
17117       TYPE_TARGET_TYPE (inner_array) =
17118         copy_type (TYPE_TARGET_TYPE (inner_array));
17119       inner_array = TYPE_TARGET_TYPE (inner_array);
17120     }
17121
17122   el_type = TYPE_TARGET_TYPE (inner_array);
17123   cnst |= TYPE_CONST (el_type);
17124   voltl |= TYPE_VOLATILE (el_type);
17125   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17126
17127   return set_die_type (die, base_type, cu);
17128 }
17129
17130 static struct type *
17131 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17132 {
17133   struct type *base_type, *cv_type;
17134
17135   base_type = die_type (die, cu);
17136
17137   /* The die_type call above may have already set the type for this DIE.  */
17138   cv_type = get_die_type (die, cu);
17139   if (cv_type)
17140     return cv_type;
17141
17142   /* In case the const qualifier is applied to an array type, the element type
17143      is so qualified, not the array type (section 6.7.3 of C99).  */
17144   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17145     return add_array_cv_type (die, cu, base_type, 1, 0);
17146
17147   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17148   return set_die_type (die, cv_type, cu);
17149 }
17150
17151 static struct type *
17152 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17153 {
17154   struct type *base_type, *cv_type;
17155
17156   base_type = die_type (die, cu);
17157
17158   /* The die_type call above may have already set the type for this DIE.  */
17159   cv_type = get_die_type (die, cu);
17160   if (cv_type)
17161     return cv_type;
17162
17163   /* In case the volatile qualifier is applied to an array type, the
17164      element type is so qualified, not the array type (section 6.7.3
17165      of C99).  */
17166   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17167     return add_array_cv_type (die, cu, base_type, 0, 1);
17168
17169   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17170   return set_die_type (die, cv_type, cu);
17171 }
17172
17173 /* Handle DW_TAG_restrict_type.  */
17174
17175 static struct type *
17176 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17177 {
17178   struct type *base_type, *cv_type;
17179
17180   base_type = die_type (die, cu);
17181
17182   /* The die_type call above may have already set the type for this DIE.  */
17183   cv_type = get_die_type (die, cu);
17184   if (cv_type)
17185     return cv_type;
17186
17187   cv_type = make_restrict_type (base_type);
17188   return set_die_type (die, cv_type, cu);
17189 }
17190
17191 /* Handle DW_TAG_atomic_type.  */
17192
17193 static struct type *
17194 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17195 {
17196   struct type *base_type, *cv_type;
17197
17198   base_type = die_type (die, cu);
17199
17200   /* The die_type call above may have already set the type for this DIE.  */
17201   cv_type = get_die_type (die, cu);
17202   if (cv_type)
17203     return cv_type;
17204
17205   cv_type = make_atomic_type (base_type);
17206   return set_die_type (die, cv_type, cu);
17207 }
17208
17209 /* Extract all information from a DW_TAG_string_type DIE and add to
17210    the user defined type vector.  It isn't really a user defined type,
17211    but it behaves like one, with other DIE's using an AT_user_def_type
17212    attribute to reference it.  */
17213
17214 static struct type *
17215 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17216 {
17217   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17218   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17219   struct type *type, *range_type, *index_type, *char_type;
17220   struct attribute *attr;
17221   unsigned int length;
17222
17223   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17224   if (attr)
17225     {
17226       length = DW_UNSND (attr);
17227     }
17228   else
17229     {
17230       /* Check for the DW_AT_byte_size attribute.  */
17231       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17232       if (attr)
17233         {
17234           length = DW_UNSND (attr);
17235         }
17236       else
17237         {
17238           length = 1;
17239         }
17240     }
17241
17242   index_type = objfile_type (objfile)->builtin_int;
17243   range_type = create_static_range_type (NULL, index_type, 1, length);
17244   char_type = language_string_char_type (cu->language_defn, gdbarch);
17245   type = create_string_type (NULL, char_type, range_type);
17246
17247   return set_die_type (die, type, cu);
17248 }
17249
17250 /* Assuming that DIE corresponds to a function, returns nonzero
17251    if the function is prototyped.  */
17252
17253 static int
17254 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17255 {
17256   struct attribute *attr;
17257
17258   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17259   if (attr && (DW_UNSND (attr) != 0))
17260     return 1;
17261
17262   /* The DWARF standard implies that the DW_AT_prototyped attribute
17263      is only meaninful for C, but the concept also extends to other
17264      languages that allow unprototyped functions (Eg: Objective C).
17265      For all other languages, assume that functions are always
17266      prototyped.  */
17267   if (cu->language != language_c
17268       && cu->language != language_objc
17269       && cu->language != language_opencl)
17270     return 1;
17271
17272   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17273      prototyped and unprototyped functions; default to prototyped,
17274      since that is more common in modern code (and RealView warns
17275      about unprototyped functions).  */
17276   if (producer_is_realview (cu->producer))
17277     return 1;
17278
17279   return 0;
17280 }
17281
17282 /* Handle DIES due to C code like:
17283
17284    struct foo
17285    {
17286    int (*funcp)(int a, long l);
17287    int b;
17288    };
17289
17290    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17291
17292 static struct type *
17293 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17294 {
17295   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17296   struct type *type;            /* Type that this function returns.  */
17297   struct type *ftype;           /* Function that returns above type.  */
17298   struct attribute *attr;
17299
17300   type = die_type (die, cu);
17301
17302   /* The die_type call above may have already set the type for this DIE.  */
17303   ftype = get_die_type (die, cu);
17304   if (ftype)
17305     return ftype;
17306
17307   ftype = lookup_function_type (type);
17308
17309   if (prototyped_function_p (die, cu))
17310     TYPE_PROTOTYPED (ftype) = 1;
17311
17312   /* Store the calling convention in the type if it's available in
17313      the subroutine die.  Otherwise set the calling convention to
17314      the default value DW_CC_normal.  */
17315   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17316   if (attr)
17317     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17318   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17319     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17320   else
17321     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17322
17323   /* Record whether the function returns normally to its caller or not
17324      if the DWARF producer set that information.  */
17325   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17326   if (attr && (DW_UNSND (attr) != 0))
17327     TYPE_NO_RETURN (ftype) = 1;
17328
17329   /* We need to add the subroutine type to the die immediately so
17330      we don't infinitely recurse when dealing with parameters
17331      declared as the same subroutine type.  */
17332   set_die_type (die, ftype, cu);
17333
17334   if (die->child != NULL)
17335     {
17336       struct type *void_type = objfile_type (objfile)->builtin_void;
17337       struct die_info *child_die;
17338       int nparams, iparams;
17339
17340       /* Count the number of parameters.
17341          FIXME: GDB currently ignores vararg functions, but knows about
17342          vararg member functions.  */
17343       nparams = 0;
17344       child_die = die->child;
17345       while (child_die && child_die->tag)
17346         {
17347           if (child_die->tag == DW_TAG_formal_parameter)
17348             nparams++;
17349           else if (child_die->tag == DW_TAG_unspecified_parameters)
17350             TYPE_VARARGS (ftype) = 1;
17351           child_die = sibling_die (child_die);
17352         }
17353
17354       /* Allocate storage for parameters and fill them in.  */
17355       TYPE_NFIELDS (ftype) = nparams;
17356       TYPE_FIELDS (ftype) = (struct field *)
17357         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17358
17359       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17360          even if we error out during the parameters reading below.  */
17361       for (iparams = 0; iparams < nparams; iparams++)
17362         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17363
17364       iparams = 0;
17365       child_die = die->child;
17366       while (child_die && child_die->tag)
17367         {
17368           if (child_die->tag == DW_TAG_formal_parameter)
17369             {
17370               struct type *arg_type;
17371
17372               /* DWARF version 2 has no clean way to discern C++
17373                  static and non-static member functions.  G++ helps
17374                  GDB by marking the first parameter for non-static
17375                  member functions (which is the this pointer) as
17376                  artificial.  We pass this information to
17377                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17378
17379                  DWARF version 3 added DW_AT_object_pointer, which GCC
17380                  4.5 does not yet generate.  */
17381               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17382               if (attr)
17383                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17384               else
17385                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17386               arg_type = die_type (child_die, cu);
17387
17388               /* RealView does not mark THIS as const, which the testsuite
17389                  expects.  GCC marks THIS as const in method definitions,
17390                  but not in the class specifications (GCC PR 43053).  */
17391               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17392                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17393                 {
17394                   int is_this = 0;
17395                   struct dwarf2_cu *arg_cu = cu;
17396                   const char *name = dwarf2_name (child_die, cu);
17397
17398                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17399                   if (attr)
17400                     {
17401                       /* If the compiler emits this, use it.  */
17402                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17403                         is_this = 1;
17404                     }
17405                   else if (name && strcmp (name, "this") == 0)
17406                     /* Function definitions will have the argument names.  */
17407                     is_this = 1;
17408                   else if (name == NULL && iparams == 0)
17409                     /* Declarations may not have the names, so like
17410                        elsewhere in GDB, assume an artificial first
17411                        argument is "this".  */
17412                     is_this = 1;
17413
17414                   if (is_this)
17415                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17416                                              arg_type, 0);
17417                 }
17418
17419               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17420               iparams++;
17421             }
17422           child_die = sibling_die (child_die);
17423         }
17424     }
17425
17426   return ftype;
17427 }
17428
17429 static struct type *
17430 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17431 {
17432   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17433   const char *name = NULL;
17434   struct type *this_type, *target_type;
17435
17436   name = dwarf2_full_name (NULL, die, cu);
17437   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17438   TYPE_TARGET_STUB (this_type) = 1;
17439   set_die_type (die, this_type, cu);
17440   target_type = die_type (die, cu);
17441   if (target_type != this_type)
17442     TYPE_TARGET_TYPE (this_type) = target_type;
17443   else
17444     {
17445       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17446          spec and cause infinite loops in GDB.  */
17447       complaint (_("Self-referential DW_TAG_typedef "
17448                    "- DIE at %s [in module %s]"),
17449                  sect_offset_str (die->sect_off), objfile_name (objfile));
17450       TYPE_TARGET_TYPE (this_type) = NULL;
17451     }
17452   return this_type;
17453 }
17454
17455 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17456    (which may be different from NAME) to the architecture back-end to allow
17457    it to guess the correct format if necessary.  */
17458
17459 static struct type *
17460 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17461                         const char *name_hint)
17462 {
17463   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17464   const struct floatformat **format;
17465   struct type *type;
17466
17467   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17468   if (format)
17469     type = init_float_type (objfile, bits, name, format);
17470   else
17471     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17472
17473   return type;
17474 }
17475
17476 /* Allocate an integer type of size BITS and name NAME.  */
17477
17478 static struct type *
17479 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17480                           int bits, int unsigned_p, const char *name)
17481 {
17482   struct type *type;
17483
17484   /* Versions of Intel's C Compiler generate an integer type called "void"
17485      instead of using DW_TAG_unspecified_type.  This has been seen on
17486      at least versions 14, 17, and 18.  */
17487   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17488       && strcmp (name, "void") == 0)
17489     type = objfile_type (objfile)->builtin_void;
17490   else
17491     type = init_integer_type (objfile, bits, unsigned_p, name);
17492
17493   return type;
17494 }
17495
17496 /* Initialise and return a floating point type of size BITS suitable for
17497    use as a component of a complex number.  The NAME_HINT is passed through
17498    when initialising the floating point type and is the name of the complex
17499    type.
17500
17501    As DWARF doesn't currently provide an explicit name for the components
17502    of a complex number, but it can be helpful to have these components
17503    named, we try to select a suitable name based on the size of the
17504    component.  */
17505 static struct type *
17506 dwarf2_init_complex_target_type (struct dwarf2_cu *cu,
17507                                  struct objfile *objfile,
17508                                  int bits, const char *name_hint)
17509 {
17510   gdbarch *gdbarch = get_objfile_arch (objfile);
17511   struct type *tt = nullptr;
17512
17513   /* Try to find a suitable floating point builtin type of size BITS.
17514      We're going to use the name of this type as the name for the complex
17515      target type that we are about to create.  */
17516   switch (cu->language)
17517     {
17518     case language_fortran:
17519       switch (bits)
17520         {
17521         case 32:
17522           tt = builtin_f_type (gdbarch)->builtin_real;
17523           break;
17524         case 64:
17525           tt = builtin_f_type (gdbarch)->builtin_real_s8;
17526           break;
17527         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17528         case 128:
17529           tt = builtin_f_type (gdbarch)->builtin_real_s16;
17530           break;
17531         }
17532       break;
17533     default:
17534       switch (bits)
17535         {
17536         case 32:
17537           tt = builtin_type (gdbarch)->builtin_float;
17538           break;
17539         case 64:
17540           tt = builtin_type (gdbarch)->builtin_double;
17541           break;
17542         case 96:        /* The x86-32 ABI specifies 96-bit long double.  */
17543         case 128:
17544           tt = builtin_type (gdbarch)->builtin_long_double;
17545           break;
17546         }
17547       break;
17548     }
17549
17550   /* If the type we found doesn't match the size we were looking for, then
17551      pretend we didn't find a type at all, the complex target type we
17552      create will then be nameless.  */
17553   if (tt != nullptr && TYPE_LENGTH (tt) * TARGET_CHAR_BIT != bits)
17554     tt = nullptr;
17555
17556   const char *name = (tt == nullptr) ? nullptr : TYPE_NAME (tt);
17557   return dwarf2_init_float_type (objfile, bits, name, name_hint);
17558 }
17559
17560 /* Find a representation of a given base type and install
17561    it in the TYPE field of the die.  */
17562
17563 static struct type *
17564 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17565 {
17566   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17567   struct type *type;
17568   struct attribute *attr;
17569   int encoding = 0, bits = 0;
17570   const char *name;
17571
17572   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17573   if (attr)
17574     {
17575       encoding = DW_UNSND (attr);
17576     }
17577   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17578   if (attr)
17579     {
17580       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17581     }
17582   name = dwarf2_name (die, cu);
17583   if (!name)
17584     {
17585       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17586     }
17587
17588   switch (encoding)
17589     {
17590       case DW_ATE_address:
17591         /* Turn DW_ATE_address into a void * pointer.  */
17592         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17593         type = init_pointer_type (objfile, bits, name, type);
17594         break;
17595       case DW_ATE_boolean:
17596         type = init_boolean_type (objfile, bits, 1, name);
17597         break;
17598       case DW_ATE_complex_float:
17599         type = dwarf2_init_complex_target_type (cu, objfile, bits / 2, name);
17600         type = init_complex_type (objfile, name, type);
17601         break;
17602       case DW_ATE_decimal_float:
17603         type = init_decfloat_type (objfile, bits, name);
17604         break;
17605       case DW_ATE_float:
17606         type = dwarf2_init_float_type (objfile, bits, name, name);
17607         break;
17608       case DW_ATE_signed:
17609         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17610         break;
17611       case DW_ATE_unsigned:
17612         if (cu->language == language_fortran
17613             && name
17614             && startswith (name, "character("))
17615           type = init_character_type (objfile, bits, 1, name);
17616         else
17617           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17618         break;
17619       case DW_ATE_signed_char:
17620         if (cu->language == language_ada || cu->language == language_m2
17621             || cu->language == language_pascal
17622             || cu->language == language_fortran)
17623           type = init_character_type (objfile, bits, 0, name);
17624         else
17625           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17626         break;
17627       case DW_ATE_unsigned_char:
17628         if (cu->language == language_ada || cu->language == language_m2
17629             || cu->language == language_pascal
17630             || cu->language == language_fortran
17631             || cu->language == language_rust)
17632           type = init_character_type (objfile, bits, 1, name);
17633         else
17634           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17635         break;
17636       case DW_ATE_UTF:
17637         {
17638           gdbarch *arch = get_objfile_arch (objfile);
17639
17640           if (bits == 16)
17641             type = builtin_type (arch)->builtin_char16;
17642           else if (bits == 32)
17643             type = builtin_type (arch)->builtin_char32;
17644           else
17645             {
17646               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17647                          bits);
17648               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17649             }
17650           return set_die_type (die, type, cu);
17651         }
17652         break;
17653
17654       default:
17655         complaint (_("unsupported DW_AT_encoding: '%s'"),
17656                    dwarf_type_encoding_name (encoding));
17657         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17658         break;
17659     }
17660
17661   if (name && strcmp (name, "char") == 0)
17662     TYPE_NOSIGN (type) = 1;
17663
17664   maybe_set_alignment (cu, die, type);
17665
17666   return set_die_type (die, type, cu);
17667 }
17668
17669 /* Parse dwarf attribute if it's a block, reference or constant and put the
17670    resulting value of the attribute into struct bound_prop.
17671    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17672
17673 static int
17674 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17675                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17676 {
17677   struct dwarf2_property_baton *baton;
17678   struct obstack *obstack
17679     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17680
17681   if (attr == NULL || prop == NULL)
17682     return 0;
17683
17684   if (attr_form_is_block (attr))
17685     {
17686       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17687       baton->referenced_type = NULL;
17688       baton->locexpr.per_cu = cu->per_cu;
17689       baton->locexpr.size = DW_BLOCK (attr)->size;
17690       baton->locexpr.data = DW_BLOCK (attr)->data;
17691       prop->data.baton = baton;
17692       prop->kind = PROP_LOCEXPR;
17693       gdb_assert (prop->data.baton != NULL);
17694     }
17695   else if (attr_form_is_ref (attr))
17696     {
17697       struct dwarf2_cu *target_cu = cu;
17698       struct die_info *target_die;
17699       struct attribute *target_attr;
17700
17701       target_die = follow_die_ref (die, attr, &target_cu);
17702       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17703       if (target_attr == NULL)
17704         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17705                                    target_cu);
17706       if (target_attr == NULL)
17707         return 0;
17708
17709       switch (target_attr->name)
17710         {
17711           case DW_AT_location:
17712             if (attr_form_is_section_offset (target_attr))
17713               {
17714                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17715                 baton->referenced_type = die_type (target_die, target_cu);
17716                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17717                 prop->data.baton = baton;
17718                 prop->kind = PROP_LOCLIST;
17719                 gdb_assert (prop->data.baton != NULL);
17720               }
17721             else if (attr_form_is_block (target_attr))
17722               {
17723                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17724                 baton->referenced_type = die_type (target_die, target_cu);
17725                 baton->locexpr.per_cu = cu->per_cu;
17726                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17727                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17728                 prop->data.baton = baton;
17729                 prop->kind = PROP_LOCEXPR;
17730                 gdb_assert (prop->data.baton != NULL);
17731               }
17732             else
17733               {
17734                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17735                                                        "dynamic property");
17736                 return 0;
17737               }
17738             break;
17739           case DW_AT_data_member_location:
17740             {
17741               LONGEST offset;
17742
17743               if (!handle_data_member_location (target_die, target_cu,
17744                                                 &offset))
17745                 return 0;
17746
17747               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17748               baton->referenced_type = read_type_die (target_die->parent,
17749                                                       target_cu);
17750               baton->offset_info.offset = offset;
17751               baton->offset_info.type = die_type (target_die, target_cu);
17752               prop->data.baton = baton;
17753               prop->kind = PROP_ADDR_OFFSET;
17754               break;
17755             }
17756         }
17757     }
17758   else if (attr_form_is_constant (attr))
17759     {
17760       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17761       prop->kind = PROP_CONST;
17762     }
17763   else
17764     {
17765       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17766                                              dwarf2_name (die, cu));
17767       return 0;
17768     }
17769
17770   return 1;
17771 }
17772
17773 /* Read the given DW_AT_subrange DIE.  */
17774
17775 static struct type *
17776 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17777 {
17778   struct type *base_type, *orig_base_type;
17779   struct type *range_type;
17780   struct attribute *attr;
17781   struct dynamic_prop low, high;
17782   int low_default_is_valid;
17783   int high_bound_is_count = 0;
17784   const char *name;
17785   ULONGEST negative_mask;
17786
17787   orig_base_type = die_type (die, cu);
17788   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17789      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17790      creating the range type, but we use the result of check_typedef
17791      when examining properties of the type.  */
17792   base_type = check_typedef (orig_base_type);
17793
17794   /* The die_type call above may have already set the type for this DIE.  */
17795   range_type = get_die_type (die, cu);
17796   if (range_type)
17797     return range_type;
17798
17799   low.kind = PROP_CONST;
17800   high.kind = PROP_CONST;
17801   high.data.const_val = 0;
17802
17803   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17804      omitting DW_AT_lower_bound.  */
17805   switch (cu->language)
17806     {
17807     case language_c:
17808     case language_cplus:
17809       low.data.const_val = 0;
17810       low_default_is_valid = 1;
17811       break;
17812     case language_fortran:
17813       low.data.const_val = 1;
17814       low_default_is_valid = 1;
17815       break;
17816     case language_d:
17817     case language_objc:
17818     case language_rust:
17819       low.data.const_val = 0;
17820       low_default_is_valid = (cu->header.version >= 4);
17821       break;
17822     case language_ada:
17823     case language_m2:
17824     case language_pascal:
17825       low.data.const_val = 1;
17826       low_default_is_valid = (cu->header.version >= 4);
17827       break;
17828     default:
17829       low.data.const_val = 0;
17830       low_default_is_valid = 0;
17831       break;
17832     }
17833
17834   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17835   if (attr)
17836     attr_to_dynamic_prop (attr, die, cu, &low);
17837   else if (!low_default_is_valid)
17838     complaint (_("Missing DW_AT_lower_bound "
17839                                       "- DIE at %s [in module %s]"),
17840                sect_offset_str (die->sect_off),
17841                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17842
17843   struct attribute *attr_ub, *attr_count;
17844   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17845   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17846     {
17847       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17848       if (attr_to_dynamic_prop (attr, die, cu, &high))
17849         {
17850           /* If bounds are constant do the final calculation here.  */
17851           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17852             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17853           else
17854             high_bound_is_count = 1;
17855         }
17856       else
17857         {
17858           if (attr_ub != NULL)
17859             complaint (_("Unresolved DW_AT_upper_bound "
17860                          "- DIE at %s [in module %s]"),
17861                        sect_offset_str (die->sect_off),
17862                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17863           if (attr_count != NULL)
17864             complaint (_("Unresolved DW_AT_count "
17865                          "- DIE at %s [in module %s]"),
17866                        sect_offset_str (die->sect_off),
17867                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17868         }
17869         
17870     }
17871
17872   /* Dwarf-2 specifications explicitly allows to create subrange types
17873      without specifying a base type.
17874      In that case, the base type must be set to the type of
17875      the lower bound, upper bound or count, in that order, if any of these
17876      three attributes references an object that has a type.
17877      If no base type is found, the Dwarf-2 specifications say that
17878      a signed integer type of size equal to the size of an address should
17879      be used.
17880      For the following C code: `extern char gdb_int [];'
17881      GCC produces an empty range DIE.
17882      FIXME: muller/2010-05-28: Possible references to object for low bound,
17883      high bound or count are not yet handled by this code.  */
17884   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17885     {
17886       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17887       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17888       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17889       struct type *int_type = objfile_type (objfile)->builtin_int;
17890
17891       /* Test "int", "long int", and "long long int" objfile types,
17892          and select the first one having a size above or equal to the
17893          architecture address size.  */
17894       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17895         base_type = int_type;
17896       else
17897         {
17898           int_type = objfile_type (objfile)->builtin_long;
17899           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17900             base_type = int_type;
17901           else
17902             {
17903               int_type = objfile_type (objfile)->builtin_long_long;
17904               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17905                 base_type = int_type;
17906             }
17907         }
17908     }
17909
17910   /* Normally, the DWARF producers are expected to use a signed
17911      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17912      But this is unfortunately not always the case, as witnessed
17913      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17914      is used instead.  To work around that ambiguity, we treat
17915      the bounds as signed, and thus sign-extend their values, when
17916      the base type is signed.  */
17917   negative_mask =
17918     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17919   if (low.kind == PROP_CONST
17920       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17921     low.data.const_val |= negative_mask;
17922   if (high.kind == PROP_CONST
17923       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17924     high.data.const_val |= negative_mask;
17925
17926   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17927
17928   if (high_bound_is_count)
17929     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17930
17931   /* Ada expects an empty array on no boundary attributes.  */
17932   if (attr == NULL && cu->language != language_ada)
17933     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17934
17935   name = dwarf2_name (die, cu);
17936   if (name)
17937     TYPE_NAME (range_type) = name;
17938
17939   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17940   if (attr)
17941     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17942
17943   maybe_set_alignment (cu, die, range_type);
17944
17945   set_die_type (die, range_type, cu);
17946
17947   /* set_die_type should be already done.  */
17948   set_descriptive_type (range_type, die, cu);
17949
17950   return range_type;
17951 }
17952
17953 static struct type *
17954 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17955 {
17956   struct type *type;
17957
17958   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17959                     NULL);
17960   TYPE_NAME (type) = dwarf2_name (die, cu);
17961
17962   /* In Ada, an unspecified type is typically used when the description
17963      of the type is defered to a different unit.  When encountering
17964      such a type, we treat it as a stub, and try to resolve it later on,
17965      when needed.  */
17966   if (cu->language == language_ada)
17967     TYPE_STUB (type) = 1;
17968
17969   return set_die_type (die, type, cu);
17970 }
17971
17972 /* Read a single die and all its descendents.  Set the die's sibling
17973    field to NULL; set other fields in the die correctly, and set all
17974    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17975    location of the info_ptr after reading all of those dies.  PARENT
17976    is the parent of the die in question.  */
17977
17978 static struct die_info *
17979 read_die_and_children (const struct die_reader_specs *reader,
17980                        const gdb_byte *info_ptr,
17981                        const gdb_byte **new_info_ptr,
17982                        struct die_info *parent)
17983 {
17984   struct die_info *die;
17985   const gdb_byte *cur_ptr;
17986   int has_children;
17987
17988   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17989   if (die == NULL)
17990     {
17991       *new_info_ptr = cur_ptr;
17992       return NULL;
17993     }
17994   store_in_ref_table (die, reader->cu);
17995
17996   if (has_children)
17997     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17998   else
17999     {
18000       die->child = NULL;
18001       *new_info_ptr = cur_ptr;
18002     }
18003
18004   die->sibling = NULL;
18005   die->parent = parent;
18006   return die;
18007 }
18008
18009 /* Read a die, all of its descendents, and all of its siblings; set
18010    all of the fields of all of the dies correctly.  Arguments are as
18011    in read_die_and_children.  */
18012
18013 static struct die_info *
18014 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18015                          const gdb_byte *info_ptr,
18016                          const gdb_byte **new_info_ptr,
18017                          struct die_info *parent)
18018 {
18019   struct die_info *first_die, *last_sibling;
18020   const gdb_byte *cur_ptr;
18021
18022   cur_ptr = info_ptr;
18023   first_die = last_sibling = NULL;
18024
18025   while (1)
18026     {
18027       struct die_info *die
18028         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18029
18030       if (die == NULL)
18031         {
18032           *new_info_ptr = cur_ptr;
18033           return first_die;
18034         }
18035
18036       if (!first_die)
18037         first_die = die;
18038       else
18039         last_sibling->sibling = die;
18040
18041       last_sibling = die;
18042     }
18043 }
18044
18045 /* Read a die, all of its descendents, and all of its siblings; set
18046    all of the fields of all of the dies correctly.  Arguments are as
18047    in read_die_and_children.
18048    This the main entry point for reading a DIE and all its children.  */
18049
18050 static struct die_info *
18051 read_die_and_siblings (const struct die_reader_specs *reader,
18052                        const gdb_byte *info_ptr,
18053                        const gdb_byte **new_info_ptr,
18054                        struct die_info *parent)
18055 {
18056   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18057                                                   new_info_ptr, parent);
18058
18059   if (dwarf_die_debug)
18060     {
18061       fprintf_unfiltered (gdb_stdlog,
18062                           "Read die from %s@0x%x of %s:\n",
18063                           get_section_name (reader->die_section),
18064                           (unsigned) (info_ptr - reader->die_section->buffer),
18065                           bfd_get_filename (reader->abfd));
18066       dump_die (die, dwarf_die_debug);
18067     }
18068
18069   return die;
18070 }
18071
18072 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18073    attributes.
18074    The caller is responsible for filling in the extra attributes
18075    and updating (*DIEP)->num_attrs.
18076    Set DIEP to point to a newly allocated die with its information,
18077    except for its child, sibling, and parent fields.
18078    Set HAS_CHILDREN to tell whether the die has children or not.  */
18079
18080 static const gdb_byte *
18081 read_full_die_1 (const struct die_reader_specs *reader,
18082                  struct die_info **diep, const gdb_byte *info_ptr,
18083                  int *has_children, int num_extra_attrs)
18084 {
18085   unsigned int abbrev_number, bytes_read, i;
18086   struct abbrev_info *abbrev;
18087   struct die_info *die;
18088   struct dwarf2_cu *cu = reader->cu;
18089   bfd *abfd = reader->abfd;
18090
18091   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18092   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18093   info_ptr += bytes_read;
18094   if (!abbrev_number)
18095     {
18096       *diep = NULL;
18097       *has_children = 0;
18098       return info_ptr;
18099     }
18100
18101   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18102   if (!abbrev)
18103     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18104            abbrev_number,
18105            bfd_get_filename (abfd));
18106
18107   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18108   die->sect_off = sect_off;
18109   die->tag = abbrev->tag;
18110   die->abbrev = abbrev_number;
18111
18112   /* Make the result usable.
18113      The caller needs to update num_attrs after adding the extra
18114      attributes.  */
18115   die->num_attrs = abbrev->num_attrs;
18116
18117   for (i = 0; i < abbrev->num_attrs; ++i)
18118     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18119                                info_ptr);
18120
18121   *diep = die;
18122   *has_children = abbrev->has_children;
18123   return info_ptr;
18124 }
18125
18126 /* Read a die and all its attributes.
18127    Set DIEP to point to a newly allocated die with its information,
18128    except for its child, sibling, and parent fields.
18129    Set HAS_CHILDREN to tell whether the die has children or not.  */
18130
18131 static const gdb_byte *
18132 read_full_die (const struct die_reader_specs *reader,
18133                struct die_info **diep, const gdb_byte *info_ptr,
18134                int *has_children)
18135 {
18136   const gdb_byte *result;
18137
18138   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18139
18140   if (dwarf_die_debug)
18141     {
18142       fprintf_unfiltered (gdb_stdlog,
18143                           "Read die from %s@0x%x of %s:\n",
18144                           get_section_name (reader->die_section),
18145                           (unsigned) (info_ptr - reader->die_section->buffer),
18146                           bfd_get_filename (reader->abfd));
18147       dump_die (*diep, dwarf_die_debug);
18148     }
18149
18150   return result;
18151 }
18152 \f
18153 /* Abbreviation tables.
18154
18155    In DWARF version 2, the description of the debugging information is
18156    stored in a separate .debug_abbrev section.  Before we read any
18157    dies from a section we read in all abbreviations and install them
18158    in a hash table.  */
18159
18160 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18161
18162 struct abbrev_info *
18163 abbrev_table::alloc_abbrev ()
18164 {
18165   struct abbrev_info *abbrev;
18166
18167   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18168   memset (abbrev, 0, sizeof (struct abbrev_info));
18169
18170   return abbrev;
18171 }
18172
18173 /* Add an abbreviation to the table.  */
18174
18175 void
18176 abbrev_table::add_abbrev (unsigned int abbrev_number,
18177                           struct abbrev_info *abbrev)
18178 {
18179   unsigned int hash_number;
18180
18181   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18182   abbrev->next = m_abbrevs[hash_number];
18183   m_abbrevs[hash_number] = abbrev;
18184 }
18185
18186 /* Look up an abbrev in the table.
18187    Returns NULL if the abbrev is not found.  */
18188
18189 struct abbrev_info *
18190 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18191 {
18192   unsigned int hash_number;
18193   struct abbrev_info *abbrev;
18194
18195   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18196   abbrev = m_abbrevs[hash_number];
18197
18198   while (abbrev)
18199     {
18200       if (abbrev->number == abbrev_number)
18201         return abbrev;
18202       abbrev = abbrev->next;
18203     }
18204   return NULL;
18205 }
18206
18207 /* Read in an abbrev table.  */
18208
18209 static abbrev_table_up
18210 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18211                          struct dwarf2_section_info *section,
18212                          sect_offset sect_off)
18213 {
18214   struct objfile *objfile = dwarf2_per_objfile->objfile;
18215   bfd *abfd = get_section_bfd_owner (section);
18216   const gdb_byte *abbrev_ptr;
18217   struct abbrev_info *cur_abbrev;
18218   unsigned int abbrev_number, bytes_read, abbrev_name;
18219   unsigned int abbrev_form;
18220   struct attr_abbrev *cur_attrs;
18221   unsigned int allocated_attrs;
18222
18223   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18224
18225   dwarf2_read_section (objfile, section);
18226   abbrev_ptr = section->buffer + to_underlying (sect_off);
18227   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18228   abbrev_ptr += bytes_read;
18229
18230   allocated_attrs = ATTR_ALLOC_CHUNK;
18231   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18232
18233   /* Loop until we reach an abbrev number of 0.  */
18234   while (abbrev_number)
18235     {
18236       cur_abbrev = abbrev_table->alloc_abbrev ();
18237
18238       /* read in abbrev header */
18239       cur_abbrev->number = abbrev_number;
18240       cur_abbrev->tag
18241         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18242       abbrev_ptr += bytes_read;
18243       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18244       abbrev_ptr += 1;
18245
18246       /* now read in declarations */
18247       for (;;)
18248         {
18249           LONGEST implicit_const;
18250
18251           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18252           abbrev_ptr += bytes_read;
18253           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18254           abbrev_ptr += bytes_read;
18255           if (abbrev_form == DW_FORM_implicit_const)
18256             {
18257               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18258                                                    &bytes_read);
18259               abbrev_ptr += bytes_read;
18260             }
18261           else
18262             {
18263               /* Initialize it due to a false compiler warning.  */
18264               implicit_const = -1;
18265             }
18266
18267           if (abbrev_name == 0)
18268             break;
18269
18270           if (cur_abbrev->num_attrs == allocated_attrs)
18271             {
18272               allocated_attrs += ATTR_ALLOC_CHUNK;
18273               cur_attrs
18274                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18275             }
18276
18277           cur_attrs[cur_abbrev->num_attrs].name
18278             = (enum dwarf_attribute) abbrev_name;
18279           cur_attrs[cur_abbrev->num_attrs].form
18280             = (enum dwarf_form) abbrev_form;
18281           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18282           ++cur_abbrev->num_attrs;
18283         }
18284
18285       cur_abbrev->attrs =
18286         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18287                    cur_abbrev->num_attrs);
18288       memcpy (cur_abbrev->attrs, cur_attrs,
18289               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18290
18291       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18292
18293       /* Get next abbreviation.
18294          Under Irix6 the abbreviations for a compilation unit are not
18295          always properly terminated with an abbrev number of 0.
18296          Exit loop if we encounter an abbreviation which we have
18297          already read (which means we are about to read the abbreviations
18298          for the next compile unit) or if the end of the abbreviation
18299          table is reached.  */
18300       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18301         break;
18302       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18303       abbrev_ptr += bytes_read;
18304       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18305         break;
18306     }
18307
18308   xfree (cur_attrs);
18309   return abbrev_table;
18310 }
18311
18312 /* Returns nonzero if TAG represents a type that we might generate a partial
18313    symbol for.  */
18314
18315 static int
18316 is_type_tag_for_partial (int tag)
18317 {
18318   switch (tag)
18319     {
18320 #if 0
18321     /* Some types that would be reasonable to generate partial symbols for,
18322        that we don't at present.  */
18323     case DW_TAG_array_type:
18324     case DW_TAG_file_type:
18325     case DW_TAG_ptr_to_member_type:
18326     case DW_TAG_set_type:
18327     case DW_TAG_string_type:
18328     case DW_TAG_subroutine_type:
18329 #endif
18330     case DW_TAG_base_type:
18331     case DW_TAG_class_type:
18332     case DW_TAG_interface_type:
18333     case DW_TAG_enumeration_type:
18334     case DW_TAG_structure_type:
18335     case DW_TAG_subrange_type:
18336     case DW_TAG_typedef:
18337     case DW_TAG_union_type:
18338       return 1;
18339     default:
18340       return 0;
18341     }
18342 }
18343
18344 /* Load all DIEs that are interesting for partial symbols into memory.  */
18345
18346 static struct partial_die_info *
18347 load_partial_dies (const struct die_reader_specs *reader,
18348                    const gdb_byte *info_ptr, int building_psymtab)
18349 {
18350   struct dwarf2_cu *cu = reader->cu;
18351   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18352   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18353   unsigned int bytes_read;
18354   unsigned int load_all = 0;
18355   int nesting_level = 1;
18356
18357   parent_die = NULL;
18358   last_die = NULL;
18359
18360   gdb_assert (cu->per_cu != NULL);
18361   if (cu->per_cu->load_all_dies)
18362     load_all = 1;
18363
18364   cu->partial_dies
18365     = htab_create_alloc_ex (cu->header.length / 12,
18366                             partial_die_hash,
18367                             partial_die_eq,
18368                             NULL,
18369                             &cu->comp_unit_obstack,
18370                             hashtab_obstack_allocate,
18371                             dummy_obstack_deallocate);
18372
18373   while (1)
18374     {
18375       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18376
18377       /* A NULL abbrev means the end of a series of children.  */
18378       if (abbrev == NULL)
18379         {
18380           if (--nesting_level == 0)
18381             return first_die;
18382
18383           info_ptr += bytes_read;
18384           last_die = parent_die;
18385           parent_die = parent_die->die_parent;
18386           continue;
18387         }
18388
18389       /* Check for template arguments.  We never save these; if
18390          they're seen, we just mark the parent, and go on our way.  */
18391       if (parent_die != NULL
18392           && cu->language == language_cplus
18393           && (abbrev->tag == DW_TAG_template_type_param
18394               || abbrev->tag == DW_TAG_template_value_param))
18395         {
18396           parent_die->has_template_arguments = 1;
18397
18398           if (!load_all)
18399             {
18400               /* We don't need a partial DIE for the template argument.  */
18401               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18402               continue;
18403             }
18404         }
18405
18406       /* We only recurse into c++ subprograms looking for template arguments.
18407          Skip their other children.  */
18408       if (!load_all
18409           && cu->language == language_cplus
18410           && parent_die != NULL
18411           && parent_die->tag == DW_TAG_subprogram)
18412         {
18413           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18414           continue;
18415         }
18416
18417       /* Check whether this DIE is interesting enough to save.  Normally
18418          we would not be interested in members here, but there may be
18419          later variables referencing them via DW_AT_specification (for
18420          static members).  */
18421       if (!load_all
18422           && !is_type_tag_for_partial (abbrev->tag)
18423           && abbrev->tag != DW_TAG_constant
18424           && abbrev->tag != DW_TAG_enumerator
18425           && abbrev->tag != DW_TAG_subprogram
18426           && abbrev->tag != DW_TAG_inlined_subroutine
18427           && abbrev->tag != DW_TAG_lexical_block
18428           && abbrev->tag != DW_TAG_variable
18429           && abbrev->tag != DW_TAG_namespace
18430           && abbrev->tag != DW_TAG_module
18431           && abbrev->tag != DW_TAG_member
18432           && abbrev->tag != DW_TAG_imported_unit
18433           && abbrev->tag != DW_TAG_imported_declaration)
18434         {
18435           /* Otherwise we skip to the next sibling, if any.  */
18436           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18437           continue;
18438         }
18439
18440       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18441                                    abbrev);
18442
18443       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18444
18445       /* This two-pass algorithm for processing partial symbols has a
18446          high cost in cache pressure.  Thus, handle some simple cases
18447          here which cover the majority of C partial symbols.  DIEs
18448          which neither have specification tags in them, nor could have
18449          specification tags elsewhere pointing at them, can simply be
18450          processed and discarded.
18451
18452          This segment is also optional; scan_partial_symbols and
18453          add_partial_symbol will handle these DIEs if we chain
18454          them in normally.  When compilers which do not emit large
18455          quantities of duplicate debug information are more common,
18456          this code can probably be removed.  */
18457
18458       /* Any complete simple types at the top level (pretty much all
18459          of them, for a language without namespaces), can be processed
18460          directly.  */
18461       if (parent_die == NULL
18462           && pdi.has_specification == 0
18463           && pdi.is_declaration == 0
18464           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18465               || pdi.tag == DW_TAG_base_type
18466               || pdi.tag == DW_TAG_subrange_type))
18467         {
18468           if (building_psymtab && pdi.name != NULL)
18469             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18470                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18471                                  psymbol_placement::STATIC,
18472                                  0, cu->language, objfile);
18473           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18474           continue;
18475         }
18476
18477       /* The exception for DW_TAG_typedef with has_children above is
18478          a workaround of GCC PR debug/47510.  In the case of this complaint
18479          type_name_or_error will error on such types later.
18480
18481          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18482          it could not find the child DIEs referenced later, this is checked
18483          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18484
18485       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18486         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18487                      "- DIE at %s [in module %s]"),
18488                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18489
18490       /* If we're at the second level, and we're an enumerator, and
18491          our parent has no specification (meaning possibly lives in a
18492          namespace elsewhere), then we can add the partial symbol now
18493          instead of queueing it.  */
18494       if (pdi.tag == DW_TAG_enumerator
18495           && parent_die != NULL
18496           && parent_die->die_parent == NULL
18497           && parent_die->tag == DW_TAG_enumeration_type
18498           && parent_die->has_specification == 0)
18499         {
18500           if (pdi.name == NULL)
18501             complaint (_("malformed enumerator DIE ignored"));
18502           else if (building_psymtab)
18503             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18504                                  VAR_DOMAIN, LOC_CONST, -1,
18505                                  cu->language == language_cplus
18506                                  ? psymbol_placement::GLOBAL
18507                                  : psymbol_placement::STATIC,
18508                                  0, cu->language, objfile);
18509
18510           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18511           continue;
18512         }
18513
18514       struct partial_die_info *part_die
18515         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18516
18517       /* We'll save this DIE so link it in.  */
18518       part_die->die_parent = parent_die;
18519       part_die->die_sibling = NULL;
18520       part_die->die_child = NULL;
18521
18522       if (last_die && last_die == parent_die)
18523         last_die->die_child = part_die;
18524       else if (last_die)
18525         last_die->die_sibling = part_die;
18526
18527       last_die = part_die;
18528
18529       if (first_die == NULL)
18530         first_die = part_die;
18531
18532       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18533          find interesting need to be in the hash table, because we
18534          also have the parent/sibling/child chains; only those that we
18535          might refer to by offset later during partial symbol reading.
18536
18537          For now this means things that might have be the target of a
18538          DW_AT_specification, DW_AT_abstract_origin, or
18539          DW_AT_extension.  DW_AT_extension will refer only to
18540          namespaces; DW_AT_abstract_origin refers to functions (and
18541          many things under the function DIE, but we do not recurse
18542          into function DIEs during partial symbol reading) and
18543          possibly variables as well; DW_AT_specification refers to
18544          declarations.  Declarations ought to have the DW_AT_declaration
18545          flag.  It happens that GCC forgets to put it in sometimes, but
18546          only for functions, not for types.
18547
18548          Adding more things than necessary to the hash table is harmless
18549          except for the performance cost.  Adding too few will result in
18550          wasted time in find_partial_die, when we reread the compilation
18551          unit with load_all_dies set.  */
18552
18553       if (load_all
18554           || abbrev->tag == DW_TAG_constant
18555           || abbrev->tag == DW_TAG_subprogram
18556           || abbrev->tag == DW_TAG_variable
18557           || abbrev->tag == DW_TAG_namespace
18558           || part_die->is_declaration)
18559         {
18560           void **slot;
18561
18562           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18563                                            to_underlying (part_die->sect_off),
18564                                            INSERT);
18565           *slot = part_die;
18566         }
18567
18568       /* For some DIEs we want to follow their children (if any).  For C
18569          we have no reason to follow the children of structures; for other
18570          languages we have to, so that we can get at method physnames
18571          to infer fully qualified class names, for DW_AT_specification,
18572          and for C++ template arguments.  For C++, we also look one level
18573          inside functions to find template arguments (if the name of the
18574          function does not already contain the template arguments).
18575
18576          For Ada, we need to scan the children of subprograms and lexical
18577          blocks as well because Ada allows the definition of nested
18578          entities that could be interesting for the debugger, such as
18579          nested subprograms for instance.  */
18580       if (last_die->has_children
18581           && (load_all
18582               || last_die->tag == DW_TAG_namespace
18583               || last_die->tag == DW_TAG_module
18584               || last_die->tag == DW_TAG_enumeration_type
18585               || (cu->language == language_cplus
18586                   && last_die->tag == DW_TAG_subprogram
18587                   && (last_die->name == NULL
18588                       || strchr (last_die->name, '<') == NULL))
18589               || (cu->language != language_c
18590                   && (last_die->tag == DW_TAG_class_type
18591                       || last_die->tag == DW_TAG_interface_type
18592                       || last_die->tag == DW_TAG_structure_type
18593                       || last_die->tag == DW_TAG_union_type))
18594               || (cu->language == language_ada
18595                   && (last_die->tag == DW_TAG_subprogram
18596                       || last_die->tag == DW_TAG_lexical_block))))
18597         {
18598           nesting_level++;
18599           parent_die = last_die;
18600           continue;
18601         }
18602
18603       /* Otherwise we skip to the next sibling, if any.  */
18604       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18605
18606       /* Back to the top, do it again.  */
18607     }
18608 }
18609
18610 partial_die_info::partial_die_info (sect_offset sect_off_,
18611                                     struct abbrev_info *abbrev)
18612   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18613 {
18614 }
18615
18616 /* Read a minimal amount of information into the minimal die structure.
18617    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18618
18619 const gdb_byte *
18620 partial_die_info::read (const struct die_reader_specs *reader,
18621                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18622 {
18623   struct dwarf2_cu *cu = reader->cu;
18624   struct dwarf2_per_objfile *dwarf2_per_objfile
18625     = cu->per_cu->dwarf2_per_objfile;
18626   unsigned int i;
18627   int has_low_pc_attr = 0;
18628   int has_high_pc_attr = 0;
18629   int high_pc_relative = 0;
18630
18631   for (i = 0; i < abbrev.num_attrs; ++i)
18632     {
18633       struct attribute attr;
18634
18635       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18636
18637       /* Store the data if it is of an attribute we want to keep in a
18638          partial symbol table.  */
18639       switch (attr.name)
18640         {
18641         case DW_AT_name:
18642           switch (tag)
18643             {
18644             case DW_TAG_compile_unit:
18645             case DW_TAG_partial_unit:
18646             case DW_TAG_type_unit:
18647               /* Compilation units have a DW_AT_name that is a filename, not
18648                  a source language identifier.  */
18649             case DW_TAG_enumeration_type:
18650             case DW_TAG_enumerator:
18651               /* These tags always have simple identifiers already; no need
18652                  to canonicalize them.  */
18653               name = DW_STRING (&attr);
18654               break;
18655             default:
18656               {
18657                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18658
18659                 name
18660                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18661                                               &objfile->per_bfd->storage_obstack);
18662               }
18663               break;
18664             }
18665           break;
18666         case DW_AT_linkage_name:
18667         case DW_AT_MIPS_linkage_name:
18668           /* Note that both forms of linkage name might appear.  We
18669              assume they will be the same, and we only store the last
18670              one we see.  */
18671           if (cu->language == language_ada)
18672             name = DW_STRING (&attr);
18673           linkage_name = DW_STRING (&attr);
18674           break;
18675         case DW_AT_low_pc:
18676           has_low_pc_attr = 1;
18677           lowpc = attr_value_as_address (&attr);
18678           break;
18679         case DW_AT_high_pc:
18680           has_high_pc_attr = 1;
18681           highpc = attr_value_as_address (&attr);
18682           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18683                 high_pc_relative = 1;
18684           break;
18685         case DW_AT_location:
18686           /* Support the .debug_loc offsets.  */
18687           if (attr_form_is_block (&attr))
18688             {
18689                d.locdesc = DW_BLOCK (&attr);
18690             }
18691           else if (attr_form_is_section_offset (&attr))
18692             {
18693               dwarf2_complex_location_expr_complaint ();
18694             }
18695           else
18696             {
18697               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18698                                                      "partial symbol information");
18699             }
18700           break;
18701         case DW_AT_external:
18702           is_external = DW_UNSND (&attr);
18703           break;
18704         case DW_AT_declaration:
18705           is_declaration = DW_UNSND (&attr);
18706           break;
18707         case DW_AT_type:
18708           has_type = 1;
18709           break;
18710         case DW_AT_abstract_origin:
18711         case DW_AT_specification:
18712         case DW_AT_extension:
18713           has_specification = 1;
18714           spec_offset = dwarf2_get_ref_die_offset (&attr);
18715           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18716                                    || cu->per_cu->is_dwz);
18717           break;
18718         case DW_AT_sibling:
18719           /* Ignore absolute siblings, they might point outside of
18720              the current compile unit.  */
18721           if (attr.form == DW_FORM_ref_addr)
18722             complaint (_("ignoring absolute DW_AT_sibling"));
18723           else
18724             {
18725               const gdb_byte *buffer = reader->buffer;
18726               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18727               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18728
18729               if (sibling_ptr < info_ptr)
18730                 complaint (_("DW_AT_sibling points backwards"));
18731               else if (sibling_ptr > reader->buffer_end)
18732                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18733               else
18734                 sibling = sibling_ptr;
18735             }
18736           break;
18737         case DW_AT_byte_size:
18738           has_byte_size = 1;
18739           break;
18740         case DW_AT_const_value:
18741           has_const_value = 1;
18742           break;
18743         case DW_AT_calling_convention:
18744           /* DWARF doesn't provide a way to identify a program's source-level
18745              entry point.  DW_AT_calling_convention attributes are only meant
18746              to describe functions' calling conventions.
18747
18748              However, because it's a necessary piece of information in
18749              Fortran, and before DWARF 4 DW_CC_program was the only
18750              piece of debugging information whose definition refers to
18751              a 'main program' at all, several compilers marked Fortran
18752              main programs with DW_CC_program --- even when those
18753              functions use the standard calling conventions.
18754
18755              Although DWARF now specifies a way to provide this
18756              information, we support this practice for backward
18757              compatibility.  */
18758           if (DW_UNSND (&attr) == DW_CC_program
18759               && cu->language == language_fortran)
18760             main_subprogram = 1;
18761           break;
18762         case DW_AT_inline:
18763           if (DW_UNSND (&attr) == DW_INL_inlined
18764               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18765             may_be_inlined = 1;
18766           break;
18767
18768         case DW_AT_import:
18769           if (tag == DW_TAG_imported_unit)
18770             {
18771               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18772               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18773                                   || cu->per_cu->is_dwz);
18774             }
18775           break;
18776
18777         case DW_AT_main_subprogram:
18778           main_subprogram = DW_UNSND (&attr);
18779           break;
18780
18781         case DW_AT_ranges:
18782           {
18783             /* It would be nice to reuse dwarf2_get_pc_bounds here,
18784                but that requires a full DIE, so instead we just
18785                reimplement it.  */
18786             int need_ranges_base = tag != DW_TAG_compile_unit;
18787             unsigned int ranges_offset = (DW_UNSND (&attr)
18788                                           + (need_ranges_base
18789                                              ? cu->ranges_base
18790                                              : 0));
18791
18792             /* Value of the DW_AT_ranges attribute is the offset in the
18793                .debug_ranges section.  */
18794             if (dwarf2_ranges_read (ranges_offset, &lowpc, &highpc, cu,
18795                                     nullptr))
18796               has_pc_info = 1;
18797           }
18798           break;
18799
18800         default:
18801           break;
18802         }
18803     }
18804
18805   if (high_pc_relative)
18806     highpc += lowpc;
18807
18808   if (has_low_pc_attr && has_high_pc_attr)
18809     {
18810       /* When using the GNU linker, .gnu.linkonce. sections are used to
18811          eliminate duplicate copies of functions and vtables and such.
18812          The linker will arbitrarily choose one and discard the others.
18813          The AT_*_pc values for such functions refer to local labels in
18814          these sections.  If the section from that file was discarded, the
18815          labels are not in the output, so the relocs get a value of 0.
18816          If this is a discarded function, mark the pc bounds as invalid,
18817          so that GDB will ignore it.  */
18818       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18819         {
18820           struct objfile *objfile = dwarf2_per_objfile->objfile;
18821           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18822
18823           complaint (_("DW_AT_low_pc %s is zero "
18824                        "for DIE at %s [in module %s]"),
18825                      paddress (gdbarch, lowpc),
18826                      sect_offset_str (sect_off),
18827                      objfile_name (objfile));
18828         }
18829       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18830       else if (lowpc >= highpc)
18831         {
18832           struct objfile *objfile = dwarf2_per_objfile->objfile;
18833           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18834
18835           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18836                        "for DIE at %s [in module %s]"),
18837                      paddress (gdbarch, lowpc),
18838                      paddress (gdbarch, highpc),
18839                      sect_offset_str (sect_off),
18840                      objfile_name (objfile));
18841         }
18842       else
18843         has_pc_info = 1;
18844     }
18845
18846   return info_ptr;
18847 }
18848
18849 /* Find a cached partial DIE at OFFSET in CU.  */
18850
18851 struct partial_die_info *
18852 dwarf2_cu::find_partial_die (sect_offset sect_off)
18853 {
18854   struct partial_die_info *lookup_die = NULL;
18855   struct partial_die_info part_die (sect_off);
18856
18857   lookup_die = ((struct partial_die_info *)
18858                 htab_find_with_hash (partial_dies, &part_die,
18859                                      to_underlying (sect_off)));
18860
18861   return lookup_die;
18862 }
18863
18864 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18865    except in the case of .debug_types DIEs which do not reference
18866    outside their CU (they do however referencing other types via
18867    DW_FORM_ref_sig8).  */
18868
18869 static const struct cu_partial_die_info
18870 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18871 {
18872   struct dwarf2_per_objfile *dwarf2_per_objfile
18873     = cu->per_cu->dwarf2_per_objfile;
18874   struct objfile *objfile = dwarf2_per_objfile->objfile;
18875   struct dwarf2_per_cu_data *per_cu = NULL;
18876   struct partial_die_info *pd = NULL;
18877
18878   if (offset_in_dwz == cu->per_cu->is_dwz
18879       && offset_in_cu_p (&cu->header, sect_off))
18880     {
18881       pd = cu->find_partial_die (sect_off);
18882       if (pd != NULL)
18883         return { cu, pd };
18884       /* We missed recording what we needed.
18885          Load all dies and try again.  */
18886       per_cu = cu->per_cu;
18887     }
18888   else
18889     {
18890       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18891       if (cu->per_cu->is_debug_types)
18892         {
18893           error (_("Dwarf Error: Type Unit at offset %s contains"
18894                    " external reference to offset %s [in module %s].\n"),
18895                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18896                  bfd_get_filename (objfile->obfd));
18897         }
18898       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18899                                                  dwarf2_per_objfile);
18900
18901       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18902         load_partial_comp_unit (per_cu);
18903
18904       per_cu->cu->last_used = 0;
18905       pd = per_cu->cu->find_partial_die (sect_off);
18906     }
18907
18908   /* If we didn't find it, and not all dies have been loaded,
18909      load them all and try again.  */
18910
18911   if (pd == NULL && per_cu->load_all_dies == 0)
18912     {
18913       per_cu->load_all_dies = 1;
18914
18915       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18916          THIS_CU->cu may already be in use.  So we can't just free it and
18917          replace its DIEs with the ones we read in.  Instead, we leave those
18918          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18919          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18920          set.  */
18921       load_partial_comp_unit (per_cu);
18922
18923       pd = per_cu->cu->find_partial_die (sect_off);
18924     }
18925
18926   if (pd == NULL)
18927     internal_error (__FILE__, __LINE__,
18928                     _("could not find partial DIE %s "
18929                       "in cache [from module %s]\n"),
18930                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18931   return { per_cu->cu, pd };
18932 }
18933
18934 /* See if we can figure out if the class lives in a namespace.  We do
18935    this by looking for a member function; its demangled name will
18936    contain namespace info, if there is any.  */
18937
18938 static void
18939 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18940                                   struct dwarf2_cu *cu)
18941 {
18942   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18943      what template types look like, because the demangler
18944      frequently doesn't give the same name as the debug info.  We
18945      could fix this by only using the demangled name to get the
18946      prefix (but see comment in read_structure_type).  */
18947
18948   struct partial_die_info *real_pdi;
18949   struct partial_die_info *child_pdi;
18950
18951   /* If this DIE (this DIE's specification, if any) has a parent, then
18952      we should not do this.  We'll prepend the parent's fully qualified
18953      name when we create the partial symbol.  */
18954
18955   real_pdi = struct_pdi;
18956   while (real_pdi->has_specification)
18957     {
18958       auto res = find_partial_die (real_pdi->spec_offset,
18959                                    real_pdi->spec_is_dwz, cu);
18960       real_pdi = res.pdi;
18961       cu = res.cu;
18962     }
18963
18964   if (real_pdi->die_parent != NULL)
18965     return;
18966
18967   for (child_pdi = struct_pdi->die_child;
18968        child_pdi != NULL;
18969        child_pdi = child_pdi->die_sibling)
18970     {
18971       if (child_pdi->tag == DW_TAG_subprogram
18972           && child_pdi->linkage_name != NULL)
18973         {
18974           char *actual_class_name
18975             = language_class_name_from_physname (cu->language_defn,
18976                                                  child_pdi->linkage_name);
18977           if (actual_class_name != NULL)
18978             {
18979               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18980               struct_pdi->name
18981                 = ((const char *)
18982                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18983                                   actual_class_name,
18984                                   strlen (actual_class_name)));
18985               xfree (actual_class_name);
18986             }
18987           break;
18988         }
18989     }
18990 }
18991
18992 void
18993 partial_die_info::fixup (struct dwarf2_cu *cu)
18994 {
18995   /* Once we've fixed up a die, there's no point in doing so again.
18996      This also avoids a memory leak if we were to call
18997      guess_partial_die_structure_name multiple times.  */
18998   if (fixup_called)
18999     return;
19000
19001   /* If we found a reference attribute and the DIE has no name, try
19002      to find a name in the referred to DIE.  */
19003
19004   if (name == NULL && has_specification)
19005     {
19006       struct partial_die_info *spec_die;
19007
19008       auto res = find_partial_die (spec_offset, spec_is_dwz, cu);
19009       spec_die = res.pdi;
19010       cu = res.cu;
19011
19012       spec_die->fixup (cu);
19013
19014       if (spec_die->name)
19015         {
19016           name = spec_die->name;
19017
19018           /* Copy DW_AT_external attribute if it is set.  */
19019           if (spec_die->is_external)
19020             is_external = spec_die->is_external;
19021         }
19022     }
19023
19024   /* Set default names for some unnamed DIEs.  */
19025
19026   if (name == NULL && tag == DW_TAG_namespace)
19027     name = CP_ANONYMOUS_NAMESPACE_STR;
19028
19029   /* If there is no parent die to provide a namespace, and there are
19030      children, see if we can determine the namespace from their linkage
19031      name.  */
19032   if (cu->language == language_cplus
19033       && !VEC_empty (dwarf2_section_info_def,
19034                      cu->per_cu->dwarf2_per_objfile->types)
19035       && die_parent == NULL
19036       && has_children
19037       && (tag == DW_TAG_class_type
19038           || tag == DW_TAG_structure_type
19039           || tag == DW_TAG_union_type))
19040     guess_partial_die_structure_name (this, cu);
19041
19042   /* GCC might emit a nameless struct or union that has a linkage
19043      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19044   if (name == NULL
19045       && (tag == DW_TAG_class_type
19046           || tag == DW_TAG_interface_type
19047           || tag == DW_TAG_structure_type
19048           || tag == DW_TAG_union_type)
19049       && linkage_name != NULL)
19050     {
19051       char *demangled;
19052
19053       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
19054       if (demangled)
19055         {
19056           const char *base;
19057
19058           /* Strip any leading namespaces/classes, keep only the base name.
19059              DW_AT_name for named DIEs does not contain the prefixes.  */
19060           base = strrchr (demangled, ':');
19061           if (base && base > demangled && base[-1] == ':')
19062             base++;
19063           else
19064             base = demangled;
19065
19066           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19067           name
19068             = ((const char *)
19069                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19070                               base, strlen (base)));
19071           xfree (demangled);
19072         }
19073     }
19074
19075   fixup_called = 1;
19076 }
19077
19078 /* Read an attribute value described by an attribute form.  */
19079
19080 static const gdb_byte *
19081 read_attribute_value (const struct die_reader_specs *reader,
19082                       struct attribute *attr, unsigned form,
19083                       LONGEST implicit_const, const gdb_byte *info_ptr)
19084 {
19085   struct dwarf2_cu *cu = reader->cu;
19086   struct dwarf2_per_objfile *dwarf2_per_objfile
19087     = cu->per_cu->dwarf2_per_objfile;
19088   struct objfile *objfile = dwarf2_per_objfile->objfile;
19089   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19090   bfd *abfd = reader->abfd;
19091   struct comp_unit_head *cu_header = &cu->header;
19092   unsigned int bytes_read;
19093   struct dwarf_block *blk;
19094
19095   attr->form = (enum dwarf_form) form;
19096   switch (form)
19097     {
19098     case DW_FORM_ref_addr:
19099       if (cu->header.version == 2)
19100         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19101       else
19102         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19103                                        &cu->header, &bytes_read);
19104       info_ptr += bytes_read;
19105       break;
19106     case DW_FORM_GNU_ref_alt:
19107       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19108       info_ptr += bytes_read;
19109       break;
19110     case DW_FORM_addr:
19111       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19112       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19113       info_ptr += bytes_read;
19114       break;
19115     case DW_FORM_block2:
19116       blk = dwarf_alloc_block (cu);
19117       blk->size = read_2_bytes (abfd, info_ptr);
19118       info_ptr += 2;
19119       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19120       info_ptr += blk->size;
19121       DW_BLOCK (attr) = blk;
19122       break;
19123     case DW_FORM_block4:
19124       blk = dwarf_alloc_block (cu);
19125       blk->size = read_4_bytes (abfd, info_ptr);
19126       info_ptr += 4;
19127       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19128       info_ptr += blk->size;
19129       DW_BLOCK (attr) = blk;
19130       break;
19131     case DW_FORM_data2:
19132       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19133       info_ptr += 2;
19134       break;
19135     case DW_FORM_data4:
19136       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19137       info_ptr += 4;
19138       break;
19139     case DW_FORM_data8:
19140       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19141       info_ptr += 8;
19142       break;
19143     case DW_FORM_data16:
19144       blk = dwarf_alloc_block (cu);
19145       blk->size = 16;
19146       blk->data = read_n_bytes (abfd, info_ptr, 16);
19147       info_ptr += 16;
19148       DW_BLOCK (attr) = blk;
19149       break;
19150     case DW_FORM_sec_offset:
19151       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19152       info_ptr += bytes_read;
19153       break;
19154     case DW_FORM_string:
19155       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19156       DW_STRING_IS_CANONICAL (attr) = 0;
19157       info_ptr += bytes_read;
19158       break;
19159     case DW_FORM_strp:
19160       if (!cu->per_cu->is_dwz)
19161         {
19162           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19163                                                    abfd, info_ptr, cu_header,
19164                                                    &bytes_read);
19165           DW_STRING_IS_CANONICAL (attr) = 0;
19166           info_ptr += bytes_read;
19167           break;
19168         }
19169       /* FALLTHROUGH */
19170     case DW_FORM_line_strp:
19171       if (!cu->per_cu->is_dwz)
19172         {
19173           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19174                                                         abfd, info_ptr,
19175                                                         cu_header, &bytes_read);
19176           DW_STRING_IS_CANONICAL (attr) = 0;
19177           info_ptr += bytes_read;
19178           break;
19179         }
19180       /* FALLTHROUGH */
19181     case DW_FORM_GNU_strp_alt:
19182       {
19183         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19184         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19185                                           &bytes_read);
19186
19187         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19188                                                           dwz, str_offset);
19189         DW_STRING_IS_CANONICAL (attr) = 0;
19190         info_ptr += bytes_read;
19191       }
19192       break;
19193     case DW_FORM_exprloc:
19194     case DW_FORM_block:
19195       blk = dwarf_alloc_block (cu);
19196       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19197       info_ptr += bytes_read;
19198       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19199       info_ptr += blk->size;
19200       DW_BLOCK (attr) = blk;
19201       break;
19202     case DW_FORM_block1:
19203       blk = dwarf_alloc_block (cu);
19204       blk->size = read_1_byte (abfd, info_ptr);
19205       info_ptr += 1;
19206       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19207       info_ptr += blk->size;
19208       DW_BLOCK (attr) = blk;
19209       break;
19210     case DW_FORM_data1:
19211       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19212       info_ptr += 1;
19213       break;
19214     case DW_FORM_flag:
19215       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19216       info_ptr += 1;
19217       break;
19218     case DW_FORM_flag_present:
19219       DW_UNSND (attr) = 1;
19220       break;
19221     case DW_FORM_sdata:
19222       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19223       info_ptr += bytes_read;
19224       break;
19225     case DW_FORM_udata:
19226       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19227       info_ptr += bytes_read;
19228       break;
19229     case DW_FORM_ref1:
19230       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19231                          + read_1_byte (abfd, info_ptr));
19232       info_ptr += 1;
19233       break;
19234     case DW_FORM_ref2:
19235       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19236                          + read_2_bytes (abfd, info_ptr));
19237       info_ptr += 2;
19238       break;
19239     case DW_FORM_ref4:
19240       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19241                          + read_4_bytes (abfd, info_ptr));
19242       info_ptr += 4;
19243       break;
19244     case DW_FORM_ref8:
19245       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19246                          + read_8_bytes (abfd, info_ptr));
19247       info_ptr += 8;
19248       break;
19249     case DW_FORM_ref_sig8:
19250       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19251       info_ptr += 8;
19252       break;
19253     case DW_FORM_ref_udata:
19254       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19255                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19256       info_ptr += bytes_read;
19257       break;
19258     case DW_FORM_indirect:
19259       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19260       info_ptr += bytes_read;
19261       if (form == DW_FORM_implicit_const)
19262         {
19263           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19264           info_ptr += bytes_read;
19265         }
19266       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19267                                        info_ptr);
19268       break;
19269     case DW_FORM_implicit_const:
19270       DW_SND (attr) = implicit_const;
19271       break;
19272     case DW_FORM_addrx:
19273     case DW_FORM_GNU_addr_index:
19274       if (reader->dwo_file == NULL)
19275         {
19276           /* For now flag a hard error.
19277              Later we can turn this into a complaint.  */
19278           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19279                  dwarf_form_name (form),
19280                  bfd_get_filename (abfd));
19281         }
19282       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19283       info_ptr += bytes_read;
19284       break;
19285     case DW_FORM_strx:
19286     case DW_FORM_strx1:
19287     case DW_FORM_strx2:
19288     case DW_FORM_strx3:
19289     case DW_FORM_strx4:
19290     case DW_FORM_GNU_str_index:
19291       if (reader->dwo_file == NULL)
19292         {
19293           /* For now flag a hard error.
19294              Later we can turn this into a complaint if warranted.  */
19295           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19296                  dwarf_form_name (form),
19297                  bfd_get_filename (abfd));
19298         }
19299       {
19300         ULONGEST str_index;
19301         if (form == DW_FORM_strx1)
19302           {
19303             str_index = read_1_byte (abfd, info_ptr);
19304             info_ptr += 1;
19305           }
19306         else if (form == DW_FORM_strx2)
19307           {
19308             str_index = read_2_bytes (abfd, info_ptr);
19309             info_ptr += 2;
19310           }
19311         else if (form == DW_FORM_strx3)
19312           {
19313             str_index = read_3_bytes (abfd, info_ptr);
19314             info_ptr += 3;
19315           }
19316         else if (form == DW_FORM_strx4)
19317           {
19318             str_index = read_4_bytes (abfd, info_ptr);
19319             info_ptr += 4;
19320           }
19321         else
19322           {
19323             str_index = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19324             info_ptr += bytes_read;
19325           }
19326         DW_STRING (attr) = read_str_index (reader, str_index);
19327         DW_STRING_IS_CANONICAL (attr) = 0;
19328       }
19329       break;
19330     default:
19331       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19332              dwarf_form_name (form),
19333              bfd_get_filename (abfd));
19334     }
19335
19336   /* Super hack.  */
19337   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19338     attr->form = DW_FORM_GNU_ref_alt;
19339
19340   /* We have seen instances where the compiler tried to emit a byte
19341      size attribute of -1 which ended up being encoded as an unsigned
19342      0xffffffff.  Although 0xffffffff is technically a valid size value,
19343      an object of this size seems pretty unlikely so we can relatively
19344      safely treat these cases as if the size attribute was invalid and
19345      treat them as zero by default.  */
19346   if (attr->name == DW_AT_byte_size
19347       && form == DW_FORM_data4
19348       && DW_UNSND (attr) >= 0xffffffff)
19349     {
19350       complaint
19351         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19352          hex_string (DW_UNSND (attr)));
19353       DW_UNSND (attr) = 0;
19354     }
19355
19356   return info_ptr;
19357 }
19358
19359 /* Read an attribute described by an abbreviated attribute.  */
19360
19361 static const gdb_byte *
19362 read_attribute (const struct die_reader_specs *reader,
19363                 struct attribute *attr, struct attr_abbrev *abbrev,
19364                 const gdb_byte *info_ptr)
19365 {
19366   attr->name = abbrev->name;
19367   return read_attribute_value (reader, attr, abbrev->form,
19368                                abbrev->implicit_const, info_ptr);
19369 }
19370
19371 /* Read dwarf information from a buffer.  */
19372
19373 static unsigned int
19374 read_1_byte (bfd *abfd, const gdb_byte *buf)
19375 {
19376   return bfd_get_8 (abfd, buf);
19377 }
19378
19379 static int
19380 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19381 {
19382   return bfd_get_signed_8 (abfd, buf);
19383 }
19384
19385 static unsigned int
19386 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19387 {
19388   return bfd_get_16 (abfd, buf);
19389 }
19390
19391 static int
19392 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19393 {
19394   return bfd_get_signed_16 (abfd, buf);
19395 }
19396
19397 static unsigned int
19398 read_3_bytes (bfd *abfd, const gdb_byte *buf)
19399 {
19400   unsigned int result = 0;
19401   for (int i = 0; i < 3; ++i)
19402     {
19403       unsigned char byte = bfd_get_8 (abfd, buf);
19404       buf++;
19405       result |= ((unsigned int) byte << (i * 8));
19406     }
19407   return result;
19408 }
19409
19410 static unsigned int
19411 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19412 {
19413   return bfd_get_32 (abfd, buf);
19414 }
19415
19416 static int
19417 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19418 {
19419   return bfd_get_signed_32 (abfd, buf);
19420 }
19421
19422 static ULONGEST
19423 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19424 {
19425   return bfd_get_64 (abfd, buf);
19426 }
19427
19428 static CORE_ADDR
19429 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19430               unsigned int *bytes_read)
19431 {
19432   struct comp_unit_head *cu_header = &cu->header;
19433   CORE_ADDR retval = 0;
19434
19435   if (cu_header->signed_addr_p)
19436     {
19437       switch (cu_header->addr_size)
19438         {
19439         case 2:
19440           retval = bfd_get_signed_16 (abfd, buf);
19441           break;
19442         case 4:
19443           retval = bfd_get_signed_32 (abfd, buf);
19444           break;
19445         case 8:
19446           retval = bfd_get_signed_64 (abfd, buf);
19447           break;
19448         default:
19449           internal_error (__FILE__, __LINE__,
19450                           _("read_address: bad switch, signed [in module %s]"),
19451                           bfd_get_filename (abfd));
19452         }
19453     }
19454   else
19455     {
19456       switch (cu_header->addr_size)
19457         {
19458         case 2:
19459           retval = bfd_get_16 (abfd, buf);
19460           break;
19461         case 4:
19462           retval = bfd_get_32 (abfd, buf);
19463           break;
19464         case 8:
19465           retval = bfd_get_64 (abfd, buf);
19466           break;
19467         default:
19468           internal_error (__FILE__, __LINE__,
19469                           _("read_address: bad switch, "
19470                             "unsigned [in module %s]"),
19471                           bfd_get_filename (abfd));
19472         }
19473     }
19474
19475   *bytes_read = cu_header->addr_size;
19476   return retval;
19477 }
19478
19479 /* Read the initial length from a section.  The (draft) DWARF 3
19480    specification allows the initial length to take up either 4 bytes
19481    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19482    bytes describe the length and all offsets will be 8 bytes in length
19483    instead of 4.
19484
19485    An older, non-standard 64-bit format is also handled by this
19486    function.  The older format in question stores the initial length
19487    as an 8-byte quantity without an escape value.  Lengths greater
19488    than 2^32 aren't very common which means that the initial 4 bytes
19489    is almost always zero.  Since a length value of zero doesn't make
19490    sense for the 32-bit format, this initial zero can be considered to
19491    be an escape value which indicates the presence of the older 64-bit
19492    format.  As written, the code can't detect (old format) lengths
19493    greater than 4GB.  If it becomes necessary to handle lengths
19494    somewhat larger than 4GB, we could allow other small values (such
19495    as the non-sensical values of 1, 2, and 3) to also be used as
19496    escape values indicating the presence of the old format.
19497
19498    The value returned via bytes_read should be used to increment the
19499    relevant pointer after calling read_initial_length().
19500
19501    [ Note:  read_initial_length() and read_offset() are based on the
19502      document entitled "DWARF Debugging Information Format", revision
19503      3, draft 8, dated November 19, 2001.  This document was obtained
19504      from:
19505
19506         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19507
19508      This document is only a draft and is subject to change.  (So beware.)
19509
19510      Details regarding the older, non-standard 64-bit format were
19511      determined empirically by examining 64-bit ELF files produced by
19512      the SGI toolchain on an IRIX 6.5 machine.
19513
19514      - Kevin, July 16, 2002
19515    ] */
19516
19517 static LONGEST
19518 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19519 {
19520   LONGEST length = bfd_get_32 (abfd, buf);
19521
19522   if (length == 0xffffffff)
19523     {
19524       length = bfd_get_64 (abfd, buf + 4);
19525       *bytes_read = 12;
19526     }
19527   else if (length == 0)
19528     {
19529       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19530       length = bfd_get_64 (abfd, buf);
19531       *bytes_read = 8;
19532     }
19533   else
19534     {
19535       *bytes_read = 4;
19536     }
19537
19538   return length;
19539 }
19540
19541 /* Cover function for read_initial_length.
19542    Returns the length of the object at BUF, and stores the size of the
19543    initial length in *BYTES_READ and stores the size that offsets will be in
19544    *OFFSET_SIZE.
19545    If the initial length size is not equivalent to that specified in
19546    CU_HEADER then issue a complaint.
19547    This is useful when reading non-comp-unit headers.  */
19548
19549 static LONGEST
19550 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19551                                         const struct comp_unit_head *cu_header,
19552                                         unsigned int *bytes_read,
19553                                         unsigned int *offset_size)
19554 {
19555   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19556
19557   gdb_assert (cu_header->initial_length_size == 4
19558               || cu_header->initial_length_size == 8
19559               || cu_header->initial_length_size == 12);
19560
19561   if (cu_header->initial_length_size != *bytes_read)
19562     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19563
19564   *offset_size = (*bytes_read == 4) ? 4 : 8;
19565   return length;
19566 }
19567
19568 /* Read an offset from the data stream.  The size of the offset is
19569    given by cu_header->offset_size.  */
19570
19571 static LONGEST
19572 read_offset (bfd *abfd, const gdb_byte *buf,
19573              const struct comp_unit_head *cu_header,
19574              unsigned int *bytes_read)
19575 {
19576   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19577
19578   *bytes_read = cu_header->offset_size;
19579   return offset;
19580 }
19581
19582 /* Read an offset from the data stream.  */
19583
19584 static LONGEST
19585 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19586 {
19587   LONGEST retval = 0;
19588
19589   switch (offset_size)
19590     {
19591     case 4:
19592       retval = bfd_get_32 (abfd, buf);
19593       break;
19594     case 8:
19595       retval = bfd_get_64 (abfd, buf);
19596       break;
19597     default:
19598       internal_error (__FILE__, __LINE__,
19599                       _("read_offset_1: bad switch [in module %s]"),
19600                       bfd_get_filename (abfd));
19601     }
19602
19603   return retval;
19604 }
19605
19606 static const gdb_byte *
19607 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19608 {
19609   /* If the size of a host char is 8 bits, we can return a pointer
19610      to the buffer, otherwise we have to copy the data to a buffer
19611      allocated on the temporary obstack.  */
19612   gdb_assert (HOST_CHAR_BIT == 8);
19613   return buf;
19614 }
19615
19616 static const char *
19617 read_direct_string (bfd *abfd, const gdb_byte *buf,
19618                     unsigned int *bytes_read_ptr)
19619 {
19620   /* If the size of a host char is 8 bits, we can return a pointer
19621      to the string, otherwise we have to copy the string to a buffer
19622      allocated on the temporary obstack.  */
19623   gdb_assert (HOST_CHAR_BIT == 8);
19624   if (*buf == '\0')
19625     {
19626       *bytes_read_ptr = 1;
19627       return NULL;
19628     }
19629   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19630   return (const char *) buf;
19631 }
19632
19633 /* Return pointer to string at section SECT offset STR_OFFSET with error
19634    reporting strings FORM_NAME and SECT_NAME.  */
19635
19636 static const char *
19637 read_indirect_string_at_offset_from (struct objfile *objfile,
19638                                      bfd *abfd, LONGEST str_offset,
19639                                      struct dwarf2_section_info *sect,
19640                                      const char *form_name,
19641                                      const char *sect_name)
19642 {
19643   dwarf2_read_section (objfile, sect);
19644   if (sect->buffer == NULL)
19645     error (_("%s used without %s section [in module %s]"),
19646            form_name, sect_name, bfd_get_filename (abfd));
19647   if (str_offset >= sect->size)
19648     error (_("%s pointing outside of %s section [in module %s]"),
19649            form_name, sect_name, bfd_get_filename (abfd));
19650   gdb_assert (HOST_CHAR_BIT == 8);
19651   if (sect->buffer[str_offset] == '\0')
19652     return NULL;
19653   return (const char *) (sect->buffer + str_offset);
19654 }
19655
19656 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19657
19658 static const char *
19659 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19660                                 bfd *abfd, LONGEST str_offset)
19661 {
19662   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19663                                               abfd, str_offset,
19664                                               &dwarf2_per_objfile->str,
19665                                               "DW_FORM_strp", ".debug_str");
19666 }
19667
19668 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19669
19670 static const char *
19671 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19672                                      bfd *abfd, LONGEST str_offset)
19673 {
19674   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19675                                               abfd, str_offset,
19676                                               &dwarf2_per_objfile->line_str,
19677                                               "DW_FORM_line_strp",
19678                                               ".debug_line_str");
19679 }
19680
19681 /* Read a string at offset STR_OFFSET in the .debug_str section from
19682    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19683    the string consists of a single NUL byte, return NULL; otherwise
19684    return a pointer to the string.  */
19685
19686 static const char *
19687 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19688                                LONGEST str_offset)
19689 {
19690   dwarf2_read_section (objfile, &dwz->str);
19691
19692   if (dwz->str.buffer == NULL)
19693     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19694              "section [in module %s]"),
19695            bfd_get_filename (dwz->dwz_bfd));
19696   if (str_offset >= dwz->str.size)
19697     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19698              ".debug_str section [in module %s]"),
19699            bfd_get_filename (dwz->dwz_bfd));
19700   gdb_assert (HOST_CHAR_BIT == 8);
19701   if (dwz->str.buffer[str_offset] == '\0')
19702     return NULL;
19703   return (const char *) (dwz->str.buffer + str_offset);
19704 }
19705
19706 /* Return pointer to string at .debug_str offset as read from BUF.
19707    BUF is assumed to be in a compilation unit described by CU_HEADER.
19708    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19709
19710 static const char *
19711 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19712                       const gdb_byte *buf,
19713                       const struct comp_unit_head *cu_header,
19714                       unsigned int *bytes_read_ptr)
19715 {
19716   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19717
19718   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19719 }
19720
19721 /* Return pointer to string at .debug_line_str offset as read from BUF.
19722    BUF is assumed to be in a compilation unit described by CU_HEADER.
19723    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19724
19725 static const char *
19726 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19727                            bfd *abfd, const gdb_byte *buf,
19728                            const struct comp_unit_head *cu_header,
19729                            unsigned int *bytes_read_ptr)
19730 {
19731   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19732
19733   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19734                                               str_offset);
19735 }
19736
19737 ULONGEST
19738 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19739                           unsigned int *bytes_read_ptr)
19740 {
19741   ULONGEST result;
19742   unsigned int num_read;
19743   int shift;
19744   unsigned char byte;
19745
19746   result = 0;
19747   shift = 0;
19748   num_read = 0;
19749   while (1)
19750     {
19751       byte = bfd_get_8 (abfd, buf);
19752       buf++;
19753       num_read++;
19754       result |= ((ULONGEST) (byte & 127) << shift);
19755       if ((byte & 128) == 0)
19756         {
19757           break;
19758         }
19759       shift += 7;
19760     }
19761   *bytes_read_ptr = num_read;
19762   return result;
19763 }
19764
19765 static LONGEST
19766 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19767                     unsigned int *bytes_read_ptr)
19768 {
19769   ULONGEST result;
19770   int shift, num_read;
19771   unsigned char byte;
19772
19773   result = 0;
19774   shift = 0;
19775   num_read = 0;
19776   while (1)
19777     {
19778       byte = bfd_get_8 (abfd, buf);
19779       buf++;
19780       num_read++;
19781       result |= ((ULONGEST) (byte & 127) << shift);
19782       shift += 7;
19783       if ((byte & 128) == 0)
19784         {
19785           break;
19786         }
19787     }
19788   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19789     result |= -(((ULONGEST) 1) << shift);
19790   *bytes_read_ptr = num_read;
19791   return result;
19792 }
19793
19794 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19795    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19796    ADDR_SIZE is the size of addresses from the CU header.  */
19797
19798 static CORE_ADDR
19799 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19800                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19801 {
19802   struct objfile *objfile = dwarf2_per_objfile->objfile;
19803   bfd *abfd = objfile->obfd;
19804   const gdb_byte *info_ptr;
19805
19806   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19807   if (dwarf2_per_objfile->addr.buffer == NULL)
19808     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19809            objfile_name (objfile));
19810   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19811     error (_("DW_FORM_addr_index pointing outside of "
19812              ".debug_addr section [in module %s]"),
19813            objfile_name (objfile));
19814   info_ptr = (dwarf2_per_objfile->addr.buffer
19815               + addr_base + addr_index * addr_size);
19816   if (addr_size == 4)
19817     return bfd_get_32 (abfd, info_ptr);
19818   else
19819     return bfd_get_64 (abfd, info_ptr);
19820 }
19821
19822 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19823
19824 static CORE_ADDR
19825 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19826 {
19827   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19828                             cu->addr_base, cu->header.addr_size);
19829 }
19830
19831 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19832
19833 static CORE_ADDR
19834 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19835                              unsigned int *bytes_read)
19836 {
19837   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19838   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19839
19840   return read_addr_index (cu, addr_index);
19841 }
19842
19843 /* Data structure to pass results from dwarf2_read_addr_index_reader
19844    back to dwarf2_read_addr_index.  */
19845
19846 struct dwarf2_read_addr_index_data
19847 {
19848   ULONGEST addr_base;
19849   int addr_size;
19850 };
19851
19852 /* die_reader_func for dwarf2_read_addr_index.  */
19853
19854 static void
19855 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19856                                const gdb_byte *info_ptr,
19857                                struct die_info *comp_unit_die,
19858                                int has_children,
19859                                void *data)
19860 {
19861   struct dwarf2_cu *cu = reader->cu;
19862   struct dwarf2_read_addr_index_data *aidata =
19863     (struct dwarf2_read_addr_index_data *) data;
19864
19865   aidata->addr_base = cu->addr_base;
19866   aidata->addr_size = cu->header.addr_size;
19867 }
19868
19869 /* Given an index in .debug_addr, fetch the value.
19870    NOTE: This can be called during dwarf expression evaluation,
19871    long after the debug information has been read, and thus per_cu->cu
19872    may no longer exist.  */
19873
19874 CORE_ADDR
19875 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19876                         unsigned int addr_index)
19877 {
19878   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19879   struct dwarf2_cu *cu = per_cu->cu;
19880   ULONGEST addr_base;
19881   int addr_size;
19882
19883   /* We need addr_base and addr_size.
19884      If we don't have PER_CU->cu, we have to get it.
19885      Nasty, but the alternative is storing the needed info in PER_CU,
19886      which at this point doesn't seem justified: it's not clear how frequently
19887      it would get used and it would increase the size of every PER_CU.
19888      Entry points like dwarf2_per_cu_addr_size do a similar thing
19889      so we're not in uncharted territory here.
19890      Alas we need to be a bit more complicated as addr_base is contained
19891      in the DIE.
19892
19893      We don't need to read the entire CU(/TU).
19894      We just need the header and top level die.
19895
19896      IWBN to use the aging mechanism to let us lazily later discard the CU.
19897      For now we skip this optimization.  */
19898
19899   if (cu != NULL)
19900     {
19901       addr_base = cu->addr_base;
19902       addr_size = cu->header.addr_size;
19903     }
19904   else
19905     {
19906       struct dwarf2_read_addr_index_data aidata;
19907
19908       /* Note: We can't use init_cutu_and_read_dies_simple here,
19909          we need addr_base.  */
19910       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19911                                dwarf2_read_addr_index_reader, &aidata);
19912       addr_base = aidata.addr_base;
19913       addr_size = aidata.addr_size;
19914     }
19915
19916   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19917                             addr_size);
19918 }
19919
19920 /* Given a DW_FORM_GNU_str_index or DW_FORM_strx, fetch the string.
19921    This is only used by the Fission support.  */
19922
19923 static const char *
19924 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19925 {
19926   struct dwarf2_cu *cu = reader->cu;
19927   struct dwarf2_per_objfile *dwarf2_per_objfile
19928     = cu->per_cu->dwarf2_per_objfile;
19929   struct objfile *objfile = dwarf2_per_objfile->objfile;
19930   const char *objf_name = objfile_name (objfile);
19931   bfd *abfd = objfile->obfd;
19932   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19933   struct dwarf2_section_info *str_offsets_section =
19934     &reader->dwo_file->sections.str_offsets;
19935   const gdb_byte *info_ptr;
19936   ULONGEST str_offset;
19937   static const char form_name[] = "DW_FORM_GNU_str_index or DW_FORM_strx";
19938
19939   dwarf2_read_section (objfile, str_section);
19940   dwarf2_read_section (objfile, str_offsets_section);
19941   if (str_section->buffer == NULL)
19942     error (_("%s used without .debug_str.dwo section"
19943              " in CU at offset %s [in module %s]"),
19944            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19945   if (str_offsets_section->buffer == NULL)
19946     error (_("%s used without .debug_str_offsets.dwo section"
19947              " in CU at offset %s [in module %s]"),
19948            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19949   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19950     error (_("%s pointing outside of .debug_str_offsets.dwo"
19951              " section in CU at offset %s [in module %s]"),
19952            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19953   info_ptr = (str_offsets_section->buffer
19954               + str_index * cu->header.offset_size);
19955   if (cu->header.offset_size == 4)
19956     str_offset = bfd_get_32 (abfd, info_ptr);
19957   else
19958     str_offset = bfd_get_64 (abfd, info_ptr);
19959   if (str_offset >= str_section->size)
19960     error (_("Offset from %s pointing outside of"
19961              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19962            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19963   return (const char *) (str_section->buffer + str_offset);
19964 }
19965
19966 /* Return the length of an LEB128 number in BUF.  */
19967
19968 static int
19969 leb128_size (const gdb_byte *buf)
19970 {
19971   const gdb_byte *begin = buf;
19972   gdb_byte byte;
19973
19974   while (1)
19975     {
19976       byte = *buf++;
19977       if ((byte & 128) == 0)
19978         return buf - begin;
19979     }
19980 }
19981
19982 static void
19983 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19984 {
19985   switch (lang)
19986     {
19987     case DW_LANG_C89:
19988     case DW_LANG_C99:
19989     case DW_LANG_C11:
19990     case DW_LANG_C:
19991     case DW_LANG_UPC:
19992       cu->language = language_c;
19993       break;
19994     case DW_LANG_Java:
19995     case DW_LANG_C_plus_plus:
19996     case DW_LANG_C_plus_plus_11:
19997     case DW_LANG_C_plus_plus_14:
19998       cu->language = language_cplus;
19999       break;
20000     case DW_LANG_D:
20001       cu->language = language_d;
20002       break;
20003     case DW_LANG_Fortran77:
20004     case DW_LANG_Fortran90:
20005     case DW_LANG_Fortran95:
20006     case DW_LANG_Fortran03:
20007     case DW_LANG_Fortran08:
20008       cu->language = language_fortran;
20009       break;
20010     case DW_LANG_Go:
20011       cu->language = language_go;
20012       break;
20013     case DW_LANG_Mips_Assembler:
20014       cu->language = language_asm;
20015       break;
20016     case DW_LANG_Ada83:
20017     case DW_LANG_Ada95:
20018       cu->language = language_ada;
20019       break;
20020     case DW_LANG_Modula2:
20021       cu->language = language_m2;
20022       break;
20023     case DW_LANG_Pascal83:
20024       cu->language = language_pascal;
20025       break;
20026     case DW_LANG_ObjC:
20027       cu->language = language_objc;
20028       break;
20029     case DW_LANG_Rust:
20030     case DW_LANG_Rust_old:
20031       cu->language = language_rust;
20032       break;
20033     case DW_LANG_Cobol74:
20034     case DW_LANG_Cobol85:
20035     default:
20036       cu->language = language_minimal;
20037       break;
20038     }
20039   cu->language_defn = language_def (cu->language);
20040 }
20041
20042 /* Return the named attribute or NULL if not there.  */
20043
20044 static struct attribute *
20045 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20046 {
20047   for (;;)
20048     {
20049       unsigned int i;
20050       struct attribute *spec = NULL;
20051
20052       for (i = 0; i < die->num_attrs; ++i)
20053         {
20054           if (die->attrs[i].name == name)
20055             return &die->attrs[i];
20056           if (die->attrs[i].name == DW_AT_specification
20057               || die->attrs[i].name == DW_AT_abstract_origin)
20058             spec = &die->attrs[i];
20059         }
20060
20061       if (!spec)
20062         break;
20063
20064       die = follow_die_ref (die, spec, &cu);
20065     }
20066
20067   return NULL;
20068 }
20069
20070 /* Return the named attribute or NULL if not there,
20071    but do not follow DW_AT_specification, etc.
20072    This is for use in contexts where we're reading .debug_types dies.
20073    Following DW_AT_specification, DW_AT_abstract_origin will take us
20074    back up the chain, and we want to go down.  */
20075
20076 static struct attribute *
20077 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20078 {
20079   unsigned int i;
20080
20081   for (i = 0; i < die->num_attrs; ++i)
20082     if (die->attrs[i].name == name)
20083       return &die->attrs[i];
20084
20085   return NULL;
20086 }
20087
20088 /* Return the string associated with a string-typed attribute, or NULL if it
20089    is either not found or is of an incorrect type.  */
20090
20091 static const char *
20092 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20093 {
20094   struct attribute *attr;
20095   const char *str = NULL;
20096
20097   attr = dwarf2_attr (die, name, cu);
20098
20099   if (attr != NULL)
20100     {
20101       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20102           || attr->form == DW_FORM_string
20103           || attr->form == DW_FORM_strx
20104           || attr->form == DW_FORM_GNU_str_index
20105           || attr->form == DW_FORM_GNU_strp_alt)
20106         str = DW_STRING (attr);
20107       else
20108         complaint (_("string type expected for attribute %s for "
20109                      "DIE at %s in module %s"),
20110                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20111                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20112     }
20113
20114   return str;
20115 }
20116
20117 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20118    and holds a non-zero value.  This function should only be used for
20119    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20120
20121 static int
20122 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20123 {
20124   struct attribute *attr = dwarf2_attr (die, name, cu);
20125
20126   return (attr && DW_UNSND (attr));
20127 }
20128
20129 static int
20130 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20131 {
20132   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20133      which value is non-zero.  However, we have to be careful with
20134      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20135      (via dwarf2_flag_true_p) follows this attribute.  So we may
20136      end up accidently finding a declaration attribute that belongs
20137      to a different DIE referenced by the specification attribute,
20138      even though the given DIE does not have a declaration attribute.  */
20139   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20140           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20141 }
20142
20143 /* Return the die giving the specification for DIE, if there is
20144    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20145    containing the return value on output.  If there is no
20146    specification, but there is an abstract origin, that is
20147    returned.  */
20148
20149 static struct die_info *
20150 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20151 {
20152   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20153                                              *spec_cu);
20154
20155   if (spec_attr == NULL)
20156     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20157
20158   if (spec_attr == NULL)
20159     return NULL;
20160   else
20161     return follow_die_ref (die, spec_attr, spec_cu);
20162 }
20163
20164 /* Stub for free_line_header to match void * callback types.  */
20165
20166 static void
20167 free_line_header_voidp (void *arg)
20168 {
20169   struct line_header *lh = (struct line_header *) arg;
20170
20171   delete lh;
20172 }
20173
20174 void
20175 line_header::add_include_dir (const char *include_dir)
20176 {
20177   if (dwarf_line_debug >= 2)
20178     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20179                         include_dirs.size () + 1, include_dir);
20180
20181   include_dirs.push_back (include_dir);
20182 }
20183
20184 void
20185 line_header::add_file_name (const char *name,
20186                             dir_index d_index,
20187                             unsigned int mod_time,
20188                             unsigned int length)
20189 {
20190   if (dwarf_line_debug >= 2)
20191     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20192                         (unsigned) file_names.size () + 1, name);
20193
20194   file_names.emplace_back (name, d_index, mod_time, length);
20195 }
20196
20197 /* A convenience function to find the proper .debug_line section for a CU.  */
20198
20199 static struct dwarf2_section_info *
20200 get_debug_line_section (struct dwarf2_cu *cu)
20201 {
20202   struct dwarf2_section_info *section;
20203   struct dwarf2_per_objfile *dwarf2_per_objfile
20204     = cu->per_cu->dwarf2_per_objfile;
20205
20206   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20207      DWO file.  */
20208   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20209     section = &cu->dwo_unit->dwo_file->sections.line;
20210   else if (cu->per_cu->is_dwz)
20211     {
20212       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20213
20214       section = &dwz->line;
20215     }
20216   else
20217     section = &dwarf2_per_objfile->line;
20218
20219   return section;
20220 }
20221
20222 /* Read directory or file name entry format, starting with byte of
20223    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20224    entries count and the entries themselves in the described entry
20225    format.  */
20226
20227 static void
20228 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20229                         bfd *abfd, const gdb_byte **bufp,
20230                         struct line_header *lh,
20231                         const struct comp_unit_head *cu_header,
20232                         void (*callback) (struct line_header *lh,
20233                                           const char *name,
20234                                           dir_index d_index,
20235                                           unsigned int mod_time,
20236                                           unsigned int length))
20237 {
20238   gdb_byte format_count, formati;
20239   ULONGEST data_count, datai;
20240   const gdb_byte *buf = *bufp;
20241   const gdb_byte *format_header_data;
20242   unsigned int bytes_read;
20243
20244   format_count = read_1_byte (abfd, buf);
20245   buf += 1;
20246   format_header_data = buf;
20247   for (formati = 0; formati < format_count; formati++)
20248     {
20249       read_unsigned_leb128 (abfd, buf, &bytes_read);
20250       buf += bytes_read;
20251       read_unsigned_leb128 (abfd, buf, &bytes_read);
20252       buf += bytes_read;
20253     }
20254
20255   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20256   buf += bytes_read;
20257   for (datai = 0; datai < data_count; datai++)
20258     {
20259       const gdb_byte *format = format_header_data;
20260       struct file_entry fe;
20261
20262       for (formati = 0; formati < format_count; formati++)
20263         {
20264           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20265           format += bytes_read;
20266
20267           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20268           format += bytes_read;
20269
20270           gdb::optional<const char *> string;
20271           gdb::optional<unsigned int> uint;
20272
20273           switch (form)
20274             {
20275             case DW_FORM_string:
20276               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20277               buf += bytes_read;
20278               break;
20279
20280             case DW_FORM_line_strp:
20281               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20282                                                          abfd, buf,
20283                                                          cu_header,
20284                                                          &bytes_read));
20285               buf += bytes_read;
20286               break;
20287
20288             case DW_FORM_data1:
20289               uint.emplace (read_1_byte (abfd, buf));
20290               buf += 1;
20291               break;
20292
20293             case DW_FORM_data2:
20294               uint.emplace (read_2_bytes (abfd, buf));
20295               buf += 2;
20296               break;
20297
20298             case DW_FORM_data4:
20299               uint.emplace (read_4_bytes (abfd, buf));
20300               buf += 4;
20301               break;
20302
20303             case DW_FORM_data8:
20304               uint.emplace (read_8_bytes (abfd, buf));
20305               buf += 8;
20306               break;
20307
20308             case DW_FORM_udata:
20309               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20310               buf += bytes_read;
20311               break;
20312
20313             case DW_FORM_block:
20314               /* It is valid only for DW_LNCT_timestamp which is ignored by
20315                  current GDB.  */
20316               break;
20317             }
20318
20319           switch (content_type)
20320             {
20321             case DW_LNCT_path:
20322               if (string.has_value ())
20323                 fe.name = *string;
20324               break;
20325             case DW_LNCT_directory_index:
20326               if (uint.has_value ())
20327                 fe.d_index = (dir_index) *uint;
20328               break;
20329             case DW_LNCT_timestamp:
20330               if (uint.has_value ())
20331                 fe.mod_time = *uint;
20332               break;
20333             case DW_LNCT_size:
20334               if (uint.has_value ())
20335                 fe.length = *uint;
20336               break;
20337             case DW_LNCT_MD5:
20338               break;
20339             default:
20340               complaint (_("Unknown format content type %s"),
20341                          pulongest (content_type));
20342             }
20343         }
20344
20345       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20346     }
20347
20348   *bufp = buf;
20349 }
20350
20351 /* Read the statement program header starting at OFFSET in
20352    .debug_line, or .debug_line.dwo.  Return a pointer
20353    to a struct line_header, allocated using xmalloc.
20354    Returns NULL if there is a problem reading the header, e.g., if it
20355    has a version we don't understand.
20356
20357    NOTE: the strings in the include directory and file name tables of
20358    the returned object point into the dwarf line section buffer,
20359    and must not be freed.  */
20360
20361 static line_header_up
20362 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20363 {
20364   const gdb_byte *line_ptr;
20365   unsigned int bytes_read, offset_size;
20366   int i;
20367   const char *cur_dir, *cur_file;
20368   struct dwarf2_section_info *section;
20369   bfd *abfd;
20370   struct dwarf2_per_objfile *dwarf2_per_objfile
20371     = cu->per_cu->dwarf2_per_objfile;
20372
20373   section = get_debug_line_section (cu);
20374   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20375   if (section->buffer == NULL)
20376     {
20377       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20378         complaint (_("missing .debug_line.dwo section"));
20379       else
20380         complaint (_("missing .debug_line section"));
20381       return 0;
20382     }
20383
20384   /* We can't do this until we know the section is non-empty.
20385      Only then do we know we have such a section.  */
20386   abfd = get_section_bfd_owner (section);
20387
20388   /* Make sure that at least there's room for the total_length field.
20389      That could be 12 bytes long, but we're just going to fudge that.  */
20390   if (to_underlying (sect_off) + 4 >= section->size)
20391     {
20392       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20393       return 0;
20394     }
20395
20396   line_header_up lh (new line_header ());
20397
20398   lh->sect_off = sect_off;
20399   lh->offset_in_dwz = cu->per_cu->is_dwz;
20400
20401   line_ptr = section->buffer + to_underlying (sect_off);
20402
20403   /* Read in the header.  */
20404   lh->total_length =
20405     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20406                                             &bytes_read, &offset_size);
20407   line_ptr += bytes_read;
20408   if (line_ptr + lh->total_length > (section->buffer + section->size))
20409     {
20410       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20411       return 0;
20412     }
20413   lh->statement_program_end = line_ptr + lh->total_length;
20414   lh->version = read_2_bytes (abfd, line_ptr);
20415   line_ptr += 2;
20416   if (lh->version > 5)
20417     {
20418       /* This is a version we don't understand.  The format could have
20419          changed in ways we don't handle properly so just punt.  */
20420       complaint (_("unsupported version in .debug_line section"));
20421       return NULL;
20422     }
20423   if (lh->version >= 5)
20424     {
20425       gdb_byte segment_selector_size;
20426
20427       /* Skip address size.  */
20428       read_1_byte (abfd, line_ptr);
20429       line_ptr += 1;
20430
20431       segment_selector_size = read_1_byte (abfd, line_ptr);
20432       line_ptr += 1;
20433       if (segment_selector_size != 0)
20434         {
20435           complaint (_("unsupported segment selector size %u "
20436                        "in .debug_line section"),
20437                      segment_selector_size);
20438           return NULL;
20439         }
20440     }
20441   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20442   line_ptr += offset_size;
20443   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20444   line_ptr += 1;
20445   if (lh->version >= 4)
20446     {
20447       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20448       line_ptr += 1;
20449     }
20450   else
20451     lh->maximum_ops_per_instruction = 1;
20452
20453   if (lh->maximum_ops_per_instruction == 0)
20454     {
20455       lh->maximum_ops_per_instruction = 1;
20456       complaint (_("invalid maximum_ops_per_instruction "
20457                    "in `.debug_line' section"));
20458     }
20459
20460   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20461   line_ptr += 1;
20462   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20463   line_ptr += 1;
20464   lh->line_range = read_1_byte (abfd, line_ptr);
20465   line_ptr += 1;
20466   lh->opcode_base = read_1_byte (abfd, line_ptr);
20467   line_ptr += 1;
20468   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20469
20470   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20471   for (i = 1; i < lh->opcode_base; ++i)
20472     {
20473       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20474       line_ptr += 1;
20475     }
20476
20477   if (lh->version >= 5)
20478     {
20479       /* Read directory table.  */
20480       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20481                               &cu->header,
20482                               [] (struct line_header *header, const char *name,
20483                                   dir_index d_index, unsigned int mod_time,
20484                                   unsigned int length)
20485         {
20486           header->add_include_dir (name);
20487         });
20488
20489       /* Read file name table.  */
20490       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20491                               &cu->header,
20492                               [] (struct line_header *header, const char *name,
20493                                   dir_index d_index, unsigned int mod_time,
20494                                   unsigned int length)
20495         {
20496           header->add_file_name (name, d_index, mod_time, length);
20497         });
20498     }
20499   else
20500     {
20501       /* Read directory table.  */
20502       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20503         {
20504           line_ptr += bytes_read;
20505           lh->add_include_dir (cur_dir);
20506         }
20507       line_ptr += bytes_read;
20508
20509       /* Read file name table.  */
20510       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20511         {
20512           unsigned int mod_time, length;
20513           dir_index d_index;
20514
20515           line_ptr += bytes_read;
20516           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20517           line_ptr += bytes_read;
20518           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20519           line_ptr += bytes_read;
20520           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20521           line_ptr += bytes_read;
20522
20523           lh->add_file_name (cur_file, d_index, mod_time, length);
20524         }
20525       line_ptr += bytes_read;
20526     }
20527   lh->statement_program_start = line_ptr;
20528
20529   if (line_ptr > (section->buffer + section->size))
20530     complaint (_("line number info header doesn't "
20531                  "fit in `.debug_line' section"));
20532
20533   return lh;
20534 }
20535
20536 /* Subroutine of dwarf_decode_lines to simplify it.
20537    Return the file name of the psymtab for included file FILE_INDEX
20538    in line header LH of PST.
20539    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20540    If space for the result is malloc'd, *NAME_HOLDER will be set.
20541    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20542
20543 static const char *
20544 psymtab_include_file_name (const struct line_header *lh, int file_index,
20545                            const struct partial_symtab *pst,
20546                            const char *comp_dir,
20547                            gdb::unique_xmalloc_ptr<char> *name_holder)
20548 {
20549   const file_entry &fe = lh->file_names[file_index];
20550   const char *include_name = fe.name;
20551   const char *include_name_to_compare = include_name;
20552   const char *pst_filename;
20553   int file_is_pst;
20554
20555   const char *dir_name = fe.include_dir (lh);
20556
20557   gdb::unique_xmalloc_ptr<char> hold_compare;
20558   if (!IS_ABSOLUTE_PATH (include_name)
20559       && (dir_name != NULL || comp_dir != NULL))
20560     {
20561       /* Avoid creating a duplicate psymtab for PST.
20562          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20563          Before we do the comparison, however, we need to account
20564          for DIR_NAME and COMP_DIR.
20565          First prepend dir_name (if non-NULL).  If we still don't
20566          have an absolute path prepend comp_dir (if non-NULL).
20567          However, the directory we record in the include-file's
20568          psymtab does not contain COMP_DIR (to match the
20569          corresponding symtab(s)).
20570
20571          Example:
20572
20573          bash$ cd /tmp
20574          bash$ gcc -g ./hello.c
20575          include_name = "hello.c"
20576          dir_name = "."
20577          DW_AT_comp_dir = comp_dir = "/tmp"
20578          DW_AT_name = "./hello.c"
20579
20580       */
20581
20582       if (dir_name != NULL)
20583         {
20584           name_holder->reset (concat (dir_name, SLASH_STRING,
20585                                       include_name, (char *) NULL));
20586           include_name = name_holder->get ();
20587           include_name_to_compare = include_name;
20588         }
20589       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20590         {
20591           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20592                                       include_name, (char *) NULL));
20593           include_name_to_compare = hold_compare.get ();
20594         }
20595     }
20596
20597   pst_filename = pst->filename;
20598   gdb::unique_xmalloc_ptr<char> copied_name;
20599   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20600     {
20601       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20602                                  pst_filename, (char *) NULL));
20603       pst_filename = copied_name.get ();
20604     }
20605
20606   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20607
20608   if (file_is_pst)
20609     return NULL;
20610   return include_name;
20611 }
20612
20613 /* State machine to track the state of the line number program.  */
20614
20615 class lnp_state_machine
20616 {
20617 public:
20618   /* Initialize a machine state for the start of a line number
20619      program.  */
20620   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20621                      bool record_lines_p);
20622
20623   file_entry *current_file ()
20624   {
20625     /* lh->file_names is 0-based, but the file name numbers in the
20626        statement program are 1-based.  */
20627     return m_line_header->file_name_at (m_file);
20628   }
20629
20630   /* Record the line in the state machine.  END_SEQUENCE is true if
20631      we're processing the end of a sequence.  */
20632   void record_line (bool end_sequence);
20633
20634   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20635      nop-out rest of the lines in this sequence.  */
20636   void check_line_address (struct dwarf2_cu *cu,
20637                            const gdb_byte *line_ptr,
20638                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20639
20640   void handle_set_discriminator (unsigned int discriminator)
20641   {
20642     m_discriminator = discriminator;
20643     m_line_has_non_zero_discriminator |= discriminator != 0;
20644   }
20645
20646   /* Handle DW_LNE_set_address.  */
20647   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20648   {
20649     m_op_index = 0;
20650     address += baseaddr;
20651     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20652   }
20653
20654   /* Handle DW_LNS_advance_pc.  */
20655   void handle_advance_pc (CORE_ADDR adjust);
20656
20657   /* Handle a special opcode.  */
20658   void handle_special_opcode (unsigned char op_code);
20659
20660   /* Handle DW_LNS_advance_line.  */
20661   void handle_advance_line (int line_delta)
20662   {
20663     advance_line (line_delta);
20664   }
20665
20666   /* Handle DW_LNS_set_file.  */
20667   void handle_set_file (file_name_index file);
20668
20669   /* Handle DW_LNS_negate_stmt.  */
20670   void handle_negate_stmt ()
20671   {
20672     m_is_stmt = !m_is_stmt;
20673   }
20674
20675   /* Handle DW_LNS_const_add_pc.  */
20676   void handle_const_add_pc ();
20677
20678   /* Handle DW_LNS_fixed_advance_pc.  */
20679   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20680   {
20681     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20682     m_op_index = 0;
20683   }
20684
20685   /* Handle DW_LNS_copy.  */
20686   void handle_copy ()
20687   {
20688     record_line (false);
20689     m_discriminator = 0;
20690   }
20691
20692   /* Handle DW_LNE_end_sequence.  */
20693   void handle_end_sequence ()
20694   {
20695     m_currently_recording_lines = true;
20696   }
20697
20698 private:
20699   /* Advance the line by LINE_DELTA.  */
20700   void advance_line (int line_delta)
20701   {
20702     m_line += line_delta;
20703
20704     if (line_delta != 0)
20705       m_line_has_non_zero_discriminator = m_discriminator != 0;
20706   }
20707
20708   struct dwarf2_cu *m_cu;
20709
20710   gdbarch *m_gdbarch;
20711
20712   /* True if we're recording lines.
20713      Otherwise we're building partial symtabs and are just interested in
20714      finding include files mentioned by the line number program.  */
20715   bool m_record_lines_p;
20716
20717   /* The line number header.  */
20718   line_header *m_line_header;
20719
20720   /* These are part of the standard DWARF line number state machine,
20721      and initialized according to the DWARF spec.  */
20722
20723   unsigned char m_op_index = 0;
20724   /* The line table index (1-based) of the current file.  */
20725   file_name_index m_file = (file_name_index) 1;
20726   unsigned int m_line = 1;
20727
20728   /* These are initialized in the constructor.  */
20729
20730   CORE_ADDR m_address;
20731   bool m_is_stmt;
20732   unsigned int m_discriminator;
20733
20734   /* Additional bits of state we need to track.  */
20735
20736   /* The last file that we called dwarf2_start_subfile for.
20737      This is only used for TLLs.  */
20738   unsigned int m_last_file = 0;
20739   /* The last file a line number was recorded for.  */
20740   struct subfile *m_last_subfile = NULL;
20741
20742   /* When true, record the lines we decode.  */
20743   bool m_currently_recording_lines = false;
20744
20745   /* The last line number that was recorded, used to coalesce
20746      consecutive entries for the same line.  This can happen, for
20747      example, when discriminators are present.  PR 17276.  */
20748   unsigned int m_last_line = 0;
20749   bool m_line_has_non_zero_discriminator = false;
20750 };
20751
20752 void
20753 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20754 {
20755   CORE_ADDR addr_adj = (((m_op_index + adjust)
20756                          / m_line_header->maximum_ops_per_instruction)
20757                         * m_line_header->minimum_instruction_length);
20758   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20759   m_op_index = ((m_op_index + adjust)
20760                 % m_line_header->maximum_ops_per_instruction);
20761 }
20762
20763 void
20764 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20765 {
20766   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20767   CORE_ADDR addr_adj = (((m_op_index
20768                           + (adj_opcode / m_line_header->line_range))
20769                          / m_line_header->maximum_ops_per_instruction)
20770                         * m_line_header->minimum_instruction_length);
20771   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20772   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20773                 % m_line_header->maximum_ops_per_instruction);
20774
20775   int line_delta = (m_line_header->line_base
20776                     + (adj_opcode % m_line_header->line_range));
20777   advance_line (line_delta);
20778   record_line (false);
20779   m_discriminator = 0;
20780 }
20781
20782 void
20783 lnp_state_machine::handle_set_file (file_name_index file)
20784 {
20785   m_file = file;
20786
20787   const file_entry *fe = current_file ();
20788   if (fe == NULL)
20789     dwarf2_debug_line_missing_file_complaint ();
20790   else if (m_record_lines_p)
20791     {
20792       const char *dir = fe->include_dir (m_line_header);
20793
20794       m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20795       m_line_has_non_zero_discriminator = m_discriminator != 0;
20796       dwarf2_start_subfile (m_cu, fe->name, dir);
20797     }
20798 }
20799
20800 void
20801 lnp_state_machine::handle_const_add_pc ()
20802 {
20803   CORE_ADDR adjust
20804     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20805
20806   CORE_ADDR addr_adj
20807     = (((m_op_index + adjust)
20808         / m_line_header->maximum_ops_per_instruction)
20809        * m_line_header->minimum_instruction_length);
20810
20811   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20812   m_op_index = ((m_op_index + adjust)
20813                 % m_line_header->maximum_ops_per_instruction);
20814 }
20815
20816 /* Return non-zero if we should add LINE to the line number table.
20817    LINE is the line to add, LAST_LINE is the last line that was added,
20818    LAST_SUBFILE is the subfile for LAST_LINE.
20819    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20820    had a non-zero discriminator.
20821
20822    We have to be careful in the presence of discriminators.
20823    E.g., for this line:
20824
20825      for (i = 0; i < 100000; i++);
20826
20827    clang can emit four line number entries for that one line,
20828    each with a different discriminator.
20829    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20830
20831    However, we want gdb to coalesce all four entries into one.
20832    Otherwise the user could stepi into the middle of the line and
20833    gdb would get confused about whether the pc really was in the
20834    middle of the line.
20835
20836    Things are further complicated by the fact that two consecutive
20837    line number entries for the same line is a heuristic used by gcc
20838    to denote the end of the prologue.  So we can't just discard duplicate
20839    entries, we have to be selective about it.  The heuristic we use is
20840    that we only collapse consecutive entries for the same line if at least
20841    one of those entries has a non-zero discriminator.  PR 17276.
20842
20843    Note: Addresses in the line number state machine can never go backwards
20844    within one sequence, thus this coalescing is ok.  */
20845
20846 static int
20847 dwarf_record_line_p (struct dwarf2_cu *cu,
20848                      unsigned int line, unsigned int last_line,
20849                      int line_has_non_zero_discriminator,
20850                      struct subfile *last_subfile)
20851 {
20852   if (cu->get_builder ()->get_current_subfile () != last_subfile)
20853     return 1;
20854   if (line != last_line)
20855     return 1;
20856   /* Same line for the same file that we've seen already.
20857      As a last check, for pr 17276, only record the line if the line
20858      has never had a non-zero discriminator.  */
20859   if (!line_has_non_zero_discriminator)
20860     return 1;
20861   return 0;
20862 }
20863
20864 /* Use the CU's builder to record line number LINE beginning at
20865    address ADDRESS in the line table of subfile SUBFILE.  */
20866
20867 static void
20868 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20869                      unsigned int line, CORE_ADDR address,
20870                      struct dwarf2_cu *cu)
20871 {
20872   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20873
20874   if (dwarf_line_debug)
20875     {
20876       fprintf_unfiltered (gdb_stdlog,
20877                           "Recording line %u, file %s, address %s\n",
20878                           line, lbasename (subfile->name),
20879                           paddress (gdbarch, address));
20880     }
20881
20882   if (cu != nullptr)
20883     cu->get_builder ()->record_line (subfile, line, addr);
20884 }
20885
20886 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20887    Mark the end of a set of line number records.
20888    The arguments are the same as for dwarf_record_line_1.
20889    If SUBFILE is NULL the request is ignored.  */
20890
20891 static void
20892 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20893                    CORE_ADDR address, struct dwarf2_cu *cu)
20894 {
20895   if (subfile == NULL)
20896     return;
20897
20898   if (dwarf_line_debug)
20899     {
20900       fprintf_unfiltered (gdb_stdlog,
20901                           "Finishing current line, file %s, address %s\n",
20902                           lbasename (subfile->name),
20903                           paddress (gdbarch, address));
20904     }
20905
20906   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20907 }
20908
20909 void
20910 lnp_state_machine::record_line (bool end_sequence)
20911 {
20912   if (dwarf_line_debug)
20913     {
20914       fprintf_unfiltered (gdb_stdlog,
20915                           "Processing actual line %u: file %u,"
20916                           " address %s, is_stmt %u, discrim %u\n",
20917                           m_line, to_underlying (m_file),
20918                           paddress (m_gdbarch, m_address),
20919                           m_is_stmt, m_discriminator);
20920     }
20921
20922   file_entry *fe = current_file ();
20923
20924   if (fe == NULL)
20925     dwarf2_debug_line_missing_file_complaint ();
20926   /* For now we ignore lines not starting on an instruction boundary.
20927      But not when processing end_sequence for compatibility with the
20928      previous version of the code.  */
20929   else if (m_op_index == 0 || end_sequence)
20930     {
20931       fe->included_p = 1;
20932       if (m_record_lines_p && (producer_is_codewarrior (m_cu) || m_is_stmt))
20933         {
20934           if (m_last_subfile != m_cu->get_builder ()->get_current_subfile ()
20935               || end_sequence)
20936             {
20937               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20938                                  m_currently_recording_lines ? m_cu : nullptr);
20939             }
20940
20941           if (!end_sequence)
20942             {
20943               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20944                                        m_line_has_non_zero_discriminator,
20945                                        m_last_subfile))
20946                 {
20947                   buildsym_compunit *builder = m_cu->get_builder ();
20948                   dwarf_record_line_1 (m_gdbarch,
20949                                        builder->get_current_subfile (),
20950                                        m_line, m_address,
20951                                        m_currently_recording_lines ? m_cu : nullptr);
20952                 }
20953               m_last_subfile = m_cu->get_builder ()->get_current_subfile ();
20954               m_last_line = m_line;
20955             }
20956         }
20957     }
20958 }
20959
20960 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20961                                       line_header *lh, bool record_lines_p)
20962 {
20963   m_cu = cu;
20964   m_gdbarch = arch;
20965   m_record_lines_p = record_lines_p;
20966   m_line_header = lh;
20967
20968   m_currently_recording_lines = true;
20969
20970   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20971      was a line entry for it so that the backend has a chance to adjust it
20972      and also record it in case it needs it.  This is currently used by MIPS
20973      code, cf. `mips_adjust_dwarf2_line'.  */
20974   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20975   m_is_stmt = lh->default_is_stmt;
20976   m_discriminator = 0;
20977 }
20978
20979 void
20980 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20981                                        const gdb_byte *line_ptr,
20982                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20983 {
20984   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20985      the pc range of the CU.  However, we restrict the test to only ADDRESS
20986      values of zero to preserve GDB's previous behaviour which is to handle
20987      the specific case of a function being GC'd by the linker.  */
20988
20989   if (address == 0 && address < unrelocated_lowpc)
20990     {
20991       /* This line table is for a function which has been
20992          GCd by the linker.  Ignore it.  PR gdb/12528 */
20993
20994       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20995       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20996
20997       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20998                  line_offset, objfile_name (objfile));
20999       m_currently_recording_lines = false;
21000       /* Note: m_currently_recording_lines is left as false until we see
21001          DW_LNE_end_sequence.  */
21002     }
21003 }
21004
21005 /* Subroutine of dwarf_decode_lines to simplify it.
21006    Process the line number information in LH.
21007    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21008    program in order to set included_p for every referenced header.  */
21009
21010 static void
21011 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21012                       const int decode_for_pst_p, CORE_ADDR lowpc)
21013 {
21014   const gdb_byte *line_ptr, *extended_end;
21015   const gdb_byte *line_end;
21016   unsigned int bytes_read, extended_len;
21017   unsigned char op_code, extended_op;
21018   CORE_ADDR baseaddr;
21019   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21020   bfd *abfd = objfile->obfd;
21021   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21022   /* True if we're recording line info (as opposed to building partial
21023      symtabs and just interested in finding include files mentioned by
21024      the line number program).  */
21025   bool record_lines_p = !decode_for_pst_p;
21026
21027   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21028
21029   line_ptr = lh->statement_program_start;
21030   line_end = lh->statement_program_end;
21031
21032   /* Read the statement sequences until there's nothing left.  */
21033   while (line_ptr < line_end)
21034     {
21035       /* The DWARF line number program state machine.  Reset the state
21036          machine at the start of each sequence.  */
21037       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
21038       bool end_sequence = false;
21039
21040       if (record_lines_p)
21041         {
21042           /* Start a subfile for the current file of the state
21043              machine.  */
21044           const file_entry *fe = state_machine.current_file ();
21045
21046           if (fe != NULL)
21047             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
21048         }
21049
21050       /* Decode the table.  */
21051       while (line_ptr < line_end && !end_sequence)
21052         {
21053           op_code = read_1_byte (abfd, line_ptr);
21054           line_ptr += 1;
21055
21056           if (op_code >= lh->opcode_base)
21057             {
21058               /* Special opcode.  */
21059               state_machine.handle_special_opcode (op_code);
21060             }
21061           else switch (op_code)
21062             {
21063             case DW_LNS_extended_op:
21064               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21065                                                    &bytes_read);
21066               line_ptr += bytes_read;
21067               extended_end = line_ptr + extended_len;
21068               extended_op = read_1_byte (abfd, line_ptr);
21069               line_ptr += 1;
21070               switch (extended_op)
21071                 {
21072                 case DW_LNE_end_sequence:
21073                   state_machine.handle_end_sequence ();
21074                   end_sequence = true;
21075                   break;
21076                 case DW_LNE_set_address:
21077                   {
21078                     CORE_ADDR address
21079                       = read_address (abfd, line_ptr, cu, &bytes_read);
21080                     line_ptr += bytes_read;
21081
21082                     state_machine.check_line_address (cu, line_ptr,
21083                                                       lowpc - baseaddr, address);
21084                     state_machine.handle_set_address (baseaddr, address);
21085                   }
21086                   break;
21087                 case DW_LNE_define_file:
21088                   {
21089                     const char *cur_file;
21090                     unsigned int mod_time, length;
21091                     dir_index dindex;
21092
21093                     cur_file = read_direct_string (abfd, line_ptr,
21094                                                    &bytes_read);
21095                     line_ptr += bytes_read;
21096                     dindex = (dir_index)
21097                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21098                     line_ptr += bytes_read;
21099                     mod_time =
21100                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21101                     line_ptr += bytes_read;
21102                     length =
21103                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21104                     line_ptr += bytes_read;
21105                     lh->add_file_name (cur_file, dindex, mod_time, length);
21106                   }
21107                   break;
21108                 case DW_LNE_set_discriminator:
21109                   {
21110                     /* The discriminator is not interesting to the
21111                        debugger; just ignore it.  We still need to
21112                        check its value though:
21113                        if there are consecutive entries for the same
21114                        (non-prologue) line we want to coalesce them.
21115                        PR 17276.  */
21116                     unsigned int discr
21117                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21118                     line_ptr += bytes_read;
21119
21120                     state_machine.handle_set_discriminator (discr);
21121                   }
21122                   break;
21123                 default:
21124                   complaint (_("mangled .debug_line section"));
21125                   return;
21126                 }
21127               /* Make sure that we parsed the extended op correctly.  If e.g.
21128                  we expected a different address size than the producer used,
21129                  we may have read the wrong number of bytes.  */
21130               if (line_ptr != extended_end)
21131                 {
21132                   complaint (_("mangled .debug_line section"));
21133                   return;
21134                 }
21135               break;
21136             case DW_LNS_copy:
21137               state_machine.handle_copy ();
21138               break;
21139             case DW_LNS_advance_pc:
21140               {
21141                 CORE_ADDR adjust
21142                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21143                 line_ptr += bytes_read;
21144
21145                 state_machine.handle_advance_pc (adjust);
21146               }
21147               break;
21148             case DW_LNS_advance_line:
21149               {
21150                 int line_delta
21151                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21152                 line_ptr += bytes_read;
21153
21154                 state_machine.handle_advance_line (line_delta);
21155               }
21156               break;
21157             case DW_LNS_set_file:
21158               {
21159                 file_name_index file
21160                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21161                                                             &bytes_read);
21162                 line_ptr += bytes_read;
21163
21164                 state_machine.handle_set_file (file);
21165               }
21166               break;
21167             case DW_LNS_set_column:
21168               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21169               line_ptr += bytes_read;
21170               break;
21171             case DW_LNS_negate_stmt:
21172               state_machine.handle_negate_stmt ();
21173               break;
21174             case DW_LNS_set_basic_block:
21175               break;
21176             /* Add to the address register of the state machine the
21177                address increment value corresponding to special opcode
21178                255.  I.e., this value is scaled by the minimum
21179                instruction length since special opcode 255 would have
21180                scaled the increment.  */
21181             case DW_LNS_const_add_pc:
21182               state_machine.handle_const_add_pc ();
21183               break;
21184             case DW_LNS_fixed_advance_pc:
21185               {
21186                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21187                 line_ptr += 2;
21188
21189                 state_machine.handle_fixed_advance_pc (addr_adj);
21190               }
21191               break;
21192             default:
21193               {
21194                 /* Unknown standard opcode, ignore it.  */
21195                 int i;
21196
21197                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21198                   {
21199                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21200                     line_ptr += bytes_read;
21201                   }
21202               }
21203             }
21204         }
21205
21206       if (!end_sequence)
21207         dwarf2_debug_line_missing_end_sequence_complaint ();
21208
21209       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21210          in which case we still finish recording the last line).  */
21211       state_machine.record_line (true);
21212     }
21213 }
21214
21215 /* Decode the Line Number Program (LNP) for the given line_header
21216    structure and CU.  The actual information extracted and the type
21217    of structures created from the LNP depends on the value of PST.
21218
21219    1. If PST is NULL, then this procedure uses the data from the program
21220       to create all necessary symbol tables, and their linetables.
21221
21222    2. If PST is not NULL, this procedure reads the program to determine
21223       the list of files included by the unit represented by PST, and
21224       builds all the associated partial symbol tables.
21225
21226    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21227    It is used for relative paths in the line table.
21228    NOTE: When processing partial symtabs (pst != NULL),
21229    comp_dir == pst->dirname.
21230
21231    NOTE: It is important that psymtabs have the same file name (via strcmp)
21232    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21233    symtab we don't use it in the name of the psymtabs we create.
21234    E.g. expand_line_sal requires this when finding psymtabs to expand.
21235    A good testcase for this is mb-inline.exp.
21236
21237    LOWPC is the lowest address in CU (or 0 if not known).
21238
21239    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21240    for its PC<->lines mapping information.  Otherwise only the filename
21241    table is read in.  */
21242
21243 static void
21244 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21245                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21246                     CORE_ADDR lowpc, int decode_mapping)
21247 {
21248   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21249   const int decode_for_pst_p = (pst != NULL);
21250
21251   if (decode_mapping)
21252     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21253
21254   if (decode_for_pst_p)
21255     {
21256       int file_index;
21257
21258       /* Now that we're done scanning the Line Header Program, we can
21259          create the psymtab of each included file.  */
21260       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21261         if (lh->file_names[file_index].included_p == 1)
21262           {
21263             gdb::unique_xmalloc_ptr<char> name_holder;
21264             const char *include_name =
21265               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21266                                          &name_holder);
21267             if (include_name != NULL)
21268               dwarf2_create_include_psymtab (include_name, pst, objfile);
21269           }
21270     }
21271   else
21272     {
21273       /* Make sure a symtab is created for every file, even files
21274          which contain only variables (i.e. no code with associated
21275          line numbers).  */
21276       buildsym_compunit *builder = cu->get_builder ();
21277       struct compunit_symtab *cust = builder->get_compunit_symtab ();
21278       int i;
21279
21280       for (i = 0; i < lh->file_names.size (); i++)
21281         {
21282           file_entry &fe = lh->file_names[i];
21283
21284           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21285
21286           if (builder->get_current_subfile ()->symtab == NULL)
21287             {
21288               builder->get_current_subfile ()->symtab
21289                 = allocate_symtab (cust,
21290                                    builder->get_current_subfile ()->name);
21291             }
21292           fe.symtab = builder->get_current_subfile ()->symtab;
21293         }
21294     }
21295 }
21296
21297 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21298    DIRNAME the name of the source directory which contains FILENAME
21299    or NULL if not known.
21300    This routine tries to keep line numbers from identical absolute and
21301    relative file names in a common subfile.
21302
21303    Using the `list' example from the GDB testsuite, which resides in
21304    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21305    of /srcdir/list0.c yields the following debugging information for list0.c:
21306
21307    DW_AT_name:          /srcdir/list0.c
21308    DW_AT_comp_dir:      /compdir
21309    files.files[0].name: list0.h
21310    files.files[0].dir:  /srcdir
21311    files.files[1].name: list0.c
21312    files.files[1].dir:  /srcdir
21313
21314    The line number information for list0.c has to end up in a single
21315    subfile, so that `break /srcdir/list0.c:1' works as expected.
21316    start_subfile will ensure that this happens provided that we pass the
21317    concatenation of files.files[1].dir and files.files[1].name as the
21318    subfile's name.  */
21319
21320 static void
21321 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21322                       const char *dirname)
21323 {
21324   char *copy = NULL;
21325
21326   /* In order not to lose the line information directory,
21327      we concatenate it to the filename when it makes sense.
21328      Note that the Dwarf3 standard says (speaking of filenames in line
21329      information): ``The directory index is ignored for file names
21330      that represent full path names''.  Thus ignoring dirname in the
21331      `else' branch below isn't an issue.  */
21332
21333   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21334     {
21335       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21336       filename = copy;
21337     }
21338
21339   cu->get_builder ()->start_subfile (filename);
21340
21341   if (copy != NULL)
21342     xfree (copy);
21343 }
21344
21345 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21346    buildsym_compunit constructor.  */
21347
21348 struct compunit_symtab *
21349 dwarf2_cu::start_symtab (const char *name, const char *comp_dir,
21350                          CORE_ADDR low_pc)
21351 {
21352   gdb_assert (m_builder == nullptr);
21353
21354   m_builder.reset (new struct buildsym_compunit
21355                    (per_cu->dwarf2_per_objfile->objfile,
21356                     name, comp_dir, language, low_pc));
21357
21358   list_in_scope = get_builder ()->get_file_symbols ();
21359
21360   get_builder ()->record_debugformat ("DWARF 2");
21361   get_builder ()->record_producer (producer);
21362
21363   processing_has_namespace_info = false;
21364
21365   return get_builder ()->get_compunit_symtab ();
21366 }
21367
21368 static void
21369 var_decode_location (struct attribute *attr, struct symbol *sym,
21370                      struct dwarf2_cu *cu)
21371 {
21372   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21373   struct comp_unit_head *cu_header = &cu->header;
21374
21375   /* NOTE drow/2003-01-30: There used to be a comment and some special
21376      code here to turn a symbol with DW_AT_external and a
21377      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21378      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21379      with some versions of binutils) where shared libraries could have
21380      relocations against symbols in their debug information - the
21381      minimal symbol would have the right address, but the debug info
21382      would not.  It's no longer necessary, because we will explicitly
21383      apply relocations when we read in the debug information now.  */
21384
21385   /* A DW_AT_location attribute with no contents indicates that a
21386      variable has been optimized away.  */
21387   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21388     {
21389       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21390       return;
21391     }
21392
21393   /* Handle one degenerate form of location expression specially, to
21394      preserve GDB's previous behavior when section offsets are
21395      specified.  If this is just a DW_OP_addr, DW_OP_addrx, or
21396      DW_OP_GNU_addr_index then mark this symbol as LOC_STATIC.  */
21397
21398   if (attr_form_is_block (attr)
21399       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21400            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21401           || ((DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21402                || DW_BLOCK (attr)->data[0] == DW_OP_addrx)
21403               && (DW_BLOCK (attr)->size
21404                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21405     {
21406       unsigned int dummy;
21407
21408       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21409         SYMBOL_VALUE_ADDRESS (sym) =
21410           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21411       else
21412         SYMBOL_VALUE_ADDRESS (sym) =
21413           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21414       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21415       fixup_symbol_section (sym, objfile);
21416       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21417                                               SYMBOL_SECTION (sym));
21418       return;
21419     }
21420
21421   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21422      expression evaluator, and use LOC_COMPUTED only when necessary
21423      (i.e. when the value of a register or memory location is
21424      referenced, or a thread-local block, etc.).  Then again, it might
21425      not be worthwhile.  I'm assuming that it isn't unless performance
21426      or memory numbers show me otherwise.  */
21427
21428   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21429
21430   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21431     cu->has_loclist = true;
21432 }
21433
21434 /* Given a pointer to a DWARF information entry, figure out if we need
21435    to make a symbol table entry for it, and if so, create a new entry
21436    and return a pointer to it.
21437    If TYPE is NULL, determine symbol type from the die, otherwise
21438    used the passed type.
21439    If SPACE is not NULL, use it to hold the new symbol.  If it is
21440    NULL, allocate a new symbol on the objfile's obstack.  */
21441
21442 static struct symbol *
21443 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21444             struct symbol *space)
21445 {
21446   struct dwarf2_per_objfile *dwarf2_per_objfile
21447     = cu->per_cu->dwarf2_per_objfile;
21448   struct objfile *objfile = dwarf2_per_objfile->objfile;
21449   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21450   struct symbol *sym = NULL;
21451   const char *name;
21452   struct attribute *attr = NULL;
21453   struct attribute *attr2 = NULL;
21454   CORE_ADDR baseaddr;
21455   struct pending **list_to_add = NULL;
21456
21457   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21458
21459   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21460
21461   name = dwarf2_name (die, cu);
21462   if (name)
21463     {
21464       const char *linkagename;
21465       int suppress_add = 0;
21466
21467       if (space)
21468         sym = space;
21469       else
21470         sym = allocate_symbol (objfile);
21471       OBJSTAT (objfile, n_syms++);
21472
21473       /* Cache this symbol's name and the name's demangled form (if any).  */
21474       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21475       linkagename = dwarf2_physname (name, die, cu);
21476       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21477
21478       /* Fortran does not have mangling standard and the mangling does differ
21479          between gfortran, iFort etc.  */
21480       if (cu->language == language_fortran
21481           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21482         symbol_set_demangled_name (&(sym->ginfo),
21483                                    dwarf2_full_name (name, die, cu),
21484                                    NULL);
21485
21486       /* Default assumptions.
21487          Use the passed type or decode it from the die.  */
21488       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21489       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21490       if (type != NULL)
21491         SYMBOL_TYPE (sym) = type;
21492       else
21493         SYMBOL_TYPE (sym) = die_type (die, cu);
21494       attr = dwarf2_attr (die,
21495                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21496                           cu);
21497       if (attr)
21498         {
21499           SYMBOL_LINE (sym) = DW_UNSND (attr);
21500         }
21501
21502       attr = dwarf2_attr (die,
21503                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21504                           cu);
21505       if (attr)
21506         {
21507           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21508           struct file_entry *fe;
21509
21510           if (cu->line_header != NULL)
21511             fe = cu->line_header->file_name_at (file_index);
21512           else
21513             fe = NULL;
21514
21515           if (fe == NULL)
21516             complaint (_("file index out of range"));
21517           else
21518             symbol_set_symtab (sym, fe->symtab);
21519         }
21520
21521       switch (die->tag)
21522         {
21523         case DW_TAG_label:
21524           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21525           if (attr)
21526             {
21527               CORE_ADDR addr;
21528
21529               addr = attr_value_as_address (attr);
21530               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21531               SYMBOL_VALUE_ADDRESS (sym) = addr;
21532             }
21533           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21534           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21535           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21536           add_symbol_to_list (sym, cu->list_in_scope);
21537           break;
21538         case DW_TAG_subprogram:
21539           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21540              finish_block.  */
21541           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21542           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21543           if ((attr2 && (DW_UNSND (attr2) != 0))
21544               || cu->language == language_ada)
21545             {
21546               /* Subprograms marked external are stored as a global symbol.
21547                  Ada subprograms, whether marked external or not, are always
21548                  stored as a global symbol, because we want to be able to
21549                  access them globally.  For instance, we want to be able
21550                  to break on a nested subprogram without having to
21551                  specify the context.  */
21552               list_to_add = cu->get_builder ()->get_global_symbols ();
21553             }
21554           else
21555             {
21556               list_to_add = cu->list_in_scope;
21557             }
21558           break;
21559         case DW_TAG_inlined_subroutine:
21560           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21561              finish_block.  */
21562           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21563           SYMBOL_INLINED (sym) = 1;
21564           list_to_add = cu->list_in_scope;
21565           break;
21566         case DW_TAG_template_value_param:
21567           suppress_add = 1;
21568           /* Fall through.  */
21569         case DW_TAG_constant:
21570         case DW_TAG_variable:
21571         case DW_TAG_member:
21572           /* Compilation with minimal debug info may result in
21573              variables with missing type entries.  Change the
21574              misleading `void' type to something sensible.  */
21575           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21576             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21577
21578           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21579           /* In the case of DW_TAG_member, we should only be called for
21580              static const members.  */
21581           if (die->tag == DW_TAG_member)
21582             {
21583               /* dwarf2_add_field uses die_is_declaration,
21584                  so we do the same.  */
21585               gdb_assert (die_is_declaration (die, cu));
21586               gdb_assert (attr);
21587             }
21588           if (attr)
21589             {
21590               dwarf2_const_value (attr, sym, cu);
21591               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21592               if (!suppress_add)
21593                 {
21594                   if (attr2 && (DW_UNSND (attr2) != 0))
21595                     list_to_add = cu->get_builder ()->get_global_symbols ();
21596                   else
21597                     list_to_add = cu->list_in_scope;
21598                 }
21599               break;
21600             }
21601           attr = dwarf2_attr (die, DW_AT_location, cu);
21602           if (attr)
21603             {
21604               var_decode_location (attr, sym, cu);
21605               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21606
21607               /* Fortran explicitly imports any global symbols to the local
21608                  scope by DW_TAG_common_block.  */
21609               if (cu->language == language_fortran && die->parent
21610                   && die->parent->tag == DW_TAG_common_block)
21611                 attr2 = NULL;
21612
21613               if (SYMBOL_CLASS (sym) == LOC_STATIC
21614                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21615                   && !dwarf2_per_objfile->has_section_at_zero)
21616                 {
21617                   /* When a static variable is eliminated by the linker,
21618                      the corresponding debug information is not stripped
21619                      out, but the variable address is set to null;
21620                      do not add such variables into symbol table.  */
21621                 }
21622               else if (attr2 && (DW_UNSND (attr2) != 0))
21623                 {
21624                   /* Workaround gfortran PR debug/40040 - it uses
21625                      DW_AT_location for variables in -fPIC libraries which may
21626                      get overriden by other libraries/executable and get
21627                      a different address.  Resolve it by the minimal symbol
21628                      which may come from inferior's executable using copy
21629                      relocation.  Make this workaround only for gfortran as for
21630                      other compilers GDB cannot guess the minimal symbol
21631                      Fortran mangling kind.  */
21632                   if (cu->language == language_fortran && die->parent
21633                       && die->parent->tag == DW_TAG_module
21634                       && cu->producer
21635                       && startswith (cu->producer, "GNU Fortran"))
21636                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21637
21638                   /* A variable with DW_AT_external is never static,
21639                      but it may be block-scoped.  */
21640                   list_to_add
21641                     = ((cu->list_in_scope
21642                         == cu->get_builder ()->get_file_symbols ())
21643                        ? cu->get_builder ()->get_global_symbols ()
21644                        : cu->list_in_scope);
21645                 }
21646               else
21647                 list_to_add = cu->list_in_scope;
21648             }
21649           else
21650             {
21651               /* We do not know the address of this symbol.
21652                  If it is an external symbol and we have type information
21653                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21654                  The address of the variable will then be determined from
21655                  the minimal symbol table whenever the variable is
21656                  referenced.  */
21657               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21658
21659               /* Fortran explicitly imports any global symbols to the local
21660                  scope by DW_TAG_common_block.  */
21661               if (cu->language == language_fortran && die->parent
21662                   && die->parent->tag == DW_TAG_common_block)
21663                 {
21664                   /* SYMBOL_CLASS doesn't matter here because
21665                      read_common_block is going to reset it.  */
21666                   if (!suppress_add)
21667                     list_to_add = cu->list_in_scope;
21668                 }
21669               else if (attr2 && (DW_UNSND (attr2) != 0)
21670                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21671                 {
21672                   /* A variable with DW_AT_external is never static, but it
21673                      may be block-scoped.  */
21674                   list_to_add
21675                     = ((cu->list_in_scope
21676                         == cu->get_builder ()->get_file_symbols ())
21677                        ? cu->get_builder ()->get_global_symbols ()
21678                        : cu->list_in_scope);
21679
21680                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21681                 }
21682               else if (!die_is_declaration (die, cu))
21683                 {
21684                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21685                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21686                   if (!suppress_add)
21687                     list_to_add = cu->list_in_scope;
21688                 }
21689             }
21690           break;
21691         case DW_TAG_formal_parameter:
21692           {
21693             /* If we are inside a function, mark this as an argument.  If
21694                not, we might be looking at an argument to an inlined function
21695                when we do not have enough information to show inlined frames;
21696                pretend it's a local variable in that case so that the user can
21697                still see it.  */
21698             struct context_stack *curr
21699               = cu->get_builder ()->get_current_context_stack ();
21700             if (curr != nullptr && curr->name != nullptr)
21701               SYMBOL_IS_ARGUMENT (sym) = 1;
21702             attr = dwarf2_attr (die, DW_AT_location, cu);
21703             if (attr)
21704               {
21705                 var_decode_location (attr, sym, cu);
21706               }
21707             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21708             if (attr)
21709               {
21710                 dwarf2_const_value (attr, sym, cu);
21711               }
21712
21713             list_to_add = cu->list_in_scope;
21714           }
21715           break;
21716         case DW_TAG_unspecified_parameters:
21717           /* From varargs functions; gdb doesn't seem to have any
21718              interest in this information, so just ignore it for now.
21719              (FIXME?) */
21720           break;
21721         case DW_TAG_template_type_param:
21722           suppress_add = 1;
21723           /* Fall through.  */
21724         case DW_TAG_class_type:
21725         case DW_TAG_interface_type:
21726         case DW_TAG_structure_type:
21727         case DW_TAG_union_type:
21728         case DW_TAG_set_type:
21729         case DW_TAG_enumeration_type:
21730           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21731           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21732
21733           {
21734             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21735                really ever be static objects: otherwise, if you try
21736                to, say, break of a class's method and you're in a file
21737                which doesn't mention that class, it won't work unless
21738                the check for all static symbols in lookup_symbol_aux
21739                saves you.  See the OtherFileClass tests in
21740                gdb.c++/namespace.exp.  */
21741
21742             if (!suppress_add)
21743               {
21744                 buildsym_compunit *builder = cu->get_builder ();
21745                 list_to_add
21746                   = (cu->list_in_scope == builder->get_file_symbols ()
21747                      && cu->language == language_cplus
21748                      ? builder->get_global_symbols ()
21749                      : cu->list_in_scope);
21750
21751                 /* The semantics of C++ state that "struct foo {
21752                    ... }" also defines a typedef for "foo".  */
21753                 if (cu->language == language_cplus
21754                     || cu->language == language_ada
21755                     || cu->language == language_d
21756                     || cu->language == language_rust)
21757                   {
21758                     /* The symbol's name is already allocated along
21759                        with this objfile, so we don't need to
21760                        duplicate it for the type.  */
21761                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21762                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21763                   }
21764               }
21765           }
21766           break;
21767         case DW_TAG_typedef:
21768           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21769           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21770           list_to_add = cu->list_in_scope;
21771           break;
21772         case DW_TAG_base_type:
21773         case DW_TAG_subrange_type:
21774           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21775           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21776           list_to_add = cu->list_in_scope;
21777           break;
21778         case DW_TAG_enumerator:
21779           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21780           if (attr)
21781             {
21782               dwarf2_const_value (attr, sym, cu);
21783             }
21784           {
21785             /* NOTE: carlton/2003-11-10: See comment above in the
21786                DW_TAG_class_type, etc. block.  */
21787
21788             list_to_add
21789               = (cu->list_in_scope == cu->get_builder ()->get_file_symbols ()
21790                  && cu->language == language_cplus
21791                  ? cu->get_builder ()->get_global_symbols ()
21792                  : cu->list_in_scope);
21793           }
21794           break;
21795         case DW_TAG_imported_declaration:
21796         case DW_TAG_namespace:
21797           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21798           list_to_add = cu->get_builder ()->get_global_symbols ();
21799           break;
21800         case DW_TAG_module:
21801           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21802           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21803           list_to_add = cu->get_builder ()->get_global_symbols ();
21804           break;
21805         case DW_TAG_common_block:
21806           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21807           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21808           add_symbol_to_list (sym, cu->list_in_scope);
21809           break;
21810         default:
21811           /* Not a tag we recognize.  Hopefully we aren't processing
21812              trash data, but since we must specifically ignore things
21813              we don't recognize, there is nothing else we should do at
21814              this point.  */
21815           complaint (_("unsupported tag: '%s'"),
21816                      dwarf_tag_name (die->tag));
21817           break;
21818         }
21819
21820       if (suppress_add)
21821         {
21822           sym->hash_next = objfile->template_symbols;
21823           objfile->template_symbols = sym;
21824           list_to_add = NULL;
21825         }
21826
21827       if (list_to_add != NULL)
21828         add_symbol_to_list (sym, list_to_add);
21829
21830       /* For the benefit of old versions of GCC, check for anonymous
21831          namespaces based on the demangled name.  */
21832       if (!cu->processing_has_namespace_info
21833           && cu->language == language_cplus)
21834         cp_scan_for_anonymous_namespaces (cu->get_builder (), sym, objfile);
21835     }
21836   return (sym);
21837 }
21838
21839 /* Given an attr with a DW_FORM_dataN value in host byte order,
21840    zero-extend it as appropriate for the symbol's type.  The DWARF
21841    standard (v4) is not entirely clear about the meaning of using
21842    DW_FORM_dataN for a constant with a signed type, where the type is
21843    wider than the data.  The conclusion of a discussion on the DWARF
21844    list was that this is unspecified.  We choose to always zero-extend
21845    because that is the interpretation long in use by GCC.  */
21846
21847 static gdb_byte *
21848 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21849                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21850 {
21851   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21852   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21853                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21854   LONGEST l = DW_UNSND (attr);
21855
21856   if (bits < sizeof (*value) * 8)
21857     {
21858       l &= ((LONGEST) 1 << bits) - 1;
21859       *value = l;
21860     }
21861   else if (bits == sizeof (*value) * 8)
21862     *value = l;
21863   else
21864     {
21865       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21866       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21867       return bytes;
21868     }
21869
21870   return NULL;
21871 }
21872
21873 /* Read a constant value from an attribute.  Either set *VALUE, or if
21874    the value does not fit in *VALUE, set *BYTES - either already
21875    allocated on the objfile obstack, or newly allocated on OBSTACK,
21876    or, set *BATON, if we translated the constant to a location
21877    expression.  */
21878
21879 static void
21880 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21881                          const char *name, struct obstack *obstack,
21882                          struct dwarf2_cu *cu,
21883                          LONGEST *value, const gdb_byte **bytes,
21884                          struct dwarf2_locexpr_baton **baton)
21885 {
21886   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21887   struct comp_unit_head *cu_header = &cu->header;
21888   struct dwarf_block *blk;
21889   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21890                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21891
21892   *value = 0;
21893   *bytes = NULL;
21894   *baton = NULL;
21895
21896   switch (attr->form)
21897     {
21898     case DW_FORM_addr:
21899     case DW_FORM_addrx:
21900     case DW_FORM_GNU_addr_index:
21901       {
21902         gdb_byte *data;
21903
21904         if (TYPE_LENGTH (type) != cu_header->addr_size)
21905           dwarf2_const_value_length_mismatch_complaint (name,
21906                                                         cu_header->addr_size,
21907                                                         TYPE_LENGTH (type));
21908         /* Symbols of this form are reasonably rare, so we just
21909            piggyback on the existing location code rather than writing
21910            a new implementation of symbol_computed_ops.  */
21911         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21912         (*baton)->per_cu = cu->per_cu;
21913         gdb_assert ((*baton)->per_cu);
21914
21915         (*baton)->size = 2 + cu_header->addr_size;
21916         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21917         (*baton)->data = data;
21918
21919         data[0] = DW_OP_addr;
21920         store_unsigned_integer (&data[1], cu_header->addr_size,
21921                                 byte_order, DW_ADDR (attr));
21922         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21923       }
21924       break;
21925     case DW_FORM_string:
21926     case DW_FORM_strp:
21927     case DW_FORM_strx:
21928     case DW_FORM_GNU_str_index:
21929     case DW_FORM_GNU_strp_alt:
21930       /* DW_STRING is already allocated on the objfile obstack, point
21931          directly to it.  */
21932       *bytes = (const gdb_byte *) DW_STRING (attr);
21933       break;
21934     case DW_FORM_block1:
21935     case DW_FORM_block2:
21936     case DW_FORM_block4:
21937     case DW_FORM_block:
21938     case DW_FORM_exprloc:
21939     case DW_FORM_data16:
21940       blk = DW_BLOCK (attr);
21941       if (TYPE_LENGTH (type) != blk->size)
21942         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21943                                                       TYPE_LENGTH (type));
21944       *bytes = blk->data;
21945       break;
21946
21947       /* The DW_AT_const_value attributes are supposed to carry the
21948          symbol's value "represented as it would be on the target
21949          architecture."  By the time we get here, it's already been
21950          converted to host endianness, so we just need to sign- or
21951          zero-extend it as appropriate.  */
21952     case DW_FORM_data1:
21953       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21954       break;
21955     case DW_FORM_data2:
21956       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21957       break;
21958     case DW_FORM_data4:
21959       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21960       break;
21961     case DW_FORM_data8:
21962       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21963       break;
21964
21965     case DW_FORM_sdata:
21966     case DW_FORM_implicit_const:
21967       *value = DW_SND (attr);
21968       break;
21969
21970     case DW_FORM_udata:
21971       *value = DW_UNSND (attr);
21972       break;
21973
21974     default:
21975       complaint (_("unsupported const value attribute form: '%s'"),
21976                  dwarf_form_name (attr->form));
21977       *value = 0;
21978       break;
21979     }
21980 }
21981
21982
21983 /* Copy constant value from an attribute to a symbol.  */
21984
21985 static void
21986 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21987                     struct dwarf2_cu *cu)
21988 {
21989   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21990   LONGEST value;
21991   const gdb_byte *bytes;
21992   struct dwarf2_locexpr_baton *baton;
21993
21994   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21995                            SYMBOL_PRINT_NAME (sym),
21996                            &objfile->objfile_obstack, cu,
21997                            &value, &bytes, &baton);
21998
21999   if (baton != NULL)
22000     {
22001       SYMBOL_LOCATION_BATON (sym) = baton;
22002       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22003     }
22004   else if (bytes != NULL)
22005      {
22006       SYMBOL_VALUE_BYTES (sym) = bytes;
22007       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22008     }
22009   else
22010     {
22011       SYMBOL_VALUE (sym) = value;
22012       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22013     }
22014 }
22015
22016 /* Return the type of the die in question using its DW_AT_type attribute.  */
22017
22018 static struct type *
22019 die_type (struct die_info *die, struct dwarf2_cu *cu)
22020 {
22021   struct attribute *type_attr;
22022
22023   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22024   if (!type_attr)
22025     {
22026       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22027       /* A missing DW_AT_type represents a void type.  */
22028       return objfile_type (objfile)->builtin_void;
22029     }
22030
22031   return lookup_die_type (die, type_attr, cu);
22032 }
22033
22034 /* True iff CU's producer generates GNAT Ada auxiliary information
22035    that allows to find parallel types through that information instead
22036    of having to do expensive parallel lookups by type name.  */
22037
22038 static int
22039 need_gnat_info (struct dwarf2_cu *cu)
22040 {
22041   /* Assume that the Ada compiler was GNAT, which always produces
22042      the auxiliary information.  */
22043   return (cu->language == language_ada);
22044 }
22045
22046 /* Return the auxiliary type of the die in question using its
22047    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22048    attribute is not present.  */
22049
22050 static struct type *
22051 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22052 {
22053   struct attribute *type_attr;
22054
22055   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22056   if (!type_attr)
22057     return NULL;
22058
22059   return lookup_die_type (die, type_attr, cu);
22060 }
22061
22062 /* If DIE has a descriptive_type attribute, then set the TYPE's
22063    descriptive type accordingly.  */
22064
22065 static void
22066 set_descriptive_type (struct type *type, struct die_info *die,
22067                       struct dwarf2_cu *cu)
22068 {
22069   struct type *descriptive_type = die_descriptive_type (die, cu);
22070
22071   if (descriptive_type)
22072     {
22073       ALLOCATE_GNAT_AUX_TYPE (type);
22074       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22075     }
22076 }
22077
22078 /* Return the containing type of the die in question using its
22079    DW_AT_containing_type attribute.  */
22080
22081 static struct type *
22082 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22083 {
22084   struct attribute *type_attr;
22085   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22086
22087   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22088   if (!type_attr)
22089     error (_("Dwarf Error: Problem turning containing type into gdb type "
22090              "[in module %s]"), objfile_name (objfile));
22091
22092   return lookup_die_type (die, type_attr, cu);
22093 }
22094
22095 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22096
22097 static struct type *
22098 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22099 {
22100   struct dwarf2_per_objfile *dwarf2_per_objfile
22101     = cu->per_cu->dwarf2_per_objfile;
22102   struct objfile *objfile = dwarf2_per_objfile->objfile;
22103   char *saved;
22104
22105   std::string message
22106     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
22107                      objfile_name (objfile),
22108                      sect_offset_str (cu->header.sect_off),
22109                      sect_offset_str (die->sect_off));
22110   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22111                                   message.c_str (), message.length ());
22112
22113   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22114 }
22115
22116 /* Look up the type of DIE in CU using its type attribute ATTR.
22117    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22118    DW_AT_containing_type.
22119    If there is no type substitute an error marker.  */
22120
22121 static struct type *
22122 lookup_die_type (struct die_info *die, const struct attribute *attr,
22123                  struct dwarf2_cu *cu)
22124 {
22125   struct dwarf2_per_objfile *dwarf2_per_objfile
22126     = cu->per_cu->dwarf2_per_objfile;
22127   struct objfile *objfile = dwarf2_per_objfile->objfile;
22128   struct type *this_type;
22129
22130   gdb_assert (attr->name == DW_AT_type
22131               || attr->name == DW_AT_GNAT_descriptive_type
22132               || attr->name == DW_AT_containing_type);
22133
22134   /* First see if we have it cached.  */
22135
22136   if (attr->form == DW_FORM_GNU_ref_alt)
22137     {
22138       struct dwarf2_per_cu_data *per_cu;
22139       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22140
22141       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22142                                                  dwarf2_per_objfile);
22143       this_type = get_die_type_at_offset (sect_off, per_cu);
22144     }
22145   else if (attr_form_is_ref (attr))
22146     {
22147       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22148
22149       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22150     }
22151   else if (attr->form == DW_FORM_ref_sig8)
22152     {
22153       ULONGEST signature = DW_SIGNATURE (attr);
22154
22155       return get_signatured_type (die, signature, cu);
22156     }
22157   else
22158     {
22159       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22160                    " at %s [in module %s]"),
22161                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22162                  objfile_name (objfile));
22163       return build_error_marker_type (cu, die);
22164     }
22165
22166   /* If not cached we need to read it in.  */
22167
22168   if (this_type == NULL)
22169     {
22170       struct die_info *type_die = NULL;
22171       struct dwarf2_cu *type_cu = cu;
22172
22173       if (attr_form_is_ref (attr))
22174         type_die = follow_die_ref (die, attr, &type_cu);
22175       if (type_die == NULL)
22176         return build_error_marker_type (cu, die);
22177       /* If we find the type now, it's probably because the type came
22178          from an inter-CU reference and the type's CU got expanded before
22179          ours.  */
22180       this_type = read_type_die (type_die, type_cu);
22181     }
22182
22183   /* If we still don't have a type use an error marker.  */
22184
22185   if (this_type == NULL)
22186     return build_error_marker_type (cu, die);
22187
22188   return this_type;
22189 }
22190
22191 /* Return the type in DIE, CU.
22192    Returns NULL for invalid types.
22193
22194    This first does a lookup in die_type_hash,
22195    and only reads the die in if necessary.
22196
22197    NOTE: This can be called when reading in partial or full symbols.  */
22198
22199 static struct type *
22200 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22201 {
22202   struct type *this_type;
22203
22204   this_type = get_die_type (die, cu);
22205   if (this_type)
22206     return this_type;
22207
22208   return read_type_die_1 (die, cu);
22209 }
22210
22211 /* Read the type in DIE, CU.
22212    Returns NULL for invalid types.  */
22213
22214 static struct type *
22215 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22216 {
22217   struct type *this_type = NULL;
22218
22219   switch (die->tag)
22220     {
22221     case DW_TAG_class_type:
22222     case DW_TAG_interface_type:
22223     case DW_TAG_structure_type:
22224     case DW_TAG_union_type:
22225       this_type = read_structure_type (die, cu);
22226       break;
22227     case DW_TAG_enumeration_type:
22228       this_type = read_enumeration_type (die, cu);
22229       break;
22230     case DW_TAG_subprogram:
22231     case DW_TAG_subroutine_type:
22232     case DW_TAG_inlined_subroutine:
22233       this_type = read_subroutine_type (die, cu);
22234       break;
22235     case DW_TAG_array_type:
22236       this_type = read_array_type (die, cu);
22237       break;
22238     case DW_TAG_set_type:
22239       this_type = read_set_type (die, cu);
22240       break;
22241     case DW_TAG_pointer_type:
22242       this_type = read_tag_pointer_type (die, cu);
22243       break;
22244     case DW_TAG_ptr_to_member_type:
22245       this_type = read_tag_ptr_to_member_type (die, cu);
22246       break;
22247     case DW_TAG_reference_type:
22248       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22249       break;
22250     case DW_TAG_rvalue_reference_type:
22251       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22252       break;
22253     case DW_TAG_const_type:
22254       this_type = read_tag_const_type (die, cu);
22255       break;
22256     case DW_TAG_volatile_type:
22257       this_type = read_tag_volatile_type (die, cu);
22258       break;
22259     case DW_TAG_restrict_type:
22260       this_type = read_tag_restrict_type (die, cu);
22261       break;
22262     case DW_TAG_string_type:
22263       this_type = read_tag_string_type (die, cu);
22264       break;
22265     case DW_TAG_typedef:
22266       this_type = read_typedef (die, cu);
22267       break;
22268     case DW_TAG_subrange_type:
22269       this_type = read_subrange_type (die, cu);
22270       break;
22271     case DW_TAG_base_type:
22272       this_type = read_base_type (die, cu);
22273       break;
22274     case DW_TAG_unspecified_type:
22275       this_type = read_unspecified_type (die, cu);
22276       break;
22277     case DW_TAG_namespace:
22278       this_type = read_namespace_type (die, cu);
22279       break;
22280     case DW_TAG_module:
22281       this_type = read_module_type (die, cu);
22282       break;
22283     case DW_TAG_atomic_type:
22284       this_type = read_tag_atomic_type (die, cu);
22285       break;
22286     default:
22287       complaint (_("unexpected tag in read_type_die: '%s'"),
22288                  dwarf_tag_name (die->tag));
22289       break;
22290     }
22291
22292   return this_type;
22293 }
22294
22295 /* See if we can figure out if the class lives in a namespace.  We do
22296    this by looking for a member function; its demangled name will
22297    contain namespace info, if there is any.
22298    Return the computed name or NULL.
22299    Space for the result is allocated on the objfile's obstack.
22300    This is the full-die version of guess_partial_die_structure_name.
22301    In this case we know DIE has no useful parent.  */
22302
22303 static char *
22304 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22305 {
22306   struct die_info *spec_die;
22307   struct dwarf2_cu *spec_cu;
22308   struct die_info *child;
22309   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22310
22311   spec_cu = cu;
22312   spec_die = die_specification (die, &spec_cu);
22313   if (spec_die != NULL)
22314     {
22315       die = spec_die;
22316       cu = spec_cu;
22317     }
22318
22319   for (child = die->child;
22320        child != NULL;
22321        child = child->sibling)
22322     {
22323       if (child->tag == DW_TAG_subprogram)
22324         {
22325           const char *linkage_name = dw2_linkage_name (child, cu);
22326
22327           if (linkage_name != NULL)
22328             {
22329               char *actual_name
22330                 = language_class_name_from_physname (cu->language_defn,
22331                                                      linkage_name);
22332               char *name = NULL;
22333
22334               if (actual_name != NULL)
22335                 {
22336                   const char *die_name = dwarf2_name (die, cu);
22337
22338                   if (die_name != NULL
22339                       && strcmp (die_name, actual_name) != 0)
22340                     {
22341                       /* Strip off the class name from the full name.
22342                          We want the prefix.  */
22343                       int die_name_len = strlen (die_name);
22344                       int actual_name_len = strlen (actual_name);
22345
22346                       /* Test for '::' as a sanity check.  */
22347                       if (actual_name_len > die_name_len + 2
22348                           && actual_name[actual_name_len
22349                                          - die_name_len - 1] == ':')
22350                         name = (char *) obstack_copy0 (
22351                           &objfile->per_bfd->storage_obstack,
22352                           actual_name, actual_name_len - die_name_len - 2);
22353                     }
22354                 }
22355               xfree (actual_name);
22356               return name;
22357             }
22358         }
22359     }
22360
22361   return NULL;
22362 }
22363
22364 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22365    prefix part in such case.  See
22366    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22367
22368 static const char *
22369 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22370 {
22371   struct attribute *attr;
22372   const char *base;
22373
22374   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22375       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22376     return NULL;
22377
22378   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22379     return NULL;
22380
22381   attr = dw2_linkage_name_attr (die, cu);
22382   if (attr == NULL || DW_STRING (attr) == NULL)
22383     return NULL;
22384
22385   /* dwarf2_name had to be already called.  */
22386   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22387
22388   /* Strip the base name, keep any leading namespaces/classes.  */
22389   base = strrchr (DW_STRING (attr), ':');
22390   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22391     return "";
22392
22393   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22394   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22395                                  DW_STRING (attr),
22396                                  &base[-1] - DW_STRING (attr));
22397 }
22398
22399 /* Return the name of the namespace/class that DIE is defined within,
22400    or "" if we can't tell.  The caller should not xfree the result.
22401
22402    For example, if we're within the method foo() in the following
22403    code:
22404
22405    namespace N {
22406      class C {
22407        void foo () {
22408        }
22409      };
22410    }
22411
22412    then determine_prefix on foo's die will return "N::C".  */
22413
22414 static const char *
22415 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22416 {
22417   struct dwarf2_per_objfile *dwarf2_per_objfile
22418     = cu->per_cu->dwarf2_per_objfile;
22419   struct die_info *parent, *spec_die;
22420   struct dwarf2_cu *spec_cu;
22421   struct type *parent_type;
22422   const char *retval;
22423
22424   if (cu->language != language_cplus
22425       && cu->language != language_fortran && cu->language != language_d
22426       && cu->language != language_rust)
22427     return "";
22428
22429   retval = anonymous_struct_prefix (die, cu);
22430   if (retval)
22431     return retval;
22432
22433   /* We have to be careful in the presence of DW_AT_specification.
22434      For example, with GCC 3.4, given the code
22435
22436      namespace N {
22437        void foo() {
22438          // Definition of N::foo.
22439        }
22440      }
22441
22442      then we'll have a tree of DIEs like this:
22443
22444      1: DW_TAG_compile_unit
22445        2: DW_TAG_namespace        // N
22446          3: DW_TAG_subprogram     // declaration of N::foo
22447        4: DW_TAG_subprogram       // definition of N::foo
22448             DW_AT_specification   // refers to die #3
22449
22450      Thus, when processing die #4, we have to pretend that we're in
22451      the context of its DW_AT_specification, namely the contex of die
22452      #3.  */
22453   spec_cu = cu;
22454   spec_die = die_specification (die, &spec_cu);
22455   if (spec_die == NULL)
22456     parent = die->parent;
22457   else
22458     {
22459       parent = spec_die->parent;
22460       cu = spec_cu;
22461     }
22462
22463   if (parent == NULL)
22464     return "";
22465   else if (parent->building_fullname)
22466     {
22467       const char *name;
22468       const char *parent_name;
22469
22470       /* It has been seen on RealView 2.2 built binaries,
22471          DW_TAG_template_type_param types actually _defined_ as
22472          children of the parent class:
22473
22474          enum E {};
22475          template class <class Enum> Class{};
22476          Class<enum E> class_e;
22477
22478          1: DW_TAG_class_type (Class)
22479            2: DW_TAG_enumeration_type (E)
22480              3: DW_TAG_enumerator (enum1:0)
22481              3: DW_TAG_enumerator (enum2:1)
22482              ...
22483            2: DW_TAG_template_type_param
22484               DW_AT_type  DW_FORM_ref_udata (E)
22485
22486          Besides being broken debug info, it can put GDB into an
22487          infinite loop.  Consider:
22488
22489          When we're building the full name for Class<E>, we'll start
22490          at Class, and go look over its template type parameters,
22491          finding E.  We'll then try to build the full name of E, and
22492          reach here.  We're now trying to build the full name of E,
22493          and look over the parent DIE for containing scope.  In the
22494          broken case, if we followed the parent DIE of E, we'd again
22495          find Class, and once again go look at its template type
22496          arguments, etc., etc.  Simply don't consider such parent die
22497          as source-level parent of this die (it can't be, the language
22498          doesn't allow it), and break the loop here.  */
22499       name = dwarf2_name (die, cu);
22500       parent_name = dwarf2_name (parent, cu);
22501       complaint (_("template param type '%s' defined within parent '%s'"),
22502                  name ? name : "<unknown>",
22503                  parent_name ? parent_name : "<unknown>");
22504       return "";
22505     }
22506   else
22507     switch (parent->tag)
22508       {
22509       case DW_TAG_namespace:
22510         parent_type = read_type_die (parent, cu);
22511         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22512            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22513            Work around this problem here.  */
22514         if (cu->language == language_cplus
22515             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22516           return "";
22517         /* We give a name to even anonymous namespaces.  */
22518         return TYPE_NAME (parent_type);
22519       case DW_TAG_class_type:
22520       case DW_TAG_interface_type:
22521       case DW_TAG_structure_type:
22522       case DW_TAG_union_type:
22523       case DW_TAG_module:
22524         parent_type = read_type_die (parent, cu);
22525         if (TYPE_NAME (parent_type) != NULL)
22526           return TYPE_NAME (parent_type);
22527         else
22528           /* An anonymous structure is only allowed non-static data
22529              members; no typedefs, no member functions, et cetera.
22530              So it does not need a prefix.  */
22531           return "";
22532       case DW_TAG_compile_unit:
22533       case DW_TAG_partial_unit:
22534         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22535         if (cu->language == language_cplus
22536             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22537             && die->child != NULL
22538             && (die->tag == DW_TAG_class_type
22539                 || die->tag == DW_TAG_structure_type
22540                 || die->tag == DW_TAG_union_type))
22541           {
22542             char *name = guess_full_die_structure_name (die, cu);
22543             if (name != NULL)
22544               return name;
22545           }
22546         return "";
22547       case DW_TAG_enumeration_type:
22548         parent_type = read_type_die (parent, cu);
22549         if (TYPE_DECLARED_CLASS (parent_type))
22550           {
22551             if (TYPE_NAME (parent_type) != NULL)
22552               return TYPE_NAME (parent_type);
22553             return "";
22554           }
22555         /* Fall through.  */
22556       default:
22557         return determine_prefix (parent, cu);
22558       }
22559 }
22560
22561 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22562    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22563    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22564    an obconcat, otherwise allocate storage for the result.  The CU argument is
22565    used to determine the language and hence, the appropriate separator.  */
22566
22567 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22568
22569 static char *
22570 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22571                  int physname, struct dwarf2_cu *cu)
22572 {
22573   const char *lead = "";
22574   const char *sep;
22575
22576   if (suffix == NULL || suffix[0] == '\0'
22577       || prefix == NULL || prefix[0] == '\0')
22578     sep = "";
22579   else if (cu->language == language_d)
22580     {
22581       /* For D, the 'main' function could be defined in any module, but it
22582          should never be prefixed.  */
22583       if (strcmp (suffix, "D main") == 0)
22584         {
22585           prefix = "";
22586           sep = "";
22587         }
22588       else
22589         sep = ".";
22590     }
22591   else if (cu->language == language_fortran && physname)
22592     {
22593       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22594          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22595
22596       lead = "__";
22597       sep = "_MOD_";
22598     }
22599   else
22600     sep = "::";
22601
22602   if (prefix == NULL)
22603     prefix = "";
22604   if (suffix == NULL)
22605     suffix = "";
22606
22607   if (obs == NULL)
22608     {
22609       char *retval
22610         = ((char *)
22611            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22612
22613       strcpy (retval, lead);
22614       strcat (retval, prefix);
22615       strcat (retval, sep);
22616       strcat (retval, suffix);
22617       return retval;
22618     }
22619   else
22620     {
22621       /* We have an obstack.  */
22622       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22623     }
22624 }
22625
22626 /* Return sibling of die, NULL if no sibling.  */
22627
22628 static struct die_info *
22629 sibling_die (struct die_info *die)
22630 {
22631   return die->sibling;
22632 }
22633
22634 /* Get name of a die, return NULL if not found.  */
22635
22636 static const char *
22637 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22638                           struct obstack *obstack)
22639 {
22640   if (name && cu->language == language_cplus)
22641     {
22642       std::string canon_name = cp_canonicalize_string (name);
22643
22644       if (!canon_name.empty ())
22645         {
22646           if (canon_name != name)
22647             name = (const char *) obstack_copy0 (obstack,
22648                                                  canon_name.c_str (),
22649                                                  canon_name.length ());
22650         }
22651     }
22652
22653   return name;
22654 }
22655
22656 /* Get name of a die, return NULL if not found.
22657    Anonymous namespaces are converted to their magic string.  */
22658
22659 static const char *
22660 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22661 {
22662   struct attribute *attr;
22663   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22664
22665   attr = dwarf2_attr (die, DW_AT_name, cu);
22666   if ((!attr || !DW_STRING (attr))
22667       && die->tag != DW_TAG_namespace
22668       && die->tag != DW_TAG_class_type
22669       && die->tag != DW_TAG_interface_type
22670       && die->tag != DW_TAG_structure_type
22671       && die->tag != DW_TAG_union_type)
22672     return NULL;
22673
22674   switch (die->tag)
22675     {
22676     case DW_TAG_compile_unit:
22677     case DW_TAG_partial_unit:
22678       /* Compilation units have a DW_AT_name that is a filename, not
22679          a source language identifier.  */
22680     case DW_TAG_enumeration_type:
22681     case DW_TAG_enumerator:
22682       /* These tags always have simple identifiers already; no need
22683          to canonicalize them.  */
22684       return DW_STRING (attr);
22685
22686     case DW_TAG_namespace:
22687       if (attr != NULL && DW_STRING (attr) != NULL)
22688         return DW_STRING (attr);
22689       return CP_ANONYMOUS_NAMESPACE_STR;
22690
22691     case DW_TAG_class_type:
22692     case DW_TAG_interface_type:
22693     case DW_TAG_structure_type:
22694     case DW_TAG_union_type:
22695       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22696          structures or unions.  These were of the form "._%d" in GCC 4.1,
22697          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22698          and GCC 4.4.  We work around this problem by ignoring these.  */
22699       if (attr && DW_STRING (attr)
22700           && (startswith (DW_STRING (attr), "._")
22701               || startswith (DW_STRING (attr), "<anonymous")))
22702         return NULL;
22703
22704       /* GCC might emit a nameless typedef that has a linkage name.  See
22705          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22706       if (!attr || DW_STRING (attr) == NULL)
22707         {
22708           char *demangled = NULL;
22709
22710           attr = dw2_linkage_name_attr (die, cu);
22711           if (attr == NULL || DW_STRING (attr) == NULL)
22712             return NULL;
22713
22714           /* Avoid demangling DW_STRING (attr) the second time on a second
22715              call for the same DIE.  */
22716           if (!DW_STRING_IS_CANONICAL (attr))
22717             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22718
22719           if (demangled)
22720             {
22721               const char *base;
22722
22723               /* FIXME: we already did this for the partial symbol... */
22724               DW_STRING (attr)
22725                 = ((const char *)
22726                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22727                                   demangled, strlen (demangled)));
22728               DW_STRING_IS_CANONICAL (attr) = 1;
22729               xfree (demangled);
22730
22731               /* Strip any leading namespaces/classes, keep only the base name.
22732                  DW_AT_name for named DIEs does not contain the prefixes.  */
22733               base = strrchr (DW_STRING (attr), ':');
22734               if (base && base > DW_STRING (attr) && base[-1] == ':')
22735                 return &base[1];
22736               else
22737                 return DW_STRING (attr);
22738             }
22739         }
22740       break;
22741
22742     default:
22743       break;
22744     }
22745
22746   if (!DW_STRING_IS_CANONICAL (attr))
22747     {
22748       DW_STRING (attr)
22749         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22750                                     &objfile->per_bfd->storage_obstack);
22751       DW_STRING_IS_CANONICAL (attr) = 1;
22752     }
22753   return DW_STRING (attr);
22754 }
22755
22756 /* Return the die that this die in an extension of, or NULL if there
22757    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22758    containing the return value on output.  */
22759
22760 static struct die_info *
22761 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22762 {
22763   struct attribute *attr;
22764
22765   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22766   if (attr == NULL)
22767     return NULL;
22768
22769   return follow_die_ref (die, attr, ext_cu);
22770 }
22771
22772 /* A convenience function that returns an "unknown" DWARF name,
22773    including the value of V.  STR is the name of the entity being
22774    printed, e.g., "TAG".  */
22775
22776 static const char *
22777 dwarf_unknown (const char *str, unsigned v)
22778 {
22779   char *cell = get_print_cell ();
22780   xsnprintf (cell, PRINT_CELL_SIZE, "DW_%s_<unknown: %u>", str, v);
22781   return cell;
22782 }
22783
22784 /* Convert a DIE tag into its string name.  */
22785
22786 static const char *
22787 dwarf_tag_name (unsigned tag)
22788 {
22789   const char *name = get_DW_TAG_name (tag);
22790
22791   if (name == NULL)
22792     return dwarf_unknown ("TAG", tag);
22793
22794   return name;
22795 }
22796
22797 /* Convert a DWARF attribute code into its string name.  */
22798
22799 static const char *
22800 dwarf_attr_name (unsigned attr)
22801 {
22802   const char *name;
22803
22804 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22805   if (attr == DW_AT_MIPS_fde)
22806     return "DW_AT_MIPS_fde";
22807 #else
22808   if (attr == DW_AT_HP_block_index)
22809     return "DW_AT_HP_block_index";
22810 #endif
22811
22812   name = get_DW_AT_name (attr);
22813
22814   if (name == NULL)
22815     return dwarf_unknown ("AT", attr);
22816
22817   return name;
22818 }
22819
22820 /* Convert a DWARF value form code into its string name.  */
22821
22822 static const char *
22823 dwarf_form_name (unsigned form)
22824 {
22825   const char *name = get_DW_FORM_name (form);
22826
22827   if (name == NULL)
22828     return dwarf_unknown ("FORM", form);
22829
22830   return name;
22831 }
22832
22833 static const char *
22834 dwarf_bool_name (unsigned mybool)
22835 {
22836   if (mybool)
22837     return "TRUE";
22838   else
22839     return "FALSE";
22840 }
22841
22842 /* Convert a DWARF type code into its string name.  */
22843
22844 static const char *
22845 dwarf_type_encoding_name (unsigned enc)
22846 {
22847   const char *name = get_DW_ATE_name (enc);
22848
22849   if (name == NULL)
22850     return dwarf_unknown ("ATE", enc);
22851
22852   return name;
22853 }
22854
22855 static void
22856 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22857 {
22858   unsigned int i;
22859
22860   print_spaces (indent, f);
22861   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22862                       dwarf_tag_name (die->tag), die->abbrev,
22863                       sect_offset_str (die->sect_off));
22864
22865   if (die->parent != NULL)
22866     {
22867       print_spaces (indent, f);
22868       fprintf_unfiltered (f, "  parent at offset: %s\n",
22869                           sect_offset_str (die->parent->sect_off));
22870     }
22871
22872   print_spaces (indent, f);
22873   fprintf_unfiltered (f, "  has children: %s\n",
22874            dwarf_bool_name (die->child != NULL));
22875
22876   print_spaces (indent, f);
22877   fprintf_unfiltered (f, "  attributes:\n");
22878
22879   for (i = 0; i < die->num_attrs; ++i)
22880     {
22881       print_spaces (indent, f);
22882       fprintf_unfiltered (f, "    %s (%s) ",
22883                dwarf_attr_name (die->attrs[i].name),
22884                dwarf_form_name (die->attrs[i].form));
22885
22886       switch (die->attrs[i].form)
22887         {
22888         case DW_FORM_addr:
22889         case DW_FORM_addrx:
22890         case DW_FORM_GNU_addr_index:
22891           fprintf_unfiltered (f, "address: ");
22892           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22893           break;
22894         case DW_FORM_block2:
22895         case DW_FORM_block4:
22896         case DW_FORM_block:
22897         case DW_FORM_block1:
22898           fprintf_unfiltered (f, "block: size %s",
22899                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22900           break;
22901         case DW_FORM_exprloc:
22902           fprintf_unfiltered (f, "expression: size %s",
22903                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22904           break;
22905         case DW_FORM_data16:
22906           fprintf_unfiltered (f, "constant of 16 bytes");
22907           break;
22908         case DW_FORM_ref_addr:
22909           fprintf_unfiltered (f, "ref address: ");
22910           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22911           break;
22912         case DW_FORM_GNU_ref_alt:
22913           fprintf_unfiltered (f, "alt ref address: ");
22914           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22915           break;
22916         case DW_FORM_ref1:
22917         case DW_FORM_ref2:
22918         case DW_FORM_ref4:
22919         case DW_FORM_ref8:
22920         case DW_FORM_ref_udata:
22921           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22922                               (long) (DW_UNSND (&die->attrs[i])));
22923           break;
22924         case DW_FORM_data1:
22925         case DW_FORM_data2:
22926         case DW_FORM_data4:
22927         case DW_FORM_data8:
22928         case DW_FORM_udata:
22929         case DW_FORM_sdata:
22930           fprintf_unfiltered (f, "constant: %s",
22931                               pulongest (DW_UNSND (&die->attrs[i])));
22932           break;
22933         case DW_FORM_sec_offset:
22934           fprintf_unfiltered (f, "section offset: %s",
22935                               pulongest (DW_UNSND (&die->attrs[i])));
22936           break;
22937         case DW_FORM_ref_sig8:
22938           fprintf_unfiltered (f, "signature: %s",
22939                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22940           break;
22941         case DW_FORM_string:
22942         case DW_FORM_strp:
22943         case DW_FORM_line_strp:
22944         case DW_FORM_strx:
22945         case DW_FORM_GNU_str_index:
22946         case DW_FORM_GNU_strp_alt:
22947           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22948                    DW_STRING (&die->attrs[i])
22949                    ? DW_STRING (&die->attrs[i]) : "",
22950                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22951           break;
22952         case DW_FORM_flag:
22953           if (DW_UNSND (&die->attrs[i]))
22954             fprintf_unfiltered (f, "flag: TRUE");
22955           else
22956             fprintf_unfiltered (f, "flag: FALSE");
22957           break;
22958         case DW_FORM_flag_present:
22959           fprintf_unfiltered (f, "flag: TRUE");
22960           break;
22961         case DW_FORM_indirect:
22962           /* The reader will have reduced the indirect form to
22963              the "base form" so this form should not occur.  */
22964           fprintf_unfiltered (f, 
22965                               "unexpected attribute form: DW_FORM_indirect");
22966           break;
22967         case DW_FORM_implicit_const:
22968           fprintf_unfiltered (f, "constant: %s",
22969                               plongest (DW_SND (&die->attrs[i])));
22970           break;
22971         default:
22972           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22973                    die->attrs[i].form);
22974           break;
22975         }
22976       fprintf_unfiltered (f, "\n");
22977     }
22978 }
22979
22980 static void
22981 dump_die_for_error (struct die_info *die)
22982 {
22983   dump_die_shallow (gdb_stderr, 0, die);
22984 }
22985
22986 static void
22987 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22988 {
22989   int indent = level * 4;
22990
22991   gdb_assert (die != NULL);
22992
22993   if (level >= max_level)
22994     return;
22995
22996   dump_die_shallow (f, indent, die);
22997
22998   if (die->child != NULL)
22999     {
23000       print_spaces (indent, f);
23001       fprintf_unfiltered (f, "  Children:");
23002       if (level + 1 < max_level)
23003         {
23004           fprintf_unfiltered (f, "\n");
23005           dump_die_1 (f, level + 1, max_level, die->child);
23006         }
23007       else
23008         {
23009           fprintf_unfiltered (f,
23010                               " [not printed, max nesting level reached]\n");
23011         }
23012     }
23013
23014   if (die->sibling != NULL && level > 0)
23015     {
23016       dump_die_1 (f, level, max_level, die->sibling);
23017     }
23018 }
23019
23020 /* This is called from the pdie macro in gdbinit.in.
23021    It's not static so gcc will keep a copy callable from gdb.  */
23022
23023 void
23024 dump_die (struct die_info *die, int max_level)
23025 {
23026   dump_die_1 (gdb_stdlog, 0, max_level, die);
23027 }
23028
23029 static void
23030 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23031 {
23032   void **slot;
23033
23034   slot = htab_find_slot_with_hash (cu->die_hash, die,
23035                                    to_underlying (die->sect_off),
23036                                    INSERT);
23037
23038   *slot = die;
23039 }
23040
23041 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
23042    required kind.  */
23043
23044 static sect_offset
23045 dwarf2_get_ref_die_offset (const struct attribute *attr)
23046 {
23047   if (attr_form_is_ref (attr))
23048     return (sect_offset) DW_UNSND (attr);
23049
23050   complaint (_("unsupported die ref attribute form: '%s'"),
23051              dwarf_form_name (attr->form));
23052   return {};
23053 }
23054
23055 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
23056  * the value held by the attribute is not constant.  */
23057
23058 static LONGEST
23059 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
23060 {
23061   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
23062     return DW_SND (attr);
23063   else if (attr->form == DW_FORM_udata
23064            || attr->form == DW_FORM_data1
23065            || attr->form == DW_FORM_data2
23066            || attr->form == DW_FORM_data4
23067            || attr->form == DW_FORM_data8)
23068     return DW_UNSND (attr);
23069   else
23070     {
23071       /* For DW_FORM_data16 see attr_form_is_constant.  */
23072       complaint (_("Attribute value is not a constant (%s)"),
23073                  dwarf_form_name (attr->form));
23074       return default_value;
23075     }
23076 }
23077
23078 /* Follow reference or signature attribute ATTR of SRC_DIE.
23079    On entry *REF_CU is the CU of SRC_DIE.
23080    On exit *REF_CU is the CU of the result.  */
23081
23082 static struct die_info *
23083 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23084                        struct dwarf2_cu **ref_cu)
23085 {
23086   struct die_info *die;
23087
23088   if (attr_form_is_ref (attr))
23089     die = follow_die_ref (src_die, attr, ref_cu);
23090   else if (attr->form == DW_FORM_ref_sig8)
23091     die = follow_die_sig (src_die, attr, ref_cu);
23092   else
23093     {
23094       dump_die_for_error (src_die);
23095       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23096              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23097     }
23098
23099   return die;
23100 }
23101
23102 /* Follow reference OFFSET.
23103    On entry *REF_CU is the CU of the source die referencing OFFSET.
23104    On exit *REF_CU is the CU of the result.
23105    Returns NULL if OFFSET is invalid.  */
23106
23107 static struct die_info *
23108 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23109                    struct dwarf2_cu **ref_cu)
23110 {
23111   struct die_info temp_die;
23112   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23113   struct dwarf2_per_objfile *dwarf2_per_objfile
23114     = cu->per_cu->dwarf2_per_objfile;
23115
23116   gdb_assert (cu->per_cu != NULL);
23117
23118   target_cu = cu;
23119
23120   if (cu->per_cu->is_debug_types)
23121     {
23122       /* .debug_types CUs cannot reference anything outside their CU.
23123          If they need to, they have to reference a signatured type via
23124          DW_FORM_ref_sig8.  */
23125       if (!offset_in_cu_p (&cu->header, sect_off))
23126         return NULL;
23127     }
23128   else if (offset_in_dwz != cu->per_cu->is_dwz
23129            || !offset_in_cu_p (&cu->header, sect_off))
23130     {
23131       struct dwarf2_per_cu_data *per_cu;
23132
23133       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23134                                                  dwarf2_per_objfile);
23135
23136       /* If necessary, add it to the queue and load its DIEs.  */
23137       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23138         load_full_comp_unit (per_cu, false, cu->language);
23139
23140       target_cu = per_cu->cu;
23141     }
23142   else if (cu->dies == NULL)
23143     {
23144       /* We're loading full DIEs during partial symbol reading.  */
23145       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23146       load_full_comp_unit (cu->per_cu, false, language_minimal);
23147     }
23148
23149   *ref_cu = target_cu;
23150   temp_die.sect_off = sect_off;
23151
23152   if (target_cu != cu)
23153     target_cu->ancestor = cu;
23154
23155   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23156                                                   &temp_die,
23157                                                   to_underlying (sect_off));
23158 }
23159
23160 /* Follow reference attribute ATTR of SRC_DIE.
23161    On entry *REF_CU is the CU of SRC_DIE.
23162    On exit *REF_CU is the CU of the result.  */
23163
23164 static struct die_info *
23165 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23166                 struct dwarf2_cu **ref_cu)
23167 {
23168   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23169   struct dwarf2_cu *cu = *ref_cu;
23170   struct die_info *die;
23171
23172   die = follow_die_offset (sect_off,
23173                            (attr->form == DW_FORM_GNU_ref_alt
23174                             || cu->per_cu->is_dwz),
23175                            ref_cu);
23176   if (!die)
23177     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23178            "at %s [in module %s]"),
23179            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23180            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23181
23182   return die;
23183 }
23184
23185 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23186    Returned value is intended for DW_OP_call*.  Returned
23187    dwarf2_locexpr_baton->data has lifetime of
23188    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23189
23190 struct dwarf2_locexpr_baton
23191 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23192                                struct dwarf2_per_cu_data *per_cu,
23193                                CORE_ADDR (*get_frame_pc) (void *baton),
23194                                void *baton, bool resolve_abstract_p)
23195 {
23196   struct dwarf2_cu *cu;
23197   struct die_info *die;
23198   struct attribute *attr;
23199   struct dwarf2_locexpr_baton retval;
23200   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
23201   struct objfile *objfile = dwarf2_per_objfile->objfile;
23202
23203   if (per_cu->cu == NULL)
23204     load_cu (per_cu, false);
23205   cu = per_cu->cu;
23206   if (cu == NULL)
23207     {
23208       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23209          Instead just throw an error, not much else we can do.  */
23210       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23211              sect_offset_str (sect_off), objfile_name (objfile));
23212     }
23213
23214   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23215   if (!die)
23216     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23217            sect_offset_str (sect_off), objfile_name (objfile));
23218
23219   attr = dwarf2_attr (die, DW_AT_location, cu);
23220   if (!attr && resolve_abstract_p
23221       && (dwarf2_per_objfile->abstract_to_concrete.find (die->sect_off)
23222           != dwarf2_per_objfile->abstract_to_concrete.end ()))
23223     {
23224       CORE_ADDR pc = (*get_frame_pc) (baton);
23225
23226       for (const auto &cand_off
23227              : dwarf2_per_objfile->abstract_to_concrete[die->sect_off])
23228         {
23229           struct dwarf2_cu *cand_cu = cu;
23230           struct die_info *cand
23231             = follow_die_offset (cand_off, per_cu->is_dwz, &cand_cu);
23232           if (!cand
23233               || !cand->parent
23234               || cand->parent->tag != DW_TAG_subprogram)
23235             continue;
23236
23237           CORE_ADDR pc_low, pc_high;
23238           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23239           if (pc_low == ((CORE_ADDR) -1)
23240               || !(pc_low <= pc && pc < pc_high))
23241             continue;
23242
23243           die = cand;
23244           attr = dwarf2_attr (die, DW_AT_location, cu);
23245           break;
23246         }
23247     }
23248
23249   if (!attr)
23250     {
23251       /* DWARF: "If there is no such attribute, then there is no effect.".
23252          DATA is ignored if SIZE is 0.  */
23253
23254       retval.data = NULL;
23255       retval.size = 0;
23256     }
23257   else if (attr_form_is_section_offset (attr))
23258     {
23259       struct dwarf2_loclist_baton loclist_baton;
23260       CORE_ADDR pc = (*get_frame_pc) (baton);
23261       size_t size;
23262
23263       fill_in_loclist_baton (cu, &loclist_baton, attr);
23264
23265       retval.data = dwarf2_find_location_expression (&loclist_baton,
23266                                                      &size, pc);
23267       retval.size = size;
23268     }
23269   else
23270     {
23271       if (!attr_form_is_block (attr))
23272         error (_("Dwarf Error: DIE at %s referenced in module %s "
23273                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23274                sect_offset_str (sect_off), objfile_name (objfile));
23275
23276       retval.data = DW_BLOCK (attr)->data;
23277       retval.size = DW_BLOCK (attr)->size;
23278     }
23279   retval.per_cu = cu->per_cu;
23280
23281   age_cached_comp_units (dwarf2_per_objfile);
23282
23283   return retval;
23284 }
23285
23286 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23287    offset.  */
23288
23289 struct dwarf2_locexpr_baton
23290 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23291                              struct dwarf2_per_cu_data *per_cu,
23292                              CORE_ADDR (*get_frame_pc) (void *baton),
23293                              void *baton)
23294 {
23295   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23296
23297   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23298 }
23299
23300 /* Write a constant of a given type as target-ordered bytes into
23301    OBSTACK.  */
23302
23303 static const gdb_byte *
23304 write_constant_as_bytes (struct obstack *obstack,
23305                          enum bfd_endian byte_order,
23306                          struct type *type,
23307                          ULONGEST value,
23308                          LONGEST *len)
23309 {
23310   gdb_byte *result;
23311
23312   *len = TYPE_LENGTH (type);
23313   result = (gdb_byte *) obstack_alloc (obstack, *len);
23314   store_unsigned_integer (result, *len, byte_order, value);
23315
23316   return result;
23317 }
23318
23319 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23320    pointer to the constant bytes and set LEN to the length of the
23321    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23322    does not have a DW_AT_const_value, return NULL.  */
23323
23324 const gdb_byte *
23325 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23326                              struct dwarf2_per_cu_data *per_cu,
23327                              struct obstack *obstack,
23328                              LONGEST *len)
23329 {
23330   struct dwarf2_cu *cu;
23331   struct die_info *die;
23332   struct attribute *attr;
23333   const gdb_byte *result = NULL;
23334   struct type *type;
23335   LONGEST value;
23336   enum bfd_endian byte_order;
23337   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23338
23339   if (per_cu->cu == NULL)
23340     load_cu (per_cu, false);
23341   cu = per_cu->cu;
23342   if (cu == NULL)
23343     {
23344       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23345          Instead just throw an error, not much else we can do.  */
23346       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23347              sect_offset_str (sect_off), objfile_name (objfile));
23348     }
23349
23350   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23351   if (!die)
23352     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23353            sect_offset_str (sect_off), objfile_name (objfile));
23354
23355   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23356   if (attr == NULL)
23357     return NULL;
23358
23359   byte_order = (bfd_big_endian (objfile->obfd)
23360                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23361
23362   switch (attr->form)
23363     {
23364     case DW_FORM_addr:
23365     case DW_FORM_addrx:
23366     case DW_FORM_GNU_addr_index:
23367       {
23368         gdb_byte *tem;
23369
23370         *len = cu->header.addr_size;
23371         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23372         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23373         result = tem;
23374       }
23375       break;
23376     case DW_FORM_string:
23377     case DW_FORM_strp:
23378     case DW_FORM_strx:
23379     case DW_FORM_GNU_str_index:
23380     case DW_FORM_GNU_strp_alt:
23381       /* DW_STRING is already allocated on the objfile obstack, point
23382          directly to it.  */
23383       result = (const gdb_byte *) DW_STRING (attr);
23384       *len = strlen (DW_STRING (attr));
23385       break;
23386     case DW_FORM_block1:
23387     case DW_FORM_block2:
23388     case DW_FORM_block4:
23389     case DW_FORM_block:
23390     case DW_FORM_exprloc:
23391     case DW_FORM_data16:
23392       result = DW_BLOCK (attr)->data;
23393       *len = DW_BLOCK (attr)->size;
23394       break;
23395
23396       /* The DW_AT_const_value attributes are supposed to carry the
23397          symbol's value "represented as it would be on the target
23398          architecture."  By the time we get here, it's already been
23399          converted to host endianness, so we just need to sign- or
23400          zero-extend it as appropriate.  */
23401     case DW_FORM_data1:
23402       type = die_type (die, cu);
23403       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23404       if (result == NULL)
23405         result = write_constant_as_bytes (obstack, byte_order,
23406                                           type, value, len);
23407       break;
23408     case DW_FORM_data2:
23409       type = die_type (die, cu);
23410       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23411       if (result == NULL)
23412         result = write_constant_as_bytes (obstack, byte_order,
23413                                           type, value, len);
23414       break;
23415     case DW_FORM_data4:
23416       type = die_type (die, cu);
23417       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23418       if (result == NULL)
23419         result = write_constant_as_bytes (obstack, byte_order,
23420                                           type, value, len);
23421       break;
23422     case DW_FORM_data8:
23423       type = die_type (die, cu);
23424       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23425       if (result == NULL)
23426         result = write_constant_as_bytes (obstack, byte_order,
23427                                           type, value, len);
23428       break;
23429
23430     case DW_FORM_sdata:
23431     case DW_FORM_implicit_const:
23432       type = die_type (die, cu);
23433       result = write_constant_as_bytes (obstack, byte_order,
23434                                         type, DW_SND (attr), len);
23435       break;
23436
23437     case DW_FORM_udata:
23438       type = die_type (die, cu);
23439       result = write_constant_as_bytes (obstack, byte_order,
23440                                         type, DW_UNSND (attr), len);
23441       break;
23442
23443     default:
23444       complaint (_("unsupported const value attribute form: '%s'"),
23445                  dwarf_form_name (attr->form));
23446       break;
23447     }
23448
23449   return result;
23450 }
23451
23452 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23453    valid type for this die is found.  */
23454
23455 struct type *
23456 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23457                                 struct dwarf2_per_cu_data *per_cu)
23458 {
23459   struct dwarf2_cu *cu;
23460   struct die_info *die;
23461
23462   if (per_cu->cu == NULL)
23463     load_cu (per_cu, false);
23464   cu = per_cu->cu;
23465   if (!cu)
23466     return NULL;
23467
23468   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23469   if (!die)
23470     return NULL;
23471
23472   return die_type (die, cu);
23473 }
23474
23475 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23476    PER_CU.  */
23477
23478 struct type *
23479 dwarf2_get_die_type (cu_offset die_offset,
23480                      struct dwarf2_per_cu_data *per_cu)
23481 {
23482   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23483   return get_die_type_at_offset (die_offset_sect, per_cu);
23484 }
23485
23486 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23487    On entry *REF_CU is the CU of SRC_DIE.
23488    On exit *REF_CU is the CU of the result.
23489    Returns NULL if the referenced DIE isn't found.  */
23490
23491 static struct die_info *
23492 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23493                   struct dwarf2_cu **ref_cu)
23494 {
23495   struct die_info temp_die;
23496   struct dwarf2_cu *sig_cu, *cu = *ref_cu;
23497   struct die_info *die;
23498
23499   /* While it might be nice to assert sig_type->type == NULL here,
23500      we can get here for DW_AT_imported_declaration where we need
23501      the DIE not the type.  */
23502
23503   /* If necessary, add it to the queue and load its DIEs.  */
23504
23505   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23506     read_signatured_type (sig_type);
23507
23508   sig_cu = sig_type->per_cu.cu;
23509   gdb_assert (sig_cu != NULL);
23510   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23511   temp_die.sect_off = sig_type->type_offset_in_section;
23512   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23513                                                  to_underlying (temp_die.sect_off));
23514   if (die)
23515     {
23516       struct dwarf2_per_objfile *dwarf2_per_objfile
23517         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23518
23519       /* For .gdb_index version 7 keep track of included TUs.
23520          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23521       if (dwarf2_per_objfile->index_table != NULL
23522           && dwarf2_per_objfile->index_table->version <= 7)
23523         {
23524           VEC_safe_push (dwarf2_per_cu_ptr,
23525                          (*ref_cu)->per_cu->imported_symtabs,
23526                          sig_cu->per_cu);
23527         }
23528
23529       *ref_cu = sig_cu;
23530       if (sig_cu != cu)
23531         sig_cu->ancestor = cu;
23532
23533       return die;
23534     }
23535
23536   return NULL;
23537 }
23538
23539 /* Follow signatured type referenced by ATTR in SRC_DIE.
23540    On entry *REF_CU is the CU of SRC_DIE.
23541    On exit *REF_CU is the CU of the result.
23542    The result is the DIE of the type.
23543    If the referenced type cannot be found an error is thrown.  */
23544
23545 static struct die_info *
23546 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23547                 struct dwarf2_cu **ref_cu)
23548 {
23549   ULONGEST signature = DW_SIGNATURE (attr);
23550   struct signatured_type *sig_type;
23551   struct die_info *die;
23552
23553   gdb_assert (attr->form == DW_FORM_ref_sig8);
23554
23555   sig_type = lookup_signatured_type (*ref_cu, signature);
23556   /* sig_type will be NULL if the signatured type is missing from
23557      the debug info.  */
23558   if (sig_type == NULL)
23559     {
23560       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23561                " from DIE at %s [in module %s]"),
23562              hex_string (signature), sect_offset_str (src_die->sect_off),
23563              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23564     }
23565
23566   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23567   if (die == NULL)
23568     {
23569       dump_die_for_error (src_die);
23570       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23571                " from DIE at %s [in module %s]"),
23572              hex_string (signature), sect_offset_str (src_die->sect_off),
23573              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23574     }
23575
23576   return die;
23577 }
23578
23579 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23580    reading in and processing the type unit if necessary.  */
23581
23582 static struct type *
23583 get_signatured_type (struct die_info *die, ULONGEST signature,
23584                      struct dwarf2_cu *cu)
23585 {
23586   struct dwarf2_per_objfile *dwarf2_per_objfile
23587     = cu->per_cu->dwarf2_per_objfile;
23588   struct signatured_type *sig_type;
23589   struct dwarf2_cu *type_cu;
23590   struct die_info *type_die;
23591   struct type *type;
23592
23593   sig_type = lookup_signatured_type (cu, signature);
23594   /* sig_type will be NULL if the signatured type is missing from
23595      the debug info.  */
23596   if (sig_type == NULL)
23597     {
23598       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23599                    " from DIE at %s [in module %s]"),
23600                  hex_string (signature), sect_offset_str (die->sect_off),
23601                  objfile_name (dwarf2_per_objfile->objfile));
23602       return build_error_marker_type (cu, die);
23603     }
23604
23605   /* If we already know the type we're done.  */
23606   if (sig_type->type != NULL)
23607     return sig_type->type;
23608
23609   type_cu = cu;
23610   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23611   if (type_die != NULL)
23612     {
23613       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23614          is created.  This is important, for example, because for c++ classes
23615          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23616       type = read_type_die (type_die, type_cu);
23617       if (type == NULL)
23618         {
23619           complaint (_("Dwarf Error: Cannot build signatured type %s"
23620                        " referenced from DIE at %s [in module %s]"),
23621                      hex_string (signature), sect_offset_str (die->sect_off),
23622                      objfile_name (dwarf2_per_objfile->objfile));
23623           type = build_error_marker_type (cu, die);
23624         }
23625     }
23626   else
23627     {
23628       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23629                    " from DIE at %s [in module %s]"),
23630                  hex_string (signature), sect_offset_str (die->sect_off),
23631                  objfile_name (dwarf2_per_objfile->objfile));
23632       type = build_error_marker_type (cu, die);
23633     }
23634   sig_type->type = type;
23635
23636   return type;
23637 }
23638
23639 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23640    reading in and processing the type unit if necessary.  */
23641
23642 static struct type *
23643 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23644                           struct dwarf2_cu *cu) /* ARI: editCase function */
23645 {
23646   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23647   if (attr_form_is_ref (attr))
23648     {
23649       struct dwarf2_cu *type_cu = cu;
23650       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23651
23652       return read_type_die (type_die, type_cu);
23653     }
23654   else if (attr->form == DW_FORM_ref_sig8)
23655     {
23656       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23657     }
23658   else
23659     {
23660       struct dwarf2_per_objfile *dwarf2_per_objfile
23661         = cu->per_cu->dwarf2_per_objfile;
23662
23663       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23664                    " at %s [in module %s]"),
23665                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23666                  objfile_name (dwarf2_per_objfile->objfile));
23667       return build_error_marker_type (cu, die);
23668     }
23669 }
23670
23671 /* Load the DIEs associated with type unit PER_CU into memory.  */
23672
23673 static void
23674 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23675 {
23676   struct signatured_type *sig_type;
23677
23678   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23679   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23680
23681   /* We have the per_cu, but we need the signatured_type.
23682      Fortunately this is an easy translation.  */
23683   gdb_assert (per_cu->is_debug_types);
23684   sig_type = (struct signatured_type *) per_cu;
23685
23686   gdb_assert (per_cu->cu == NULL);
23687
23688   read_signatured_type (sig_type);
23689
23690   gdb_assert (per_cu->cu != NULL);
23691 }
23692
23693 /* die_reader_func for read_signatured_type.
23694    This is identical to load_full_comp_unit_reader,
23695    but is kept separate for now.  */
23696
23697 static void
23698 read_signatured_type_reader (const struct die_reader_specs *reader,
23699                              const gdb_byte *info_ptr,
23700                              struct die_info *comp_unit_die,
23701                              int has_children,
23702                              void *data)
23703 {
23704   struct dwarf2_cu *cu = reader->cu;
23705
23706   gdb_assert (cu->die_hash == NULL);
23707   cu->die_hash =
23708     htab_create_alloc_ex (cu->header.length / 12,
23709                           die_hash,
23710                           die_eq,
23711                           NULL,
23712                           &cu->comp_unit_obstack,
23713                           hashtab_obstack_allocate,
23714                           dummy_obstack_deallocate);
23715
23716   if (has_children)
23717     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23718                                                   &info_ptr, comp_unit_die);
23719   cu->dies = comp_unit_die;
23720   /* comp_unit_die is not stored in die_hash, no need.  */
23721
23722   /* We try not to read any attributes in this function, because not
23723      all CUs needed for references have been loaded yet, and symbol
23724      table processing isn't initialized.  But we have to set the CU language,
23725      or we won't be able to build types correctly.
23726      Similarly, if we do not read the producer, we can not apply
23727      producer-specific interpretation.  */
23728   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23729 }
23730
23731 /* Read in a signatured type and build its CU and DIEs.
23732    If the type is a stub for the real type in a DWO file,
23733    read in the real type from the DWO file as well.  */
23734
23735 static void
23736 read_signatured_type (struct signatured_type *sig_type)
23737 {
23738   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23739
23740   gdb_assert (per_cu->is_debug_types);
23741   gdb_assert (per_cu->cu == NULL);
23742
23743   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23744                            read_signatured_type_reader, NULL);
23745   sig_type->per_cu.tu_read = 1;
23746 }
23747
23748 /* Decode simple location descriptions.
23749    Given a pointer to a dwarf block that defines a location, compute
23750    the location and return the value.
23751
23752    NOTE drow/2003-11-18: This function is called in two situations
23753    now: for the address of static or global variables (partial symbols
23754    only) and for offsets into structures which are expected to be
23755    (more or less) constant.  The partial symbol case should go away,
23756    and only the constant case should remain.  That will let this
23757    function complain more accurately.  A few special modes are allowed
23758    without complaint for global variables (for instance, global
23759    register values and thread-local values).
23760
23761    A location description containing no operations indicates that the
23762    object is optimized out.  The return value is 0 for that case.
23763    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23764    callers will only want a very basic result and this can become a
23765    complaint.
23766
23767    Note that stack[0] is unused except as a default error return.  */
23768
23769 static CORE_ADDR
23770 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23771 {
23772   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23773   size_t i;
23774   size_t size = blk->size;
23775   const gdb_byte *data = blk->data;
23776   CORE_ADDR stack[64];
23777   int stacki;
23778   unsigned int bytes_read, unsnd;
23779   gdb_byte op;
23780
23781   i = 0;
23782   stacki = 0;
23783   stack[stacki] = 0;
23784   stack[++stacki] = 0;
23785
23786   while (i < size)
23787     {
23788       op = data[i++];
23789       switch (op)
23790         {
23791         case DW_OP_lit0:
23792         case DW_OP_lit1:
23793         case DW_OP_lit2:
23794         case DW_OP_lit3:
23795         case DW_OP_lit4:
23796         case DW_OP_lit5:
23797         case DW_OP_lit6:
23798         case DW_OP_lit7:
23799         case DW_OP_lit8:
23800         case DW_OP_lit9:
23801         case DW_OP_lit10:
23802         case DW_OP_lit11:
23803         case DW_OP_lit12:
23804         case DW_OP_lit13:
23805         case DW_OP_lit14:
23806         case DW_OP_lit15:
23807         case DW_OP_lit16:
23808         case DW_OP_lit17:
23809         case DW_OP_lit18:
23810         case DW_OP_lit19:
23811         case DW_OP_lit20:
23812         case DW_OP_lit21:
23813         case DW_OP_lit22:
23814         case DW_OP_lit23:
23815         case DW_OP_lit24:
23816         case DW_OP_lit25:
23817         case DW_OP_lit26:
23818         case DW_OP_lit27:
23819         case DW_OP_lit28:
23820         case DW_OP_lit29:
23821         case DW_OP_lit30:
23822         case DW_OP_lit31:
23823           stack[++stacki] = op - DW_OP_lit0;
23824           break;
23825
23826         case DW_OP_reg0:
23827         case DW_OP_reg1:
23828         case DW_OP_reg2:
23829         case DW_OP_reg3:
23830         case DW_OP_reg4:
23831         case DW_OP_reg5:
23832         case DW_OP_reg6:
23833         case DW_OP_reg7:
23834         case DW_OP_reg8:
23835         case DW_OP_reg9:
23836         case DW_OP_reg10:
23837         case DW_OP_reg11:
23838         case DW_OP_reg12:
23839         case DW_OP_reg13:
23840         case DW_OP_reg14:
23841         case DW_OP_reg15:
23842         case DW_OP_reg16:
23843         case DW_OP_reg17:
23844         case DW_OP_reg18:
23845         case DW_OP_reg19:
23846         case DW_OP_reg20:
23847         case DW_OP_reg21:
23848         case DW_OP_reg22:
23849         case DW_OP_reg23:
23850         case DW_OP_reg24:
23851         case DW_OP_reg25:
23852         case DW_OP_reg26:
23853         case DW_OP_reg27:
23854         case DW_OP_reg28:
23855         case DW_OP_reg29:
23856         case DW_OP_reg30:
23857         case DW_OP_reg31:
23858           stack[++stacki] = op - DW_OP_reg0;
23859           if (i < size)
23860             dwarf2_complex_location_expr_complaint ();
23861           break;
23862
23863         case DW_OP_regx:
23864           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23865           i += bytes_read;
23866           stack[++stacki] = unsnd;
23867           if (i < size)
23868             dwarf2_complex_location_expr_complaint ();
23869           break;
23870
23871         case DW_OP_addr:
23872           stack[++stacki] = read_address (objfile->obfd, &data[i],
23873                                           cu, &bytes_read);
23874           i += bytes_read;
23875           break;
23876
23877         case DW_OP_const1u:
23878           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23879           i += 1;
23880           break;
23881
23882         case DW_OP_const1s:
23883           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23884           i += 1;
23885           break;
23886
23887         case DW_OP_const2u:
23888           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23889           i += 2;
23890           break;
23891
23892         case DW_OP_const2s:
23893           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23894           i += 2;
23895           break;
23896
23897         case DW_OP_const4u:
23898           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23899           i += 4;
23900           break;
23901
23902         case DW_OP_const4s:
23903           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23904           i += 4;
23905           break;
23906
23907         case DW_OP_const8u:
23908           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23909           i += 8;
23910           break;
23911
23912         case DW_OP_constu:
23913           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23914                                                   &bytes_read);
23915           i += bytes_read;
23916           break;
23917
23918         case DW_OP_consts:
23919           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23920           i += bytes_read;
23921           break;
23922
23923         case DW_OP_dup:
23924           stack[stacki + 1] = stack[stacki];
23925           stacki++;
23926           break;
23927
23928         case DW_OP_plus:
23929           stack[stacki - 1] += stack[stacki];
23930           stacki--;
23931           break;
23932
23933         case DW_OP_plus_uconst:
23934           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23935                                                  &bytes_read);
23936           i += bytes_read;
23937           break;
23938
23939         case DW_OP_minus:
23940           stack[stacki - 1] -= stack[stacki];
23941           stacki--;
23942           break;
23943
23944         case DW_OP_deref:
23945           /* If we're not the last op, then we definitely can't encode
23946              this using GDB's address_class enum.  This is valid for partial
23947              global symbols, although the variable's address will be bogus
23948              in the psymtab.  */
23949           if (i < size)
23950             dwarf2_complex_location_expr_complaint ();
23951           break;
23952
23953         case DW_OP_GNU_push_tls_address:
23954         case DW_OP_form_tls_address:
23955           /* The top of the stack has the offset from the beginning
23956              of the thread control block at which the variable is located.  */
23957           /* Nothing should follow this operator, so the top of stack would
23958              be returned.  */
23959           /* This is valid for partial global symbols, but the variable's
23960              address will be bogus in the psymtab.  Make it always at least
23961              non-zero to not look as a variable garbage collected by linker
23962              which have DW_OP_addr 0.  */
23963           if (i < size)
23964             dwarf2_complex_location_expr_complaint ();
23965           stack[stacki]++;
23966           break;
23967
23968         case DW_OP_GNU_uninit:
23969           break;
23970
23971         case DW_OP_addrx:
23972         case DW_OP_GNU_addr_index:
23973         case DW_OP_GNU_const_index:
23974           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23975                                                          &bytes_read);
23976           i += bytes_read;
23977           break;
23978
23979         default:
23980           {
23981             const char *name = get_DW_OP_name (op);
23982
23983             if (name)
23984               complaint (_("unsupported stack op: '%s'"),
23985                          name);
23986             else
23987               complaint (_("unsupported stack op: '%02x'"),
23988                          op);
23989           }
23990
23991           return (stack[stacki]);
23992         }
23993
23994       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23995          outside of the allocated space.  Also enforce minimum>0.  */
23996       if (stacki >= ARRAY_SIZE (stack) - 1)
23997         {
23998           complaint (_("location description stack overflow"));
23999           return 0;
24000         }
24001
24002       if (stacki <= 0)
24003         {
24004           complaint (_("location description stack underflow"));
24005           return 0;
24006         }
24007     }
24008   return (stack[stacki]);
24009 }
24010
24011 /* memory allocation interface */
24012
24013 static struct dwarf_block *
24014 dwarf_alloc_block (struct dwarf2_cu *cu)
24015 {
24016   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24017 }
24018
24019 static struct die_info *
24020 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24021 {
24022   struct die_info *die;
24023   size_t size = sizeof (struct die_info);
24024
24025   if (num_attrs > 1)
24026     size += (num_attrs - 1) * sizeof (struct attribute);
24027
24028   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24029   memset (die, 0, sizeof (struct die_info));
24030   return (die);
24031 }
24032
24033 \f
24034 /* Macro support.  */
24035
24036 /* Return file name relative to the compilation directory of file number I in
24037    *LH's file name table.  The result is allocated using xmalloc; the caller is
24038    responsible for freeing it.  */
24039
24040 static char *
24041 file_file_name (int file, struct line_header *lh)
24042 {
24043   /* Is the file number a valid index into the line header's file name
24044      table?  Remember that file numbers start with one, not zero.  */
24045   if (1 <= file && file <= lh->file_names.size ())
24046     {
24047       const file_entry &fe = lh->file_names[file - 1];
24048
24049       if (!IS_ABSOLUTE_PATH (fe.name))
24050         {
24051           const char *dir = fe.include_dir (lh);
24052           if (dir != NULL)
24053             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
24054         }
24055       return xstrdup (fe.name);
24056     }
24057   else
24058     {
24059       /* The compiler produced a bogus file number.  We can at least
24060          record the macro definitions made in the file, even if we
24061          won't be able to find the file by name.  */
24062       char fake_name[80];
24063
24064       xsnprintf (fake_name, sizeof (fake_name),
24065                  "<bad macro file number %d>", file);
24066
24067       complaint (_("bad file number in macro information (%d)"),
24068                  file);
24069
24070       return xstrdup (fake_name);
24071     }
24072 }
24073
24074 /* Return the full name of file number I in *LH's file name table.
24075    Use COMP_DIR as the name of the current directory of the
24076    compilation.  The result is allocated using xmalloc; the caller is
24077    responsible for freeing it.  */
24078 static char *
24079 file_full_name (int file, struct line_header *lh, const char *comp_dir)
24080 {
24081   /* Is the file number a valid index into the line header's file name
24082      table?  Remember that file numbers start with one, not zero.  */
24083   if (1 <= file && file <= lh->file_names.size ())
24084     {
24085       char *relative = file_file_name (file, lh);
24086
24087       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
24088         return relative;
24089       return reconcat (relative, comp_dir, SLASH_STRING,
24090                        relative, (char *) NULL);
24091     }
24092   else
24093     return file_file_name (file, lh);
24094 }
24095
24096
24097 static struct macro_source_file *
24098 macro_start_file (struct dwarf2_cu *cu,
24099                   int file, int line,
24100                   struct macro_source_file *current_file,
24101                   struct line_header *lh)
24102 {
24103   /* File name relative to the compilation directory of this source file.  */
24104   char *file_name = file_file_name (file, lh);
24105
24106   if (! current_file)
24107     {
24108       /* Note: We don't create a macro table for this compilation unit
24109          at all until we actually get a filename.  */
24110       struct macro_table *macro_table = cu->get_builder ()->get_macro_table ();
24111
24112       /* If we have no current file, then this must be the start_file
24113          directive for the compilation unit's main source file.  */
24114       current_file = macro_set_main (macro_table, file_name);
24115       macro_define_special (macro_table);
24116     }
24117   else
24118     current_file = macro_include (current_file, line, file_name);
24119
24120   xfree (file_name);
24121
24122   return current_file;
24123 }
24124
24125 static const char *
24126 consume_improper_spaces (const char *p, const char *body)
24127 {
24128   if (*p == ' ')
24129     {
24130       complaint (_("macro definition contains spaces "
24131                    "in formal argument list:\n`%s'"),
24132                  body);
24133
24134       while (*p == ' ')
24135         p++;
24136     }
24137
24138   return p;
24139 }
24140
24141
24142 static void
24143 parse_macro_definition (struct macro_source_file *file, int line,
24144                         const char *body)
24145 {
24146   const char *p;
24147
24148   /* The body string takes one of two forms.  For object-like macro
24149      definitions, it should be:
24150
24151         <macro name> " " <definition>
24152
24153      For function-like macro definitions, it should be:
24154
24155         <macro name> "() " <definition>
24156      or
24157         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24158
24159      Spaces may appear only where explicitly indicated, and in the
24160      <definition>.
24161
24162      The Dwarf 2 spec says that an object-like macro's name is always
24163      followed by a space, but versions of GCC around March 2002 omit
24164      the space when the macro's definition is the empty string.
24165
24166      The Dwarf 2 spec says that there should be no spaces between the
24167      formal arguments in a function-like macro's formal argument list,
24168      but versions of GCC around March 2002 include spaces after the
24169      commas.  */
24170
24171
24172   /* Find the extent of the macro name.  The macro name is terminated
24173      by either a space or null character (for an object-like macro) or
24174      an opening paren (for a function-like macro).  */
24175   for (p = body; *p; p++)
24176     if (*p == ' ' || *p == '(')
24177       break;
24178
24179   if (*p == ' ' || *p == '\0')
24180     {
24181       /* It's an object-like macro.  */
24182       int name_len = p - body;
24183       char *name = savestring (body, name_len);
24184       const char *replacement;
24185
24186       if (*p == ' ')
24187         replacement = body + name_len + 1;
24188       else
24189         {
24190           dwarf2_macro_malformed_definition_complaint (body);
24191           replacement = body + name_len;
24192         }
24193
24194       macro_define_object (file, line, name, replacement);
24195
24196       xfree (name);
24197     }
24198   else if (*p == '(')
24199     {
24200       /* It's a function-like macro.  */
24201       char *name = savestring (body, p - body);
24202       int argc = 0;
24203       int argv_size = 1;
24204       char **argv = XNEWVEC (char *, argv_size);
24205
24206       p++;
24207
24208       p = consume_improper_spaces (p, body);
24209
24210       /* Parse the formal argument list.  */
24211       while (*p && *p != ')')
24212         {
24213           /* Find the extent of the current argument name.  */
24214           const char *arg_start = p;
24215
24216           while (*p && *p != ',' && *p != ')' && *p != ' ')
24217             p++;
24218
24219           if (! *p || p == arg_start)
24220             dwarf2_macro_malformed_definition_complaint (body);
24221           else
24222             {
24223               /* Make sure argv has room for the new argument.  */
24224               if (argc >= argv_size)
24225                 {
24226                   argv_size *= 2;
24227                   argv = XRESIZEVEC (char *, argv, argv_size);
24228                 }
24229
24230               argv[argc++] = savestring (arg_start, p - arg_start);
24231             }
24232
24233           p = consume_improper_spaces (p, body);
24234
24235           /* Consume the comma, if present.  */
24236           if (*p == ',')
24237             {
24238               p++;
24239
24240               p = consume_improper_spaces (p, body);
24241             }
24242         }
24243
24244       if (*p == ')')
24245         {
24246           p++;
24247
24248           if (*p == ' ')
24249             /* Perfectly formed definition, no complaints.  */
24250             macro_define_function (file, line, name,
24251                                    argc, (const char **) argv,
24252                                    p + 1);
24253           else if (*p == '\0')
24254             {
24255               /* Complain, but do define it.  */
24256               dwarf2_macro_malformed_definition_complaint (body);
24257               macro_define_function (file, line, name,
24258                                      argc, (const char **) argv,
24259                                      p);
24260             }
24261           else
24262             /* Just complain.  */
24263             dwarf2_macro_malformed_definition_complaint (body);
24264         }
24265       else
24266         /* Just complain.  */
24267         dwarf2_macro_malformed_definition_complaint (body);
24268
24269       xfree (name);
24270       {
24271         int i;
24272
24273         for (i = 0; i < argc; i++)
24274           xfree (argv[i]);
24275       }
24276       xfree (argv);
24277     }
24278   else
24279     dwarf2_macro_malformed_definition_complaint (body);
24280 }
24281
24282 /* Skip some bytes from BYTES according to the form given in FORM.
24283    Returns the new pointer.  */
24284
24285 static const gdb_byte *
24286 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24287                  enum dwarf_form form,
24288                  unsigned int offset_size,
24289                  struct dwarf2_section_info *section)
24290 {
24291   unsigned int bytes_read;
24292
24293   switch (form)
24294     {
24295     case DW_FORM_data1:
24296     case DW_FORM_flag:
24297       ++bytes;
24298       break;
24299
24300     case DW_FORM_data2:
24301       bytes += 2;
24302       break;
24303
24304     case DW_FORM_data4:
24305       bytes += 4;
24306       break;
24307
24308     case DW_FORM_data8:
24309       bytes += 8;
24310       break;
24311
24312     case DW_FORM_data16:
24313       bytes += 16;
24314       break;
24315
24316     case DW_FORM_string:
24317       read_direct_string (abfd, bytes, &bytes_read);
24318       bytes += bytes_read;
24319       break;
24320
24321     case DW_FORM_sec_offset:
24322     case DW_FORM_strp:
24323     case DW_FORM_GNU_strp_alt:
24324       bytes += offset_size;
24325       break;
24326
24327     case DW_FORM_block:
24328       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24329       bytes += bytes_read;
24330       break;
24331
24332     case DW_FORM_block1:
24333       bytes += 1 + read_1_byte (abfd, bytes);
24334       break;
24335     case DW_FORM_block2:
24336       bytes += 2 + read_2_bytes (abfd, bytes);
24337       break;
24338     case DW_FORM_block4:
24339       bytes += 4 + read_4_bytes (abfd, bytes);
24340       break;
24341
24342     case DW_FORM_addrx:
24343     case DW_FORM_sdata:
24344     case DW_FORM_strx:
24345     case DW_FORM_udata:
24346     case DW_FORM_GNU_addr_index:
24347     case DW_FORM_GNU_str_index:
24348       bytes = gdb_skip_leb128 (bytes, buffer_end);
24349       if (bytes == NULL)
24350         {
24351           dwarf2_section_buffer_overflow_complaint (section);
24352           return NULL;
24353         }
24354       break;
24355
24356     case DW_FORM_implicit_const:
24357       break;
24358
24359     default:
24360       {
24361         complaint (_("invalid form 0x%x in `%s'"),
24362                    form, get_section_name (section));
24363         return NULL;
24364       }
24365     }
24366
24367   return bytes;
24368 }
24369
24370 /* A helper for dwarf_decode_macros that handles skipping an unknown
24371    opcode.  Returns an updated pointer to the macro data buffer; or,
24372    on error, issues a complaint and returns NULL.  */
24373
24374 static const gdb_byte *
24375 skip_unknown_opcode (unsigned int opcode,
24376                      const gdb_byte **opcode_definitions,
24377                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24378                      bfd *abfd,
24379                      unsigned int offset_size,
24380                      struct dwarf2_section_info *section)
24381 {
24382   unsigned int bytes_read, i;
24383   unsigned long arg;
24384   const gdb_byte *defn;
24385
24386   if (opcode_definitions[opcode] == NULL)
24387     {
24388       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24389                  opcode);
24390       return NULL;
24391     }
24392
24393   defn = opcode_definitions[opcode];
24394   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24395   defn += bytes_read;
24396
24397   for (i = 0; i < arg; ++i)
24398     {
24399       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24400                                  (enum dwarf_form) defn[i], offset_size,
24401                                  section);
24402       if (mac_ptr == NULL)
24403         {
24404           /* skip_form_bytes already issued the complaint.  */
24405           return NULL;
24406         }
24407     }
24408
24409   return mac_ptr;
24410 }
24411
24412 /* A helper function which parses the header of a macro section.
24413    If the macro section is the extended (for now called "GNU") type,
24414    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24415    the header, or issues a complaint and returns NULL on error.  */
24416
24417 static const gdb_byte *
24418 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24419                           bfd *abfd,
24420                           const gdb_byte *mac_ptr,
24421                           unsigned int *offset_size,
24422                           int section_is_gnu)
24423 {
24424   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24425
24426   if (section_is_gnu)
24427     {
24428       unsigned int version, flags;
24429
24430       version = read_2_bytes (abfd, mac_ptr);
24431       if (version != 4 && version != 5)
24432         {
24433           complaint (_("unrecognized version `%d' in .debug_macro section"),
24434                      version);
24435           return NULL;
24436         }
24437       mac_ptr += 2;
24438
24439       flags = read_1_byte (abfd, mac_ptr);
24440       ++mac_ptr;
24441       *offset_size = (flags & 1) ? 8 : 4;
24442
24443       if ((flags & 2) != 0)
24444         /* We don't need the line table offset.  */
24445         mac_ptr += *offset_size;
24446
24447       /* Vendor opcode descriptions.  */
24448       if ((flags & 4) != 0)
24449         {
24450           unsigned int i, count;
24451
24452           count = read_1_byte (abfd, mac_ptr);
24453           ++mac_ptr;
24454           for (i = 0; i < count; ++i)
24455             {
24456               unsigned int opcode, bytes_read;
24457               unsigned long arg;
24458
24459               opcode = read_1_byte (abfd, mac_ptr);
24460               ++mac_ptr;
24461               opcode_definitions[opcode] = mac_ptr;
24462               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24463               mac_ptr += bytes_read;
24464               mac_ptr += arg;
24465             }
24466         }
24467     }
24468
24469   return mac_ptr;
24470 }
24471
24472 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24473    including DW_MACRO_import.  */
24474
24475 static void
24476 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24477                           bfd *abfd,
24478                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24479                           struct macro_source_file *current_file,
24480                           struct line_header *lh,
24481                           struct dwarf2_section_info *section,
24482                           int section_is_gnu, int section_is_dwz,
24483                           unsigned int offset_size,
24484                           htab_t include_hash)
24485 {
24486   struct dwarf2_per_objfile *dwarf2_per_objfile
24487     = cu->per_cu->dwarf2_per_objfile;
24488   struct objfile *objfile = dwarf2_per_objfile->objfile;
24489   enum dwarf_macro_record_type macinfo_type;
24490   int at_commandline;
24491   const gdb_byte *opcode_definitions[256];
24492
24493   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24494                                       &offset_size, section_is_gnu);
24495   if (mac_ptr == NULL)
24496     {
24497       /* We already issued a complaint.  */
24498       return;
24499     }
24500
24501   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24502      GDB is still reading the definitions from command line.  First
24503      DW_MACINFO_start_file will need to be ignored as it was already executed
24504      to create CURRENT_FILE for the main source holding also the command line
24505      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24506      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24507
24508   at_commandline = 1;
24509
24510   do
24511     {
24512       /* Do we at least have room for a macinfo type byte?  */
24513       if (mac_ptr >= mac_end)
24514         {
24515           dwarf2_section_buffer_overflow_complaint (section);
24516           break;
24517         }
24518
24519       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24520       mac_ptr++;
24521
24522       /* Note that we rely on the fact that the corresponding GNU and
24523          DWARF constants are the same.  */
24524       DIAGNOSTIC_PUSH
24525       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24526       switch (macinfo_type)
24527         {
24528           /* A zero macinfo type indicates the end of the macro
24529              information.  */
24530         case 0:
24531           break;
24532
24533         case DW_MACRO_define:
24534         case DW_MACRO_undef:
24535         case DW_MACRO_define_strp:
24536         case DW_MACRO_undef_strp:
24537         case DW_MACRO_define_sup:
24538         case DW_MACRO_undef_sup:
24539           {
24540             unsigned int bytes_read;
24541             int line;
24542             const char *body;
24543             int is_define;
24544
24545             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24546             mac_ptr += bytes_read;
24547
24548             if (macinfo_type == DW_MACRO_define
24549                 || macinfo_type == DW_MACRO_undef)
24550               {
24551                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24552                 mac_ptr += bytes_read;
24553               }
24554             else
24555               {
24556                 LONGEST str_offset;
24557
24558                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24559                 mac_ptr += offset_size;
24560
24561                 if (macinfo_type == DW_MACRO_define_sup
24562                     || macinfo_type == DW_MACRO_undef_sup
24563                     || section_is_dwz)
24564                   {
24565                     struct dwz_file *dwz
24566                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24567
24568                     body = read_indirect_string_from_dwz (objfile,
24569                                                           dwz, str_offset);
24570                   }
24571                 else
24572                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24573                                                          abfd, str_offset);
24574               }
24575
24576             is_define = (macinfo_type == DW_MACRO_define
24577                          || macinfo_type == DW_MACRO_define_strp
24578                          || macinfo_type == DW_MACRO_define_sup);
24579             if (! current_file)
24580               {
24581                 /* DWARF violation as no main source is present.  */
24582                 complaint (_("debug info with no main source gives macro %s "
24583                              "on line %d: %s"),
24584                            is_define ? _("definition") : _("undefinition"),
24585                            line, body);
24586                 break;
24587               }
24588             if ((line == 0 && !at_commandline)
24589                 || (line != 0 && at_commandline))
24590               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24591                          at_commandline ? _("command-line") : _("in-file"),
24592                          is_define ? _("definition") : _("undefinition"),
24593                          line == 0 ? _("zero") : _("non-zero"), line, body);
24594
24595             if (body == NULL)
24596               {
24597                 /* Fedora's rpm-build's "debugedit" binary
24598                    corrupted .debug_macro sections.
24599
24600                    For more info, see
24601                    https://bugzilla.redhat.com/show_bug.cgi?id=1708786 */
24602                 complaint (_("debug info gives %s invalid macro %s "
24603                              "without body (corrupted?) at line %d "
24604                              "on file %s"),
24605                            at_commandline ? _("command-line") : _("in-file"),
24606                            is_define ? _("definition") : _("undefinition"),
24607                            line, current_file->filename);
24608               }
24609             else if (is_define)
24610               parse_macro_definition (current_file, line, body);
24611             else
24612               {
24613                 gdb_assert (macinfo_type == DW_MACRO_undef
24614                             || macinfo_type == DW_MACRO_undef_strp
24615                             || macinfo_type == DW_MACRO_undef_sup);
24616                 macro_undef (current_file, line, body);
24617               }
24618           }
24619           break;
24620
24621         case DW_MACRO_start_file:
24622           {
24623             unsigned int bytes_read;
24624             int line, file;
24625
24626             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24627             mac_ptr += bytes_read;
24628             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24629             mac_ptr += bytes_read;
24630
24631             if ((line == 0 && !at_commandline)
24632                 || (line != 0 && at_commandline))
24633               complaint (_("debug info gives source %d included "
24634                            "from %s at %s line %d"),
24635                          file, at_commandline ? _("command-line") : _("file"),
24636                          line == 0 ? _("zero") : _("non-zero"), line);
24637
24638             if (at_commandline)
24639               {
24640                 /* This DW_MACRO_start_file was executed in the
24641                    pass one.  */
24642                 at_commandline = 0;
24643               }
24644             else
24645               current_file = macro_start_file (cu, file, line, current_file,
24646                                                lh);
24647           }
24648           break;
24649
24650         case DW_MACRO_end_file:
24651           if (! current_file)
24652             complaint (_("macro debug info has an unmatched "
24653                          "`close_file' directive"));
24654           else
24655             {
24656               current_file = current_file->included_by;
24657               if (! current_file)
24658                 {
24659                   enum dwarf_macro_record_type next_type;
24660
24661                   /* GCC circa March 2002 doesn't produce the zero
24662                      type byte marking the end of the compilation
24663                      unit.  Complain if it's not there, but exit no
24664                      matter what.  */
24665
24666                   /* Do we at least have room for a macinfo type byte?  */
24667                   if (mac_ptr >= mac_end)
24668                     {
24669                       dwarf2_section_buffer_overflow_complaint (section);
24670                       return;
24671                     }
24672
24673                   /* We don't increment mac_ptr here, so this is just
24674                      a look-ahead.  */
24675                   next_type
24676                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24677                                                                   mac_ptr);
24678                   if (next_type != 0)
24679                     complaint (_("no terminating 0-type entry for "
24680                                  "macros in `.debug_macinfo' section"));
24681
24682                   return;
24683                 }
24684             }
24685           break;
24686
24687         case DW_MACRO_import:
24688         case DW_MACRO_import_sup:
24689           {
24690             LONGEST offset;
24691             void **slot;
24692             bfd *include_bfd = abfd;
24693             struct dwarf2_section_info *include_section = section;
24694             const gdb_byte *include_mac_end = mac_end;
24695             int is_dwz = section_is_dwz;
24696             const gdb_byte *new_mac_ptr;
24697
24698             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24699             mac_ptr += offset_size;
24700
24701             if (macinfo_type == DW_MACRO_import_sup)
24702               {
24703                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24704
24705                 dwarf2_read_section (objfile, &dwz->macro);
24706
24707                 include_section = &dwz->macro;
24708                 include_bfd = get_section_bfd_owner (include_section);
24709                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24710                 is_dwz = 1;
24711               }
24712
24713             new_mac_ptr = include_section->buffer + offset;
24714             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24715
24716             if (*slot != NULL)
24717               {
24718                 /* This has actually happened; see
24719                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24720                 complaint (_("recursive DW_MACRO_import in "
24721                              ".debug_macro section"));
24722               }
24723             else
24724               {
24725                 *slot = (void *) new_mac_ptr;
24726
24727                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24728                                           include_mac_end, current_file, lh,
24729                                           section, section_is_gnu, is_dwz,
24730                                           offset_size, include_hash);
24731
24732                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24733               }
24734           }
24735           break;
24736
24737         case DW_MACINFO_vendor_ext:
24738           if (!section_is_gnu)
24739             {
24740               unsigned int bytes_read;
24741
24742               /* This reads the constant, but since we don't recognize
24743                  any vendor extensions, we ignore it.  */
24744               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24745               mac_ptr += bytes_read;
24746               read_direct_string (abfd, mac_ptr, &bytes_read);
24747               mac_ptr += bytes_read;
24748
24749               /* We don't recognize any vendor extensions.  */
24750               break;
24751             }
24752           /* FALLTHROUGH */
24753
24754         default:
24755           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24756                                          mac_ptr, mac_end, abfd, offset_size,
24757                                          section);
24758           if (mac_ptr == NULL)
24759             return;
24760           break;
24761         }
24762       DIAGNOSTIC_POP
24763     } while (macinfo_type != 0);
24764 }
24765
24766 static void
24767 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24768                      int section_is_gnu)
24769 {
24770   struct dwarf2_per_objfile *dwarf2_per_objfile
24771     = cu->per_cu->dwarf2_per_objfile;
24772   struct objfile *objfile = dwarf2_per_objfile->objfile;
24773   struct line_header *lh = cu->line_header;
24774   bfd *abfd;
24775   const gdb_byte *mac_ptr, *mac_end;
24776   struct macro_source_file *current_file = 0;
24777   enum dwarf_macro_record_type macinfo_type;
24778   unsigned int offset_size = cu->header.offset_size;
24779   const gdb_byte *opcode_definitions[256];
24780   void **slot;
24781   struct dwarf2_section_info *section;
24782   const char *section_name;
24783
24784   if (cu->dwo_unit != NULL)
24785     {
24786       if (section_is_gnu)
24787         {
24788           section = &cu->dwo_unit->dwo_file->sections.macro;
24789           section_name = ".debug_macro.dwo";
24790         }
24791       else
24792         {
24793           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24794           section_name = ".debug_macinfo.dwo";
24795         }
24796     }
24797   else
24798     {
24799       if (section_is_gnu)
24800         {
24801           section = &dwarf2_per_objfile->macro;
24802           section_name = ".debug_macro";
24803         }
24804       else
24805         {
24806           section = &dwarf2_per_objfile->macinfo;
24807           section_name = ".debug_macinfo";
24808         }
24809     }
24810
24811   dwarf2_read_section (objfile, section);
24812   if (section->buffer == NULL)
24813     {
24814       complaint (_("missing %s section"), section_name);
24815       return;
24816     }
24817   abfd = get_section_bfd_owner (section);
24818
24819   /* First pass: Find the name of the base filename.
24820      This filename is needed in order to process all macros whose definition
24821      (or undefinition) comes from the command line.  These macros are defined
24822      before the first DW_MACINFO_start_file entry, and yet still need to be
24823      associated to the base file.
24824
24825      To determine the base file name, we scan the macro definitions until we
24826      reach the first DW_MACINFO_start_file entry.  We then initialize
24827      CURRENT_FILE accordingly so that any macro definition found before the
24828      first DW_MACINFO_start_file can still be associated to the base file.  */
24829
24830   mac_ptr = section->buffer + offset;
24831   mac_end = section->buffer + section->size;
24832
24833   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24834                                       &offset_size, section_is_gnu);
24835   if (mac_ptr == NULL)
24836     {
24837       /* We already issued a complaint.  */
24838       return;
24839     }
24840
24841   do
24842     {
24843       /* Do we at least have room for a macinfo type byte?  */
24844       if (mac_ptr >= mac_end)
24845         {
24846           /* Complaint is printed during the second pass as GDB will probably
24847              stop the first pass earlier upon finding
24848              DW_MACINFO_start_file.  */
24849           break;
24850         }
24851
24852       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24853       mac_ptr++;
24854
24855       /* Note that we rely on the fact that the corresponding GNU and
24856          DWARF constants are the same.  */
24857       DIAGNOSTIC_PUSH
24858       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24859       switch (macinfo_type)
24860         {
24861           /* A zero macinfo type indicates the end of the macro
24862              information.  */
24863         case 0:
24864           break;
24865
24866         case DW_MACRO_define:
24867         case DW_MACRO_undef:
24868           /* Only skip the data by MAC_PTR.  */
24869           {
24870             unsigned int bytes_read;
24871
24872             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24873             mac_ptr += bytes_read;
24874             read_direct_string (abfd, mac_ptr, &bytes_read);
24875             mac_ptr += bytes_read;
24876           }
24877           break;
24878
24879         case DW_MACRO_start_file:
24880           {
24881             unsigned int bytes_read;
24882             int line, file;
24883
24884             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24885             mac_ptr += bytes_read;
24886             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24887             mac_ptr += bytes_read;
24888
24889             current_file = macro_start_file (cu, file, line, current_file, lh);
24890           }
24891           break;
24892
24893         case DW_MACRO_end_file:
24894           /* No data to skip by MAC_PTR.  */
24895           break;
24896
24897         case DW_MACRO_define_strp:
24898         case DW_MACRO_undef_strp:
24899         case DW_MACRO_define_sup:
24900         case DW_MACRO_undef_sup:
24901           {
24902             unsigned int bytes_read;
24903
24904             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24905             mac_ptr += bytes_read;
24906             mac_ptr += offset_size;
24907           }
24908           break;
24909
24910         case DW_MACRO_import:
24911         case DW_MACRO_import_sup:
24912           /* Note that, according to the spec, a transparent include
24913              chain cannot call DW_MACRO_start_file.  So, we can just
24914              skip this opcode.  */
24915           mac_ptr += offset_size;
24916           break;
24917
24918         case DW_MACINFO_vendor_ext:
24919           /* Only skip the data by MAC_PTR.  */
24920           if (!section_is_gnu)
24921             {
24922               unsigned int bytes_read;
24923
24924               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24925               mac_ptr += bytes_read;
24926               read_direct_string (abfd, mac_ptr, &bytes_read);
24927               mac_ptr += bytes_read;
24928             }
24929           /* FALLTHROUGH */
24930
24931         default:
24932           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24933                                          mac_ptr, mac_end, abfd, offset_size,
24934                                          section);
24935           if (mac_ptr == NULL)
24936             return;
24937           break;
24938         }
24939       DIAGNOSTIC_POP
24940     } while (macinfo_type != 0 && current_file == NULL);
24941
24942   /* Second pass: Process all entries.
24943
24944      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24945      command-line macro definitions/undefinitions.  This flag is unset when we
24946      reach the first DW_MACINFO_start_file entry.  */
24947
24948   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24949                                            htab_eq_pointer,
24950                                            NULL, xcalloc, xfree));
24951   mac_ptr = section->buffer + offset;
24952   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24953   *slot = (void *) mac_ptr;
24954   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24955                             current_file, lh, section,
24956                             section_is_gnu, 0, offset_size,
24957                             include_hash.get ());
24958 }
24959
24960 /* Check if the attribute's form is a DW_FORM_block*
24961    if so return true else false.  */
24962
24963 static int
24964 attr_form_is_block (const struct attribute *attr)
24965 {
24966   return (attr == NULL ? 0 :
24967       attr->form == DW_FORM_block1
24968       || attr->form == DW_FORM_block2
24969       || attr->form == DW_FORM_block4
24970       || attr->form == DW_FORM_block
24971       || attr->form == DW_FORM_exprloc);
24972 }
24973
24974 /* Return non-zero if ATTR's value is a section offset --- classes
24975    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24976    You may use DW_UNSND (attr) to retrieve such offsets.
24977
24978    Section 7.5.4, "Attribute Encodings", explains that no attribute
24979    may have a value that belongs to more than one of these classes; it
24980    would be ambiguous if we did, because we use the same forms for all
24981    of them.  */
24982
24983 static int
24984 attr_form_is_section_offset (const struct attribute *attr)
24985 {
24986   return (attr->form == DW_FORM_data4
24987           || attr->form == DW_FORM_data8
24988           || attr->form == DW_FORM_sec_offset);
24989 }
24990
24991 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24992    zero otherwise.  When this function returns true, you can apply
24993    dwarf2_get_attr_constant_value to it.
24994
24995    However, note that for some attributes you must check
24996    attr_form_is_section_offset before using this test.  DW_FORM_data4
24997    and DW_FORM_data8 are members of both the constant class, and of
24998    the classes that contain offsets into other debug sections
24999    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
25000    that, if an attribute's can be either a constant or one of the
25001    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
25002    taken as section offsets, not constants.
25003
25004    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
25005    cannot handle that.  */
25006
25007 static int
25008 attr_form_is_constant (const struct attribute *attr)
25009 {
25010   switch (attr->form)
25011     {
25012     case DW_FORM_sdata:
25013     case DW_FORM_udata:
25014     case DW_FORM_data1:
25015     case DW_FORM_data2:
25016     case DW_FORM_data4:
25017     case DW_FORM_data8:
25018     case DW_FORM_implicit_const:
25019       return 1;
25020     default:
25021       return 0;
25022     }
25023 }
25024
25025
25026 /* DW_ADDR is always stored already as sect_offset; despite for the forms
25027    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
25028
25029 static int
25030 attr_form_is_ref (const struct attribute *attr)
25031 {
25032   switch (attr->form)
25033     {
25034     case DW_FORM_ref_addr:
25035     case DW_FORM_ref1:
25036     case DW_FORM_ref2:
25037     case DW_FORM_ref4:
25038     case DW_FORM_ref8:
25039     case DW_FORM_ref_udata:
25040     case DW_FORM_GNU_ref_alt:
25041       return 1;
25042     default:
25043       return 0;
25044     }
25045 }
25046
25047 /* Return the .debug_loc section to use for CU.
25048    For DWO files use .debug_loc.dwo.  */
25049
25050 static struct dwarf2_section_info *
25051 cu_debug_loc_section (struct dwarf2_cu *cu)
25052 {
25053   struct dwarf2_per_objfile *dwarf2_per_objfile
25054     = cu->per_cu->dwarf2_per_objfile;
25055
25056   if (cu->dwo_unit)
25057     {
25058       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
25059       
25060       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
25061     }
25062   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
25063                                   : &dwarf2_per_objfile->loc);
25064 }
25065
25066 /* A helper function that fills in a dwarf2_loclist_baton.  */
25067
25068 static void
25069 fill_in_loclist_baton (struct dwarf2_cu *cu,
25070                        struct dwarf2_loclist_baton *baton,
25071                        const struct attribute *attr)
25072 {
25073   struct dwarf2_per_objfile *dwarf2_per_objfile
25074     = cu->per_cu->dwarf2_per_objfile;
25075   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25076
25077   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
25078
25079   baton->per_cu = cu->per_cu;
25080   gdb_assert (baton->per_cu);
25081   /* We don't know how long the location list is, but make sure we
25082      don't run off the edge of the section.  */
25083   baton->size = section->size - DW_UNSND (attr);
25084   baton->data = section->buffer + DW_UNSND (attr);
25085   baton->base_address = cu->base_address;
25086   baton->from_dwo = cu->dwo_unit != NULL;
25087 }
25088
25089 static void
25090 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
25091                              struct dwarf2_cu *cu, int is_block)
25092 {
25093   struct dwarf2_per_objfile *dwarf2_per_objfile
25094     = cu->per_cu->dwarf2_per_objfile;
25095   struct objfile *objfile = dwarf2_per_objfile->objfile;
25096   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25097
25098   if (attr_form_is_section_offset (attr)
25099       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
25100          the section.  If so, fall through to the complaint in the
25101          other branch.  */
25102       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
25103     {
25104       struct dwarf2_loclist_baton *baton;
25105
25106       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
25107
25108       fill_in_loclist_baton (cu, baton, attr);
25109
25110       if (cu->base_known == 0)
25111         complaint (_("Location list used without "
25112                      "specifying the CU base address."));
25113
25114       SYMBOL_ACLASS_INDEX (sym) = (is_block
25115                                    ? dwarf2_loclist_block_index
25116                                    : dwarf2_loclist_index);
25117       SYMBOL_LOCATION_BATON (sym) = baton;
25118     }
25119   else
25120     {
25121       struct dwarf2_locexpr_baton *baton;
25122
25123       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25124       baton->per_cu = cu->per_cu;
25125       gdb_assert (baton->per_cu);
25126
25127       if (attr_form_is_block (attr))
25128         {
25129           /* Note that we're just copying the block's data pointer
25130              here, not the actual data.  We're still pointing into the
25131              info_buffer for SYM's objfile; right now we never release
25132              that buffer, but when we do clean up properly this may
25133              need to change.  */
25134           baton->size = DW_BLOCK (attr)->size;
25135           baton->data = DW_BLOCK (attr)->data;
25136         }
25137       else
25138         {
25139           dwarf2_invalid_attrib_class_complaint ("location description",
25140                                                  SYMBOL_NATURAL_NAME (sym));
25141           baton->size = 0;
25142         }
25143
25144       SYMBOL_ACLASS_INDEX (sym) = (is_block
25145                                    ? dwarf2_locexpr_block_index
25146                                    : dwarf2_locexpr_index);
25147       SYMBOL_LOCATION_BATON (sym) = baton;
25148     }
25149 }
25150
25151 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25152    came from a separate debuginfo file, then the master objfile is
25153    returned.  */
25154
25155 struct objfile *
25156 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25157 {
25158   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25159
25160   /* Return the master objfile, so that we can report and look up the
25161      correct file containing this variable.  */
25162   if (objfile->separate_debug_objfile_backlink)
25163     objfile = objfile->separate_debug_objfile_backlink;
25164
25165   return objfile;
25166 }
25167
25168 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25169    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25170    CU_HEADERP first.  */
25171
25172 static const struct comp_unit_head *
25173 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25174                        struct dwarf2_per_cu_data *per_cu)
25175 {
25176   const gdb_byte *info_ptr;
25177
25178   if (per_cu->cu)
25179     return &per_cu->cu->header;
25180
25181   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25182
25183   memset (cu_headerp, 0, sizeof (*cu_headerp));
25184   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25185                        rcuh_kind::COMPILE);
25186
25187   return cu_headerp;
25188 }
25189
25190 /* Return the address size given in the compilation unit header for CU.  */
25191
25192 int
25193 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25194 {
25195   struct comp_unit_head cu_header_local;
25196   const struct comp_unit_head *cu_headerp;
25197
25198   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25199
25200   return cu_headerp->addr_size;
25201 }
25202
25203 /* Return the offset size given in the compilation unit header for CU.  */
25204
25205 int
25206 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25207 {
25208   struct comp_unit_head cu_header_local;
25209   const struct comp_unit_head *cu_headerp;
25210
25211   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25212
25213   return cu_headerp->offset_size;
25214 }
25215
25216 /* See its dwarf2loc.h declaration.  */
25217
25218 int
25219 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25220 {
25221   struct comp_unit_head cu_header_local;
25222   const struct comp_unit_head *cu_headerp;
25223
25224   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25225
25226   if (cu_headerp->version == 2)
25227     return cu_headerp->addr_size;
25228   else
25229     return cu_headerp->offset_size;
25230 }
25231
25232 /* Return the text offset of the CU.  The returned offset comes from
25233    this CU's objfile.  If this objfile came from a separate debuginfo
25234    file, then the offset may be different from the corresponding
25235    offset in the parent objfile.  */
25236
25237 CORE_ADDR
25238 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25239 {
25240   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25241
25242   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25243 }
25244
25245 /* Return DWARF version number of PER_CU.  */
25246
25247 short
25248 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25249 {
25250   return per_cu->dwarf_version;
25251 }
25252
25253 /* Locate the .debug_info compilation unit from CU's objfile which contains
25254    the DIE at OFFSET.  Raises an error on failure.  */
25255
25256 static struct dwarf2_per_cu_data *
25257 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25258                                   unsigned int offset_in_dwz,
25259                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25260 {
25261   struct dwarf2_per_cu_data *this_cu;
25262   int low, high;
25263
25264   low = 0;
25265   high = dwarf2_per_objfile->all_comp_units.size () - 1;
25266   while (high > low)
25267     {
25268       struct dwarf2_per_cu_data *mid_cu;
25269       int mid = low + (high - low) / 2;
25270
25271       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25272       if (mid_cu->is_dwz > offset_in_dwz
25273           || (mid_cu->is_dwz == offset_in_dwz
25274               && mid_cu->sect_off + mid_cu->length >= sect_off))
25275         high = mid;
25276       else
25277         low = mid + 1;
25278     }
25279   gdb_assert (low == high);
25280   this_cu = dwarf2_per_objfile->all_comp_units[low];
25281   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
25282     {
25283       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25284         error (_("Dwarf Error: could not find partial DIE containing "
25285                "offset %s [in module %s]"),
25286                sect_offset_str (sect_off),
25287                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25288
25289       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25290                   <= sect_off);
25291       return dwarf2_per_objfile->all_comp_units[low-1];
25292     }
25293   else
25294     {
25295       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25296           && sect_off >= this_cu->sect_off + this_cu->length)
25297         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25298       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25299       return this_cu;
25300     }
25301 }
25302
25303 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25304
25305 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25306   : per_cu (per_cu_),
25307     mark (false),
25308     has_loclist (false),
25309     checked_producer (false),
25310     producer_is_gxx_lt_4_6 (false),
25311     producer_is_gcc_lt_4_3 (false),
25312     producer_is_icc (false),
25313     producer_is_icc_lt_14 (false),
25314     producer_is_codewarrior (false),
25315     processing_has_namespace_info (false)
25316 {
25317   per_cu->cu = this;
25318 }
25319
25320 /* Destroy a dwarf2_cu.  */
25321
25322 dwarf2_cu::~dwarf2_cu ()
25323 {
25324   per_cu->cu = NULL;
25325 }
25326
25327 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25328
25329 static void
25330 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25331                        enum language pretend_language)
25332 {
25333   struct attribute *attr;
25334
25335   /* Set the language we're debugging.  */
25336   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25337   if (attr)
25338     set_cu_language (DW_UNSND (attr), cu);
25339   else
25340     {
25341       cu->language = pretend_language;
25342       cu->language_defn = language_def (cu->language);
25343     }
25344
25345   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25346 }
25347
25348 /* Increase the age counter on each cached compilation unit, and free
25349    any that are too old.  */
25350
25351 static void
25352 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25353 {
25354   struct dwarf2_per_cu_data *per_cu, **last_chain;
25355
25356   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25357   per_cu = dwarf2_per_objfile->read_in_chain;
25358   while (per_cu != NULL)
25359     {
25360       per_cu->cu->last_used ++;
25361       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25362         dwarf2_mark (per_cu->cu);
25363       per_cu = per_cu->cu->read_in_chain;
25364     }
25365
25366   per_cu = dwarf2_per_objfile->read_in_chain;
25367   last_chain = &dwarf2_per_objfile->read_in_chain;
25368   while (per_cu != NULL)
25369     {
25370       struct dwarf2_per_cu_data *next_cu;
25371
25372       next_cu = per_cu->cu->read_in_chain;
25373
25374       if (!per_cu->cu->mark)
25375         {
25376           delete per_cu->cu;
25377           *last_chain = next_cu;
25378         }
25379       else
25380         last_chain = &per_cu->cu->read_in_chain;
25381
25382       per_cu = next_cu;
25383     }
25384 }
25385
25386 /* Remove a single compilation unit from the cache.  */
25387
25388 static void
25389 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25390 {
25391   struct dwarf2_per_cu_data *per_cu, **last_chain;
25392   struct dwarf2_per_objfile *dwarf2_per_objfile
25393     = target_per_cu->dwarf2_per_objfile;
25394
25395   per_cu = dwarf2_per_objfile->read_in_chain;
25396   last_chain = &dwarf2_per_objfile->read_in_chain;
25397   while (per_cu != NULL)
25398     {
25399       struct dwarf2_per_cu_data *next_cu;
25400
25401       next_cu = per_cu->cu->read_in_chain;
25402
25403       if (per_cu == target_per_cu)
25404         {
25405           delete per_cu->cu;
25406           per_cu->cu = NULL;
25407           *last_chain = next_cu;
25408           break;
25409         }
25410       else
25411         last_chain = &per_cu->cu->read_in_chain;
25412
25413       per_cu = next_cu;
25414     }
25415 }
25416
25417 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25418    We store these in a hash table separate from the DIEs, and preserve them
25419    when the DIEs are flushed out of cache.
25420
25421    The CU "per_cu" pointer is needed because offset alone is not enough to
25422    uniquely identify the type.  A file may have multiple .debug_types sections,
25423    or the type may come from a DWO file.  Furthermore, while it's more logical
25424    to use per_cu->section+offset, with Fission the section with the data is in
25425    the DWO file but we don't know that section at the point we need it.
25426    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25427    because we can enter the lookup routine, get_die_type_at_offset, from
25428    outside this file, and thus won't necessarily have PER_CU->cu.
25429    Fortunately, PER_CU is stable for the life of the objfile.  */
25430
25431 struct dwarf2_per_cu_offset_and_type
25432 {
25433   const struct dwarf2_per_cu_data *per_cu;
25434   sect_offset sect_off;
25435   struct type *type;
25436 };
25437
25438 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25439
25440 static hashval_t
25441 per_cu_offset_and_type_hash (const void *item)
25442 {
25443   const struct dwarf2_per_cu_offset_and_type *ofs
25444     = (const struct dwarf2_per_cu_offset_and_type *) item;
25445
25446   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25447 }
25448
25449 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25450
25451 static int
25452 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25453 {
25454   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25455     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25456   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25457     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25458
25459   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25460           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25461 }
25462
25463 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25464    table if necessary.  For convenience, return TYPE.
25465
25466    The DIEs reading must have careful ordering to:
25467     * Not cause infite loops trying to read in DIEs as a prerequisite for
25468       reading current DIE.
25469     * Not trying to dereference contents of still incompletely read in types
25470       while reading in other DIEs.
25471     * Enable referencing still incompletely read in types just by a pointer to
25472       the type without accessing its fields.
25473
25474    Therefore caller should follow these rules:
25475      * Try to fetch any prerequisite types we may need to build this DIE type
25476        before building the type and calling set_die_type.
25477      * After building type call set_die_type for current DIE as soon as
25478        possible before fetching more types to complete the current type.
25479      * Make the type as complete as possible before fetching more types.  */
25480
25481 static struct type *
25482 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25483 {
25484   struct dwarf2_per_objfile *dwarf2_per_objfile
25485     = cu->per_cu->dwarf2_per_objfile;
25486   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25487   struct objfile *objfile = dwarf2_per_objfile->objfile;
25488   struct attribute *attr;
25489   struct dynamic_prop prop;
25490
25491   /* For Ada types, make sure that the gnat-specific data is always
25492      initialized (if not already set).  There are a few types where
25493      we should not be doing so, because the type-specific area is
25494      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25495      where the type-specific area is used to store the floatformat).
25496      But this is not a problem, because the gnat-specific information
25497      is actually not needed for these types.  */
25498   if (need_gnat_info (cu)
25499       && TYPE_CODE (type) != TYPE_CODE_FUNC
25500       && TYPE_CODE (type) != TYPE_CODE_FLT
25501       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25502       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25503       && TYPE_CODE (type) != TYPE_CODE_METHOD
25504       && !HAVE_GNAT_AUX_INFO (type))
25505     INIT_GNAT_SPECIFIC (type);
25506
25507   /* Read DW_AT_allocated and set in type.  */
25508   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25509   if (attr_form_is_block (attr))
25510     {
25511       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25512         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25513     }
25514   else if (attr != NULL)
25515     {
25516       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25517                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25518                  sect_offset_str (die->sect_off));
25519     }
25520
25521   /* Read DW_AT_associated and set in type.  */
25522   attr = dwarf2_attr (die, DW_AT_associated, cu);
25523   if (attr_form_is_block (attr))
25524     {
25525       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25526         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25527     }
25528   else if (attr != NULL)
25529     {
25530       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25531                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25532                  sect_offset_str (die->sect_off));
25533     }
25534
25535   /* Read DW_AT_data_location and set in type.  */
25536   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25537   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25538     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25539
25540   if (dwarf2_per_objfile->die_type_hash == NULL)
25541     {
25542       dwarf2_per_objfile->die_type_hash =
25543         htab_create_alloc_ex (127,
25544                               per_cu_offset_and_type_hash,
25545                               per_cu_offset_and_type_eq,
25546                               NULL,
25547                               &objfile->objfile_obstack,
25548                               hashtab_obstack_allocate,
25549                               dummy_obstack_deallocate);
25550     }
25551
25552   ofs.per_cu = cu->per_cu;
25553   ofs.sect_off = die->sect_off;
25554   ofs.type = type;
25555   slot = (struct dwarf2_per_cu_offset_and_type **)
25556     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25557   if (*slot)
25558     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25559                sect_offset_str (die->sect_off));
25560   *slot = XOBNEW (&objfile->objfile_obstack,
25561                   struct dwarf2_per_cu_offset_and_type);
25562   **slot = ofs;
25563   return type;
25564 }
25565
25566 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25567    or return NULL if the die does not have a saved type.  */
25568
25569 static struct type *
25570 get_die_type_at_offset (sect_offset sect_off,
25571                         struct dwarf2_per_cu_data *per_cu)
25572 {
25573   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25574   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25575
25576   if (dwarf2_per_objfile->die_type_hash == NULL)
25577     return NULL;
25578
25579   ofs.per_cu = per_cu;
25580   ofs.sect_off = sect_off;
25581   slot = ((struct dwarf2_per_cu_offset_and_type *)
25582           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25583   if (slot)
25584     return slot->type;
25585   else
25586     return NULL;
25587 }
25588
25589 /* Look up the type for DIE in CU in die_type_hash,
25590    or return NULL if DIE does not have a saved type.  */
25591
25592 static struct type *
25593 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25594 {
25595   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25596 }
25597
25598 /* Add a dependence relationship from CU to REF_PER_CU.  */
25599
25600 static void
25601 dwarf2_add_dependence (struct dwarf2_cu *cu,
25602                        struct dwarf2_per_cu_data *ref_per_cu)
25603 {
25604   void **slot;
25605
25606   if (cu->dependencies == NULL)
25607     cu->dependencies
25608       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25609                               NULL, &cu->comp_unit_obstack,
25610                               hashtab_obstack_allocate,
25611                               dummy_obstack_deallocate);
25612
25613   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25614   if (*slot == NULL)
25615     *slot = ref_per_cu;
25616 }
25617
25618 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25619    Set the mark field in every compilation unit in the
25620    cache that we must keep because we are keeping CU.  */
25621
25622 static int
25623 dwarf2_mark_helper (void **slot, void *data)
25624 {
25625   struct dwarf2_per_cu_data *per_cu;
25626
25627   per_cu = (struct dwarf2_per_cu_data *) *slot;
25628
25629   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25630      reading of the chain.  As such dependencies remain valid it is not much
25631      useful to track and undo them during QUIT cleanups.  */
25632   if (per_cu->cu == NULL)
25633     return 1;
25634
25635   if (per_cu->cu->mark)
25636     return 1;
25637   per_cu->cu->mark = true;
25638
25639   if (per_cu->cu->dependencies != NULL)
25640     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25641
25642   return 1;
25643 }
25644
25645 /* Set the mark field in CU and in every other compilation unit in the
25646    cache that we must keep because we are keeping CU.  */
25647
25648 static void
25649 dwarf2_mark (struct dwarf2_cu *cu)
25650 {
25651   if (cu->mark)
25652     return;
25653   cu->mark = true;
25654   if (cu->dependencies != NULL)
25655     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25656 }
25657
25658 static void
25659 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25660 {
25661   while (per_cu)
25662     {
25663       per_cu->cu->mark = false;
25664       per_cu = per_cu->cu->read_in_chain;
25665     }
25666 }
25667
25668 /* Trivial hash function for partial_die_info: the hash value of a DIE
25669    is its offset in .debug_info for this objfile.  */
25670
25671 static hashval_t
25672 partial_die_hash (const void *item)
25673 {
25674   const struct partial_die_info *part_die
25675     = (const struct partial_die_info *) item;
25676
25677   return to_underlying (part_die->sect_off);
25678 }
25679
25680 /* Trivial comparison function for partial_die_info structures: two DIEs
25681    are equal if they have the same offset.  */
25682
25683 static int
25684 partial_die_eq (const void *item_lhs, const void *item_rhs)
25685 {
25686   const struct partial_die_info *part_die_lhs
25687     = (const struct partial_die_info *) item_lhs;
25688   const struct partial_die_info *part_die_rhs
25689     = (const struct partial_die_info *) item_rhs;
25690
25691   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25692 }
25693
25694 struct cmd_list_element *set_dwarf_cmdlist;
25695 struct cmd_list_element *show_dwarf_cmdlist;
25696
25697 static void
25698 set_dwarf_cmd (const char *args, int from_tty)
25699 {
25700   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25701              gdb_stdout);
25702 }
25703
25704 static void
25705 show_dwarf_cmd (const char *args, int from_tty)
25706 {
25707   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25708 }
25709
25710 int dwarf_always_disassemble;
25711
25712 static void
25713 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25714                                struct cmd_list_element *c, const char *value)
25715 {
25716   fprintf_filtered (file,
25717                     _("Whether to always disassemble "
25718                       "DWARF expressions is %s.\n"),
25719                     value);
25720 }
25721
25722 static void
25723 show_check_physname (struct ui_file *file, int from_tty,
25724                      struct cmd_list_element *c, const char *value)
25725 {
25726   fprintf_filtered (file,
25727                     _("Whether to check \"physname\" is %s.\n"),
25728                     value);
25729 }
25730
25731 void
25732 _initialize_dwarf2_read (void)
25733 {
25734   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25735 Set DWARF specific variables.\n\
25736 Configure DWARF variables such as the cache size"),
25737                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25738                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25739
25740   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25741 Show DWARF specific variables\n\
25742 Show DWARF variables such as the cache size"),
25743                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25744                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25745
25746   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25747                             &dwarf_max_cache_age, _("\
25748 Set the upper bound on the age of cached DWARF compilation units."), _("\
25749 Show the upper bound on the age of cached DWARF compilation units."), _("\
25750 A higher limit means that cached compilation units will be stored\n\
25751 in memory longer, and more total memory will be used.  Zero disables\n\
25752 caching, which can slow down startup."),
25753                             NULL,
25754                             show_dwarf_max_cache_age,
25755                             &set_dwarf_cmdlist,
25756                             &show_dwarf_cmdlist);
25757
25758   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25759                            &dwarf_always_disassemble, _("\
25760 Set whether `info address' always disassembles DWARF expressions."), _("\
25761 Show whether `info address' always disassembles DWARF expressions."), _("\
25762 When enabled, DWARF expressions are always printed in an assembly-like\n\
25763 syntax.  When disabled, expressions will be printed in a more\n\
25764 conversational style, when possible."),
25765                            NULL,
25766                            show_dwarf_always_disassemble,
25767                            &set_dwarf_cmdlist,
25768                            &show_dwarf_cmdlist);
25769
25770   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25771 Set debugging of the DWARF reader."), _("\
25772 Show debugging of the DWARF reader."), _("\
25773 When enabled (non-zero), debugging messages are printed during DWARF\n\
25774 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25775 information.  A value greater than 1 provides more verbose information."),
25776                             NULL,
25777                             NULL,
25778                             &setdebuglist, &showdebuglist);
25779
25780   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25781 Set debugging of the DWARF DIE reader."), _("\
25782 Show debugging of the DWARF DIE reader."), _("\
25783 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25784 The value is the maximum depth to print."),
25785                              NULL,
25786                              NULL,
25787                              &setdebuglist, &showdebuglist);
25788
25789   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25790 Set debugging of the dwarf line reader."), _("\
25791 Show debugging of the dwarf line reader."), _("\
25792 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25793 A value of 1 (one) provides basic information.\n\
25794 A value greater than 1 provides more verbose information."),
25795                              NULL,
25796                              NULL,
25797                              &setdebuglist, &showdebuglist);
25798
25799   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25800 Set cross-checking of \"physname\" code against demangler."), _("\
25801 Show cross-checking of \"physname\" code against demangler."), _("\
25802 When enabled, GDB's internal \"physname\" code is checked against\n\
25803 the demangler."),
25804                            NULL, show_check_physname,
25805                            &setdebuglist, &showdebuglist);
25806
25807   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25808                            no_class, &use_deprecated_index_sections, _("\
25809 Set whether to use deprecated gdb_index sections."), _("\
25810 Show whether to use deprecated gdb_index sections."), _("\
25811 When enabled, deprecated .gdb_index sections are used anyway.\n\
25812 Normally they are ignored either because of a missing feature or\n\
25813 performance issue.\n\
25814 Warning: This option must be enabled before gdb reads the file."),
25815                            NULL,
25816                            NULL,
25817                            &setlist, &showlist);
25818
25819   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25820                                                         &dwarf2_locexpr_funcs);
25821   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25822                                                         &dwarf2_loclist_funcs);
25823
25824   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25825                                         &dwarf2_block_frame_base_locexpr_funcs);
25826   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25827                                         &dwarf2_block_frame_base_loclist_funcs);
25828
25829 #if GDB_SELF_TEST
25830   selftests::register_test ("dw2_expand_symtabs_matching",
25831                             selftests::dw2_expand_symtabs_matching::run_test);
25832 #endif
25833 }